[
  {
    "path": ".github/ISSUE_TEMPLATE/custom.md",
    "content": "---\nname: Custom issue template\nabout: Describe this issue template's purpose here.\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "**Please fill the details before contributing.**\n\n<!-- These are the comment to assist you better, anything you put inside these standard html tags is not visible to us-->\n<!-- Use [x] to mark as checked -->\n\n# ⚠️Important!!\n<!--NOTE: Your PR will be marked as SPAM if you check this without actually reading the mentioned file or creating a wrong PR after reading it.-->\n<!--You will be disqualified from Hacktoberfest after 2+ spam reports!-->\n- [ ] Done reading [CONTRIBUTING.md](https://github.com/Sagar0-0/DsA/blob/main/CONTRIBUTING.md)?<!--MUST READ-->\n\n# Adding Code PRs?🔥<!-- If adding new code files, only then fill this portion-->\n⚠️Do not add multiple files for the same solution!!!\n- [ ] Added problem statement(Readme.md) with solution?<!--Choice-->\n<!--Check one out or these two-->\n- [ ] Contributing new file?\n- [ ] Appending your code in already existing file?\n\n### From Platform:\n<!--Check one out of these three-->\n- [ ] Leetcode \n- [ ] GFG \n- [ ] Interviewbit\n- [ ] Others(only acceptable after DISCUSSIONS)\n\n# Migration PRs?🤝<!-- ONLY fill out this portion, If helping in migrating old code files in their respective directories -->\n\n- [ ] Done deleteing file from home directory?<!--MUST-->\n- [ ] Added file with correct name and correct directory?<!--MUST-->\n\n"
  },
  {
    "path": "0012-integer-to-roman/0012-integer-to-roman.java",
    "content": "class Solution {\n    \n   \n    public String intToRoman(int num) {\n       \n         int[] val = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };\n    String[] code = { \"M\", \"CM\", \"D\", \"CD\", \"C\", \"XC\", \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\" };\n\n        \n        StringBuilder sb = new StringBuilder();\n\n        while (num > 0) {\n\n            for (int i = 0; i < 13; i++) {\n\n                if (num >= val[i]) {\n\n                    num -= val[i];\n                    sb.append(code[i]);\n                    break;\n                }\n            }\n        }\n\n        return sb.toString();\n\n    }\n}"
  },
  {
    "path": "0012-integer-to-roman/0012-integer-to-roman.py",
    "content": "class Solution:\n    def intToRoman(self, num: int) -> str:\n        d = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}\n        res = ''\n        for k in d:\n            while num >= k:\n                res += d[k]\n                num -= k\n        return res"
  },
  {
    "path": "0012-integer-to-roman/NOTES.md",
    "content": "​"
  },
  {
    "path": "0012-integer-to-roman/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/integer-to-roman/\">12. Integer to Roman</a></h2><h3>Medium</h3><hr><div><p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p>\n\n<pre><strong>Symbol</strong>       <strong>Value</strong>\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000</pre>\n\n<p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two one's added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p>\n\n<p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p>\n\n<ul>\n\t<li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li>\n\t<li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li>\n\t<li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li>\n</ul>\n\n<p>Given an integer, convert it to a roman numeral.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> num = 3\n<strong>Output:</strong> \"III\"\n<strong>Explanation:</strong> 3 is represented as 3 ones.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> num = 58\n<strong>Output:</strong> \"LVIII\"\n<strong>Explanation:</strong> L = 50, V = 5, III = 3.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> num = 1994\n<strong>Output:</strong> \"MCMXCIV\"\n<strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt;= 3999</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0026-remove-duplicates-from-sorted-array/0026-remove-duplicates-from-sorted-array.java",
    "content": "class Solution {\n    public int removeDuplicates(int[] nums) {\n        int idx=0;\n        int i=0;\n        while(i<nums.length-1){\n            while(i<nums.length-1 && nums[i]==nums[i+1]){\n                i++;\n            }\n            nums[idx]=nums[i];\n            idx++;\n            i++;\n        }\n        if(i==nums.length)return idx;\n        nums[idx]=nums[i];\n        return idx+1;\n    }\n}"
  },
  {
    "path": "0026-remove-duplicates-from-sorted-array/0026-remove-duplicates-from-sorted-array.py",
    "content": "class Solution(object):\n    def removeDuplicates(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: int\n        \"\"\"\n        x = 1\n        for i in range(len(nums)-1):\n            if(nums[i]!=nums[i+1]):\n                nums[x] = nums[i+1]\n                x+=1\n        return(x)"
  },
  {
    "path": "0026-remove-duplicates-from-sorted-array/NOTES.md",
    "content": "​"
  },
  {
    "path": "0026-remove-duplicates-from-sorted-array/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/remove-duplicates-from-sorted-array/\">26. Remove Duplicates from Sorted Array</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>.</p>\n\n<p>Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the <strong>first part</strong> of the array <code>nums</code>. More formally, if there are <code>k</code> elements after removing the duplicates, then the first <code>k</code> elements of <code>nums</code>&nbsp;should hold the final result. It does not matter what you leave beyond the first&nbsp;<code>k</code>&nbsp;elements.</p>\n\n<p>Return <code>k</code><em> after placing the final result in the first </em><code>k</code><em> slots of </em><code>nums</code>.</p>\n\n<p>Do <strong>not</strong> allocate extra space for another array. You must do this by <strong>modifying the input array <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in-place</a></strong> with O(1) extra memory.</p>\n\n<p><strong>Custom Judge:</strong></p>\n\n<p>The judge will test your solution with the following code:</p>\n\n<pre>int[] 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</pre>\n\n<p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,1,2]\n<strong>Output:</strong> 2, nums = [1,2,_]\n<strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4]\n<strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_]\n<strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n\t<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>\n</ul>\n</div>"
  },
  {
    "path": "0036-valid-sudoku/0036-valid-sudoku.java",
    "content": "class Solution {\n    public static boolean isCorrect(char[][] board,int x,int y){\n        for(int i=0;i<board.length;i++){\n            if(i!=y && board[x][i]==board[x][y]) return false;\n            if(i!=x && board[i][y]==board[x][y]) return false;\n        }\n        int row=(x/3)*3; \n        int col=(y/3)*3;\n        for(int i=row;i<row+3;i++){\n            for(int j=col;j<col+3;j++){\n                if((i!=x && j!=y) && board[i][j]==board[x][y]) return false;\n            }\n        } \n        return true;\n    }\n\n    public boolean isValidSudoku(char[][] board) {\n        for(int i=0;i<board.length;i++){\n            for(int j=0;j<board.length;j++){\n                if(board[i][j]!='.'){\n                    if(!isCorrect(board,i,j)){\n                        return false;\n                    }\n                }\n            }\n        }\n        return true;\n    }\n    \n}"
  },
  {
    "path": "0036-valid-sudoku/0036-valid-sudoku.py",
    "content": "class Solution:\n    def isValidSudoku(self, board) -> bool:\n        seen = sum(([(c, i), (j, c), (i//3, j//3, c)]\n                for i in range(9) for j in range(9)\n                for c in [board[i][j]] if c != '.'), [])\n        return len(seen) == len(set(seen))"
  },
  {
    "path": "0036-valid-sudoku/NOTES.md",
    "content": "​"
  },
  {
    "path": "0036-valid-sudoku/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/valid-sudoku/\">36. Valid Sudoku</a></h2><h3>Medium</h3><hr><div><p>Determine if a&nbsp;<code>9 x 9</code> Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p>\n\n<ol>\n\t<li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li>\n\t<li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li>\n\t<li>Each of the nine&nbsp;<code>3 x 3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li>\n</ol>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n\t<li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li>\n\t<li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png\" style=\"height:250px; width:250px\">\n<pre><strong>Input:</strong> 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\"]]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> 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\"]]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8's in the top left 3x3 sub-box, it is invalid.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>board.length == 9</code></li>\n\t<li><code>board[i].length == 9</code></li>\n\t<li><code>board[i][j]</code> is a digit <code>1-9</code> or <code>'.'</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0037-sudoku-solver/0037-sudoku-solver.java",
    "content": "class Solution {\n    public void solveSudoku(char[][] board) {\n        dfs(0,0,board);\n    }\n    boolean dfs(int i,int j,char[][]board){\n        if(i==9)return true;\n        if(board[i][j]!='.'){\n            if(j==8){\n                return dfs(i+1,0,board);\n            }else{\n                return dfs(i,j+1,board);\n            }\n        }\n        \n        for(int num=1;num<=9;num++){\n            board[i][j]=(char)(num+'0');\n            if(safe(board,i,j)){\n                boolean ans;\n                if(j==8){\n                    ans=dfs(i+1,0,board);\n                }else{\n                    ans=dfs(i,j+1,board);\n                }\n                if(ans)return true;\n            }\n            board[i][j]='.';\n        }\n        \n        return false;\n    }\n    boolean notInRow(char arr[][], int row)\n    {\n        HashSet<Character> st = new HashSet<>();\n        for (int i = 0; i < 9; i++) {\n            if (st.contains(arr[row][i]))\n                return false;\n \n            if (arr[row][i] != '.')\n                st.add(arr[row][i]);\n        }\n        return true;\n    }\n    boolean notInCol(char arr[][], int col)\n    {\n        HashSet<Character> st = new HashSet<>();\n        for (int i = 0; i < 9; i++) {\n            if (st.contains(arr[i][col]))\n                return false;\n            if (arr[i][col] != '.')\n                st.add(arr[i][col]);\n        }\n        return true;\n    }\n    boolean notInBox(char arr[][], int startRow, int startCol)\n    {\n        HashSet<Character> st = new HashSet<>();\n \n        for (int row = 0; row < 3; row++) {\n            for (int col = 0; col < 3; col++) {\n                char curr = arr[row + startRow][col + startCol];\n                if (st.contains(curr))\n                    return false;\n                \n                if (curr != '.')\n                    st.add(curr);\n            }\n        }\n        return true;\n    }\n    boolean safe(char arr[][], int row,\n                                  int col)\n    {\n        return notInRow(arr, row) && notInCol(arr, col)\n            && notInBox(arr, row - row % 3, col - col % 3);\n    }\n}"
  },
  {
    "path": "0037-sudoku-solver/NOTES.md",
    "content": "​"
  },
  {
    "path": "0037-sudoku-solver/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/sudoku-solver/\">37. Sudoku Solver</a></h2><h3>Hard</h3><hr><div><p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p>\n\n<p>A sudoku solution must satisfy <strong>all of the following rules</strong>:</p>\n\n<ol>\n\t<li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li>\n\t<li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li>\n\t<li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li>\n</ol>\n\n<p>The <code>'.'</code> character indicates empty cells.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png\" style=\"height:250px; width:250px\">\n<pre><strong>Input:</strong> 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\"]]\n<strong>Output:</strong> [[\"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\"]]\n<strong>Explanation:</strong>&nbsp;The input board is shown above and the only valid solution is shown below:\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png\" style=\"height:250px; width:250px\">\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>board.length == 9</code></li>\n\t<li><code>board[i].length == 9</code></li>\n\t<li><code>board[i][j]</code> is a digit or <code>'.'</code>.</li>\n\t<li>It is <strong>guaranteed</strong> that the input board has only one solution.</li>\n</ul>\n</div>"
  },
  {
    "path": "0038-count-and-say/0038-count-and-say.java",
    "content": "class Solution {\n    public String countAndSay(int n) {\n        StringBuilder sb = new StringBuilder(\"1\");\n        for (int i = 2; i <= n; i++) {\n            sb = getNextState(sb);\n        }\n        return sb.toString();\n    }\n\n    private StringBuilder getNextState(StringBuilder curSb) {\n        StringBuilder nextSb = new StringBuilder();\n        int len = curSb.length();\n        int i = 0;\n\t\t\n        while (i < len) {\n            char c = curSb.charAt(i++);\n            int count = 1;\n            while (i < len && c == curSb.charAt(i)) {\n                count++;\n                i++;\n            }\n            nextSb.append(count).append(c);\n        }\n\t\t\n        return nextSb;\n    }\n}"
  },
  {
    "path": "0038-count-and-say/0038-count-and-say.py",
    "content": "import re\nclass Solution:\n    def countAndSay(self, n: int) -> str:\n        s = '1'\n        for _ in range(n - 1):\n            s = re.sub(r'(.)\\1*', lambda m: str(len(m.group(0))) + m.group(1), s)\n        return s"
  },
  {
    "path": "0038-count-and-say/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/count-and-say/\">38. Count and Say</a></h2><h3>Medium</h3><hr><div><p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p>\n\n<ul>\n\t<li><code>countAndSay(1) = \"1\"</code></li>\n\t<li><code>countAndSay(n)</code> is the way you would \"say\" the digit string from <code>countAndSay(n-1)</code>, which is then converted into a different digit string.</li>\n</ul>\n\n<p>To determine how you \"say\" a digit string, split it into the <strong>minimal</strong> number of substrings such that each substring contains exactly <strong>one</strong> unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.</p>\n\n<p>For example, the saying and conversion for digit string <code>\"3322251\"</code>:</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/23/countandsay.jpg\" style=\"width: 581px; height: 172px;\">\n<p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> term of the <strong>count-and-say</strong> sequence</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> \"1\"\n<strong>Explanation:</strong> This is the base case.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 4\n<strong>Output:</strong> \"1211\"\n<strong>Explanation:</strong>\ncountAndSay(1) = \"1\"\ncountAndSay(2) = say \"1\" = one 1 = \"11\"\ncountAndSay(3) = say \"11\" = two 1's = \"21\"\ncountAndSay(4) = say \"21\" = one 2 + one 1 = \"12\" + \"11\" = \"1211\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 30</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0049-group-anagrams/0049-group-anagrams.java",
    "content": "class Solution {\n    public List<List<String>> groupAnagrams(String[] strs) {\n        Set<Map<Character,Integer>> set=new HashSet<>();\n        Map<Map<Character,Integer>,Integer>map=new HashMap<>();\n        List<List<String>> ans=new ArrayList<>();\n        for(String s:strs){\n            Map<Character,Integer> curr=new HashMap<>();\n            for(char c:s.toCharArray()){\n                curr.put(c,curr.getOrDefault(c,0)+1);\n            }\n            if(set.contains(curr)){\n                int idx=map.get(curr);\n                ans.get(idx).add(s);\n            }else{\n                set.add(curr);\n                ans.add(new ArrayList<>());\n                ans.get(ans.size()-1).add(s);\n                map.put(curr,ans.size()-1);\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "0049-group-anagrams/0049-group-anagrams.py",
    "content": "from collections import defaultdict\n\nclass Solution:\n    def groupAnagrams(self, strs):\n        letters_to_words = defaultdict(list)\n        for word in strs:\n            letters_to_words[tuple(sorted(word))].append(word)\n        return list(letters_to_words.values())"
  },
  {
    "path": "0049-group-anagrams/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/group-anagrams/\">49. Group Anagrams</a></h2><h3>Medium</h3><hr><div><p>Given an array of strings <code>strs</code>, group <strong>the anagrams</strong> together. You can return the answer in <strong>any order</strong>.</p>\n\n<p>An <strong>Anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\n<strong>Output:</strong> [[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> strs = [\"\"]\n<strong>Output:</strong> [[\"\"]]\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> strs = [\"a\"]\n<strong>Output:</strong> [[\"a\"]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= strs[i].length &lt;= 100</code></li>\n\t<li><code>strs[i]</code> consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "0055-jump-game/0055-jump-game.java",
    "content": "class Solution {\n    public boolean canJump(int[] nums) {\n        int maxReachableDistance=nums[0];\n        int i=1;\n        while(maxReachableDistance>=i && i<nums.length){\n            maxReachableDistance=Math.max(maxReachableDistance,nums[i]+i);\n            i++;\n        }\n        return maxReachableDistance>=nums.length-1;\n        \n    }\n}"
  },
  {
    "path": "0055-jump-game/0055-jump-game.py",
    "content": "class Solution:\n    def canJump(self, nums: List[int]) -> bool:\n        if len(nums) <= 1:\n            return True\n        j = len(nums) - 2\n        i = len(nums) - 1    \n        while j > -1:\n            if j + nums[j] >= i:\n                i = j\n                j -= 1\n                \n            else:\n                j -= 1\n        #print('i', i, 'j', j)\n        if i <= 0:\n            return True\n        else:\n            return False"
  },
  {
    "path": "0055-jump-game/NOTES.md",
    "content": "​"
  },
  {
    "path": "0055-jump-game/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/jump-game/\">55. Jump Game</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>nums</code>. You are initially positioned at the array's <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p>\n\n<p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,3,1,1,4]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [3,2,1,0,4]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0057-insert-interval/0057-insert-interval.java",
    "content": "class Solution {\n    public int[][] insert(int[][] intervals, int[] newInterval) {\n        List<int[]> inter = new ArrayList<>(intervals.length);\n\n        for(int[] curr : intervals){\n            if(curr[0] > newInterval[1]){\n                inter.add(newInterval);\n                newInterval = curr;\n            }\n            else if(curr[1] < newInterval[0]){\n                inter.add(curr);\n            }\n            else{\n                int st = Math.min(curr[0],newInterval[0]);\n                int end = Math.max(curr[1],newInterval[1]);\n                newInterval[0] = st;\n                newInterval[1] = end;\n            }\n        }\n        inter.add(newInterval);\n\n        int[][] retu = new int[inter.size()][];\n        for(int i=0;i<inter.size();i++){\n            retu[i] = inter.get(i);\n        }\n        return retu;\n    }\n}"
  },
  {
    "path": "0057-insert-interval/0057-insert-interval.py",
    "content": "class Solution:\n    def insert(self, intervals, newInterval):\n        res = []\n        i = 0\n        n = len(intervals)\n        while i < n and intervals[i][1] < newInterval[0]:\n            res.append(intervals[i])\n            i += 1\n        while i < n and intervals[i][0] <= newInterval[1]:\n            newInterval[0] = min(intervals[i][0], newInterval[0])\n            newInterval[1] = max(intervals[i][1], newInterval[1])\n            i += 1\n        res.append(newInterval)\n        while i < n:\n            res.append(intervals[i])\n            i += 1\n        return res"
  },
  {
    "path": "0057-insert-interval/NOTES.md",
    "content": "​"
  },
  {
    "path": "0057-insert-interval/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/insert-interval/\">57. Insert Interval</a></h2><h3>Medium</h3><hr><div><p>You are given an array of non-overlapping intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represent the start and the end of the <code>i<sup>th</sup></code> interval and <code>intervals</code> is sorted in ascending order by <code>start<sub>i</sub></code>. You are also given an interval <code>newInterval = [start, end]</code> that represents the start and end of another interval.</p>\n\n<p>Insert <code>newInterval</code> into <code>intervals</code> such that <code>intervals</code> is still sorted in ascending order by <code>start<sub>i</sub></code> and <code>intervals</code> still does not have any overlapping intervals (merge overlapping intervals if necessary).</p>\n\n<p>Return <code>intervals</code><em> after the insertion</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]\n<strong>Output:</strong> [[1,5],[6,9]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\n<strong>Output:</strong> [[1,2],[3,10],[12,16]]\n<strong>Explanation:</strong> Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>intervals[i].length == 2</code></li>\n\t<li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n\t<li><code>intervals</code> is sorted by <code>start<sub>i</sub></code> in <strong>ascending</strong> order.</li>\n\t<li><code>newInterval.length == 2</code></li>\n\t<li><code>0 &lt;= start &lt;= end &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0070-climbing-stairs/0070-climbing-stairs.java",
    "content": "class Solution {\n    public int climbStairs(int n) {\n        if (n < 3) return n;\n        int oneStep = 1, twoStep = 2;\n        for (int i = 3; i <= n; i++) {\n            int count = oneStep + twoStep;\n            oneStep = twoStep;\n            twoStep = count;\n        }\n        return twoStep;\n    }\n}"
  },
  {
    "path": "0070-climbing-stairs/NOTES.md",
    "content": "​"
  },
  {
    "path": "0070-climbing-stairs/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/climbing-stairs/\">70. Climbing Stairs</a></h2><h3>Easy</h3><hr><div><p>You are climbing a staircase. It takes <code>n</code> steps to reach the top.</p>\n\n<p>Each time you can either climb <code>1</code> or <code>2</code> steps. In how many distinct ways can you climb to the top?</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 2\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 3\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 45</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0076-minimum-window-substring/0076-minimum-window-substring.java",
    "content": "class Solution {\n    public String minWindow(String s, String t) {\n        int[] cs = new int[256];\n        for (char ch : t.toCharArray()) {\n            cs[ch]++;\n        }\n        int l = 0, r = 0, cnt = t.length();\n        int start = -1, end = s.length(); // substring [start, end)\n        while (r < s.length()) {\n            if (cs[s.charAt(r++)]-- > 0) {\n                cnt--;\n            }\n            while (cnt == 0) {\n                if (cs[s.charAt(l++)]++ == 0) {\n                    cnt++;\n                }\n                if (r - l + 1 < end - start) {\n                    start = l - 1;\n                    end = r;\n                }\n            }\n        }\n        return end - start > s.length() ? \"\" : s.substring(start, end);\n    }\n}"
  },
  {
    "path": "0076-minimum-window-substring/NOTES.md",
    "content": "​"
  },
  {
    "path": "0076-minimum-window-substring/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-window-substring/\">76. Minimum Window Substring</a></h2><h3>Hard</h3><hr><div><p>Given two strings <code>s</code> and <code>t</code> of lengths <code>m</code> and <code>n</code> respectively, return <em>the <strong>minimum window substring</strong> of </em><code>s</code><em> such that every character in </em><code>t</code><em> (<strong>including duplicates</strong>) is included in the window. If there is no such substring</em><em>, return the empty string </em><code>\"\"</code><em>.</em></p>\n\n<p>The testcases will be generated such that the answer is <strong>unique</strong>.</p>\n\n<p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"ADOBECODEBANC\", t = \"ABC\"\n<strong>Output:</strong> \"BANC\"\n<strong>Explanation:</strong> The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"a\", t = \"a\"\n<strong>Output:</strong> \"a\"\n<strong>Explanation:</strong> The entire string s is the minimum window.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"a\", t = \"aa\"\n<strong>Output:</strong> \"\"\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == s.length</code></li>\n\t<li><code>n == t.length</code></li>\n\t<li><code>1 &lt;= m, n&nbsp;&lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> and <code>t</code> consist of uppercase and lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you find an algorithm that runs in <code>O(m + n)</code> time?</p>\n</div>"
  },
  {
    "path": "0079-word-search/0079-word-search.java",
    "content": "class Solution {\n    int[][] dirs = new int[][] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n    \n    public boolean exist(char[][] board, String word) {\n        int[] alphFreqForBoard = new int[26]; \n        int[] alphFreqForWord = new int[26]; \n        \n        for (char cc : word.toCharArray()) {\n            alphFreqForWord[cc - 'A']++; \n        }\n        \n        for (char[] row : board) {\n            for (char c : row) {\n                alphFreqForBoard[c - 'A']++; \n            }\n        }\n        \n        for (char cc : word.toCharArray()) {\n            if (alphFreqForBoard[cc - 'A'] < alphFreqForWord[cc - 'A']) {\n                return false; \n            }\n        }\n        \n        if (alphFreqForBoard[word.charAt(0) - 'A'] > alphFreqForWord[word.charAt(word.length() - 1) - 'A']) {\n            word = new StringBuilder(word).reverse().toString();\n        }\n        \n        for(int i = 0; i < board.length; i++) {\n            for(int j = 0; j < board[i].length; j++) {\n                if(dfs(board, word, i, j, 0)) {\n                    return true;\n                }\n            }\n        }\n        \n        return false;\n    }\n    \n    private boolean dfs(char[][] board, String word, int i, int j, int ci) {\n        if(ci == word.length()) {\n            return true;\n        }\n        \n        if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) {\n            return false;\n        }\n        \n        char c = board[i][j];\n        \n        if(c != word.charAt(ci) || c == '#') {\n            return false;\n        }\n        \n        board[i][j] = '#';\n        \n        for(int[] dir : dirs) {\n            if(dfs(board, word, i + dir[0], j + dir[1], ci + 1)) {\n                board[i][j] = c; // Restore the original character\n                return true;\n            }\n        }\n        \n        board[i][j] = c; // Restore the original character\n        \n        return false;\n    }\n}\n"
  },
  {
    "path": "0079-word-search/NOTES.md",
    "content": "​"
  },
  {
    "path": "0079-word-search/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/word-search/\">79. Word Search</a></h2><h3>Medium</h3><hr><div><p>Given an <code>m x n</code> grid of characters <code>board</code> and a string <code>word</code>, return <code>true</code> <em>if</em> <code>word</code> <em>exists in the grid</em>.</p>\n\n<p>The 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.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/word2.jpg\" style=\"width: 322px; height: 242px;\">\n<pre><strong>Input:</strong> board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg\" style=\"width: 322px; height: 242px;\">\n<pre><strong>Input:</strong> board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/15/word3.jpg\" style=\"width: 322px; height: 242px;\">\n<pre><strong>Input:</strong> board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n = board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 6</code></li>\n\t<li><code>1 &lt;= word.length &lt;= 15</code></li>\n\t<li><code>board</code> and <code>word</code> consists of only lowercase and uppercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you use search pruning to make your solution faster with a larger <code>board</code>?</p>\n</div>"
  },
  {
    "path": "0093-restore-ip-addresses/0093-restore-ip-addresses.java",
    "content": "class Solution {\n    private boolean valid(String s, int start, int length) {\n        return length == 1 || \n            (s.charAt(start) != '0' && \n             (length < 3 || \n              s.substring(start, start + length).compareTo(\"255\") <= 0));\n    }\n    \n    private void helper(String s, int startIndex, List<Integer> dots, List<String> ans) {\n        final int remainingLength = s.length() - startIndex;\n        final int remainingNumberOfIntegers = 4 - dots.size();\n        if (remainingLength > remainingNumberOfIntegers * 3 || \n            remainingLength < remainingNumberOfIntegers) {\n            return;\n        }\n        if (dots.size() == 3) {\n            if (valid(s, startIndex, remainingLength)) {\n                StringBuilder sb = new StringBuilder();\n                int last = 0;\n                for (Integer dot : dots) {\n                    sb.append(s.substring(last, last + dot));\n                    last += dot;\n                    sb.append('.');\n                }\n                sb.append(s.substring(startIndex));\n                ans.add(sb.toString());\n            }\n            return;\n        }\n        for (int curPos = 1; curPos <= 3 && curPos <= remainingLength; ++curPos) {\n            // Append a dot at the current position.\n            dots.add(curPos);\n            // Try making all combinations with the remaining string.\n            if (valid(s, startIndex, curPos)) {\n                helper(s, startIndex + curPos, dots, ans);\n            }\n            // Backtrack, i.e. remove the dot to try placing it at the next position.\n            dots.remove(dots.size() - 1);\n        }\n    }\n    \n    public List<String> restoreIpAddresses(String s) {\n        List<String> ans = new ArrayList<>();\n        helper(s, 0, new ArrayList<>(), ans);\n        return ans;   \n    }\n}"
  },
  {
    "path": "0093-restore-ip-addresses/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/restore-ip-addresses/\">93. Restore IP Addresses</a></h2><h3>Medium</h3><hr><div><p>A <strong>valid IP address</strong> consists of exactly four integers separated by single dots. Each integer is between <code>0</code> and <code>255</code> (<strong>inclusive</strong>) and cannot have leading zeros.</p>\n\n<ul>\n\t<li>For example, <code>\"0.1.2.201\"</code> and <code>\"192.168.1.1\"</code> are <strong>valid</strong> IP addresses, but <code>\"0.011.255.245\"</code>, <code>\"192.168.1.312\"</code> and <code>\"192.168@1.1\"</code> are <strong>invalid</strong> IP addresses.</li>\n</ul>\n\n<p>Given a string <code>s</code> containing only digits, return <em>all possible valid IP addresses that can be formed by inserting dots into </em><code>s</code>. You are <strong>not</strong> allowed to reorder or remove any digits in <code>s</code>. You may return the valid IP addresses in <strong>any</strong> order.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"25525511135\"\n<strong>Output:</strong> [\"255.255.11.135\",\"255.255.111.35\"]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"0000\"\n<strong>Output:</strong> [\"0.0.0.0\"]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"101023\"\n<strong>Output:</strong> [\"1.0.10.23\",\"1.0.102.3\",\"10.1.0.23\",\"10.10.2.3\",\"101.0.2.3\"]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 20</code></li>\n\t<li><code>s</code> consists of digits only.</li>\n</ul>\n</div>"
  },
  {
    "path": "0100-same-tree/0100-same-tree.java",
    "content": "class Solution {\n    public boolean isSameTree(TreeNode p, TreeNode q) {\n        // return recursive traversal of tree\n        return inOrderTraversal(q,p);\n        \n    }\n    \n    public boolean inOrderTraversal(TreeNode node1, TreeNode node2) {\n        // initialize boolean result as true\n        boolean result = true;\n        \n        // if one of the nodes is null and the other isn't, result is false\n        if( (node1 == null && node2 != null) || (node2 == null && node1 != null) ) {\n            result = false;\n        }\n        // else determine if node1 isn't null (if so, assumes both nodes aren't null)\n        else if( node1 != null ) {\n            // determine if node1 shares don't value with node2\n            if( node1.val != node2.val ) {\n                // if so, result is false\n                result = false;\n            }\n            // else (assume node1 and node2 share value)\n            else {\n                // recursively call on left nodes\n                result = inOrderTraversal(node1.left, node2.left);\n                \n                // if result is true for recursive call\n                if( result == true ) {\n                    // recursively call on right nodes\n                    result = inOrderTraversal(node1.right, node2.right);\n                }\n            }\n        }\n        // return result\n        return result;\n    }\n}"
  },
  {
    "path": "0100-same-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "0100-same-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/same-tree/\">100. Same Tree</a></h2><h3>Easy</h3><hr><div><p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p>\n\n<p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg\" style=\"width: 622px; height: 182px;\">\n<pre><strong>Input:</strong> p = [1,2,3], q = [1,2,3]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg\" style=\"width: 382px; height: 182px;\">\n<pre><strong>Input:</strong> p = [1,2], q = [1,null,2]\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg\" style=\"width: 622px; height: 182px;\">\n<pre><strong>Input:</strong> p = [1,2,1], q = [1,1,2]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.java",
    "content": "\nclass Solution {\n    public int maxPathSum(TreeNode root) {\n        maxSum = Integer.MIN_VALUE;\n        gainFromSubtree(root);\n        return maxSum;\n    }\n\n    private int maxSum;\n\n    // post order traversal of subtree rooted at `root`\n    private int gainFromSubtree(TreeNode root) {\n        if (root == null) {\n            return 0;\n        }\n\n        // add the path sum from left subtree. Note that if the path\n        // sum is negative, we can ignore it, or count it as 0.\n        // This is the reason we use `Math.max` here.\n        int gainFromLeft = Math.max(gainFromSubtree(root.left), 0);\n\n        // add the path sum from right subtree. 0 if negative\n        int gainFromRight = Math.max(gainFromSubtree(root.right), 0);\n\n        // if left or right path sum are negative, they are counted\n        // as 0, so this statement takes care of all four scenarios\n        maxSum = Math.max(maxSum, gainFromLeft + gainFromRight + root.val);\n\n        // return the max sum for a path starting at the root of subtree\n        return Math.max(gainFromLeft + root.val, gainFromRight + root.val);\n    }\n}\n"
  },
  {
    "path": "0124-binary-tree-maximum-path-sum/NOTES.md",
    "content": "​"
  },
  {
    "path": "0124-binary-tree-maximum-path-sum/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-tree-maximum-path-sum/\">124. Binary Tree Maximum Path Sum</a></h2><h3>Hard</h3><hr><div><p>A <strong>path</strong> 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 <strong>at most once</strong>. Note that the path does not need to pass through the root.</p>\n\n<p>The <strong>path sum</strong> of a path is the sum of the node's values in the path.</p>\n\n<p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg\" style=\"width: 322px; height: 182px;\">\n<pre><strong>Input:</strong> root = [1,2,3]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg\">\n<pre><strong>Input:</strong> root = [-10,9,20,null,null,15,7]\n<strong>Output:</strong> 42\n<strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0125-valid-palindrome/0125-valid-palindrome.java",
    "content": "class Solution {\n    public boolean isPalindrome(String s) {\n        int i=0;\n        int j= s.length()-1;\n        while(i<j){\n            char a=s.charAt(i);\n            char b=s.charAt(j);\n            if(!Character.isLetterOrDigit(a)){\n                i++;\n            }else if(!Character.isLetterOrDigit(b)){\n                j--;\n            }else{\n                if(Character.isUpperCase(a)){\n                    a=Character.toLowerCase(a);\n                }\n                if(Character.isUpperCase(b)){\n                    b=Character.toLowerCase(b);\n                }\n                if(a==b){\n                    i++;\n                    j--;\n                }else{\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "0125-valid-palindrome/NOTES.md",
    "content": "​"
  },
  {
    "path": "0125-valid-palindrome/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/valid-palindrome/\">125. Valid Palindrome</a></h2><h3>Easy</h3><hr><div><p>A phrase is a <strong>palindrome</strong> 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.</p>\n\n<p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"A man, a plan, a canal: Panama\"\n<strong>Output:</strong> true\n<strong>Explanation:</strong> \"amanaplanacanalpanama\" is a palindrome.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"race a car\"\n<strong>Output:</strong> false\n<strong>Explanation:</strong> \"raceacar\" is not a palindrome.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \" \"\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists only of printable ASCII characters.</li>\n</ul>\n</div>"
  },
  {
    "path": "0131-palindrome-partitioning/0131-palindrome-partitioning.java",
    "content": "class Solution {\n     public List<List<String>> partition(String s) {\n        List<List<String>> Al1 = new ArrayList<>();\n        List<String> Al2 = new ArrayList<>();\n        String[][] dp = new String[s.length()][s.length()]; \n        palPart(Al1,Al2,s,0,dp);\n        return Al1;\n    }\n    \n    public void palPart(List<List<String>> Al1, List<String> Al2,String s, int start,String[][] dp){\n        if (start == s.length())\n            Al1.add(new ArrayList<>(Al2));\n        \n        for (int i=start;i<s.length();i++)\n        {\n            if (dp[start][i] != null){\n                Al2.add(dp[start][i]); \n                palPart(Al1,Al2,s,i+1,dp);\n                dp[start][i] = Al2.remove(Al2.size()-1);\n            }else if (isPalindrome(start,i,s)){\n                Al2.add(s.substring(start,i+1)); \n                palPart(Al1,Al2,s,i+1,dp);\n                dp[start][i] = Al2.remove(Al2.size()-1);\n            }\n        }\n        \n    }\n    \n    public boolean isPalindrome(int start, int i, String s)\n    {\n        while (start < i)\n        {\n            if (s.charAt(start++) != s.charAt(i--)) return false;\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "0131-palindrome-partitioning/NOTES.md",
    "content": "​"
  },
  {
    "path": "0131-palindrome-partitioning/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/palindrome-partitioning/\">131. Palindrome Partitioning</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword=\"substring-nonempty\">substring</span> of the partition is a <span data-keyword=\"palindrome-string\"><strong>palindrome</strong></span>. Return <em>all possible palindrome partitioning of </em><code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"aab\"\n<strong>Output:</strong> [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"a\"\n<strong>Output:</strong> [[\"a\"]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 16</code></li>\n\t<li><code>s</code> contains only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "0134-gas-station/0134-gas-station.java",
    "content": "class Solution {\n    public int canCompleteCircuit(int[] gas, int[] cost) {\n        int sum = 0, n = gas.length;\n        int gasInTank = 0, start = 0;\n        for(int i=0;i<n;i++) {\n            gasInTank += gas[i]-cost[i];\n            sum += gas[i]-cost[i];\n            // if we are not able to reach next station from i, \n            if(gasInTank < 0) {\n                start = i+1;\n                gasInTank = 0;\n            }\n        }\n        \n        return sum >= 0 ? start : -1;\n    }\n}"
  },
  {
    "path": "0134-gas-station/NOTES.md",
    "content": "​"
  },
  {
    "path": "0134-gas-station/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/gas-station/\">134. Gas Station</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> gas stations along a circular route, where the amount of gas at the <code>i<sup>th</sup></code> station is <code>gas[i]</code>.</p>\n\n<p>You have a car with an unlimited gas tank and it costs <code>cost[i]</code> of gas to travel from the <code>i<sup>th</sup></code> station to its next <code>(i + 1)<sup>th</sup></code> station. You begin the journey with an empty tank at one of the gas stations.</p>\n\n<p>Given two integer arrays <code>gas</code> and <code>cost</code>, return <em>the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return</em> <code>-1</code>. If there exists a solution, it is <strong>guaranteed</strong> to be <strong>unique</strong></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> gas = [2,3,4], cost = [3,4,3]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == gas.length == cost.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= gas[i], cost[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0144-binary-tree-preorder-traversal/0144-binary-tree-preorder-traversal.java",
    "content": "/**\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<Integer> preorderTraversal(TreeNode root) {\n        List<Integer> list = new ArrayList<>();\n        preOrder(root,list);\n        return list;\n    }\n    void preOrder(TreeNode root, List<Integer> list){\n        if(root==null)return;\n        list.add(root.val);\n        preOrder(root.left,list);\n        preOrder(root.right,list);\n    }\n}"
  },
  {
    "path": "0144-binary-tree-preorder-traversal/NOTES.md",
    "content": "​"
  },
  {
    "path": "0144-binary-tree-preorder-traversal/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-tree-preorder-traversal/\">144. Binary Tree Preorder Traversal</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the preorder traversal of its nodes' values</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg\" style=\"width: 125px; height: 200px;\">\n<pre><strong>Input:</strong> root = [1,null,2,3]\n<strong>Output:</strong> [1,2,3]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [1]\n<strong>Output:</strong> [1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>\n</div>"
  },
  {
    "path": "0149-max-points-on-a-line/0149-max-points-on-a-line.java",
    "content": "class Solution {\n    public int maxPoints(int[][] points) {\n        int n = points.length;\n        if (n == 1) {\n            return 1;\n        }\n        int result = 2;\n        for (int i = 0; i < n; i++) {\n            Map<Double, Integer> cnt = new HashMap<>();\n            for (int j = 0; j < n; j++) {\n                if (j != i) {\n                    cnt.merge(Math.atan2(points[j][1] - points[i][1],\n                    \tpoints[j][0] - points[i][0]), 1, Integer::sum);\n                }\n            }\n            result = Math.max(result, Collections.max(cnt.values()) + 1);\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "0149-max-points-on-a-line/NOTES.md",
    "content": "​"
  },
  {
    "path": "0149-max-points-on-a-line/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/max-points-on-a-line/\">149. Max Points on a Line</a></h2><h3>Hard</h3><hr><div><p>Given an array of <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents a point on the <strong>X-Y</strong> plane, return <em>the maximum number of points that lie on the same straight line</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg\" style=\"width: 300px; height: 294px;\">\n<pre><strong>Input:</strong> points = [[1,1],[2,2],[3,3]]\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg\" style=\"width: 300px; height: 294px;\">\n<pre><strong>Input:</strong> points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= points.length &lt;= 300</code></li>\n\t<li><code>points[i].length == 2</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n\t<li>All the <code>points</code> are <strong>unique</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0150-evaluate-reverse-polish-notation/0150-evaluate-reverse-polish-notation.java",
    "content": "class Solution {\n    public int evalRPN(String[] tokens) {\n                  int[] nxtPos = new int[1];\n\n          return eval(tokens, tokens.length - 1, nxtPos);\n    }\n\n    private int eval(String[] tokens, int pos, int[] nxtPos) {\n\n        char ac = tokens[pos].charAt(0);\n\n        if (tokens[pos].length() == 1 && (ac == '+' || ac == '-' || ac == '*' || ac == '/')) {\n\n            // get operands\n            int a = eval(tokens, pos - 1, nxtPos);\n            int b = eval(tokens, nxtPos[0], nxtPos);\n\n            // perform operation\n            if (ac == '+') {\n                \n                return b + a;\n            } else if (ac == '-') {\n\n                return b - a;\n            } else if (ac == '*') {\n\n                return b * a;\n            } else {\n\n                return b / a;\n            }\n        } else {\n\n            nxtPos[0] = pos - 1;\n            return Integer.parseInt(tokens[pos]);\n        }\n    }\n}"
  },
  {
    "path": "0150-evaluate-reverse-polish-notation/NOTES.md",
    "content": "​"
  },
  {
    "path": "0150-evaluate-reverse-polish-notation/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/evaluate-reverse-polish-notation/\">150. Evaluate Reverse Polish Notation</a></h2><h3>Medium</h3><hr><div><p>Evaluate the value of an arithmetic expression in <a href=\"http://en.wikipedia.org/wiki/Reverse_Polish_notation\" target=\"_blank\">Reverse Polish Notation</a>.</p>\n\n<p>Valid operators are <code>+</code>, <code>-</code>, <code>*</code>, and <code>/</code>. Each operand may be an integer or another expression.</p>\n\n<p><strong>Note</strong> that division between two integers should truncate toward zero.</p>\n\n<p>It 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.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]\n<strong>Output:</strong> 9\n<strong>Explanation:</strong> ((2 + 1) * 3) = 9\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> (4 + (13 / 5)) = 6\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]\n<strong>Output:</strong> 22\n<strong>Explanation:</strong> ((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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= tokens.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>tokens[i]</code> is either an operator: <code>\"+\"</code>, <code>\"-\"</code>, <code>\"*\"</code>, or <code>\"/\"</code>, or an integer in the range <code>[-200, 200]</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0151-reverse-words-in-a-string/0151-reverse-words-in-a-string.java",
    "content": "class Solution {\n    public String reverseWords(String s) {\n        List<StringBuilder> arr=new ArrayList<>();\n        StringBuilder sb=new StringBuilder();\n        boolean word=false;\n        for(int i=0;i<s.length();i++){\n            char ch=s.charAt(i);\n            if(Character.isLetterOrDigit(ch)){\n                sb.append(ch);\n                word=true;\n            }else{\n                if(word){\n                    word=false;   \n                    arr.add(sb);\n                    sb=new StringBuilder();\n                }\n            }\n        }\n        if(sb.length()>0)arr.add(sb);\n        sb=new StringBuilder();\n        for(int i=arr.size()-1;i>=0;i--){\n            sb.append(arr.get(i));\n            if(i!=0){\n                sb.append(\" \");\n            }\n        }\n        return sb.toString();\n    }\n}"
  },
  {
    "path": "0151-reverse-words-in-a-string/NOTES.md",
    "content": "​"
  },
  {
    "path": "0151-reverse-words-in-a-string/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/reverse-words-in-a-string/\">151. Reverse Words in a String</a></h2><h3>Medium</h3><hr><div><p>Given an input string <code>s</code>, reverse the order of the <strong>words</strong>.</p>\n\n<p>A <strong>word</strong> is defined as a sequence of non-space characters. The <strong>words</strong> in <code>s</code> will be separated by at least one space.</p>\n\n<p>Return <em>a string of the words in reverse order concatenated by a single space.</em></p>\n\n<p><b>Note</b> that <code>s</code> 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.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"the sky is blue\"\n<strong>Output:</strong> \"blue is sky the\"\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"  hello world  \"\n<strong>Output:</strong> \"world hello\"\n<strong>Explanation:</strong> Your reversed string should not contain leading or trailing spaces.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"a good   example\"\n<strong>Output:</strong> \"example good a\"\n<strong>Explanation:</strong> You need to reduce multiple spaces between two words to a single space in the reversed string.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> contains English letters (upper-case and lower-case), digits, and spaces <code>' '</code>.</li>\n\t<li>There is <strong>at least one</strong> word in <code>s</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><b data-stringify-type=\"bold\">Follow-up:&nbsp;</b>If the string data type is mutable in your language, can&nbsp;you solve it&nbsp;<b data-stringify-type=\"bold\">in-place</b>&nbsp;with&nbsp;<code data-stringify-type=\"code\">O(1)</code>&nbsp;extra space?</p>\n</div>"
  },
  {
    "path": "0198-house-robber/0198-house-robber.java",
    "content": "class Solution {\n    public int rob(int[] nums) {\n        \n        int n = nums.length;\n        \n        if(n == 1) return nums[0];\n        \n        int dp2=nums[0], dp1=Math.max(nums[0],nums[1]),dp=dp1;\n        \n        for(int i = 2; i < n; i++){\n            dp = Math.max(dp1, dp2 + nums[i]);\n            dp2 = dp1;\n            dp1 = dp;\n        }\n        return dp;\n\n    }\n}"
  },
  {
    "path": "0198-house-robber/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/house-robber/\">198. House Robber</a></h2><h3>Medium</h3><hr><div><p>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 <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p>\n\n<p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,1]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,7,9,3,1]\n<strong>Output:</strong> 12\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 400</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0212-word-search-ii/0212-word-search-ii.java",
    "content": "class Solution {\n    private static final char HASH_TAG = '#';\n    private Tree root = new Tree();\n    \n    public List<String> findWords(char[][] board, String[] words) {\n        for (String word : words) {\n            Tree temp = root;\n            // Test case 60/63 \n            for (int i = word.length() - 1; i >= 0; i--) {\n                int idx = word.charAt(i) - 'a';\n                if (temp.val[idx] == null) {\n                    temp.val[idx] = new Tree();\n                    temp.val[idx].parent = temp;\n                    temp.val[idx].idx = idx;\n                }\n                temp = temp.val[idx];\n            }\n            temp.word = word;\n        }    \n        return searchWord(board);\n    }\n    \n    private List<String> searchWord(char[][] board) {\n        List<String> res = new ArrayList<>();\n        \n        for (int i = 0; i < board.length; i++)\n            for (int j = 0; j < board[0].length; j++) {\n                Tree temp = root;\n                checkWord(res, i, j, board, temp);\n            }\n        \n        return res;\n    }\n    \n    private void checkWord(List<String> res, int y, int x, char[][] board, Tree temp) {\n        \n        if (x >= board[0].length || x < 0\n            || y >= board.length || y < 0)\n            return;\n        \n        char ch = board[y][x];\n        if (ch== HASH_TAG || temp.val[ch - 'a'] == null)\n            return;\n        \n        temp = temp.val[ch - 'a'];\n        \n        if (temp.word != null) {\n            res.add(temp.word);\n            temp.word = null; // Test case 17/63: When there is more than one answer\n            Tree ptr = temp;\n            while (ptr.parent != null \n                    && ptr.isEmpty()) {\n                int idx = ptr.idx;\n                ptr = ptr.parent;\n                ptr.val[idx] = null;\n            }\n        }\n        \n        board[y][x] = HASH_TAG;\n\n        checkWord(res, y, x + 1, board, temp);\n        checkWord(res, y, x - 1, board, temp);\n        checkWord(res, y + 1, x, board, temp);\n        checkWord(res, y - 1, x, board, temp);\n        \n        board[y][x] = ch;\n    }\n    \n    class Tree {\n        Tree parent;\n        Tree[] val = new Tree[26];\n        String word;\n        int idx;\n\n        public boolean isEmpty() {\n            for (int i = 0; i < 26; i++) \n                if (val[i] != null)\n                    return false;\n\n            return true;\n        }\n    }\n}"
  },
  {
    "path": "0212-word-search-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "0212-word-search-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/word-search-ii/\">212. Word Search II</a></h2><h3>Hard</h3><hr><div><p>Given an <code>m x n</code> <code>board</code>&nbsp;of characters and a list of strings <code>words</code>, return <em>all words on the board</em>.</p>\n\n<p>Each word must be constructed from letters of sequentially adjacent cells, where <strong>adjacent cells</strong> are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/07/search1.jpg\" style=\"width: 322px; height: 322px;\">\n<pre><strong>Input:</strong> board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]\n<strong>Output:</strong> [\"eat\",\"oath\"]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/07/search2.jpg\" style=\"width: 162px; height: 162px;\">\n<pre><strong>Input:</strong> board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 12</code></li>\n\t<li><code>board[i][j]</code> is a lowercase English letter.</li>\n\t<li><code>1 &lt;= words.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 10</code></li>\n\t<li><code>words[i]</code> consists of lowercase English letters.</li>\n\t<li>All the strings of <code>words</code> are unique.</li>\n</ul>\n</div>"
  },
  {
    "path": "0219-contains-duplicate-ii/0219-contains-duplicate-ii.java",
    "content": "class Solution {\n    public boolean containsNearbyDuplicate(int[] nums, int k) {\n        Map<Integer, Integer> list = new HashMap();\n        for(int i=0; i<nums.length; i++)\n        {\n            if(list.containsKey(nums[i]))\n            {\n                if(i-list.get(nums[i])<=k)\n                {\n                    return true;\n                }\n            }\n            list.put(nums[i], i);\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "0219-contains-duplicate-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "0219-contains-duplicate-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/contains-duplicate-ii/\">219. Contains Duplicate II</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> if there are two <strong>distinct indices</strong> <code>i</code> and <code>j</code> in the array such that <code>nums[i] == nums[j]</code> and <code>abs(i - j) &lt;= k</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,1], k = 3\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,0,1,1], k = 1\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0222-count-complete-tree-nodes/0222-count-complete-tree-nodes.java",
    "content": "class Solution {\n    public int countNodes(TreeNode root) {\n        if(root ==  null){\n            return 0;\n        }\n        int leftDep=1;\n        TreeNode leftNode = root.left;\n        while(leftNode != null){\n            leftDep++;\n            leftNode = leftNode.left;\n        }\n        int rightDep = 1;\n        TreeNode rightNode = root.right;\n        while(rightNode != null){\n            rightDep++;\n            rightNode = rightNode.right;\n        }\n        if(leftDep == rightDep){\n            return (int)Math.pow(2,leftDep)-1;\n        }\n        return countNodes(root.left)+countNodes(root.right)+1;\n    }\n}"
  },
  {
    "path": "0222-count-complete-tree-nodes/NOTES.md",
    "content": "​"
  },
  {
    "path": "0222-count-complete-tree-nodes/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/count-complete-tree-nodes/\">222. Count Complete Tree Nodes</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a <strong>complete</strong> binary tree, return the number of the nodes in the tree.</p>\n\n<p>According to <strong><a href=\"http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees\" target=\"_blank\">Wikipedia</a></strong>, 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 <code>1</code> and <code>2<sup>h</sup></code> nodes inclusive at the last level <code>h</code>.</p>\n\n<p>Design an algorithm that runs in less than&nbsp;<code data-stringify-type=\"code\">O(n)</code>&nbsp;time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/14/complete.jpg\" style=\"width: 372px; height: 302px;\">\n<pre><strong>Input:</strong> root = [1,2,3,4,5,6]\n<strong>Output:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = []\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [1]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li>The tree is guaranteed to be <strong>complete</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0223-rectangle-area/0223-rectangle-area.java",
    "content": "class Solution {\n    public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n        int areaOfA = (ay2 - ay1) * (ax2 - ax1);\n        int areaOfB = (by2 - by1) * (bx2 - bx1);\n\n        // calculate x overlap\n        int left = Math.max(ax1, bx1);\n        int right = Math.min(ax2, bx2);\n        int xOverlap = right - left;\n\n        // calculate y overlap\n        int top = Math.min(ay2, by2);\n        int bottom = Math.max(ay1, by1);\n        int yOverlap = top - bottom;\n\n        int areaOfOverlap = 0;\n        // if the rectangles overlap each other, then calculate\n        // the area of the overlap\n        if (xOverlap > 0 && yOverlap > 0) {\n            areaOfOverlap = xOverlap * yOverlap;\n        }\n\n        // areaOfOverlap is counted twice when in the summation of\n        // areaOfA and areaOfB, so we need to subtract it from the\n        // total, to get the toal area covered by both the rectangles\n        int totalArea = areaOfA + areaOfB - areaOfOverlap;\n\n        return totalArea;\n    }\n}"
  },
  {
    "path": "0223-rectangle-area/NOTES.md",
    "content": "​"
  },
  {
    "path": "0223-rectangle-area/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/rectangle-area/\">223. Rectangle Area</a></h2><h3>Medium</h3><hr><div><p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p>\n\n<p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p>\n\n<p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"Rectangle Area\" src=\"https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png\" style=\"width: 700px; height: 365px;\">\n<pre><strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\n<strong>Output:</strong> 45\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\n<strong>Output:</strong> 16\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-10<sup>4</sup> &lt;= ax1 &lt;= ax2 &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= ay1 &lt;= ay2 &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= bx1 &lt;= bx2 &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= by1 &lt;= by2 &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0224-basic-calculator/0224-basic-calculator.java",
    "content": "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 calc(s);\n    }\n    \n    private int calc(String s) {\n        int res = 0, num = 0, sign = 1;\n        while (idx < s.length()) {\n            char c = s.charAt(idx++);\n            if (c >= '0' && c <= '9') num = num * 10 + c - '0';\n            else if (c == '(') num = calc(s); // ( is start of a new sub-problem, Let recursion solve the sub-problem\n            else if (c == ')') return res + sign * num;\n            else if (c == '+' || c == '-') { // only when we meet a new sign, we know a while number has been read\n                res += sign * num;\n                num = 0;\n                sign = c == '-' ? -1 : 1;\n            }\n        }\n        return res + sign * num; // last number is not processed yet\n    }\n}"
  },
  {
    "path": "0224-basic-calculator/NOTES.md",
    "content": "​"
  },
  {
    "path": "0224-basic-calculator/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/basic-calculator/\">224. Basic Calculator</a></h2><h3>Hard</h3><hr><div><p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>\n\n<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"1 + 1\"\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \" 2-1 + 2 \"\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"(1+(4+5+2)-3)+(6+8)\"\n<strong>Output:</strong> 23\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>\n\t<li><code>s</code> represents a valid expression.</li>\n\t<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>\"+1\"</code> and <code>\"+(2 + 3)\"</code> is invalid).</li>\n\t<li><code>'-'</code> could be used as a unary operation (i.e., <code>\"-1\"</code> and <code>\"-(2 + 3)\"</code> is valid).</li>\n\t<li>There will be no two consecutive operators in the input.</li>\n\t<li>Every number and running calculation will fit in a signed 32-bit integer.</li>\n</ul>\n</div>"
  },
  {
    "path": "0232-implement-queue-using-stacks/0232-implement-queue-using-stacks.java",
    "content": "class MyQueue {\n    private Stack<Integer> s1 = new Stack<>();\n    private Stack<Integer> s2 = new Stack<>();\n\n    /** Initialize your data structure here. */\n    public MyQueue() {\n        \n    }\n    \n    /** Push element x to the back of queue. */\n    public void push(int x) {\n        s1.push(x);\n    }\n    \n    /** Removes the element from in front of queue and returns that element. */\n    public int pop() {\n        if (s2.isEmpty()) {\n            while (!s1.isEmpty())\n                s2.push(s1.pop());\n        }\n        return s2.pop();\n    }\n    \n    /** Get the front element. */\n    public int peek() {\n        if (s2.isEmpty()) {\n            while (!s1.isEmpty())\n                s2.push(s1.pop());\n        }\n        return s2.peek();\n    }\n    \n    /** Returns whether the queue is empty. */\n    public boolean empty() {\n        return s1.isEmpty() && s2.isEmpty();\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 * boolean param_4 = obj.empty();\n */"
  },
  {
    "path": "0232-implement-queue-using-stacks/NOTES.md",
    "content": "​"
  },
  {
    "path": "0232-implement-queue-using-stacks/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/implement-queue-using-stacks/\">232. Implement Queue using Stacks</a></h2><h3>Easy</h3><hr><div><p>Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (<code>push</code>, <code>peek</code>, <code>pop</code>, and <code>empty</code>).</p>\n\n<p>Implement the <code>MyQueue</code> class:</p>\n\n<ul>\n\t<li><code>void push(int x)</code> Pushes element x to the back of the queue.</li>\n\t<li><code>int pop()</code> Removes the element from the front of the queue and returns it.</li>\n\t<li><code>int peek()</code> Returns the element at the front of the queue.</li>\n\t<li><code>boolean empty()</code> Returns <code>true</code> if the queue is empty, <code>false</code> otherwise.</li>\n</ul>\n\n<p><strong>Notes:</strong></p>\n\n<ul>\n\t<li>You must use <strong>only</strong> standard operations of a stack, which means only <code>push to top</code>, <code>peek/pop from top</code>, <code>size</code>, and <code>is empty</code> operations are valid.</li>\n\t<li>Depending 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.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]\n<strong>Output</strong>\n[null, null, null, 1, 1, false]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= x &lt;= 9</code></li>\n\t<li>At most <code>100</code>&nbsp;calls will be made to <code>push</code>, <code>pop</code>, <code>peek</code>, and <code>empty</code>.</li>\n\t<li>All the calls to <code>pop</code> and <code>peek</code> are valid.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow-up:</strong> Can you implement the queue such that each operation is <strong><a href=\"https://en.wikipedia.org/wiki/Amortized_analysis\" target=\"_blank\">amortized</a></strong> <code>O(1)</code> time complexity? In other words, performing <code>n</code> operations will take overall <code>O(n)</code> time even if one of those operations may take longer.</p>\n</div>"
  },
  {
    "path": "0236-lowest-common-ancestor-of-a-binary-tree/0236-lowest-common-ancestor-of-a-binary-tree.java",
    "content": "class Solution {\n    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n        if (root == null || root == p || root == q) return root;\n        TreeNode left = lowestCommonAncestor(root.left, p, q);\n        TreeNode right = lowestCommonAncestor(root.right, p, q);\n        if (left != null && right != null) return root;\n        return left != null ? left : right;\n    }\n}"
  },
  {
    "path": "0236-lowest-common-ancestor-of-a-binary-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "0236-lowest-common-ancestor-of-a-binary-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/\">236. Lowest Common Ancestor of a Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p>\n\n<p>According to the <a href=\"https://en.wikipedia.org/wiki/Lowest_common_ancestor\" target=\"_blank\">definition of LCA on Wikipedia</a>: “The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <b>a node to be a descendant of itself</b>).”</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarytree.png\" style=\"width: 200px; height: 190px;\">\n<pre><strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarytree.png\" style=\"width: 200px; height: 190px;\">\n<pre><strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [1,2], p = 1, q = 2\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li>\n\t<li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li>\n\t<li>All <code>Node.val</code> are <strong>unique</strong>.</li>\n\t<li><code>p != q</code></li>\n\t<li><code>p</code> and <code>q</code> will exist in the tree.</li>\n</ul>\n</div>"
  },
  {
    "path": "0237-delete-node-in-a-linked-list/0237-delete-node-in-a-linked-list.java",
    "content": "class Solution {\n    public void deleteNode(ListNode node) {\n        // Since we know input node is not last node, so nextNode will not be null\n        ListNode nextNode = node.next;\n        // Step 2\n        node.val = nextNode.val;\n        // Step 3\n        node.next = nextNode.next;\n        nextNode.next = null;\n    }\n}"
  },
  {
    "path": "0237-delete-node-in-a-linked-list/NOTES.md",
    "content": "​"
  },
  {
    "path": "0237-delete-node-in-a-linked-list/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/delete-node-in-a-linked-list/\">237. Delete Node in a Linked List</a></h2><h3>Medium</h3><hr><div><p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p>\n\n<p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p>\n\n<p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p>\n\n<p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p>\n\n<ul>\n\t<li>The value of the given node should not exist in the linked list.</li>\n\t<li>The number of nodes in the linked list should decrease by one.</li>\n\t<li>All the values before <code>node</code> should be in the same order.</li>\n\t<li>All the values after <code>node</code> should be in the same order.</li>\n</ul>\n\n<p><strong>Custom testing:</strong></p>\n\n<ul>\n\t<li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li>\n\t<li>We will build the linked list and pass the node to your function.</li>\n\t<li>The output will be the entire list after calling your function.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/node1.jpg\" style=\"width: 400px; height: 286px;\">\n<pre><strong>Input:</strong> head = [4,5,1,9], node = 5\n<strong>Output:</strong> [4,1,9]\n<strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/node2.jpg\" style=\"width: 400px; height: 315px;\">\n<pre><strong>Input:</strong> head = [4,5,1,9], node = 1\n<strong>Output:</strong> [4,5,9]\n<strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li>The value of each node in the list is <strong>unique</strong>.</li>\n\t<li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li>\n</ul>\n</div>"
  },
  {
    "path": "0242-valid-anagram/0242-valid-anagram.cpp",
    "content": "class Solution {\npublic:\n    bool isAnagram(string s, string t) {\n    sort(s.begin(),s.end());\n    sort(t.begin(),t.end());\n    if(s==t)\n    return true;\n    else\n    return false;\n    }\n};\n"
  },
  {
    "path": "0242-valid-anagram/0242-valid-anagram.java",
    "content": "class Solution {\n    public boolean isAnagram(String a, String b) {\n        int[] arr=new int[128]; //O(1)\n        if(a.length()!=b.length()){\n            return false;\n        }\n        // abca\n        // caba\n        for(int i=0;i<a.length();i++){\n            char ch1=a.charAt(i);\n            char ch2=b.charAt(i);\n            arr[ch1]++;\n            arr[ch2]--;\n        }//O(n)\n        for(int i=0;i<arr.length;i++){\n            if(arr[i]!=0){\n                return false;\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "0242-valid-anagram/NOTES.md",
    "content": "​"
  },
  {
    "path": "0242-valid-anagram/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/valid-anagram/\">242. Valid Anagram</a></h2><h3>Easy</h3><hr><div><p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> <em>if</em> <code>t</code> <em>is an anagram of</em> <code>s</code><em>, and</em> <code>false</code> <em>otherwise</em>.</p>\n\n<p>An <strong>Anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"anagram\", t = \"nagaram\"\n<strong>Output:</strong> true\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"rat\", t = \"car\"\n<strong>Output:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>\n</div>"
  },
  {
    "path": "0263-ugly-number/0263-ugly-number.java",
    "content": "class Solution {\n    public boolean isUgly(int n) {\n        while(n!=0){\n            if(n==1 || n==2 || n==3 || n==5){\n                return true;\n            }\n            if(n%2==0){\n                n/=2;\n            }\n            else if(n%3==0){\n                n/=3;\n            }\n            else if(n%5==0){\n                n/=5;\n            }else{\n                return false;\n            }\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "0263-ugly-number/NOTES.md",
    "content": "​"
  },
  {
    "path": "0263-ugly-number/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/ugly-number/\">263. Ugly Number</a></h2><h3>Easy</h3><hr><div><p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p>\n\n<p>Given an integer <code>n</code>, return <code>true</code> <em>if</em> <code>n</code> <em>is an <strong>ugly number</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 6\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 6 = 2 × 3\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 14\n<strong>Output:</strong> false\n<strong>Explanation:</strong> 14 is not ugly since it includes the prime factor 7.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0279-perfect-squares/0279-perfect-squares.java",
    "content": "class Solution {\n    public int numSquares(int n) {\n\tint sqrt = (int) Math.sqrt(n);\n\n\tif (sqrt * sqrt == n) // Perfect square\n\t\treturn 1;\n\n\twhile (n % 4 == 0) // 4^a (8b + 7)\n\t\tn = n / 4;\n\n\tif (n % 8 == 7)\n\t\treturn 4;\n\n\tfor (int i = 1; i * i <= n; i++) { // Sum of two perfect squares\n\t\tint square = i * i;\n\t\tint base = (int) Math.sqrt(n - square);\n\n\t\tif (base * base == n - square)\n\t\t\treturn 2;\n\t}\n\n\treturn 3;\n}\n}"
  },
  {
    "path": "0279-perfect-squares/NOTES.md",
    "content": "​"
  },
  {
    "path": "0279-perfect-squares/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/perfect-squares/\">279. Perfect Squares</a></h2><h3>Medium</h3><hr><div><p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p>\n\n<p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 12\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 12 = 4 + 4 + 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 13\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 13 = 4 + 9.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0290-word-pattern/0290-word-pattern.java",
    "content": "class Solution {\n    public boolean wordPattern(String pattern, String s) {\n        String[] words = s.split(\" \");\n        Map<Character,String> wordMap = new HashMap<>();\n        Map<String, Character> charMap = new HashMap<>();\n        if(pattern.length()!=words.length){\n            return false;\n        }\n        for(int i= 0;i<pattern.length();i++){\n            if(wordMap.containsKey(pattern.charAt(i)) && words[i].equals(wordMap.get(pattern.charAt(i)))){\n                continue;\n            } else if(!wordMap.containsKey(pattern.charAt(i))){\n                if(wordMap.containsValue(words[i])){\n                    return false;\n                }\n                wordMap.put(pattern.charAt(i), words[i]);\n            } else if(wordMap.containsKey(pattern.charAt(i)) && !words[i].equals(wordMap.get(pattern.charAt(i)))){\n                return false;\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "0290-word-pattern/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/word-pattern/\">290. Word Pattern</a></h2><h3>Easy</h3><hr><div><p>Given a <code>pattern</code> and a string <code>s</code>, find if <code>s</code>&nbsp;follows the same pattern.</p>\n\n<p>Here <b>follow</b> means a full match, such that there is a bijection between a letter in <code>pattern</code> and a <b>non-empty</b> word in <code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> pattern = \"abba\", s = \"dog cat cat dog\"\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> pattern = \"abba\", s = \"dog cat cat fish\"\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> pattern = \"aaaa\", s = \"dog cat cat dog\"\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= pattern.length &lt;= 300</code></li>\n\t<li><code>pattern</code> contains only lower-case English letters.</li>\n\t<li><code>1 &lt;= s.length &lt;= 3000</code></li>\n\t<li><code>s</code> contains only lowercase English letters and spaces <code>' '</code>.</li>\n\t<li><code>s</code> <strong>does not contain</strong> any leading or trailing spaces.</li>\n\t<li>All the words in <code>s</code> are separated by a <strong>single space</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0295-find-median-from-data-stream/0295-find-median-from-data-stream.java",
    "content": "class MedianFinder {\n    \n    ArrayList<Integer> list;\n\n    public MedianFinder() {\n        list = new ArrayList<>();\n    }\n    \n    public void addNum(int num) {\n        int i;\n        if(list.size() > 0){\n            for (i = 0; (i < list.size()  && list.get(i) < num); i++);\n            if(i == -1){\n                i = 0;\n            }\n            list.add(i , num);\n        }else{\n            list.add(num);\n        }\n    }\n    \n    public double findMedian() {\n        // System.out.println(list);\n        int index = list.size()/2;\n        if(list.size() % 2 == 0){\n            return (double) (list.get(index) + list.get(index - 1))/2;\n        }else{\n            return list.get(index);\n        }\n        \n    }\n}"
  },
  {
    "path": "0295-find-median-from-data-stream/NOTES.md",
    "content": "​"
  },
  {
    "path": "0295-find-median-from-data-stream/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-median-from-data-stream/\">295. Find Median from Data Stream</a></h2><h3>Hard</h3><hr><div><p>The <strong>median</strong> 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.</p>\n\n<ul>\n\t<li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li>\n\t<li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li>\n</ul>\n\n<p>Implement the MedianFinder class:</p>\n\n<ul>\n\t<li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li>\n\t<li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li>\n\t<li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n[[], [1], [2], [], [3], []]\n<strong>Output</strong>\n[null, null, null, 1.5, null, 2.0]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li>\n\t<li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li>\n\t<li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li>\n\t<li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li>\n</ul>\n</div>"
  },
  {
    "path": "0309-best-time-to-buy-and-sell-stock-with-cooldown/0309-best-time-to-buy-and-sell-stock-with-cooldown.java",
    "content": "class Solution {\n    public int maxProfit(int[] prices) {\n        if (prices == null || prices.length <= 1) {\n            return 0;\n        }\n        int len = prices.length;\n        int[] hold = new int[len];\n        int[] unHold = new int[len];\n        hold[0] = -prices[0];\n        hold[1] = Math.max(-prices[0], -prices[1]);\n        unHold[0] = 0;\n        unHold[1] = Math.max(0, prices[1] - prices[0]);\n        for (int i = 2; i < len; i++) {\n            hold[i] = Math.max(hold[i - 1], unHold[i - 2] - prices[i]);        \n            unHold[i] = Math.max(unHold[i - 1], hold[i - 1] + prices[i]);\n        }\n        return unHold[len - 1];\n    }\n}"
  },
  {
    "path": "0309-best-time-to-buy-and-sell-stock-with-cooldown/NOTES.md",
    "content": "​"
  },
  {
    "path": "0309-best-time-to-buy-and-sell-stock-with-cooldown/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/\">309. Best Time to Buy and Sell Stock with Cooldown</a></h2><h3>Medium</h3><hr><div><p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>\n\n<p>Find 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:</p>\n\n<ul>\n\t<li>After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).</li>\n</ul>\n\n<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> prices = [1,2,3,0,2]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> transactions = [buy, sell, cooldown, buy, sell]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> prices = [1]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 5000</code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0328-odd-even-linked-list/0328-odd-even-linked-list.java",
    "content": "/**\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 oddEvenList(ListNode head) {\n        if(head==null || head.next==null)return head;\n        ListNode oddHead=head;\n        ListNode evenHead=head.next;\n        ListNode odd=head;\n        ListNode even=head.next;\n        while(odd!=null && even!=null && even.next!=null){\n            odd.next=odd.next.next;\n            even.next=even.next.next;\n            odd=odd.next;\n            even=even.next;\n        }\n        if(odd==null)even.next=oddHead;\n        else odd.next=evenHead;\n        return oddHead;\n    }\n}"
  },
  {
    "path": "0328-odd-even-linked-list/NOTES.md",
    "content": "​"
  },
  {
    "path": "0328-odd-even-linked-list/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/odd-even-linked-list/\">328. Odd Even Linked List</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return <em>the reordered list</em>.</p>\n\n<p>The <strong>first</strong> node is considered <strong>odd</strong>, and the <strong>second</strong> node is <strong>even</strong>, and so on.</p>\n\n<p>Note that the relative order inside both the even and odd groups should remain as it was in the input.</p>\n\n<p>You must solve the problem&nbsp;in <code>O(1)</code>&nbsp;extra space complexity and <code>O(n)</code> time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/oddeven-linked-list.jpg\" style=\"width: 300px; height: 123px;\">\n<pre><strong>Input:</strong> head = [1,2,3,4,5]\n<strong>Output:</strong> [1,3,5,2,4]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/oddeven2-linked-list.jpg\" style=\"width: 500px; height: 142px;\">\n<pre><strong>Input:</strong> head = [2,1,3,5,6,4,7]\n<strong>Output:</strong> [2,3,6,7,1,5,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the linked list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>6</sup> &lt;= Node.val &lt;= 10<sup>6</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0334-increasing-triplet-subsequence/0334-increasing-triplet-subsequence.java",
    "content": "class Solution {\n    public boolean increasingTriplet(int[] nums) {\n        int first_num = Integer.MAX_VALUE;\n        int second_num = Integer.MAX_VALUE;\n        for(int num:nums)\n        {\n            if(num<=first_num)\n            {\n                first_num = num;\n            }\n            else if(num<=second_num)\n            {\n                second_num = num;\n            }else\n            {\n                return true;\n            }\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "0334-increasing-triplet-subsequence/NOTES.md",
    "content": "​"
  },
  {
    "path": "0334-increasing-triplet-subsequence/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/increasing-triplet-subsequence/\">334. Increasing Triplet Subsequence</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,4,5]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> Any triplet where i &lt; j &lt; k is valid.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [5,4,3,2,1]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> No triplet exists.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,1,5,0,4,6]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?</div>"
  },
  {
    "path": "0345-reverse-vowels-of-a-string/0345-reverse-vowels-of-a-string.java",
    "content": "class Solution {\n    public String reverseVowels(String s) {\n        int i=0;\n        int j=s.length()-1;\n        char[]arr=s.toCharArray();\n        while(i<j){\n            while(i<j && !vowel(arr[i]))i++;\n            while(j>i && !vowel(arr[j]))j--;\n            if(i>j)break;\n            char temp=arr[i];\n            arr[i]=arr[j];\n            arr[j]=temp;\n            i++;\n            j--;\n        }\n        return new String(arr);\n    }\n    boolean vowel(char c){\n        return switch (c) {\n            case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' -> true;\n            default -> false;\n        };\n        \n    }\n}"
  },
  {
    "path": "0345-reverse-vowels-of-a-string/NOTES.md",
    "content": "​"
  },
  {
    "path": "0345-reverse-vowels-of-a-string/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/reverse-vowels-of-a-string/\">345. Reverse Vowels of a String</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code>, reverse only all the vowels in the string and return it.</p>\n\n<p>The vowels are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>, and they can appear in both lower and upper cases, more than once.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"hello\"\n<strong>Output:</strong> \"holle\"\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"leetcode\"\n<strong>Output:</strong> \"leotcede\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consist of <strong>printable ASCII</strong> characters.</li>\n</ul>\n</div>"
  },
  {
    "path": "0374-guess-number-higher-or-lower/0374-guess-number-higher-or-lower.java",
    "content": "/* The guess API is defined in the parent class GuessGame.\n   @param num, your guess\n   @return -1 if my number is lower, 1 if my number is higher, otherwise return 0\n      int guess(int num); */\n\npublic class Solution extends GuessGame {\n    public int guessNumber(int n) {\n        int low = 1;\n        int high = n;\n        while (low <= high) {\n            int mid1 = low + (high - low) / 3;\n            int mid2 = high - (high - low) / 3;\n            int res1 = guess(mid1);\n            int res2 = guess(mid2);\n            if (res1 == 0)\n                return mid1;\n            if (res2 == 0)\n                return mid2;\n            else if (res1 < 0)\n                high = mid1 - 1;\n            else if (res2 > 0)\n                low = mid2 + 1;\n            else {\n                low = mid1 + 1;\n                high = mid2 - 1;\n            }\n        }\n        return -1;\n    }\n}"
  },
  {
    "path": "0374-guess-number-higher-or-lower/NOTES.md",
    "content": "​"
  },
  {
    "path": "0374-guess-number-higher-or-lower/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/guess-number-higher-or-lower/\">374. Guess Number Higher or Lower</a></h2><h3>Easy</h3><hr><div><p>We are playing the Guess Game. The game is as follows:</p>\n\n<p>I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked.</p>\n\n<p>Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.</p>\n\n<p>You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:</p>\n\n<ul>\n\t<li><code>-1</code>: Your guess is higher than the number I picked (i.e. <code>num &gt; pick</code>).</li>\n\t<li><code>1</code>: Your guess is lower than the number I picked (i.e. <code>num &lt; pick</code>).</li>\n\t<li><code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).</li>\n</ul>\n\n<p>Return <em>the number that I picked</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 10, pick = 6\n<strong>Output:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 1, pick = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 2, pick = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= pick &lt;= n</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0380-insert-delete-getrandom-o1/0380-insert-delete-getrandom-o1.java",
    "content": "class RandomizedSet {\n    List<Integer> list;\n    HashMap<Integer,Integer> map;\n    \n    public RandomizedSet() {\n        list=new ArrayList<>();\n        map=new HashMap<>();\n    }\n    \n    public boolean insert(int val) {\n        if(!map.containsKey(val)){\n            list.add(val);\n            map.put(val,list.size()-1);\n            return true;\n        }\n        return false;\n    }\n    \n    // Swap value to be removed with last value. Remove now the value at last \n    // index & update map with new index and remove the value to be removed.\n    public boolean remove(int val) {\n        if(map.containsKey(val)){\n            int index=map.get(val);\n            swap(index);\n            list.remove(list.size()-1);\n            map.remove(val);\n            return true;\n        }\n        return false;\n    }\n    \n    // User defined.\n    private void swap(int index) {\n        int lastIndex=list.size()-1;\n        int lastVal=list.get(lastIndex);\n        \n        int temp=list.get(index);\n        list.set(index,lastVal);\n        \n        map.put(lastVal,index);\n    }\n    \n    public int getRandom() {\n        return list.get(new Random().nextInt(list.size()));\n    }\n}"
  },
  {
    "path": "0380-insert-delete-getrandom-o1/NOTES.md",
    "content": "​"
  },
  {
    "path": "0380-insert-delete-getrandom-o1/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/insert-delete-getrandom-o1/\">380. Insert Delete GetRandom O(1)</a></h2><h3>Medium</h3><hr><div><p>Implement the <code>RandomizedSet</code> class:</p>\n\n<ul>\n\t<li><code>RandomizedSet()</code> Initializes the <code>RandomizedSet</code> object.</li>\n\t<li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the set if not present. Returns <code>true</code> if the item was not present, <code>false</code> otherwise.</li>\n\t<li><code>bool remove(int val)</code> Removes an item <code>val</code> from the set if present. Returns <code>true</code> if the item was present, <code>false</code> otherwise.</li>\n\t<li><code>int getRandom()</code> 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 <b>same probability</b> of being returned.</li>\n</ul>\n\n<p>You must implement the functions of the class such that each function works in&nbsp;<strong>average</strong>&nbsp;<code>O(1)</code>&nbsp;time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n[[], [1], [2], [2], [], [1], [2], []]\n<strong>Output</strong>\n[null, true, false, true, 2, true, false, 2]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>At most <code>2 *&nbsp;</code><code>10<sup>5</sup></code> calls will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li>\n\t<li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li>\n</ul>\n</div>"
  },
  {
    "path": "0409-longest-palindrome/0409-longest-palindrome.java",
    "content": "class Solution {\n    public int longestPalindrome(String s) {\n        int[]freq=new int[123];\n        for(char c:s.toCharArray()){\n            freq[c]++;\n        }\n        int ans=0;\n        boolean hasOdd=false;\n        for(int i:freq){\n            if((i&1)==1){\n                hasOdd=true;\n                ans+=i-1;\n            }else{\n                ans+=i;\n            }\n        }\n        return hasOdd?ans+1:ans;\n    }\n}"
  },
  {
    "path": "0409-longest-palindrome/NOTES.md",
    "content": "​"
  },
  {
    "path": "0409-longest-palindrome/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-palindrome/\">409. Longest Palindrome</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code> which consists of lowercase or uppercase letters, return <em>the length of the <strong>longest palindrome</strong></em>&nbsp;that can be built with those letters.</p>\n\n<p>Letters are <strong>case sensitive</strong>, for example,&nbsp;<code>\"Aa\"</code> is not considered a palindrome here.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"abccccdd\"\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> One longest palindrome that can be built is \"dccaccd\", whose length is 7.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"a\"\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The longest palindrome that can be built is \"a\", whose length is 1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 2000</code></li>\n\t<li><code>s</code> consists of lowercase <strong>and/or</strong> uppercase English&nbsp;letters only.</li>\n</ul>\n</div>"
  },
  {
    "path": "0446-arithmetic-slices-ii-subsequence/0446-arithmetic-slices-ii-subsequence.java",
    "content": "\nclass Solution {\n    public int numberOfArithmeticSlices(int[] A) {\n        int n = A.length;\n        long ans = 0;\n        Map<Integer, Integer>[] cnt = new Map[n];\n        for (int i = 0; i < n; i++) {\n            cnt[i] = new HashMap<>(i);\n            for (int j = 0; j < i; j++) {\n                long delta = (long)A[i] - (long)A[j];\n                if (delta < Integer.MIN_VALUE || delta > Integer.MAX_VALUE) {\n                    continue;\n                }\n                int diff = (int)delta;\n                int sum = cnt[j].getOrDefault(diff, 0);\n                int origin = cnt[i].getOrDefault(diff, 0);\n                cnt[i].put(diff, origin + sum + 1);\n                ans += sum;\n            }\n        }\n        return (int)ans;        \n    }\n}"
  },
  {
    "path": "0446-arithmetic-slices-ii-subsequence/NOTES.md",
    "content": "​"
  },
  {
    "path": "0446-arithmetic-slices-ii-subsequence/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/arithmetic-slices-ii-subsequence/\">446. Arithmetic Slices II - Subsequence</a></h2><h3>Hard</h3><hr><div><p>Given an integer array <code>nums</code>, return <em>the number of all the <strong>arithmetic subsequences</strong> of</em> <code>nums</code>.</p>\n\n<p>A sequence of numbers is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p>\n\n<ul>\n\t<li>For example, <code>[1, 3, 5, 7, 9]</code>, <code>[7, 7, 7, 7]</code>, and <code>[3, -1, -5, -9]</code> are arithmetic sequences.</li>\n\t<li>For example, <code>[1, 1, 2, 5, 7]</code> is not an arithmetic sequence.</li>\n</ul>\n\n<p>A <strong>subsequence</strong> of an array is a sequence that can be formed by removing some elements (possibly none) of the array.</p>\n\n<ul>\n\t<li>For example, <code>[2,5,10]</code> is a subsequence of <code>[1,2,1,<strong><u>2</u></strong>,4,1,<u><strong>5</strong></u>,<u><strong>10</strong></u>]</code>.</li>\n</ul>\n\n<p>The test cases are generated so that the answer fits in <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,4,6,8,10]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [7,7,7,7,7]\n<strong>Output:</strong> 16\n<strong>Explanation:</strong> Any subsequence of this array is arithmetic.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1&nbsp; &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0451-sort-characters-by-frequency/0451-sort-characters-by-frequency.java",
    "content": "class Solution {\n    public String frequencySort(String s) {\n        int[] a = new int[750];\n        \n        for(int i=0;i<s.length();i++)\n            a[s.charAt(i)-48]++;\n        \n        StringBuffer sb = new StringBuffer();\n        while(sb.length()!=s.length())\n        {\n            int max_freq=0;\n            for(int i=0;i<a.length;i++)\n            {\n                if(a[i]>a[max_freq])\n                    max_freq=i;\n            }\n            sb.append(String.valueOf((char)(max_freq+48)).repeat(a[max_freq]));\n            a[max_freq]=0; \n        }\n        return sb.toString();\n    }\n}"
  },
  {
    "path": "0451-sort-characters-by-frequency/NOTES.md",
    "content": "​"
  },
  {
    "path": "0451-sort-characters-by-frequency/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/sort-characters-by-frequency/\">451. Sort Characters By Frequency</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p>\n\n<p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"tree\"\n<strong>Output:</strong> \"eert\"\n<strong>Explanation:</strong> '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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"cccaaa\"\n<strong>Output:</strong> \"aaaccc\"\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"Aabb\"\n<strong>Output:</strong> \"bbAa\"\n<strong>Explanation:</strong> \"bbaA\" is also a valid answer, but \"Aabb\" is incorrect.\nNote that 'A' and 'a' are treated as two different characters.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of uppercase and lowercase English letters and digits.</li>\n</ul>\n</div>"
  },
  {
    "path": "0452-minimum-number-of-arrows-to-burst-balloons/0452-minimum-number-of-arrows-to-burst-balloons.java",
    "content": "class Solution {\n    public int findMinArrowShots(int[][] points) {\n        \n        // This Problem is similar to Non Overlapping Interval Problem of Greedy Approach\n        // Link for detiled discussion : http://www.leetcode-solution.com/2019/06/01/0452-minimum-number-of-arrows-to-burst-balloons.html\n        \n        // Base case\n        if(points.length == 0)\n            return 0;\n        \n        // Sort the point accroding to their end points i.e., a[1] - b[1]\n        Arrays.sort(points, (a,b) -> a[1] - b[1]);\n        \n        // Position arrow at end (Extreme Right) as it has maximum chance of hittng there\n        int arrPos = points[0][1];\n        int count = 1; // Minimun 1 arrow is required to shoot any points\n        \n        for(int i = 1; i < points.length; i++ ) // start with 1 as 0th index end will be check for start of 1st \n        {\n            int left  = points[i][0];\n            int right = points[i][1];\n            \n            \n            //check whether the arrowFired can burst other balloons.\n            //if not fire arrow at the next point end value\n            if (!(arrPos >= left && arrPos <= right)) \n            {\n                \n                count++; // increase the arrowsFired by 1.\n                arrPos = points[i][1];  // next point end value.\n                \n            }\n          /*  if(arrPos >= points[i][0]) // Since Current arrow position than start pos of array that means we can \n            {                          // continue, but as soon as it not true we break as our current arrow pos\n                continue;              // cant handle beyond that point . so update its pos and count++\n            }\n            count++ ;                 // As we are done with current pos \n            arrPos = points[i][1];    // Update as we already exhausted our option with previous position\n        */\n        \n        }\n        \n        return count;\n    }\n}\n"
  },
  {
    "path": "0452-minimum-number-of-arrows-to-burst-balloons/NOTES.md",
    "content": "​"
  },
  {
    "path": "0452-minimum-number-of-arrows-to-burst-balloons/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/\">452. Minimum Number of Arrows to Burst Balloons</a></h2><h3>Medium</h3><hr><div><p>There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array <code>points</code> where <code>points[i] = [x<sub>start</sub>, x<sub>end</sub>]</code> denotes a balloon whose <strong>horizontal diameter</strong> stretches between <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code>. You do not know the exact y-coordinates of the balloons.</p>\n\n<p>Arrows can be shot up <strong>directly vertically</strong> (in the positive y-direction) from different points along the x-axis. A balloon with <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code> is <strong>burst</strong> by an arrow shot at <code>x</code> if <code>x<sub>start</sub> &lt;= x &lt;= x<sub>end</sub></code>. There is <strong>no limit</strong> to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.</p>\n\n<p>Given the array <code>points</code>, return <em>the <strong>minimum</strong> number of arrows that must be shot to burst all balloons</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> points = [[10,16],[2,8],[1,6],[7,12]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> points = [[1,2],[3,4],[5,6],[7,8]]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> One arrow needs to be shot for each balloon for a total of 4 arrows.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> points = [[1,2],[2,3],[3,4],[4,5]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= points.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>points[i].length == 2</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= x<sub>start</sub> &lt; x<sub>end</sub> &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0491-non-decreasing-subsequences/0491-non-decreasing-subsequences.java",
    "content": "class Solution {\n    private void backtrack(int[] nums, int index, List<Integer> sequence,\n            Set<List<Integer>> result) {\n        // if we have checked all elements\n        if (index == nums.length) {\n            if (sequence.size() >= 2) {\n                result.add(new ArrayList<>(sequence));\n            }\n            return;\n        }\n        // if the sequence remains increasing after appending nums[index]\n        if (sequence.isEmpty() ||\n                sequence.get(sequence.size() - 1) <= nums[index]) {\n            // append nums[index] to the sequence\n            sequence.add(nums[index]);\n            // call recursively\n            backtrack(nums, index + 1, sequence, result);\n            // delete nums[index] from the end of the sequence\n            sequence.remove(sequence.size() - 1);\n        }\n        // call recursively not appending an element\n        backtrack(nums, index + 1, sequence, result);\n    }\n\n    public List<List<Integer>> findSubsequences(int[] nums) {\n        Set<List<Integer>> result = new HashSet<List<Integer>>();\n        List<Integer> sequence = new ArrayList<Integer>();\n        backtrack(nums, 0, sequence, result);\n        return new ArrayList(result);\n    }\n}"
  },
  {
    "path": "0491-non-decreasing-subsequences/NOTES.md",
    "content": "​"
  },
  {
    "path": "0491-non-decreasing-subsequences/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/non-decreasing-subsequences/\">491. Non-decreasing Subsequences</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, return <em>all the different possible non-decreasing subsequences of the given array with at least two elements</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [4,6,7,7]\n<strong>Output:</strong> [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [4,4,3,2,1]\n<strong>Output:</strong> [[4,4]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 15</code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0520-detect-capital/0520-detect-capital.java",
    "content": "class Solution {\n    public boolean detectCapitalUse(String word) {\n        int n = word.length();\n        if (n == 1) {\n            return true;\n        }\n\n        // case 1: All capital\n        if (Character.isUpperCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))) {\n            for (int i = 2; i < n; i++) {\n                if (Character.isLowerCase(word.charAt(i))) {\n                    return false;\n                }\n            }\n        // case 2 and case 3\n        } else {\n            for (int i = 1; i < n; i++) {\n                if (Character.isUpperCase(word.charAt(i))) {\n                    return false;\n                }\n            }\n        }\n\n        // if pass one of the cases\n        return true;\n    }\n}"
  },
  {
    "path": "0520-detect-capital/NOTES.md",
    "content": "​"
  },
  {
    "path": "0523-continuous-subarray-sum/0523-continuous-subarray-sum.java",
    "content": "class Solution \n{\n    public boolean checkSubarraySum(int[] nums, int k) \n    {\n        int prefixSum = 0;\n        \n        HashMap<Integer, Integer> map = new HashMap<>();\n        \n        map.put(0, -1);\n\n        for (int i = 0; i < nums.length; i++)\n        {\n            prefixSum += nums[i];\n            \n            // this is the twist\n            if (k != 0)\n            {\n                prefixSum = prefixSum % k;  //whose elements sum up to a multiple of k\n            }\n            \n            // this is general\n            if (map.containsKey(prefixSum))\n            {\n                //  if nums has a continuous subarray of size at least two elements\n                if (i - map.get(prefixSum) > 1)  \n                {\n                    return true;\n                }\n            }\n            else\n            {\n                map.put(prefixSum, i);  // adding the index\n            }\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "0523-continuous-subarray-sum/NOTES.md",
    "content": "​"
  },
  {
    "path": "0523-continuous-subarray-sum/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/continuous-subarray-sum/\">523. Continuous Subarray Sum</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if </em><code>nums</code><em> has a continuous subarray of size <strong>at least two</strong> whose elements sum up to a multiple of</em> <code>k</code><em>, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>An integer <code>x</code> is a multiple of <code>k</code> if there exists an integer <code>n</code> such that <code>x = n * k</code>. <code>0</code> is <strong>always</strong> a multiple of <code>k</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [23,<u>2,4</u>,6,7], k = 6\n<strong>Output:</strong> true\n<strong>Explanation:</strong> [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [<u>23,2,6,4,7</u>], k = 6\n<strong>Output:</strong> true\n<strong>Explanation:</strong> [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</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [23,2,6,4,7], k = 13\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= sum(nums[i]) &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= k &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0587-erect-the-fence/0587-erect-the-fence.java",
    "content": "public class Solution {\n    public int orientation(int[] p, int[] q, int[] r) {\n        return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]);\n    }\n    public int[][] outerTrees(int[][] points) {\n        Arrays.sort(points, new Comparator<int[]> () {\n            public int compare(int[] p, int[] q) {\n                return q[0] - p[0] == 0 ? q[1] - p[1] : q[0] - p[0];\n            }\n        });\n        Stack<int[]> hull = new Stack<>();\n        for (int i = 0; i < points.length; i++) {\n            while (hull.size() >= 2 && orientation(hull.get(hull.size() - 2), hull.get(hull.size() - 1), points[i]) > 0)\n                hull.pop();\n            hull.push(points[i]);\n        }\n        hull.pop();\n        for (int i = points.length - 1; i >= 0; i--) {\n            while (hull.size() >= 2 && orientation(hull.get(hull.size() - 2), hull.get(hull.size() - 1), points[i]) > 0)\n                hull.pop();\n            hull.push(points[i]);\n        }\n        // remove redundant elements from the stack\n        HashSet<int[]> ret = new HashSet<>(hull);\n        return ret.toArray(new int[ret.size()][]);\n    }\n}"
  },
  {
    "path": "0587-erect-the-fence/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/erect-the-fence/\">587. Erect the Fence</a></h2><h3>Hard</h3><hr><div><p>You are given an array <code>trees</code> where <code>trees[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the location of a tree in the garden.</p>\n\n<p>You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if <strong>all the trees are enclosed</strong>.</p>\n\n<p>Return <em>the coordinates of trees that are exactly located on the fence perimeter</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/erect2-plane.jpg\" style=\"width: 509px; height: 500px;\">\n<pre><strong>Input:</strong> points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\n<strong>Output:</strong> [[1,1],[2,0],[3,3],[2,4],[4,2]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/erect1-plane.jpg\" style=\"width: 509px; height: 500px;\">\n<pre><strong>Input:</strong> points = [[1,2],[2,2],[4,2]]\n<strong>Output:</strong> [[4,2],[2,2],[1,2]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= points.length &lt;= 3000</code></li>\n\t<li><code>points[i].length == 2</code></li>\n\t<li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 100</code></li>\n\t<li>All the given points are <strong>unique</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0645-set-mismatch/0645-set-mismatch.java",
    "content": "class Solution {\n    public int[] findErrorNums(int[] nums) {\n        /** Assume m is the missing and d is the duplicate element\n         diff= m-d;\n         squareDiff= m^2-d^2;\n         sum=m+d= squareDiff/diff\n         =>sum    = (m+d)(m-d)/(m-d);\n         now m=(sum+diff)2;\n         and d= (sum-diff)2;\n        **/\n        int diff=0;\n        int sqaureDiff=0;\n        for(int i=0;i<nums.length;i++){\n            /** \n            The order doesnot matter. keep adding the 1 to n and simultaneously subracting  corresponding array element.\n            Use i+1 to get 1 to n  since i is the index number which is zero based.\n            **/\n            diff+=(i+1)-nums[i];\n            /** squareDiff is also calculated in the same way as diff is calculated. **/\n            sqaureDiff+= (i+1)*(i+1)-nums[i]*nums[i];\n        } \n       int sum=sqaureDiff/diff;\n      return new int[]{(sum-diff)/2,(sum+diff)/2};\n    }\n}"
  },
  {
    "path": "0645-set-mismatch/NOTES.md",
    "content": "x-repeat\ny-missing\n​\n(sum-realSum)=(x-y)\n(sqrSum-realSqrSum)=(x+y)(x-y)\n​\n​\n(x-y)=(sum-realSum)\n(x+y)=(sqrSum-realSqrSum)/(sum-realSum)\n---------------------\nx=((sum-realSum)+(sqrSum-realSqrSum)/(sum-realSum))/2\n​\n​"
  },
  {
    "path": "0645-set-mismatch/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/set-mismatch/\">645. Set Mismatch</a></h2><h3>Easy</h3><hr><div><p>You have a set of integers <code>s</code>, which originally contains all the numbers from <code>1</code> to <code>n</code>. Unfortunately, due to some error, one of the numbers in <code>s</code> got duplicated to another number in the set, which results in <strong>repetition of one</strong> number and <strong>loss of another</strong> number.</p>\n\n<p>You are given an integer array <code>nums</code> representing the data status of this set after the error.</p>\n\n<p>Find the number that occurs twice and the number that is missing and return <em>them in the form of an array</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,2,2,4]\n<strong>Output:</strong> [2,3]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [1,1]\n<strong>Output:</strong> [1,2]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0692-top-k-frequent-words/0692-top-k-frequent-words.java",
    "content": "class Solution {\n    public List<String> topKFrequent(String[] words, int k) {\n        Map<String,Integer> map = new HashMap<>();\n        for(String w : words){\n            int c = map.getOrDefault(w,0);\n            c++;\n            map.put(w,c);\n        }\n        Queue<Map.Entry<String,Integer>> pq = new PriorityQueue<>((a,b)->(a.getValue() == b.getValue() ? a.getKey().compareTo(b.getKey()) : (a.getValue()-b.getValue())*-1));\n\n        for(Map.Entry<String,Integer> e : map.entrySet()){\n            pq.offer(e);\n        }\n        List<String> result = new ArrayList<>();\n        while(k > 0){\n            k--;\n            result.add(pq.poll().getKey());\n        }\n        return result;\n\n    }\n}"
  },
  {
    "path": "0692-top-k-frequent-words/NOTES.md",
    "content": "​"
  },
  {
    "path": "0692-top-k-frequent-words/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/top-k-frequent-words/\">692. Top K Frequent Words</a></h2><h3>Medium</h3><hr><div><p>Given an array of strings <code>words</code> and an integer <code>k</code>, return <em>the </em><code>k</code><em> most frequent strings</em>.</p>\n\n<p>Return the answer <strong>sorted</strong> by <strong>the frequency</strong> from highest to lowest. Sort the words with the same frequency by their <strong>lexicographical order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2\n<strong>Output:</strong> [\"i\",\"love\"]\n<strong>Explanation:</strong> \"i\" and \"love\" are the two most frequent words.\nNote that \"i\" comes before \"love\" due to a lower alphabetical order.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4\n<strong>Output:</strong> [\"the\",\"is\",\"sunny\",\"day\"]\n<strong>Explanation:</strong> \"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 500</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 10</code></li>\n\t<li><code>words[i]</code> consists of lowercase English letters.</li>\n\t<li><code>k</code> is in the range <code>[1, The number of <strong>unique</strong> words[i]]</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow-up:</strong> Could you solve it in <code>O(n log(k))</code> time and <code>O(n)</code> extra space?</p>\n</div>"
  },
  {
    "path": "0739-daily-temperatures/0739-daily-temperatures.java",
    "content": "class Solution {\n    public int[] dailyTemperatures(int[] a) {\n        Deque<Integer> s=new ArrayDeque<>();\n        int[]ans=new int[a.length];\n        for(int i=a.length-1;i>=0;i--){\n            while(!s.isEmpty() && a[s.peek()]<=a[i]){\n                s.pop();\n            }\n            if(s.isEmpty()){\n                ans[i]=0;\n            }else{\n                ans[i]=s.peek()-i;\n            }\n            s.push(i);\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "0739-daily-temperatures/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/daily-temperatures/\">739. Daily Temperatures</a></h2><h3>Medium</h3><hr><div><p>Given an array of integers <code>temperatures</code> represents the daily temperatures, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is the number of days you have to wait after the</em> <code>i<sup>th</sup></code> <em>day to get a warmer temperature</em>. If there is no future day for which this is possible, keep <code>answer[i] == 0</code> instead.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> temperatures = [73,74,75,71,69,72,76,73]\n<strong>Output:</strong> [1,1,4,2,1,1,0,0]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> temperatures = [30,40,50,60]\n<strong>Output:</strong> [1,1,1,0]\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> temperatures = [30,60,90]\n<strong>Output:</strong> [1,1,0]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;=&nbsp;temperatures.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>30 &lt;=&nbsp;temperatures[i] &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0766-toeplitz-matrix/0766-toeplitz-matrix.java",
    "content": "class Solution {\n    public boolean isToeplitzMatrix(int[][] matrix) {\n        for(int i=0;i<matrix.length-1;i++){\n            int[]mat1=matrix[i];\n            int[]mat2=matrix[i+1];\n            for(int j=0;j<mat1.length-1;j++){\n                if(mat1[j]!=mat2[j+1])return false;\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "0766-toeplitz-matrix/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/toeplitz-matrix/\">766. Toeplitz Matrix</a></h2><h3>Easy</h3><hr><div><p>Given an <code>m x n</code> <code>matrix</code>, return&nbsp;<em><code>true</code>&nbsp;if the matrix is Toeplitz. Otherwise, return <code>false</code>.</em></p>\n\n<p>A matrix is <strong>Toeplitz</strong> if every diagonal from top-left to bottom-right has the same elements.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/ex1.jpg\" style=\"width: 322px; height: 242px;\">\n<pre><strong>Input:</strong> matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\n<strong>Output:</strong> true\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/ex2.jpg\" style=\"width: 162px; height: 162px;\">\n<pre><strong>Input:</strong> matrix = [[1,2],[2,2]]\n<strong>Output:</strong> false\n<strong>Explanation:</strong>\nThe diagonal \"[1, 2]\" has different elements.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 20</code></li>\n\t<li><code>0 &lt;= matrix[i][j] &lt;= 99</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>What if the <code>matrix</code> 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?</li>\n\t<li>What if the <code>matrix</code> is so large that you can only load up a partial row into the memory at once?</li>\n</ul>\n</div>"
  },
  {
    "path": "0787-cheapest-flights-within-k-stops/0787-cheapest-flights-within-k-stops.java",
    "content": "class Solution {\n    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {\n        Map<Integer, List<int[]>> adj = new HashMap<>();\n        for (int[] i : flights)\n            adj.computeIfAbsent(i[0], value -> new ArrayList<>()).add(new int[] { i[1], i[2] });\n\n        int[] dist = new int[n];\n        Arrays.fill(dist, Integer.MAX_VALUE);\n\n        Queue<int[]> q = new LinkedList<>();\n        q.offer(new int[] { src, 0 });\n        int stops = 0;\n\n        while (stops <= k && !q.isEmpty()) {\n            int sz = q.size();\n            // Iterate on current level.\n            while (sz-- > 0) {\n                int[] temp = q.poll();\n                int node = temp[0];\n                int distance = temp[1];\n\n                if (!adj.containsKey(node))\n                    continue;\n                // Loop over neighbors of popped node.\n                for (int[] e : adj.get(node)) {\n                    int neighbour = e[0];\n                    int price = e[1];\n                    if (price + distance >= dist[neighbour])\n                        continue;\n                    dist[neighbour] = price + distance;\n                    q.offer(new int[] { neighbour, dist[neighbour] });\n                }\n            }\n            stops++;\n        }\n        return dist[dst] == Integer.MAX_VALUE ? -1 : dist[dst];\n    }\n}"
  },
  {
    "path": "0787-cheapest-flights-within-k-stops/NOTES.md",
    "content": "​"
  },
  {
    "path": "0787-cheapest-flights-within-k-stops/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/cheapest-flights-within-k-stops/\">787. Cheapest Flights Within K Stops</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> cities connected by some number of flights. You are given an array <code>flights</code> where <code>flights[i] = [from<sub>i</sub>, to<sub>i</sub>, price<sub>i</sub>]</code> indicates that there is a flight from city <code>from<sub>i</sub></code> to city <code>to<sub>i</sub></code> with cost <code>price<sub>i</sub></code>.</p>\n\n<p>You are also given three integers <code>src</code>, <code>dst</code>, and <code>k</code>, return <em><strong>the cheapest price</strong> from </em><code>src</code><em> to </em><code>dst</code><em> with at most </em><code>k</code><em> stops. </em>If there is no such route, return<em> </em><code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-3drawio.png\" style=\"width: 332px; height: 392px;\">\n<pre><strong>Input:</strong> n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1\n<strong>Output:</strong> 700\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-1drawio.png\" style=\"width: 332px; height: 242px;\">\n<pre><strong>Input:</strong> n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1\n<strong>Output:</strong> 200\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-2drawio.png\" style=\"width: 332px; height: 242px;\">\n<pre><strong>Input:</strong> n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0\n<strong>Output:</strong> 500\n<strong>Explanation:</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 100</code></li>\n\t<li><code>0 &lt;= flights.length &lt;= (n * (n - 1) / 2)</code></li>\n\t<li><code>flights[i].length == 3</code></li>\n\t<li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub> &lt; n</code></li>\n\t<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>\n\t<li><code>1 &lt;= price<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n\t<li>There will not be any multiple flights between two cities.</li>\n\t<li><code>0 &lt;= src, dst, k &lt; n</code></li>\n\t<li><code>src != dst</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0790-domino-and-tromino-tiling/0790-domino-and-tromino-tiling.java",
    "content": "class Solution {\n    public int numTilings(int n) {\n        int dp[] = new int[n+4];\n        \n        int mod = (int)(Math.pow(10,9)+7);\n        dp[1] = 1;\n        dp[2] = 2;\n        dp[3] = 5;\n        \n        for(int i=4;i<=n;i++){\n            dp[i] = ((2*dp[i-1])%mod)+dp[i-3];\n            dp[i] %= mod;\n        }\n        \n        return dp[n];\n    }\n}"
  },
  {
    "path": "0790-domino-and-tromino-tiling/NOTES.md",
    "content": "​"
  },
  {
    "path": "0790-domino-and-tromino-tiling/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/domino-and-tromino-tiling/\">790. Domino and Tromino Tiling</a></h2><h3>Medium</h3><hr><div><p>You have two types of tiles: a <code>2 x 1</code> domino shape and a tromino shape. You may rotate these shapes.</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/15/lc-domino.jpg\" style=\"width: 362px; height: 195px;\">\n<p>Given an integer n, return <em>the number of ways to tile an</em> <code>2 x n</code> <em>board</em>. Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>In 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.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/15/lc-domino1.jpg\" style=\"width: 500px; height: 226px;\">\n<pre><strong>Input:</strong> n = 3\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The five different ways are show above.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0797-all-paths-from-source-to-target/0797-all-paths-from-source-to-target.java",
    "content": "class Solution {\n    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {\n        \n        List<List<Integer>> ans = new ArrayList<>();\n        List<Integer> temp = new ArrayList<>();\n        temp.add(0);\n        dfs(graph,ans,temp,0);\n        return ans;\n    }\n    \n   public void dfs(int[][] graph, List<List<Integer>> ans, List<Integer> temp, int start){\n       \n        if(start == graph.length-1){\n            ans.add(new ArrayList<>(temp));\n            return;\n        }\n        \n        for(int i : graph[start]){\n            temp.add(i);\n            dfs(graph,ans,temp,i);\n            temp.remove(temp.size()-1);  \n        }\n        \n    }\n}"
  },
  {
    "path": "0797-all-paths-from-source-to-target/NOTES.md",
    "content": "​"
  },
  {
    "path": "0797-all-paths-from-source-to-target/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/all-paths-from-source-to-target/\">797. All Paths From Source to Target</a></h2><h3>Medium</h3><hr><div><p>Given a directed acyclic graph (<strong>DAG</strong>) of <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, find all possible paths from node <code>0</code> to node <code>n - 1</code> and return them in <strong>any order</strong>.</p>\n\n<p>The graph is given as follows: <code>graph[i]</code> is a list of all nodes you can visit from node <code>i</code> (i.e., there is a directed edge from node <code>i</code> to node <code>graph[i][j]</code>).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/28/all_1.jpg\" style=\"width: 242px; height: 242px;\">\n<pre><strong>Input:</strong> graph = [[1,2],[3],[3],[]]\n<strong>Output:</strong> [[0,1,3],[0,2,3]]\n<strong>Explanation:</strong> There are two paths: 0 -&gt; 1 -&gt; 3 and 0 -&gt; 2 -&gt; 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/28/all_2.jpg\" style=\"width: 423px; height: 301px;\">\n<pre><strong>Input:</strong> graph = [[4,3,1],[3,2,4],[3],[4],[]]\n<strong>Output:</strong> [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == graph.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 15</code></li>\n\t<li><code>0 &lt;= graph[i][j] &lt; n</code></li>\n\t<li><code>graph[i][j] != i</code> (i.e., there will be no self-loops).</li>\n\t<li>All the elements of <code>graph[i]</code> are <strong>unique</strong>.</li>\n\t<li>The input graph is <strong>guaranteed</strong> to be a <strong>DAG</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0834-sum-of-distances-in-tree/0834-sum-of-distances-in-tree.java",
    "content": "class Solution {\n    public int[] sumOfDistancesInTree(int n, int[][] edges) {\n        final int[] parents = buildParents(n, edges);\n        final int[] counts = new int[n];\n        final int[] childrenCount = new int[n];\n        final int[] distanceToChildren = new int[n];\n        for (int p : parents) {\n        \tif (p >= 0) counts[p]++;\n        }\n        int start = 0, end = 0;\n        for (int i = 0; i < parents.length; i++) {\n        \tif (counts[i] == 0) {\n        \t\tq[end++] = i;\n        \t}\n        }\n        while (start < end) {\n        \tfinal int node = q[start++];\n        \tfinal int parent = parents[node];\n        \tif (parent < 0) break;\n        \tfinal int c = childrenCount[node] + 1;\n        \tchildrenCount[parent] += c;\n        \tdistanceToChildren[parent] += distanceToChildren[node] + c;\n        \tif (--counts[parent] == 0) {\n        \t\tq[end++] = parent;\n        \t}\n        }\n//        System.out.println(\"Parents: \" + Arrays.toString(parents));\n//        System.out.println(\"ChildrenCount: \" + Arrays.toString(childrenCount));\n//        System.out.println(\"distanceToChildren: \" + Arrays.toString(distanceToChildren));\n        final int root = q[end - 1];\n        final int[] r = new int[n];\n        r[root] = distanceToChildren[root];\n        for (int i = end - 2; i >= 0; i--) {\n        \tfinal int node = q[i];\n        \tfinal int parent = parents[node];\n        \tfinal int minus = childrenCount[node] + 1;\n        \tr[node] = r[parent] + n - 2 * minus;\n        }\n        return r;\n    }\n\t\n\tstatic final int[] q = new int[30001];\n\t\n\tstatic int[] buildParents(int n, int[][] edges) {\n\t\tfinal int[][] next = buildNext(n, edges);\n        final int[] parents = new int[n];\n        Arrays.fill(parents, -1);\n        int start = 0, end = 0;\n        q[end++] = 0;\n        while (start < end) {\n        \tfinal int parent = q[start++];\n        \tfor (int c : next[parent]) {\n        \t\tif (parents[c] < 0) {\n        \t\t\tparents[c] = parent;\n        \t\t\tq[end++] = c;\n        \t\t}\n        \t}\n        }\n        parents[0] = -1;\n        return parents;\n\t}\n\t\n\tstatic int[][] buildNext(final int n, final int[][] edges) {\n\t\tfinal int[] counts = new int[n];\n\t\tfor (final int[] e : edges) {\n\t\t\tcounts[e[0]]++;\n\t\t\tcounts[e[1]]++;\n\t\t}\n\t\tfinal int[][] res = new int[n][];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tres[i] = new int[counts[i]];\n\t\t}\n\t\tfor (final int[] e : edges) {\n\t\t\tfinal int l = e[0];\n\t\t\tfinal int r = e[1];\n\t\t\tres[l][--counts[l]] = r;\n\t\t\tres[r][--counts[r]] = l;\n\t\t}\n\t\treturn res;\n\t}\n}"
  },
  {
    "path": "0834-sum-of-distances-in-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "0834-sum-of-distances-in-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/sum-of-distances-in-tree/\">834. Sum of Distances in Tree</a></h2><h3>Hard</h3><hr><div><p>There is an undirected connected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code> and <code>n - 1</code> edges.</p>\n\n<p>You are given the integer <code>n</code> and the array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>\n\n<p>Return an array <code>answer</code> of length <code>n</code> where <code>answer[i]</code> is the sum of the distances between the <code>i<sup>th</sup></code> node in the tree and all other nodes.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist1.jpg\" style=\"width: 304px; height: 224px;\">\n<pre><strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\n<strong>Output:</strong> [8,12,6,10,10,10]\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist2.jpg\" style=\"width: 64px; height: 65px;\">\n<pre><strong>Input:</strong> n = 1, edges = []\n<strong>Output:</strong> [0]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist3.jpg\" style=\"width: 144px; height: 145px;\">\n<pre><strong>Input:</strong> n = 2, edges = [[1,0]]\n<strong>Output:</strong> [1,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>edges.length == n - 1</code></li>\n\t<li><code>edges[i].length == 2</code></li>\n\t<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li>The given input represents a valid tree.</li>\n</ul>\n</div>"
  },
  {
    "path": "0835-image-overlap/0835-image-overlap.java",
    "content": "class Solution {\n\n    protected int convolute(int[][] A, int[][] kernel, int xShift, int yShift) {\n        int result = 0;\n        for (int row = 0; row < A.length; ++row)\n            for (int col = 0; col < A.length; ++col)\n                result += A[row][col] * kernel[row + yShift][col + xShift];\n        return result;\n    }\n\n    public int largestOverlap(int[][] A, int[][] B) {\n\n        int N = A.length;\n        int[][] B_padded = new int[3 * N - 2][3 * N - 2];\n        for (int row = 0; row < N; ++row)\n            for (int col = 0; col < N; ++col)\n                B_padded[row + N - 1][col + N - 1] = B[row][col];\n\n        int maxOverlaps = 0;\n        for (int xShift = 0; xShift < 2 * N - 1; ++xShift)\n            for (int yShift = 0; yShift < 2 * N - 1; ++yShift) {\n                maxOverlaps = Math.max(maxOverlaps,\n                    convolute(A, B_padded, xShift, yShift));\n            }\n\n        return maxOverlaps;\n    }\n}"
  },
  {
    "path": "0835-image-overlap/NOTES.md",
    "content": "​"
  },
  {
    "path": "0835-image-overlap/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/image-overlap/\">835. Image Overlap</a></h2><h3>Medium</h3><hr><div><p>You are given two images, <code>img1</code> and <code>img2</code>, represented as binary, square matrices of size <code>n x n</code>. A binary matrix has only <code>0</code>s and <code>1</code>s as values.</p>\n\n<p>We <strong>translate</strong> one image however we choose by sliding all the <code>1</code> bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the <strong>overlap</strong> by counting the number of positions that have a <code>1</code> in <strong>both</strong> images.</p>\n\n<p>Note also that a translation does <strong>not</strong> include any kind of rotation. Any <code>1</code> bits that are translated outside of the matrix borders are erased.</p>\n\n<p>Return <em>the largest possible overlap</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/09/overlap1.jpg\" style=\"width: 450px; height: 231px;\">\n<pre><strong>Input:</strong> img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> We translate img1 to right by 1 unit and down by 1 unit.\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/09/overlap_step1.jpg\" style=\"width: 450px; height: 105px;\">\nThe number of positions that have a 1 in both images is 3 (shown in red).\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/09/overlap_step2.jpg\" style=\"width: 450px; height: 231px;\">\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> img1 = [[1]], img2 = [[1]]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> img1 = [[0]], img2 = [[0]]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == img1.length == img1[i].length</code></li>\n\t<li><code>n == img2.length == img2[i].length</code></li>\n\t<li><code>1 &lt;= n &lt;= 30</code></li>\n\t<li><code>img1[i][j]</code> is either <code>0</code> or <code>1</code>.</li>\n\t<li><code>img2[i][j]</code> is either <code>0</code> or <code>1</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0841-keys-and-rooms/0841-keys-and-rooms.java",
    "content": "class Solution {\n    public boolean canVisitAllRooms(List<List<Integer>> rooms) {\n        boolean[] visited = new boolean[rooms.size()];\n        int count = 0;\n        count = dfs(rooms,0, visited, count);\n        return count == rooms.size();\n    }\n\n    public int dfs(List<List<Integer>> rooms, int currRoom, boolean[] visited, int count) {\n        if (visited[currRoom] == true) {\n            return count;\n        }\n        visited[currRoom] = true;\n        ++count;\n        for (Integer roomKey: rooms.get(currRoom)) {\n            count = dfs(rooms, roomKey, visited, count);\n        }\n        return count;\n    }\n}"
  },
  {
    "path": "0841-keys-and-rooms/NOTES.md",
    "content": "​"
  },
  {
    "path": "0841-keys-and-rooms/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/keys-and-rooms/\">841. Keys and Rooms</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> rooms labeled from <code>0</code> to <code>n - 1</code>&nbsp;and all the rooms are locked except for room <code>0</code>. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.</p>\n\n<p>When you visit a room, you may find a set of <strong>distinct keys</strong> 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.</p>\n\n<p>Given an array <code>rooms</code> where <code>rooms[i]</code> is the set of keys that you can obtain if you visited room <code>i</code>, return <code>true</code> <em>if you can visit <strong>all</strong> the rooms, or</em> <code>false</code> <em>otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> rooms = [[1],[2],[3],[]]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> \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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> rooms = [[1,3],[3,0,1],[2],[0]]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> We can not enter room number 2 since the only key that unlocks it is in that room.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == rooms.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 1000</code></li>\n\t<li><code>0 &lt;= rooms[i].length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= sum(rooms[i].length) &lt;= 3000</code></li>\n\t<li><code>0 &lt;= rooms[i][j] &lt; n</code></li>\n\t<li>All the values of <code>rooms[i]</code> are <strong>unique</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0872-leaf-similar-trees/0872-leaf-similar-trees.java",
    "content": "/**\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 boolean leafSimilar(TreeNode root1, TreeNode root2) {\n        // Collect the leaf values from each tree\n    List<Integer> leafValues1 = getLeafValues(root1, new ArrayList<>());\n    List<Integer> leafValues2 = getLeafValues(root2, new ArrayList<>());\n    \n    // Compare the leaf value lists\n    return leafValues1.equals(leafValues2);\n    }\n    List<Integer> getLeafValues(TreeNode node, List<Integer> values) {\n        // If the node is null, return\n        if (node == null) {\n            return values;\n        }\n        \n        // If the node is a leaf node, add its value to the list\n        if (node.left == null && node.right == null) {\n            values.add(node.val);\n        }\n        \n        // Recursively traverse the left and right subtrees\n        getLeafValues(node.left, values);\n        getLeafValues(node.right, values);\n        \n        return values;\n    }\n}"
  },
  {
    "path": "0872-leaf-similar-trees/NOTES.md",
    "content": "​"
  },
  {
    "path": "0872-leaf-similar-trees/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/leaf-similar-trees/\">872. Leaf-Similar Trees</a></h2><h3>Easy</h3><hr><div><p>Consider all the leaves of a binary tree, from&nbsp;left to right order, the values of those&nbsp;leaves form a <strong>leaf value sequence</strong><em>.</em></p>\n\n<p><img alt=\"\" src=\"https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png\" style=\"width: 400px; height: 336px;\"></p>\n\n<p>For example, in the given tree above, the leaf value sequence is <code>(6, 7, 4, 9, 8)</code>.</p>\n\n<p>Two binary trees are considered <em>leaf-similar</em>&nbsp;if their leaf value sequence is the same.</p>\n\n<p>Return <code>true</code> if and only if the two given trees with head nodes <code>root1</code> and <code>root2</code> are leaf-similar.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg\" style=\"width: 600px; height: 237px;\">\n<pre><strong>Input:</strong> 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]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg\" style=\"width: 300px; height: 110px;\">\n<pre><strong>Input:</strong> root1 = [1,2,3], root2 = [1,3,2]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in each tree will be in the range <code>[1, 200]</code>.</li>\n\t<li>Both of the given trees will have values in the range <code>[0, 200]</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.java",
    "content": "class Solution {\n    public ListNode middleNode(ListNode head) {\n        ListNode slow = head, fast = head;\n        while (fast != null && fast.next != null) {\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n        return slow;\n    }\n}"
  },
  {
    "path": "0876-middle-of-the-linked-list/NOTES.md",
    "content": "​"
  },
  {
    "path": "0876-middle-of-the-linked-list/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/middle-of-the-linked-list/\">876. Middle of the Linked List</a></h2><h3>Easy</h3><hr><div><p>Given the <code>head</code> of a singly linked list, return <em>the middle node of the linked list</em>.</p>\n\n<p>If there are two middle nodes, return <strong>the second middle</strong> node.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/23/lc-midlist1.jpg\" style=\"width: 544px; height: 65px;\">\n<pre><strong>Input:</strong> head = [1,2,3,4,5]\n<strong>Output:</strong> [3,4,5]\n<strong>Explanation:</strong> The middle node of the list is node 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/23/lc-midlist2.jpg\" style=\"width: 664px; height: 65px;\">\n<pre><strong>Input:</strong> head = [1,2,3,4,5,6]\n<strong>Output:</strong> [4,5,6]\n<strong>Explanation:</strong> Since the list has two middle nodes with values 3 and 4, we return the second one.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[1, 100]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "0886-possible-bipartition/0886-possible-bipartition.java",
    "content": "class Solution {\n    public boolean possibleBipartition(int n, int[][] dislikes) {\n        int[] colour = new int[n+1];\n        ArrayList<Integer>[] dislikeMap = new ArrayList[n+1];\n        \n        for(int i = 1; i <= n; i++)\n            dislikeMap[i] = new ArrayList<Integer>();\n        \n        for(int[] d: dislikes) {\n            dislikeMap[d[0]].add(d[1]);\n            dislikeMap[d[1]].add(d[0]);\n        }\n        \n        \n        Queue<Integer> queue = new LinkedList<>();\n        for(int i = 1; i <= n; i++) {\n            if(colour[i] == 0) {\n                colour[i] = 1;\n                queue = new LinkedList<>();\n                queue.offer(i);\n                \n                while(!queue.isEmpty()) {\n                    int curr = queue.poll();\n                    \n                    for(int neighbour: dislikeMap[curr]) {\n                        if(colour[neighbour] == 0) {\n                            colour[neighbour] = colour[curr] == 1?-1:1;\n                            queue.offer(neighbour);\n                        }\n                        else {\n                            if(colour[neighbour] == colour[curr])\n                                return false;\n                        }\n                    }\n                }\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "0886-possible-bipartition/NOTES.md",
    "content": "​"
  },
  {
    "path": "0886-possible-bipartition/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/possible-bipartition/\">886. Possible Bipartition</a></h2><h3>Medium</h3><hr><div><p>We want to split a group of <code>n</code> people (labeled from <code>1</code> to <code>n</code>) into two groups of <strong>any size</strong>. Each person may dislike some other people, and they should not go into the same group.</p>\n\n<p>Given the integer <code>n</code> and the array <code>dislikes</code> where <code>dislikes[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that the person labeled <code>a<sub>i</sub></code> does not like the person labeled <code>b<sub>i</sub></code>, return <code>true</code> <em>if it is possible to split everyone into two groups in this way</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 4, dislikes = [[1,2],[1,3],[2,4]]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> group1 [1,4] and group2 [2,3].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 3, dislikes = [[1,2],[1,3],[2,3]]\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2000</code></li>\n\t<li><code>0 &lt;= dislikes.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>dislikes[i].length == 2</code></li>\n\t<li><code>1 &lt;= dislikes[i][j] &lt;= n</code></li>\n\t<li><code>a<sub>i</sub> &lt; b<sub>i</sub></code></li>\n\t<li>All the pairs of <code>dislikes</code> are <strong>unique</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0899-orderly-queue/0899-orderly-queue.java",
    "content": "class Solution {\n    public String orderlyQueue(String s, int k) {\n        if (k == 1) {\n            String ans = s;\n            for (int i = 0; i < s.length(); ++i) {\n                String temp = s.substring(i) + s.substring(0, i);\n                if (temp.compareTo(ans) < 0) {\n                    ans = temp;\n                }\n            }\n            return ans;\n        } else {\n            char[] chars = s.toCharArray();\n            Arrays.sort(chars);\n            return new String(chars);\n        }\n    }\n}"
  },
  {
    "path": "0899-orderly-queue/NOTES.md",
    "content": "​"
  },
  {
    "path": "0899-orderly-queue/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/orderly-queue/\">899. Orderly Queue</a></h2><h3>Hard</h3><hr><div><p>You are given a string <code>s</code> and an integer <code>k</code>. You can choose one of the first <code>k</code> letters of <code>s</code> and append it at the end of the string..</p>\n\n<p>Return <em>the lexicographically smallest string you could have after applying the mentioned step any number of moves</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"cba\", k = 1\n<strong>Output:</strong> \"acb\"\n<strong>Explanation:</strong> \nIn the first move, we move the 1<sup>st</sup> character 'c' to the end, obtaining the string \"bac\".\nIn the second move, we move the 1<sup>st</sup> character 'b' to the end, obtaining the final result \"acb\".\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"baaca\", k = 3\n<strong>Output:</strong> \"aaabc\"\n<strong>Explanation:</strong> \nIn the first move, we move the 1<sup>st</sup> character 'b' to the end, obtaining the string \"aacab\".\nIn the second move, we move the 3<sup>rd</sup> character 'c' to the end, obtaining the final result \"aaabc\".\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consist of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "0901-online-stock-span/0901-online-stock-span.java",
    "content": "class StockSpanner {\n    Stack<int[]> stack = new Stack<>();\n    \n    public int next(int price) {\n        int ans = 1;\n        while (!stack.isEmpty() && stack.peek()[0] <= price) {\n            ans += stack.pop()[1];\n        }\n        \n        stack.push(new int[] {price, ans});\n        return ans;\n    }\n}\n\n/**\n * Your StockSpanner object will be instantiated and called as such:\n * StockSpanner obj = new StockSpanner();\n * int param_1 = obj.next(price);\n */"
  },
  {
    "path": "0901-online-stock-span/NOTES.md",
    "content": "​"
  },
  {
    "path": "0901-online-stock-span/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/online-stock-span/\">901. Online Stock Span</a></h2><h3>Medium</h3><hr><div><p>Design an algorithm that collects daily price quotes for some stock and returns <strong>the span</strong> of that stock's price for the current day.</p>\n\n<p>The <strong>span</strong> of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price.</p>\n\n<ul>\n\t<li>For example, if the price of a stock over the next <code>7</code> days were <code>[100,80,60,70,60,75,85]</code>, then the stock spans would be <code>[1,1,1,2,1,4,6]</code>.</li>\n</ul>\n\n<p>Implement the <code>StockSpanner</code> class:</p>\n\n<ul>\n\t<li><code>StockSpanner()</code> Initializes the object of the class.</li>\n\t<li><code>int next(int price)</code> Returns the <strong>span</strong> of the stock's price given that today's price is <code>price</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n[[], [100], [80], [60], [70], [60], [75], [85]]\n<strong>Output</strong>\n[null, 1, 1, 1, 2, 1, 4, 6]\n\n<strong>Explanation</strong>\nStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80);  // return 1\nstockSpanner.next(60);  // return 1\nstockSpanner.next(70);  // return 2\nstockSpanner.next(60);  // return 1\nstockSpanner.next(75);  // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85);  // return 6\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= price &lt;= 10<sup>5</sup></code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>next</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0907-sum-of-subarray-minimums/0907-sum-of-subarray-minimums.java",
    "content": "\nclass Solution {\n    public int sumSubarrayMins(int[] arr) {\n        int MOD = 1000000007;\n\n        Stack<Integer> stack = new Stack<>();\n        long sumOfMinimums = 0;\n\n        // building monotonically increasing stack\n        for (int i = 0; i <= arr.length; i++) {\n\n            // when i reaches the array length, it is an indication that\n            // all the elements have been processed, and the remaining\n            // elements in the stack should now be popped out.\n\n            while (!stack.empty() && (i == arr.length || arr[stack.peek()] >= arr[i])) {\n\n                // Notice the sign \">=\", This ensures that no contribution\n                // is counted twice. rightBoundary takes equal or smaller \n                // elements into account while leftBoundary takes only the\n                // strictly smaller elements into account\n\n                int mid = stack.pop();\n                int leftBoundary = stack.empty() ? -1 : stack.peek();\n                int rightBoundary = i;\n\n                // count of subarrays where mid is the minimum element\n                long count = (mid - leftBoundary) * (rightBoundary - mid) % MOD;\n\n                sumOfMinimums += (count * arr[mid]) % MOD;\n                sumOfMinimums %= MOD;\n            }\n            stack.push(i);\n        }\n\n        return (int) (sumOfMinimums);\n    }\n}\n"
  },
  {
    "path": "0907-sum-of-subarray-minimums/NOTES.md",
    "content": "​"
  },
  {
    "path": "0907-sum-of-subarray-minimums/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/sum-of-subarray-minimums/\">907. Sum of Subarray Minimums</a></h2><h3>Medium</h3><hr><div><p>Given an array of integers arr, find the sum of <code>min(b)</code>, where <code>b</code> ranges over every (contiguous) subarray of <code>arr</code>. Since the answer may be large, return the answer <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> arr = [3,1,2,4]\n<strong>Output:</strong> 17\n<strong>Explanation:</strong> \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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> arr = [11,81,94,43,3]\n<strong>Output:</strong> 444\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= arr.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= arr[i] &lt;= 3 * 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0909-snakes-and-ladders/0909-snakes-and-ladders.java",
    "content": "class Solution {\n    public int snakesAndLadders(int[][] board) {\n        int n = board.length;\n        Pair<Integer, Integer>[] cells = new Pair[n * n + 1];\n        int label = 1;\n        Integer[] columns = new Integer[n];\n        for (int i = 0; i < n; i++) {\n            columns[i] = i;\n        }\n        for (int row = n - 1; row >= 0; row--) {\n            for (int column : columns) {\n                cells[label++] = new Pair<>(row, column);\n            }\n            Collections.reverse(Arrays.asList(columns));\n        }\n        int[] dist = new int[n * n + 1];\n        Arrays.fill(dist, -1);\n        Queue<Integer> q = new LinkedList<Integer>();\n        dist[1] = 0;\n        q.add(1);\n        while (!q.isEmpty()) {\n            int curr = q.remove();\n            for (int next = curr + 1; next <= Math.min(curr + 6, n * n); next++) {\n                int row = cells[next].getKey(), column = cells[next].getValue();\n                int destination = board[row][column] != -1 ? board[row][column] : next;\n                if (dist[destination] == -1) {\n                    dist[destination] = dist[curr] + 1;\n                    q.add(destination);\n                }\n            }\n        }\n        return dist[n * n];\n    }\n}"
  },
  {
    "path": "0909-snakes-and-ladders/NOTES.md",
    "content": "​"
  },
  {
    "path": "0909-snakes-and-ladders/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/snakes-and-ladders/\">909. Snakes and Ladders</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>n x n</code> integer matrix <code>board</code> where the cells are labeled from <code>1</code> to <code>n<sup>2</sup></code> in a <a href=\"https://en.wikipedia.org/wiki/Boustrophedon\" target=\"_blank\"><strong>Boustrophedon style</strong></a> starting from the bottom left of the board (i.e. <code>board[n - 1][0]</code>) and alternating direction each row.</p>\n\n<p>You start on square <code>1</code> of the board. In each move, starting from square <code>curr</code>, do the following:</p>\n\n<ul>\n\t<li>Choose a destination square <code>next</code> with a label in the range <code>[curr + 1, min(curr + 6, n<sup>2</sup>)]</code>.\n\n\t<ul>\n\t\t<li>This choice simulates the result of a standard <strong>6-sided die roll</strong>: i.e., there are always at most 6 destinations, regardless of the size of the board.</li>\n\t</ul>\n\t</li>\n\t<li>If <code>next</code> has a snake or ladder, you <strong>must</strong> move to the destination of that snake or ladder. Otherwise, you move to <code>next</code>.</li>\n\t<li>The game ends when you reach the square <code>n<sup>2</sup></code>.</li>\n</ul>\n\n<p>A board square on row <code>r</code> and column <code>c</code> has a snake or ladder if <code>board[r][c] != -1</code>. The destination of that snake or ladder is <code>board[r][c]</code>. Squares <code>1</code> and <code>n<sup>2</sup></code> do not have a snake or ladder.</p>\n\n<p>Note 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 <strong>not</strong> follow the subsequent&nbsp;snake or ladder.</p>\n\n<ul>\n\t<li>For example, suppose the board is <code>[[-1,4],[-1,3]]</code>, and on the first move, your destination square is <code>2</code>. You follow the ladder to square <code>3</code>, but do <strong>not</strong> follow the subsequent ladder to <code>4</code>.</li>\n</ul>\n\n<p>Return <em>the least number of moves required to reach the square </em><code>n<sup>2</sup></code><em>. If it is not possible to reach the square, return </em><code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/09/23/snakes.png\" style=\"width: 500px; height: 394px;\">\n<pre><strong>Input:</strong> 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]]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> \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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> board = [[-1,-1],[-1,3]]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == board.length == board[i].length</code></li>\n\t<li><code>2 &lt;= n &lt;= 20</code></li>\n\t<li><code>grid[i][j]</code> is either <code>-1</code> or in the range <code>[1, n<sup>2</sup>]</code>.</li>\n\t<li>The squares labeled <code>1</code> and <code>n<sup>2</sup></code> do not have any ladders or snakes.</li>\n</ul>\n</div>"
  },
  {
    "path": "0918-maximum-sum-circular-subarray/0918-maximum-sum-circular-subarray.java",
    "content": "class Solution {\n    public int maxSubarraySumCircular(int[] nums) {\n        int curMax = 0, curMin = 0, sum = 0, maxSum = nums[0], minSum = nums[0];\n        for (int num : nums) {\n            curMax = Math.max(curMax, 0) + num;\n            maxSum = Math.max(maxSum, curMax);\n            curMin = Math.min(curMin, 0) + num;\n            minSum = Math.min(minSum, curMin);\n            sum += num;  \n        }\n        return sum == minSum ? maxSum : Math.max(maxSum, sum - minSum);\n    }\n}"
  },
  {
    "path": "0918-maximum-sum-circular-subarray/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-sum-circular-subarray/\">918. Maximum Sum Circular Subarray</a></h2><h3>Medium</h3><hr><div><p>Given a <strong>circular integer array</strong> <code>nums</code> of length <code>n</code>, return <em>the maximum possible sum of a non-empty <strong>subarray</strong> of </em><code>nums</code>.</p>\n\n<p>A <strong>circular array</strong> means the end of the array connects to the beginning of the array. Formally, the next element of <code>nums[i]</code> is <code>nums[(i + 1) % n]</code> and the previous element of <code>nums[i]</code> is <code>nums[(i - 1 + n) % n]</code>.</p>\n\n<p>A <strong>subarray</strong> may only include each element of the fixed buffer <code>nums</code> at most once. Formally, for a subarray <code>nums[i], nums[i + 1], ..., nums[j]</code>, there does not exist <code>i &lt;= k1</code>, <code>k2 &lt;= j</code> with <code>k1 % n == k2 % n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,-2,3,-2]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Subarray [3] has maximum sum 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [5,-3,5]\n<strong>Output:</strong> 10\n<strong>Explanation:</strong> Subarray [5,5] has maximum sum 5 + 5 = 10.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [-3,-2,-3]\n<strong>Output:</strong> -2\n<strong>Explanation:</strong> Subarray [-2] has maximum sum -2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-3 * 10<sup>4</sup> &lt;= nums[i] &lt;= 3 * 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0926-flip-string-to-monotone-increasing/0926-flip-string-to-monotone-increasing.java",
    "content": "class Solution {\n    public int minFlipsMonoIncr(String s) {\n        int ans = 0, num = 0;\n        for (int i = 0; i < s.length(); ++i) {\n            if (s.charAt(i) == '0') {\n                ans = Math.min(num, ans + 1);\n            } else {\n                ++num;\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "0926-flip-string-to-monotone-increasing/NOTES.md",
    "content": "​"
  },
  {
    "path": "0938-range-sum-of-bst/0938-range-sum-of-bst.java",
    "content": "/**\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 rangeSumBST(TreeNode root, int low, int high) {\n        return root == null ? 0 :\n    \t\t   (root.val >= low && root.val <= high ? root.val : 0) +\n    \t\t   (root.val > low  ? rangeSumBST(root.left,  low, high) : 0) + \n    \t\t   (root.val < high ? rangeSumBST(root.right, low, high) : 0);\n    }\n}"
  },
  {
    "path": "0938-range-sum-of-bst/NOTES.md",
    "content": "​"
  },
  {
    "path": "0938-range-sum-of-bst/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/range-sum-of-bst/\">938. Range Sum of BST</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> node of a binary search tree and two integers <code>low</code> and <code>high</code>, return <em>the sum of values of all nodes with a value in the <strong>inclusive</strong> range </em><code>[low, high]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg\" style=\"width: 400px; height: 222px;\">\n<pre><strong>Input:</strong> root = [10,5,15,3,7,null,18], low = 7, high = 15\n<strong>Output:</strong> 32\n<strong>Explanation:</strong> Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg\" style=\"width: 400px; height: 335px;\">\n<pre><strong>Input:</strong> root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10\n<strong>Output:</strong> 23\n<strong>Explanation:</strong> Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 2 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= low &lt;= high &lt;= 10<sup>5</sup></code></li>\n\t<li>All <code>Node.val</code> are <strong>unique</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "0944-delete-columns-to-make-sorted/0944-delete-columns-to-make-sorted.java",
    "content": "class Solution {\n    public int minDeletionSize(String[] strs) {\n        int cols=strs[0].length();\n        int ans=0;\n        for(int col=0;col<cols;col++){\n            for(int i=0;i<strs.length-1;i++){\n                if(strs[i+1].charAt(col)<strs[i].charAt(col)){\n                    ans++;\n                    break;\n                }\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "0944-delete-columns-to-make-sorted/NOTES.md",
    "content": "​"
  },
  {
    "path": "0944-delete-columns-to-make-sorted/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/delete-columns-to-make-sorted/\">944. Delete Columns to Make Sorted</a></h2><h3>Easy</h3><hr><div><p>You are given an array of <code>n</code> strings <code>strs</code>, all of the same length.</p>\n\n<p>The strings can be arranged such that there is one on each line, making a grid. For example, <code>strs = [\"abc\", \"bce\", \"cae\"]</code> can be arranged as:</p>\n\n<pre>abc\nbce\ncae\n</pre>\n\n<p>You want to <strong>delete</strong> the columns that are <strong>not sorted lexicographically</strong>. In the above example (0-indexed), columns 0 (<code>'a'</code>, <code>'b'</code>, <code>'c'</code>) and 2 (<code>'c'</code>, <code>'e'</code>, <code>'e'</code>) are sorted while column 1 (<code>'b'</code>, <code>'c'</code>, <code>'a'</code>) is not, so you would delete column 1.</p>\n\n<p>Return <em>the number of columns that you will delete</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> strs = [\"cba\",\"daf\",\"ghi\"]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> strs = [\"a\",\"b\"]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> strs = [\"zyx\",\"wvu\",\"tsr\"]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The grid looks as follows:\n  zyx\n  wvu\n  tsr\nAll 3 columns are not sorted, so you will delete all 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == strs.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 100</code></li>\n\t<li><code>1 &lt;= strs[i].length &lt;= 1000</code></li>\n\t<li><code>strs[i]</code> consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "0947-most-stones-removed-with-same-row-or-column/0947-most-stones-removed-with-same-row-or-column.java",
    "content": "class Solution {\n    public int removeStones(int[][] stones) {\n        if (stones == null || stones.length <= 1) {\n            return 0;\n        }\n\n        int n = stones.length;\n\n        UnionFind uf = new UnionFind();\n        for (int[] edge : stones) {\n            uf.union(edge[0] + 10001, edge[1]);\n        }\n\n        return n - uf.count;\n    }\n\n    class UnionFind {\n        Map<Integer, Integer> parents;\n        int count;\n\n        public UnionFind() {\n            parents = new HashMap<>();\n            count = 0;\n        }\n\n        public int find(int x) {\n            if (!parents.containsKey(x)) {\n                parents.put(x, x);\n                count++;\n            }\n\n            if (x != parents.get(x)) {\n                parents.put(x, find(parents.get(x)));\n            }\n\n            return parents.get(x);\n        }\n\n        public void union(int x, int y) {\n            int rootX = find(x);\n            int rootY = find(y);\n            if (rootX == rootY) {\n                return;\n            }\n\n            parents.put(rootX, rootY);\n            count--;\n        }\n    }\n}"
  },
  {
    "path": "0947-most-stones-removed-with-same-row-or-column/NOTES.md",
    "content": "​"
  },
  {
    "path": "0947-most-stones-removed-with-same-row-or-column/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/\">947. Most Stones Removed with Same Row or Column</a></h2><h3>Medium</h3><hr><div><p>On a 2D plane, we place <code>n</code> stones at some integer coordinate points. Each coordinate point may have at most one stone.</p>\n\n<p>A stone can be removed if it shares either <strong>the same row or the same column</strong> as another stone that has not been removed.</p>\n\n<p>Given an array <code>stones</code> of length <code>n</code> where <code>stones[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the location of the <code>i<sup>th</sup></code> stone, return <em>the largest possible number of stones that can be removed</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> stones = [[0,0]]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> [0,0] is the only stone on the plane, so you cannot remove it.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= stones.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n\t<li>No two stones are at the same coordinate point.</li>\n</ul>\n</div>"
  },
  {
    "path": "0974-subarray-sums-divisible-by-k/0974-subarray-sums-divisible-by-k.java",
    "content": "class Solution {\n    public int subarraysDivByK(int[] nums, int k) {\n        int n = nums.length;\n        int prefixMod = 0, result = 0;\n\n        // There are k mod groups 0...k-1.\n        int[] modGroups = new int[k];\n        modGroups[0] = 1;\n\n        for (int num: nums) {\n            // Take modulo twice to avoid negative remainders.\n            prefixMod = (prefixMod + 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 += modGroups[prefixMod];\n            modGroups[prefixMod]++;\n        }\n\n        return result;\n    }\n}"
  },
  {
    "path": "0974-subarray-sums-divisible-by-k/NOTES.md",
    "content": "​"
  },
  {
    "path": "0974-subarray-sums-divisible-by-k/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/subarray-sums-divisible-by-k/\">974. Subarray Sums Divisible by K</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of non-empty <strong>subarrays</strong> that have a sum divisible by </em><code>k</code>.</p>\n\n<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [4,5,0,-2,-3,1], k = 5\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [5], k = 9\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>2 &lt;= k &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0976-largest-perimeter-triangle/0976-largest-perimeter-triangle.java",
    "content": "class Solution {\n    public int largestPerimeter(int[] nums) {\n        Arrays.sort(nums);\n        int i=nums.length-1;\n        while(i>1){\n            int a=nums[i];\n            int b=nums[i-1];\n            int c=nums[i-2];\n            if(c+b>a){\n                return a+b+c;\n            }else{\n                i--;\n            }\n        }\n        return 0;\n    }\n}"
  },
  {
    "path": "0976-largest-perimeter-triangle/NOTES.md",
    "content": "​"
  },
  {
    "path": "0976-largest-perimeter-triangle/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/largest-perimeter-triangle/\">976. Largest Perimeter Triangle</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code>, return <em>the largest perimeter of a triangle with a non-zero area, formed from three of these lengths</em>. If it is impossible to form any triangle of a non-zero area, return <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,1,2]\n<strong>Output:</strong> 5\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,1]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "0980-unique-paths-iii/0980-unique-paths-iii.java",
    "content": "class Solution {\n    public int uniquePathsIII(int[][] grid) {\n        int zero = 0; // Count the 0's\n        int sx = 0; // starting x index\n        int sy = 0; // starting y index\n        \n        for(int r = 0; r < grid.length; r++){ // r = row\n            for(int c = 0; c < grid[0].length; c++){ // c = column\n                if(grid[r][c] == 0) zero++; // if current cell is 0, count it.\n                else if(grid[r][c] == 1){\n                    sx = r; // starting x co-ordinate\n                    sy = c; // starting y co-ordinate\n                }\n            }\n        }\n        return dfs(grid, sx, sy, zero);\n    }\n    public int dfs(int grid[][], int x, int y, int zero){\n        // Base Condition\n        if(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || 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 then the zero count. \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}"
  },
  {
    "path": "0980-unique-paths-iii/NOTES.md",
    "content": "​"
  },
  {
    "path": "0980-unique-paths-iii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/unique-paths-iii/\">980. Unique Paths III</a></h2><h3>Hard</h3><hr><div><p>You are given an <code>m x n</code> integer array <code>grid</code> where <code>grid[i][j]</code> could be:</p>\n\n<ul>\n\t<li><code>1</code> representing the starting square. There is exactly one starting square.</li>\n\t<li><code>2</code> representing the ending square. There is exactly one ending square.</li>\n\t<li><code>0</code> representing empty squares we can walk over.</li>\n\t<li><code>-1</code> representing obstacles that we cannot walk over.</li>\n</ul>\n\n<p>Return <em>the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/08/02/lc-unique1.jpg\" style=\"width: 324px; height: 245px;\">\n<pre><strong>Input:</strong> grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/08/02/lc-unique2.jpg\" style=\"width: 324px; height: 245px;\">\n<pre><strong>Input:</strong> grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/08/02/lc-unique3-.jpg\" style=\"width: 164px; height: 165px;\">\n<pre><strong>Input:</strong> grid = [[0,1],[2,0]]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 20</code></li>\n\t<li><code>1 &lt;= m * n &lt;= 20</code></li>\n\t<li><code>-1 &lt;= grid[i][j] &lt;= 2</code></li>\n\t<li>There is exactly one starting cell and one ending cell.</li>\n</ul>\n</div>"
  },
  {
    "path": "0997-find-the-town-judge/0997-find-the-town-judge.java",
    "content": "class Solution {\n    public int findJudge(int n, int[][] trust) {\n        \n        int count[] = new int[n+1];\n        \n        for(int t[] : trust){\n            count[t[0]]--;     // outdegree\n            count[t[1]]++;   // indegree\n        }\n        \n        for(int i=1;i<=n;i++){\n            if(count[i]==n-1) return i;\n        }\n        \n        return -1;\n        \n    }\n}"
  },
  {
    "path": "0997-find-the-town-judge/NOTES.md",
    "content": "​"
  },
  {
    "path": "0997-find-the-town-judge/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-the-town-judge/\">997. Find the Town Judge</a></h2><h3>Easy</h3><hr><div><p>In a town, there are <code>n</code> people labeled from <code>1</code> to <code>n</code>. There is a rumor that one of these people is secretly the town judge.</p>\n\n<p>If the town judge exists, then:</p>\n\n<ol>\n\t<li>The town judge trusts nobody.</li>\n\t<li>Everybody (except for the town judge) trusts the town judge.</li>\n\t<li>There is exactly one person that satisfies properties <strong>1</strong> and <strong>2</strong>.</li>\n</ol>\n\n<p>You are given an array <code>trust</code> where <code>trust[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> representing that the person labeled <code>a<sub>i</sub></code> trusts the person labeled <code>b<sub>i</sub></code>.</p>\n\n<p>Return <em>the label of the town judge if the town judge exists and can be identified, or return </em><code>-1</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 2, trust = [[1,2]]\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 3, trust = [[1,3],[2,3]]\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 3, trust = [[1,3],[2,3],[3,1]]\n<strong>Output:</strong> -1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n\t<li><code>0 &lt;= trust.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>trust[i].length == 2</code></li>\n\t<li>All the pairs of <code>trust</code> are <strong>unique</strong>.</li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li><code>1 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1007-minimum-domino-rotations-for-equal-row/1007-minimum-domino-rotations-for-equal-row.java",
    "content": "class Solution {\n    public int minDominoRotations(int[] tops, int[] bottoms) {\n        int ans =-1;\n        for(int i=1;i<=6;i++){\n            int currAns = helper(i,tops,bottoms);\n            if (currAns != -1 && (ans == -1 || ans > currAns)) {\n                ans = currAns;\n            }\n        }\n        return ans;\n    }\n    \n    private int helper(int target,int[] a,int[] b){\n        int numswapA =0;\n        int numswapB =0;\n        for(int i=0;i<a.length;i++){\n            if(a[i] != target && b[i] != target){\n                return -1;\n            }\n            if(a[i] != target){\n                numswapA++;\n            } else if(b[i] != target){\n                numswapB++;\n            }\n        }\n        return Math.min(numswapA,numswapB);\n    }\n}"
  },
  {
    "path": "1007-minimum-domino-rotations-for-equal-row/NOTES.md",
    "content": "​"
  },
  {
    "path": "1007-minimum-domino-rotations-for-equal-row/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/\">1007. Minimum Domino Rotations For Equal Row</a></h2><h3>Medium</h3><hr><div><p>In a row of dominoes, <code>tops[i]</code> and <code>bottoms[i]</code> represent the top and bottom halves of the <code>i<sup>th</sup></code> domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)</p>\n\n<p>We may rotate the <code>i<sup>th</sup></code> domino, so that <code>tops[i]</code> and <code>bottoms[i]</code> swap values.</p>\n\n<p>Return the minimum number of rotations so that all the values in <code>tops</code> are the same, or all the values in <code>bottoms</code> are the same.</p>\n\n<p>If it cannot be done, return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/14/domino.png\" style=\"height: 300px; width: 421px;\">\n<pre><strong>Input:</strong> tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> \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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> \nIn this case, it is not possible to rotate the dominoes to make one row of values equal.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= tops.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>bottoms.length == tops.length</code></li>\n\t<li><code>1 &lt;= tops[i], bottoms[i] &lt;= 6</code></li>\n</ul>\n</div>"
  },
  {
    "path": "102-binary-tree-level-order-traversal/102-binary-tree-level-order-traversal.java",
    "content": "/**\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>> levelOrder(TreeNode root) {\n        List<List<Integer>> ans=new ArrayList<>();\n        if(root==null)return ans;\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(root);\n        while(!q.isEmpty()){\n            int sz=q.size();\n            List<Integer> list=new ArrayList<>();\n            while(sz-->0){\n                TreeNode node=q.remove();\n                list.add(node.val);\n                if(node.left!=null)q.add(node.left);\n                if(node.right!=null)q.add(node.right);\n            }\n            ans.add(list);\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "102-binary-tree-level-order-traversal/102-binary-tree-level-order-traversal.py",
    "content": "# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n        \n        res = []\n        \n        # Breadth-First-Search Algo\n        \n        def traverse(node, i):\n            if node:\n                if i<len(res):\n                    res[i].append(node.val)\n                else:\n                    res.append([node.val])\n                    \n                traverse(node.left, i+1)\n                traverse(node.right, i+1)\n                \n                \n        traverse(root, 0)\n        return res\n"
  },
  {
    "path": "102-binary-tree-level-order-traversal/NOTES.md",
    "content": "​"
  },
  {
    "path": "102-binary-tree-level-order-traversal/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-tree-level-order-traversal/\">102. Binary Tree Level Order Traversal</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes' values</em>. (i.e., from left to right, level by level).</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg\" style=\"width: 277px; height: 302px;\">\n<pre><strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> [[3],[9,20],[15,7]]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = [1]\n<strong>Output:</strong> [[1]]\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1020-number-of-enclaves/1020-number-of-enclaves.cpp",
    "content": "class Solution {\npublic:\npair<int,bool> bfs(vector<vector<int>>& gr, vector<vector<bool>>& vis, int x, int y) {\n\tqueue<pair<int, int>>qq;\n\t// (1,2)  (2,1)  (1,0)  (0,1)\n\tvector<int>xmoves = { 0,1,0,-1 };\n\tvector<int>ymoves = { 1,0,-1,0 };\n\n\tqq.push(make_pair(x, y));\n\tvis[x][y] = true;\n\tpair<int, int>temp;\n\tint r,c;\n\tbool is_at_boundary = false;\n\tint count = 0;\n\twhile (!qq.empty()) {\n\t\ttemp = qq.front();\n\t\tqq.pop();\n\t\t++count;\n\t\t\n\t\tfor (int i = 0;i < 4;i++) {\n\t\t\tr = temp.first + xmoves[i];\n\t\t\tc = temp.second + ymoves[i];\n\n\t\t\tif (r < 0 || c < 0 || r >= gr.size() || c >= gr[0].size())\n\t\t\t\tis_at_boundary = true;\n\t\t\telse if (!vis[r][c] && gr[r][c]) {\n\t\t\t\tvis[r][c] = true;\n\t\t\t\tqq.push(make_pair(r, c));\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn { count,is_at_boundary };\n}\n    int numEnclaves(vector<vector<int>>& grid) {\n        int n = grid.size(), m = grid[0].size();\n\tint answer = 0;\n\tvector<vector<bool>>vis(n, vector<bool>(m,false));\n\tpair<int, bool>result;\n\tfor (int i = 0;i < n;i++) {\n\t\tfor (int j = 0;j < m;j++) {\n\t\t\tif (!vis[i][j] && grid[i][j]) {\n\t\t\t\tresult = bfs(grid, vis, i, j);\n\t\t\t\t//cout <<\"result is \"<< result.first << endl;\n\t\t\t\tif (!result.second)answer += result.first;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn answer;\n    }\n};"
  },
  {
    "path": "1020. Number of Enclaves.java",
    "content": "class Solution {\n    public int numEnclaves(int[][] grid) {\n        int n=grid.length;\n        int m=grid[0].length;\n\n        int[][] vis=new int[n][m];\n        \n        for(int j=0;j<m;j++){\n            if(grid[0][j]==1 && vis[0][j]==0) dfs(grid,vis,0,j);\n        }\n        for(int i=0;i<n;i++){\n            if(grid[i][0]==1 && vis[i][0]==0) dfs(grid,vis,i,0);\n        }\n        for(int i=0;i<n;i++){\n            if(grid[i][m-1]==1 && vis[i][m-1]==0) dfs(grid,vis,i,m-1);\n        }\n        for(int j=0;j<m;j++){\n            if(grid[n-1][j]==1 && vis[n-1][j]==0) dfs(grid,vis,n-1,j);\n        }\n        \n        int cnt=0;\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(grid[i][j]==1 && vis[i][j]==0){\n                    cnt++;\n                }\n            }\n        }\n        \n        return cnt;\n    }\n    \n    public void dfs(int[][] a,int[][] vis,int i,int j){\n        if(i<0 || i>=a.length || j<0 || j>=a[0].length || vis[i][j]==1 || a[i][j]==0){\n            return ;\n        }\n        vis[i][j]=1;\n        \n        dfs(a,vis,i+1,j);\n        dfs(a,vis,i-1,j);\n        dfs(a,vis,i,j+1);\n        dfs(a,vis,i,j-1);\n        \n        return;\n    }\n}\n"
  },
  {
    "path": "1026-maximum-difference-between-node-and-ancestor/1026-maximum-difference-between-node-and-ancestor.java",
    "content": "class Solution {\n   int maxDifference = 0;\n    public int maxAncestorDiff(TreeNode root) {\n         int max = Integer.MIN_VALUE;\n         int min = Integer.MAX_VALUE;\n        dfs(root, max, min);\n        return maxDifference;\n    }\n    \n   void dfs(TreeNode root, int max, int min){\n        if(root == null) return;\n        \n        if(root.val < min) {\n            min = root.val;\n            \n            }\n        if(root.val > max) {\n            max = root.val;\n            };\n        \n        if(Math.abs(min - max) > maxDifference) {\n            maxDifference = Math.abs(min - max);\n        }\n         dfs(root.left, max, min);\n         dfs(root.right, max, min);\n    }\n}"
  },
  {
    "path": "1026-maximum-difference-between-node-and-ancestor/NOTES.md",
    "content": "​"
  },
  {
    "path": "1026-maximum-difference-between-node-and-ancestor/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/\">1026. Maximum Difference Between Node and Ancestor</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, find the maximum value <code>v</code> for which there exist <strong>different</strong> nodes <code>a</code> and <code>b</code> where <code>v = |a.val - b.val|</code> and <code>a</code> is an ancestor of <code>b</code>.</p>\n\n<p>A node <code>a</code> is an ancestor of <code>b</code> if either: any child of <code>a</code> is equal to <code>b</code>&nbsp;or any child of <code>a</code> is an ancestor of <code>b</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/09/tmp-tree.jpg\" style=\"width: 400px; height: 390px;\">\n<pre><strong>Input:</strong> root = [8,3,10,1,6,null,14,null,null,4,7,13]\n<strong>Output:</strong> 7\n<strong>Explanation: </strong>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.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/09/tmp-tree-1.jpg\" style=\"width: 250px; height: 349px;\">\n<pre><strong>Input:</strong> root = [1,null,2,null,0,3]\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 5000]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1029-two-city-scheduling/1029-two-city-scheduling.java",
    "content": "class Solution {\n    public int twoCitySchedCost(int[][] costs) {\n        int n=costs.length;\n        int[][]diff=new int[n][3];\n        for(int i=0;i<n;i++){\n            int dif=costs[i][1]-costs[i][0];\n            diff[i]=new int[]{dif,costs[i][0],costs[i][1]};\n        }\n        Arrays.sort(diff,(o1,o2)->o1[0]-o2[0]);\n        int ans=0;\n        for(int i=0;i<n;i++){\n            if(i>=n/2){\n                ans+=diff[i][1];\n            }else{\n                ans+=diff[i][2];\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "1029-two-city-scheduling/NOTES.md",
    "content": "​"
  },
  {
    "path": "1029-two-city-scheduling/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/two-city-scheduling/\">1029. Two City Scheduling</a></h2><h3>Medium</h3><hr><div><p>A company is planning to interview <code>2n</code> people. Given the array <code>costs</code> where <code>costs[i] = [aCost<sub>i</sub>, bCost<sub>i</sub>]</code>,&nbsp;the cost of flying the <code>i<sup>th</sup></code> person to city <code>a</code> is <code>aCost<sub>i</sub></code>, and the cost of flying the <code>i<sup>th</sup></code> person to city <code>b</code> is <code>bCost<sub>i</sub></code>.</p>\n\n<p>Return <em>the minimum cost to fly every person to a city</em> such that exactly <code>n</code> people arrive in each city.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> costs = [[10,20],[30,200],[400,50],[30,20]]\n<strong>Output:</strong> 110\n<strong>Explanation: </strong>\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\n<strong>Output:</strong> 1859\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]\n<strong>Output:</strong> 3086\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 * n == costs.length</code></li>\n\t<li><code>2 &lt;= costs.length &lt;= 100</code></li>\n\t<li><code>costs.length</code> is even.</li>\n\t<li><code>1 &lt;= aCost<sub>i</sub>, bCost<sub>i</sub> &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1046-last-stone-weight/1046-last-stone-weight.java",
    "content": "class Solution {\n    public int lastStoneWeight(int[] stones) {\n        int c = stones.length;\n        while(c > 1){\n            Arrays.sort(stones);\n            stones[c-2]=stones[c-1] - stones[c-2];\n            c--;\n        }\n        \n        return stones[0];\n        \n    }\n}"
  },
  {
    "path": "1046-last-stone-weight/NOTES.md",
    "content": "​"
  },
  {
    "path": "1046-last-stone-weight/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/last-stone-weight/\">1046. Last Stone Weight</a></h2><h3>Easy</h3><hr><div><p>You are given an array of integers <code>stones</code> where <code>stones[i]</code> is the weight of the <code>i<sup>th</sup></code> stone.</p>\n\n<p>We are playing a game with the stones. On each turn, we choose the <strong>heaviest two stones</strong> and smash them together. Suppose the heaviest two stones have weights <code>x</code> and <code>y</code> with <code>x &lt;= y</code>. The result of this smash is:</p>\n\n<ul>\n\t<li>If <code>x == y</code>, both stones are destroyed, and</li>\n\t<li>If <code>x != y</code>, the stone of weight <code>x</code> is destroyed, and the stone of weight <code>y</code> has new weight <code>y - x</code>.</li>\n</ul>\n\n<p>At the end of the game, there is <strong>at most one</strong> stone left.</p>\n\n<p>Return <em>the smallest possible weight of the left stone</em>. If there are no stones left, return <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> stones = [2,7,4,1,8,1]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> \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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> stones = [1]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= stones.length &lt;= 30</code></li>\n\t<li><code>1 &lt;= stones[i] &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1047-remove-all-adjacent-duplicates-in-string/1047-remove-all-adjacent-duplicates-in-string.java",
    "content": "class Solution {\n    public String removeDuplicates(String s) {\n        int i = 0;\n        int len = s.length();\n\n        char arr[] = s.toCharArray();\n        for(int j = 0; j<len; j++){\n            arr[i] = arr[j];\n            if(i>0 && arr[i]==arr[i-1]){\n                i -= 2;\n            }\n            i++;\n        }\n        return new String(arr, 0, i);\n\n    }\n}"
  },
  {
    "path": "1047-remove-all-adjacent-duplicates-in-string/NOTES.md",
    "content": "​"
  },
  {
    "path": "1047-remove-all-adjacent-duplicates-in-string/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/\">1047. Remove All Adjacent Duplicates In String</a></h2><h3>Easy</h3><hr><div><p>You are given a string <code>s</code> consisting of lowercase English letters. A <strong>duplicate removal</strong> consists of choosing two <strong>adjacent</strong> and <strong>equal</strong> letters and removing them.</p>\n\n<p>We repeatedly make <strong>duplicate removals</strong> on <code>s</code> until we no longer can.</p>\n\n<p>Return <em>the final string after all such duplicate removals have been made</em>. It can be proven that the answer is <strong>unique</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"abbaca\"\n<strong>Output:</strong> \"ca\"\n<strong>Explanation:</strong> \nFor example, in \"abbaca\" we could remove \"bb\" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is \"aaca\", of which only \"aa\" is possible, so the final string is \"ca\".\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"azxxzy\"\n<strong>Output:</strong> \"ay\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1048-longest-string-chain/1048-longest-string-chain.java",
    "content": "class Solution {\n    public int longestStrChain(String[] words) {\n        Arrays.sort(words,(a,b)->a.length()-b.length());\n        Map<String,Integer> map=new HashMap<>();\n        int res=0;\n        for(String word:words){\n            map.put(word,1);\n            for(int i=0;i<word.length();i++){\n                StringBuilder curr=new StringBuilder(word);\n                String next=curr.deleteCharAt(i).toString();\n                if(map.containsKey(next)){\n                    map.put(word,Math.max(map.get(word),map.get(next)+1));\n                }\n            }\n            res=Math.max(res,map.get(word));\n        }\n        return res;\n    }\n}"
  },
  {
    "path": "1048-longest-string-chain/NOTES.md",
    "content": "​"
  },
  {
    "path": "1048-longest-string-chain/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-string-chain/\">1048. Longest String Chain</a></h2><h3>Medium</h3><hr><div><p>You are given an array of <code>words</code> where each word consists of lowercase English letters.</p>\n\n<p><code>word<sub>A</sub></code> is a <strong>predecessor</strong> of <code>word<sub>B</sub></code> if and only if we can insert <strong>exactly one</strong> letter anywhere in <code>word<sub>A</sub></code> <strong>without changing the order of the other characters</strong> to make it equal to <code>word<sub>B</sub></code>.</p>\n\n<ul>\n\t<li>For example, <code>\"abc\"</code> is a <strong>predecessor</strong> of <code>\"ab<u>a</u>c\"</code>, while <code>\"cba\"</code> is not a <strong>predecessor</strong> of <code>\"bcad\"</code>.</li>\n</ul>\n\n<p>A <strong>word chain</strong><em> </em>is a sequence of words <code>[word<sub>1</sub>, word<sub>2</sub>, ..., word<sub>k</sub>]</code> with <code>k &gt;= 1</code>, where <code>word<sub>1</sub></code> is a <strong>predecessor</strong> of <code>word<sub>2</sub></code>, <code>word<sub>2</sub></code> is a <strong>predecessor</strong> of <code>word<sub>3</sub></code>, and so on. A single word is trivially a <strong>word chain</strong> with <code>k == 1</code>.</p>\n\n<p>Return <em>the <strong>length</strong> of the <strong>longest possible word chain</strong> with words chosen from the given list of </em><code>words</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]\n<strong>Output:</strong> 4\n<strong>Explanation</strong>: One of the longest word chains is [\"a\",\"<u>b</u>a\",\"b<u>d</u>a\",\"bd<u>c</u>a\"].\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> All the words can be put in a word chain [\"xb\", \"xb<u>c</u>\", \"<u>c</u>xbc\", \"<u>p</u>cxbc\", \"pcxbc<u>f</u>\"].\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"abcd\",\"dbqca\"]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 16</code></li>\n\t<li><code>words[i]</code> only consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "105-construct-binary-tree-from-preorder-and-inorder-traversal/105-construct-binary-tree-from-preorder-and-inorder-traversal.java",
    "content": "class Solution {\n    int preorderIndex;\n    Map<Integer, Integer> inorderIndexMap;\n    public TreeNode buildTree(int[] preorder, int[] inorder) {\n        preorderIndex = 0;\n        // build a hashmap to store value -> its index relations\n        inorderIndexMap = new HashMap<>();\n        for (int i = 0; i < inorder.length; i++) {\n            inorderIndexMap.put(inorder[i], i);\n        }\n\n        return arrayToTree(preorder, 0, preorder.length - 1);\n    }\n\n    private TreeNode arrayToTree(int[] preorder, int left, int right) {\n        // if there are no elements to construct the tree\n        if (left > right) return null;\n\n        // select the preorder_index element as the root and increment it\n        int rootValue = preorder[preorderIndex++];\n        TreeNode root = new TreeNode(rootValue);\n\n        // build left and right subtree\n        // excluding inorderIndexMap[rootValue] element because it's the root\n        root.left = arrayToTree(preorder, left, inorderIndexMap.get(rootValue) - 1);\n        root.right = arrayToTree(preorder, inorderIndexMap.get(rootValue) + 1, right);\n        return root;\n    }\n}"
  },
  {
    "path": "105-construct-binary-tree-from-preorder-and-inorder-traversal/NOTES.md",
    "content": "​"
  },
  {
    "path": "105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/\">105. Construct Binary Tree from Preorder and Inorder Traversal</a></h2><h3>Medium</h3><hr><div><p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree.jpg\" style=\"width: 277px; height: 302px;\">\n<pre><strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\n<strong>Output:</strong> [3,9,20,null,null,15,7]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> preorder = [-1], inorder = [-1]\n<strong>Output:</strong> [-1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= preorder.length &lt;= 3000</code></li>\n\t<li><code>inorder.length == preorder.length</code></li>\n\t<li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li>\n\t<li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li>\n\t<li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li>\n\t<li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li>\n\t<li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li>\n</ul>\n</div>"
  },
  {
    "path": "1061-lexicographically-smallest-equivalent-string/1061-lexicographically-smallest-equivalent-string.java",
    "content": "class Solution {\n    int representative[] = new int[26];\n\n    // Returns the root representative of the component.\n    int find(int x) {\n        if (representative[x] == x) {\n            return x;\n        }\n\n        return representative[x] = find(representative[x]);\n    }\n\n    // Perform union if x and y aren't in the same component.\n    void performUnion(int x, int y) {\n        x = find(x);\n        y = find(y);\n\n        if (x == y) {\n            return;\n        }\n\n        // Make the smaller character representative.\n        if (x < y) {\n            representative[y] = x;\n        } else {\n            representative[x] = y;\n        }\n    }\n\n    public String smallestEquivalentString(String s1, String s2, String baseStr) {\n        // Make each character representative of itself.\n        for (int i = 0; i < 26; i++) {\n            representative[i] = i;\n        }\n\n        // Perform union merge for all the edges.\n        for (int i = 0; i < s1.length(); i++) {\n            performUnion(s1.charAt(i) - 'a', s2.charAt(i) - 'a');\n        }\n\n        String ans = \"\";\n        // Create the answer string with final mappings.\n        for (char c : baseStr.toCharArray()) {\n            ans += (char)(find(c - 'a') + 'a');\n        }\n\n        return ans;\n    }\n}"
  },
  {
    "path": "1061-lexicographically-smallest-equivalent-string/NOTES.md",
    "content": "​"
  },
  {
    "path": "1061-lexicographically-smallest-equivalent-string/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/lexicographically-smallest-equivalent-string/\">1061. Lexicographically Smallest Equivalent String</a></h2><h3>Medium</h3><hr><div><p>You are given two strings of the same length <code>s1</code> and <code>s2</code> and a string <code>baseStr</code>.</p>\n\n<p>We say <code>s1[i]</code> and <code>s2[i]</code> are equivalent characters.</p>\n\n<ul>\n\t<li>For example, if <code>s1 = \"abc\"</code> and <code>s2 = \"cde\"</code>, then we have <code>'a' == 'c'</code>, <code>'b' == 'd'</code>, and <code>'c' == 'e'</code>.</li>\n</ul>\n\n<p>Equivalent characters follow the usual rules of any equivalence relation:</p>\n\n<ul>\n\t<li><strong>Reflexivity:</strong> <code>'a' == 'a'</code>.</li>\n\t<li><strong>Symmetry:</strong> <code>'a' == 'b'</code> implies <code>'b' == 'a'</code>.</li>\n\t<li><strong>Transitivity:</strong> <code>'a' == 'b'</code> and <code>'b' == 'c'</code> implies <code>'a' == 'c'</code>.</li>\n</ul>\n\n<p>For example, given the equivalency information from <code>s1 = \"abc\"</code> and <code>s2 = \"cde\"</code>, <code>\"acd\"</code> and <code>\"aab\"</code> are equivalent strings of <code>baseStr = \"eed\"</code>, and <code>\"aab\"</code> is the lexicographically smallest equivalent string of <code>baseStr</code>.</p>\n\n<p>Return <em>the lexicographically smallest equivalent string of </em><code>baseStr</code><em> by using the equivalency information from </em><code>s1</code><em> and </em><code>s2</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s1 = \"parker\", s2 = \"morris\", baseStr = \"parser\"\n<strong>Output:</strong> \"makkek\"\n<strong>Explanation:</strong> Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i].\nThe characters in each group are equivalent and sorted in lexicographical order.\nSo the answer is \"makkek\".\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s1 = \"hello\", s2 = \"world\", baseStr = \"hold\"\n<strong>Output:</strong> \"hdld\"\n<strong>Explanation: </strong>Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r].\nSo only the second letter 'o' in baseStr is changed to 'd', the answer is \"hdld\".\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s1 = \"leetcode\", s2 = \"programs\", baseStr = \"sourcecode\"\n<strong>Output:</strong> \"aauaaaaada\"\n<strong>Explanation:</strong> We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is \"aauaaaaada\".\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s1.length, s2.length, baseStr &lt;= 1000</code></li>\n\t<li><code>s1.length == s2.length</code></li>\n\t<li><code>s1</code>, <code>s2</code>, and <code>baseStr</code> consist of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1074-number-of-submatrices-that-sum-to-target/1074-number-of-submatrices-that-sum-to-target.java",
    "content": "class Solution {\n    public int numSubmatrixSumTarget(int[][] matrix, int target) {\n        int m = matrix.length;\n        int n = matrix[0].length;\n        int res = 0;\n        \n        // traverse upper boundary\n        for (int top = 0; top < m; top++) {\n            \n            // for each upper boundary, we have a prefix sum array\n            int[] sum = new int[n];\n            \n            // traverse lower boundary\n            for (int bottom = top; bottom < m; bottom++) {\n                \n                // count the prefix sum for each column\n                for (int col = 0; col < n; col++) {\n                    sum[col] += matrix[bottom][col];\n                }\n          \n                // traverse left and right boundary\n                for (int left = 0; left < n; left++) {\n                    int cnt = 0;\n                    for (int right = left; right < n; right++) {\n                        cnt += sum[right];\n                        if (cnt == target) res++;\n                    }\n                }\n            }\n        }\n        return res;\n    }\n}"
  },
  {
    "path": "1074-number-of-submatrices-that-sum-to-target/NOTES.md",
    "content": "​"
  },
  {
    "path": "108-convert-sorted-array-to-binary-search-tree/108-convert-sorted-array-to-binary-search-tree.java",
    "content": "/**\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 sortedArrayToBST(int[] nums) {\n        return create(nums,0,nums.length-1);\n    }\n    TreeNode create(int[]nums,int i,int j){\n        if(j<i)return null;\n        int mid=i+(j-i)/2;\n        TreeNode node=new TreeNode(nums[mid]);\n        node.left=create(nums,i,mid-1);\n        node.right=create(nums,mid+1,j);\n        return node;\n    }\n}"
  },
  {
    "path": "108-convert-sorted-array-to-binary-search-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "108-convert-sorted-array-to-binary-search-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/\">108. Convert Sorted Array to Binary Search Tree</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a <strong>height-balanced</strong> binary search tree</em>.</p>\n\n<p>A <strong>height-balanced</strong> binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg\" style=\"width: 302px; height: 222px;\">\n<pre><strong>Input:</strong> nums = [-10,-3,0,5,9]\n<strong>Output:</strong> [0,-3,9,-10,null,5]\n<strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted:\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/btree2.jpg\" style=\"width: 302px; height: 222px;\">\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/btree.jpg\" style=\"width: 342px; height: 142px;\">\n<pre><strong>Input:</strong> nums = [1,3]\n<strong>Output:</strong> [3,1]\n<strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li>\n</ul>\n</div>"
  },
  {
    "path": "1081-smallest-subsequence-of-distinct-characters/1081-smallest-subsequence-of-distinct-characters.java",
    "content": "class Solution {\n    public String smallestSubsequence(String s) {\n        int[]freq=new int[26];\n        int[]done=new int[26];\n        for(char c:s.toCharArray()){\n            freq[c-97]++;\n        }\n        Deque<Character> stack=new ArrayDeque<>();\n        for(int i=0;i<s.length();i++){\n            char ch=s.charAt(i);\n            if(done[ch-97]==0){\n                while(stack.size()>0 && stack.peek()>ch){\n                    if(freq[stack.peek()-97]>0){\n                        char out=stack.pop();\n                        done[out-97]=0;\n                    }else{\n                        break;\n                    }\n                }\n                done[ch-97]=1;\n                stack.push(ch);\n            }\n            freq[ch-97]--;\n        }\n        StringBuilder sb=new StringBuilder();\n        while(stack.size()>0){\n            sb.append(stack.pop());\n        }\n        return sb.reverse().toString();\n    }\n}"
  },
  {
    "path": "1081-smallest-subsequence-of-distinct-characters/NOTES.md",
    "content": "​"
  },
  {
    "path": "1081-smallest-subsequence-of-distinct-characters/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/\">1081. Smallest Subsequence of Distinct Characters</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, return <em>the lexicographically smallest subsequence of</em> <code>s</code> <em>that contains all the distinct characters of</em> <code>s</code> <em>exactly once</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"bcabc\"\n<strong>Output:</strong> \"abc\"\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"cbacdcbc\"\n<strong>Output:</strong> \"acdb\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Note:</strong> This question is the same as 316: <a href=\"https://leetcode.com/problems/remove-duplicate-letters/\" target=\"_blank\">https://leetcode.com/problems/remove-duplicate-letters/</a></div>"
  },
  {
    "path": "1091-shortest-path-in-binary-matrix/1091-shortest-path-in-binary-matrix.java",
    "content": "class Solution {\n   public int shortestPathBinaryMatrix(int[][] grid) {\n        int n=grid.length;\n        if(grid[0][0]==1||grid[n-1][n-1]==1)return -1;\n        if(n==1&&grid[0][0]==0)return 1;\n        grid[0][0]=1;\n        List<int[]> pos=new ArrayList<>();\n        pos.add(new int[]{0,0});\n        check(grid,pos);\n        if(grid[n-1][n-1]==0)return -1;\n        return grid[n-1][n-1];\n        \n    }\n    public void check(int[][] grid,List<int[]> pos){\n        int n=grid.length;\n        List<int[]> newpos=new ArrayList<>();\n        for(int[] p:pos){\n            int i=p[0];\n            int j=p[1];\n            int curdis=grid[i][j]+1;\n            if(i>0&&j>0&&grid[i-1][j-1]==0){\n                grid[i-1][j-1]=curdis;\n                newpos.add(new int[]{i-1,j-1});\n            }\n            if(i<n-1&&j>0&&grid[i+1][j-1]==0){\n                grid[i+1][j-1]=curdis;\n                newpos.add(new int[]{i+1,j-1});\n            }\n            if(i>0&&j<n-1&&grid[i-1][j+1]==0){\n                grid[i-1][j+1]=curdis;\n                newpos.add(new int[]{i-1,j+1});\n            }\n            if(i<n-1&&j<n-1&&grid[i+1][j+1]==0){\n                grid[i+1][j+1]=curdis;\n                newpos.add(new int[]{i+1,j+1});\n            }\n            if(j>0&&grid[i][j-1]==0){\n                grid[i][j-1]=curdis;\n                newpos.add(new int[]{i,j-1});\n            }\n            if(j<n-1&&grid[i][j+1]==0){\n                grid[i][j+1]=curdis;\n                newpos.add(new int[]{i,j+1});\n            }\n            if(i<n-1&&grid[i+1][j]==0){\n                grid[i+1][j]=curdis;\n                newpos.add(new int[]{i+1,j});\n            }\n            if(i>0&&grid[i-1][j]==0){\n                grid[i-1][j]=curdis;\n                newpos.add(new int[]{i-1,j});\n            }\n        }\n        if(!newpos.isEmpty())check(grid,newpos);\n        \n        \n    }\n}"
  },
  {
    "path": "1091-shortest-path-in-binary-matrix/NOTES.md",
    "content": "​"
  },
  {
    "path": "1091-shortest-path-in-binary-matrix/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/shortest-path-in-binary-matrix/\">1091. Shortest Path in Binary Matrix</a></h2><h3>Medium</h3><hr><div><p>Given an <code>n x n</code> binary matrix <code>grid</code>, return <em>the length of the shortest <strong>clear path</strong> in the matrix</em>. If there is no clear path, return <code>-1</code>.</p>\n\n<p>A <strong>clear path</strong> in a binary matrix is a path from the <strong>top-left</strong> cell (i.e., <code>(0, 0)</code>) to the <strong>bottom-right</strong> cell (i.e., <code>(n - 1, n - 1)</code>) such that:</p>\n\n<ul>\n\t<li>All the visited cells of the path are <code>0</code>.</li>\n\t<li>All the adjacent cells of the path are <strong>8-directionally</strong> connected (i.e., they are different and they share an edge or a corner).</li>\n</ul>\n\n<p>The <strong>length of a clear path</strong> is the number of visited cells of this path.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/example1_1.png\" style=\"width: 500px; height: 234px;\">\n<pre><strong>Input:</strong> grid = [[0,1],[1,0]]\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/example2_1.png\" style=\"height: 216px; width: 500px;\">\n<pre><strong>Input:</strong> grid = [[0,0,0],[1,1,0],[1,1,0]]\n<strong>Output:</strong> 4\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> grid = [[1,0,0],[1,1,0],[1,1,0]]\n<strong>Output:</strong> -1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= n &lt;= 100</code></li>\n\t<li><code>grid[i][j] is 0 or 1</code></li>\n</ul>\n</div>"
  },
  {
    "path": "11-container-with-most-water/11-container-with-most-water.java",
    "content": "class Solution {\n    public int maxArea(int[] height) {\n        int result = 0;\n        int left = 0;\n        int right = height.length - 1;\n        while (left < right) {\n            int hLeft = height[left];\n            int hRight = height[right];\n            \n            result = Math.max(result, Math.min(hLeft, hRight) * (right - left));\n            \n            if (hLeft < hRight) {\n                while (left < right && height[left] <= hLeft) {\n                    left++;                    \n                }\n            } else {\n                while (left < right && height[right] <= hRight) {\n                    right--;                    \n                }\n            }\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "11-container-with-most-water/Container_With_Most_Water.cpp",
    "content": "class Solution {\npublic:\n    int maxArea(vector<int>& h) {\n        int maxi = 0;\n        int i=0,j=h.size()-1;\n        while(i<j){\n            maxi = max((min(h[i],h[j])*(j-i)),maxi);\n            if(h[i]<h[j]){\n                i++;\n            }\n            else{\n                j--;\n            }\n        }\n        return maxi;\n    }\n};\n"
  },
  {
    "path": "11-container-with-most-water/NOTES.md",
    "content": "​"
  },
  {
    "path": "11-container-with-most-water/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/container-with-most-water/\">11. Container With Most Water</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p>\n\n<p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p>\n\n<p>Return <em>the maximum amount of water a container can store</em>.</p>\n\n<p><strong>Notice</strong> that you may not slant the container.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg\" style=\"width: 600px; height: 287px;\">\n<pre><strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7]\n<strong>Output:</strong> 49\n<strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> height = [1,1]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == height.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "112-path-sum/112-path-sum.java",
    "content": "class Solution{\n    public boolean hasPathSum(TreeNode root, int targetSum) {\n        if(root==null){\n            return false;\n        }\n        if(root.left==null && root.right==null && targetSum-root.val==0){\n            return true;\n        }\n        \n        return hasPathSum(root.left, targetSum-root.val) || hasPathSum(root.right, targetSum-root.val);\n            \n    }\n}    \n    "
  },
  {
    "path": "112-path-sum/NOTES.md",
    "content": "​"
  },
  {
    "path": "112-path-sum/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/path-sum/\">112. Path Sum</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p>\n\n<p>A <strong>leaf</strong> is a node with no children.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg\" style=\"width: 500px; height: 356px;\">\n<pre><strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The root-to-leaf path with the target sum is shown.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg\">\n<pre><strong>Input:</strong> root = [1,2,3], targetSum = 5\n<strong>Output:</strong> false\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [], targetSum = 0\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= targetSum &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "113 Path Sum II med s24.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    vector<vector<int>> ans;\n    void dfs(TreeNode* node, vector<int>& path, int remainingSum) {\n        if (!node) return;\n        path.push_back(node-> val);\n        if (!node->left && !node->right && remainingSum == node->val) ans.push_back(path);\n        dfs(node-> left, path, remainingSum - node-> val);\n        dfs(node-> right, path, remainingSum - node-> val);\n        // backtrack \n        path.pop_back();\n    }\n    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {\n        // used to store current route\n        vector<int> path;\n        // dfs from the root\n        dfs(root, path, targetSum);\n        return ans;  \n    }\n};"
  },
  {
    "path": "113-Path-Sum-II.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>>ans;\n    void dfs(vector<int>&curr,TreeNode* root,int target)\n    {\n        if(!root)\n            return;\n        curr.push_back(root->val);\n        if(root->val==target && !root->left && !root->right)\n            ans.push_back(curr);\n        dfs(curr,root->left,target-root->val);\n        dfs(curr,root->right,target-root->val);\n        curr.pop_back();\n    }\n    ///////\n    vector<vector<int>> pathSum(TreeNode* root, int targetSum) \n    {\n        vector<int>curr;\n        dfs(curr,root,targetSum);\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "113-path-sum-ii/113-path-sum-ii.java",
    "content": "class Solution {\n    public void check(TreeNode root,int T,List<Integer> curr,List<List<Integer>> list){\n        if(root == null){\n            return;\n        }\n        if(T-root.val==0 && root.left == root.right){\n            curr.add(root.val);\n            list.add(new ArrayList<>(curr));\n            curr.remove(curr.size()-1);\n            return;\n        }\n        curr.add(root.val);\n        check(root.left,T-root.val,curr,list);\n        check(root.right,T-root.val,curr,list);\n        curr.remove(curr.size()-1);\n        \n    }\n    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {\n        List<List<Integer>> list = new ArrayList<>();\n        List<Integer> curr = new ArrayList<>();\n        check(root,targetSum,curr,list);\n        return list;\n    }\n}"
  },
  {
    "path": "113-path-sum-ii/113. Path Sum II.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> v;    \n    void dfs(TreeNode* root, int targetSum, vector<int> &t){\n        if(!root) return;\n        t.push_back(root->val);\n        targetSum -= root->val;\n        if(!root->left and !root->right and targetSum == 0){\n            v.push_back(t);            \n        }else{\n            dfs(root->left, targetSum, t);\n            dfs(root->right, targetSum, t);\n        }\n        // backtracking\n        t.pop_back();\n        return;\n    }\n    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {        \n        if(!root) return {};   \n        vector<int> t;\n        dfs(root, targetSum, t);\n        return v;\n    }\n};\n"
  },
  {
    "path": "113-path-sum-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "113-path-sum-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/path-sum-ii/\">113. Path Sum II</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>all <strong>root-to-leaf</strong> paths where the sum of the node values in the path equals </em><code>targetSum</code><em>. Each path should be returned as a list of the node <strong>values</strong>, not node references</em>.</p>\n\n<p>A <strong>root-to-leaf</strong> path is a path starting from the root and ending at any leaf node. A <strong>leaf</strong> is a node with no children.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg\" style=\"width: 500px; height: 356px;\">\n<pre><strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\n<strong>Output:</strong> [[5,4,11,2],[5,8,4,5]]\n<strong>Explanation:</strong> There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg\" style=\"width: 212px; height: 181px;\">\n<pre><strong>Input:</strong> root = [1,2,3], targetSum = 5\n<strong>Output:</strong> []\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [1,2], targetSum = 0\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= targetSum &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "114-flatten-binary-tree-to-linked-list/114-flatten-binary-tree-to-linked-list.java",
    "content": "/**\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 void flatten(TreeNode root) {\n        if(root==null)return;\n        flatten(root.left);\n        TreeNode righty=root.right;\n        root.right=root.left;\n        root.left=null;\n        flatten(righty);\n        TreeNode temp=root;\n        while(temp.right!=null){\n            temp=temp.right;\n        }\n        temp.right=righty;\n    }\n}"
  },
  {
    "path": "114-flatten-binary-tree-to-linked-list/NOTES.md",
    "content": "​"
  },
  {
    "path": "114-flatten-binary-tree-to-linked-list/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/flatten-binary-tree-to-linked-list/\">114. Flatten Binary Tree to Linked List</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, flatten the tree into a \"linked list\":</p>\n\n<ul>\n\t<li>The \"linked list\" should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li>\n\t<li>The \"linked list\" should be in the same order as a <a href=\"https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR\" target=\"_blank\"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg\" style=\"width: 500px; height: 226px;\">\n<pre><strong>Input:</strong> root = [1,2,5,3,4,null,6]\n<strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [0]\n<strong>Output:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?</div>"
  },
  {
    "path": "114-flatten-binary-tree-to-linked-list/SolutionCode.cpp",
    "content": "class Solution\n{\n    public:\n    Node* helper(Node* root){\n        if(!root) return NULL;\n        \n        if(!root->left && !root->right) return root;\n        \n        Node* l = helper(root->left);\n        Node* r = helper(root->right);\n        \n        root->left = NULL;\n        if(l){\n            root->right = l;\n            while(l->right){\n                l = l->right;\n            }\n            l-> right = r;\n        }\n        else if(r) root->right = r;\n        \n        return root;\n    }\n    void flatten(Node *root)\n    {\n        helper(root); \n    }\n};\n"
  },
  {
    "path": "1143-longest-common-subsequence/1143-longest-common-subsequence.java",
    "content": "class Solution {\n    public int longestCommonSubsequence(String s1, String s2) {\n        int[][]dp=new int[s1.length()+1][s2.length()+1];\n        for(int i=1;i<=s1.length();i++){\n            for(int j=1;j<=s2.length();j++){\n                if(s1.charAt(i-1)==s2.charAt(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        }\n        return dp[s1.length()][s2.length()];\n    }\n}"
  },
  {
    "path": "1143-longest-common-subsequence/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-common-subsequence/\">1143. Longest Common Subsequence</a></h2><h3>Medium</h3><hr><div><p>Given two strings <code>text1</code> and <code>text2</code>, return <em>the length of their longest <strong>common subsequence</strong>. </em>If there is no <strong>common subsequence</strong>, return <code>0</code>.</p>\n\n<p>A <strong>subsequence</strong> 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.</p>\n\n<ul>\n\t<li>For example, <code>\"ace\"</code> is a subsequence of <code>\"abcde\"</code>.</li>\n</ul>\n\n<p>A <strong>common subsequence</strong> of two strings is a subsequence that is common to both strings.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> text1 = \"abcde\", text2 = \"ace\" \n<strong>Output:</strong> 3  \n<strong>Explanation:</strong> The longest common subsequence is \"ace\" and its length is 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> text1 = \"abc\", text2 = \"abc\"\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The longest common subsequence is \"abc\" and its length is 3.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> text1 = \"abc\", text2 = \"def\"\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> There is no such common subsequence, so the result is 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= text1.length, text2.length &lt;= 1000</code></li>\n\t<li><code>text1</code> and <code>text2</code> consist of only lowercase English characters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1155-number-of-dice-rolls-with-target-sum/1155-number-of-dice-rolls-with-target-sum.java",
    "content": "class Solution {\n    static int MOD = (int)1e9 + 7;\n    int helper(int n,int t,int k,int dp[][]){\n        if(n < 0 || t < 0) return 0;\n        if(n == 0 && t == 0) return 1;\n        if(dp[n][t] != -1) return dp[n][t];\n        int c_ans = 0;\n        for(int i = 1;i <= k;i++){\n            c_ans = (c_ans + helper(n - 1,t - i,k,dp)) % MOD;\n        }\n        return dp[n][t] = c_ans;\n    }\n    public int numRollsToTarget(int n, int k, int target) {\n        int dp[][] =  new int[n + 1][target + 1];\n        for(var a:dp) Arrays.fill(a,-1);\n        return helper(n,target,k,dp);\n    }\n}"
  },
  {
    "path": "1155-number-of-dice-rolls-with-target-sum/NOTES.md",
    "content": "​"
  },
  {
    "path": "1155-number-of-dice-rolls-with-target-sum/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/\">1155. Number of Dice Rolls With Target Sum</a></h2><h3>Medium</h3><hr><div><p>You have <code>n</code> dice and each die has <code>k</code> faces numbered from <code>1</code> to <code>k</code>.</p>\n\n<p>Given three integers <code>n</code>, <code>k</code>, and <code>target</code>, return <em>the number of possible ways (out of the </em><code>k<sup>n</sup></code><em> total ways) </em><em>to roll the dice so the sum of the face-up numbers equals </em><code>target</code>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 1, k = 6, target = 3\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> You throw one die with 6 faces.\nThere is only one way to get a sum of 3.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 2, k = 6, target = 7\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 30, k = 30, target = 500\n<strong>Output:</strong> 222616187\n<strong>Explanation:</strong> The answer must be returned modulo 10<sup>9</sup> + 7.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n, k &lt;= 30</code></li>\n\t<li><code>1 &lt;= target &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "117-populating-next-right-pointers-in-each-node-ii/117-populating-next-right-pointers-in-each-node-ii.java",
    "content": "class Solution {\n    public Node connect(Node root) {\n        if (root == null || (root.left == null && root.right == null) ) {\n            return root;\n        }\n        \n        // connect left child to right child\n        if (root.left != null && root.right != null) {\n            root.left.next = root.right;\n        }\n        \n        // connect right child (or left if right is abasent) to child of next nodes.\n        Node lNode = (root.right == null) ? root.left : root.right;\n        \n        Node next = root.next;\n        while (next != null && next.left == null && next.right == null) {\n            next = next.next;\n        }\n\n        if (next != null) {\n            lNode.next = (next.left != null) ? next.left : next.right;\n        }\n        \n        // process right child first\n        connect(root.right);\n        connect(root.left);\n        \n        return root;\n    }\n}"
  },
  {
    "path": "117-populating-next-right-pointers-in-each-node-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "117-populating-next-right-pointers-in-each-node-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/\">117. Populating Next Right Pointers in Each Node II</a></h2><h3>Medium</h3><hr><div><p>Given a binary tree</p>\n\n<pre>struct Node {\n  int val;\n  Node *left;\n  Node *right;\n  Node *next;\n}\n</pre>\n\n<p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p>\n\n<p>Initially, all next pointers are set to <code>NULL</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/02/15/117_sample.png\" style=\"width: 500px; height: 171px;\">\n<pre><strong>Input:</strong> root = [1,2,3,4,5,null,7]\n<strong>Output:</strong> [1,#,2,3,#,4,5,7,#]\n<strong>Explanation: </strong>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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 6000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow-up:</strong></p>\n\n<ul>\n\t<li>You may only use constant extra space.</li>\n\t<li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li>\n</ul>\n</div>"
  },
  {
    "path": "118-pascals-triangle/118-pascals-triangle.java",
    "content": "class Solution {\n    public List<List<Integer>> generate(int numRows) {\n        List<List<Integer>> triangle = new ArrayList<>();\n        \n        triangle.add(new ArrayList<Integer>());\n        triangle.get(0).add(1);\n        \n        for(int i=1; i<numRows; i++) {\n            List<Integer> row = new ArrayList<>();\n            List<Integer> previousRow = triangle.get(i-1);\n            \n            //first element is always 1\n            row.add(1);\n            \n            for(int j=1; j<i; j++) {\n                //Add two cells directly above the current row\n                row.add(previousRow.get(j-1) + previousRow.get(j));\n            }\n            \n            //last element of a row is also 1\n            row.add(1);\n            \n            triangle.add(row);\n        }\n        return triangle;\n    }\n}"
  },
  {
    "path": "118-pascals-triangle/NOTES.md",
    "content": "​"
  },
  {
    "path": "118-pascals-triangle/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/pascals-triangle/\">118. Pascal's Triangle</a></h2><h3>Easy</h3><hr><div><p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal's triangle</strong>.</p>\n\n<p>In <strong>Pascal's triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p>\n<img alt=\"\" src=\"https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif\" style=\"height:240px; width:260px\">\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> numRows = 5\n<strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> numRows = 1\n<strong>Output:</strong> [[1]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= numRows &lt;= 30</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1192-critical-connections-in-a-network/1192-critical-connections-in-a-network.java",
    "content": "class Solution {\n    int[] disc, low;\n    int time = 1;\n    List<List<Integer>> ans = new ArrayList<>();\n    Map<Integer,List<Integer>> edgeMap = new HashMap<>();\n    public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {\n        disc = new int[n];\n        low = new int[n];\n        for (int i = 0; i < n; i++)\n            edgeMap.put(i, new ArrayList<Integer>());\n        for (List<Integer> conn : connections) {\n            edgeMap.get(conn.get(0)).add(conn.get(1));\n            edgeMap.get(conn.get(1)).add(conn.get(0));\n        }\n        dfs(0, -1);\n        return ans;\n    }\n    public void dfs(int curr, int prev) {\n        disc[curr] = low[curr] = time++;\n        for (int next : edgeMap.get(curr)) {\n            if (disc[next] == 0) {\n                dfs(next, curr);\n                low[curr] = Math.min(low[curr], low[next]);\n            } else if (next != prev)\n                low[curr] = Math.min(low[curr], disc[next]);\n            if (low[next] > disc[curr]) \n                ans.add(Arrays.asList(curr, next));\n        }\n    }\n}"
  },
  {
    "path": "1192-critical-connections-in-a-network/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/critical-connections-in-a-network/\">1192. Critical Connections in a Network</a></h2><h3>Hard</h3><hr><div><p>There are <code>n</code> servers numbered from <code>0</code> to <code>n - 1</code> connected by undirected server-to-server <code>connections</code> forming a network where <code>connections[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> represents a connection between servers <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code>. Any server can reach other servers directly or indirectly through the network.</p>\n\n<p>A <em>critical connection</em> is a connection that, if removed, will make some servers unable to reach some other server.</p>\n\n<p>Return all critical connections in the network in any order.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/09/03/1537_ex1_2.png\" style=\"width: 198px; height: 248px;\">\n<pre><strong>Input:</strong> n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\n<strong>Output:</strong> [[1,3]]\n<strong>Explanation:</strong> [[3,1]] is also accepted.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 2, connections = [[0,1]]\n<strong>Output:</strong> [[0,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>n - 1 &lt;= connections.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li>There are no repeated connections.</li>\n</ul>\n</div>"
  },
  {
    "path": "12-integer-to-roman/12-Leetcode-Integer-to-roman.cpp",
    "content": "class Solution {\npublic:\n    string intToRoman(int num) {\n        vector<pair<int, string>> vp{{1, \"I\"}, {4, \"IV\"}, {5, \"V\"}, {9, \"IX\"}, {10, \"X\"}, {40, \"XL\"}, {50, \"L\"}, {90, \"XC\"}, {100, \"C\"}, {400, \"CD\"}, {500, \"D\"}, {900, \"CM\"}, {1000, \"M\"}};\n        string s = \"\";\n        int j = vp.size() - 1;\n        while(num != 0){            \n            for(int i = j; i >= 0; i--){\n                if(vp[i].first <= num){\n                    s += vp[i].second;\n                    num -= vp[i].first;\n                    j = i;\n                    break;\n                }\n            }\n        }\n        return s;\n    }\n};\n"
  },
  {
    "path": "12-integer-to-roman/12-integer-to-roman.java",
    "content": "public class Solution {\n    public String intToRoman(int A) {\n        StringBuilder sb=new StringBuilder();\n        while(A!=0){\n            String str=Integer.toString(A);\n            String num=\"\";\n            for(int i=str.length()-1;i>=0;i--){\n                if(str.charAt(i)!='0'){\n                    num=str.substring(i);\n                    break;\n                }\n            }\n            String roman=getRoman(Integer.parseInt(num));\n            sb.insert(0,roman);\n            A-=Integer.parseInt(num);\n        }\n        return sb.toString();\n    }\n    public String getRoman(int a){\n        switch(a){\n            case 1:\n                return \"I\";\n            case 2:\n                return \"II\";\n            case 3:\n                return \"III\";\n            case 4:\n                return \"IV\";\n            case 5:\n                return \"V\";\n            case 6:\n                return \"VI\";\n            case 7:\n                return \"VII\";\n            case 8:\n                return \"VIII\";\n            case 9:\n                return \"IX\";\n            case 10:\n                return \"X\";\n            case 20:\n                return \"XX\";\n            case 30:\n                return \"XXX\";\n            case 40:\n                return \"XL\";\n            case 50:\n                return \"L\";\n            case 60:\n                return \"LX\";\n            case 70:\n                return \"LXX\";\n            case 80:\n                return \"LXXX\";\n            case 90:\n                return \"XC\";\n            case 100:\n                return \"C\";\n            case 200:\n                return \"CC\";\n            case 300:\n                return \"CCC\";\n            case 400:\n                return \"CD\";\n            case 500:\n                return \"D\";\n            case 600:\n                return \"DC\";\n            case 700:\n                return \"DCC\";\n            case 800:\n                return \"DCCC\";\n            case 900:\n                return \"CM\";\n            case 1000:\n                return \"M\";\n            case 2000:\n                return \"MM\";\n            case 3000:\n                return \"MMM\";\n        }\n        return \"\";\n    }\n}"
  },
  {
    "path": "12-integer-to-roman/NOTES.md",
    "content": "​"
  },
  {
    "path": "12-integer-to-roman/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/integer-to-roman/\">12. Integer to Roman</a></h2><h3>Medium</h3><hr><div><p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p>\n\n<pre><strong>Symbol</strong>       <strong>Value</strong>\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000</pre>\n\n<p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two one's added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p>\n\n<p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p>\n\n<ul>\n\t<li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li>\n\t<li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li>\n\t<li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li>\n</ul>\n\n<p>Given an integer, convert it to a roman numeral.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> num = 3\n<strong>Output:</strong> \"III\"\n<strong>Explanation:</strong> 3 is represented as 3 ones.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> num = 58\n<strong>Output:</strong> \"LVIII\"\n<strong>Explanation:</strong> L = 50, V = 5, III = 3.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> num = 1994\n<strong>Output:</strong> \"MCMXCIV\"\n<strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt;= 3999</code></li>\n</ul>\n</div>"
  },
  {
    "path": "120-triangle/120-triangle.java",
    "content": "class Solution {\n    public int minimumTotal(List<List<Integer>> list) {\n        int sz=list.size();\n        if(sz==1)\n            return list.get(0).get(0);\n        int dp[]=new int[sz+1];\n        for(int row=sz-1;row>=0;row--)\n        {\n            int len=list.get(row).size();\n            for(int col=0;col<len;col++)\n            {\n                dp[col]=Math.min(dp[col],dp[col+1])+list.get(row).get(col);\n            }\n        }\n        return dp[0];\n    }\n}"
  },
  {
    "path": "120-triangle/NOTES.md",
    "content": "​"
  },
  {
    "path": "120-triangle/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/triangle/\">120. Triangle</a></h2><h3>Medium</h3><hr><div><p>Given a <code>triangle</code> array, return <em>the minimum path sum from top to bottom</em>.</p>\n\n<p>For each step, you may move to an adjacent number of the row below. More formally, if you are on index <code>i</code> on the current row, you may move to either index <code>i</code> or index <code>i + 1</code> on the next row.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\n<strong>Output:</strong> 11\n<strong>Explanation:</strong> The triangle looks like:\n   <u>2</u>\n  <u>3</u> 4\n 6 <u>5</u> 7\n4 <u>1</u> 8 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> triangle = [[-10]]\n<strong>Output:</strong> -10\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= triangle.length &lt;= 200</code></li>\n\t<li><code>triangle[0].length == 1</code></li>\n\t<li><code>triangle[i].length == triangle[i - 1].length + 1</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you&nbsp;do this using only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?</div>"
  },
  {
    "path": "1207-unique-number-of-occurrences/1207-unique-number-of-occurrences.java",
    "content": "class Solution {\n    public boolean uniqueOccurrences(int[] arr) {\n\t\tint min = Integer.MAX_VALUE;\n\t\tint max = Integer.MIN_VALUE;\n\n\t\tfor (int num : arr) {\n\t\t\tmin = Math.min(min, num);\n\t\t\tmax = Math.max(max, num);\n\t\t}\n\n\t\tint[] frequency = new int[max - min + 1];\n\t\tboolean[] frequency2 = new boolean[arr.length + 1];\n\n\t\tfor (int num : arr) {\n\t\t\tfrequency[num - min]++;\n\t\t}\n\n\t\tfor (int num : frequency) {\n\t\t\tif (num > 0) {\n\t\t\t\tif (frequency2[num]) return false;\n\n\t\t\t\tfrequency2[num]=true;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n    }\n}"
  },
  {
    "path": "1207-unique-number-of-occurrences/NOTES.md",
    "content": "​"
  },
  {
    "path": "1207-unique-number-of-occurrences/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/unique-number-of-occurrences/\">1207. Unique Number of Occurrences</a></h2><h3>Easy</h3><hr><div><p>Given an array of integers <code>arr</code>, return <code>true</code> if the number of occurrences of each value in the array is <strong>unique</strong>, or <code>false</code> otherwise.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> arr = [1,2,2,1,1,3]\n<strong>Output:</strong> true\n<strong>Explanation:</strong>&nbsp;The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> arr = [1,2]\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> arr = [-3,0,1,-3,1,1,1,-3,10,0]\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= arr.length&nbsp;&lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= arr[i] &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1209-remove-all-adjacent-duplicates-in-string-ii/1209-remove-all-adjacent-duplicates-in-string-ii.java",
    "content": "class Solution {\n    public String removeDuplicates(String s, int k) {\n        int w = 0;\n        int n = s.length();\n        int []count = new int[n];\n        char[] ar = s.toCharArray();\n        for(int i=0;i<n;i++){\n            ar[w]=ar[i];          \n            if(w==0||ar[w-1]!=ar[w]){\n                count[w]=1;\n            }else{\n                count[w]=count[w-1]+1;\n                if(count[w]==k){\n                    w=w-k;\n                }\n            }\n            w++;\n        }\n        \n        return new String(ar, 0, w);\n    }\n}"
  },
  {
    "path": "1209-remove-all-adjacent-duplicates-in-string-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "1209-remove-all-adjacent-duplicates-in-string-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/\">1209. Remove All Adjacent Duplicates in String II</a></h2><h3>Medium</h3><hr><div><p>You are given a string <code>s</code> and an integer <code>k</code>, a <code>k</code> <strong>duplicate removal</strong> consists of choosing <code>k</code> adjacent and equal letters from <code>s</code> and removing them, causing the left and the right side of the deleted substring to concatenate together.</p>\n\n<p>We repeatedly make <code>k</code> <strong>duplicate removals</strong> on <code>s</code> until we no longer can.</p>\n\n<p>Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"abcd\", k = 2\n<strong>Output:</strong> \"abcd\"\n<strong>Explanation: </strong>There's nothing to delete.</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"deeedbbcccbdaa\", k = 3\n<strong>Output:</strong> \"aa\"\n<strong>Explanation: \n</strong>First delete \"eee\" and \"ccc\", get \"ddbbbdaa\"\nThen delete \"bbb\", get \"dddaa\"\nFinally delete \"ddd\", get \"aa\"</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"pbbcggttciiippooaais\", k = 2\n<strong>Output:</strong> \"ps\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>2 &lt;= k &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> only contains lower case English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1220-count-vowels-permutation/1220-count-vowels-permutation.java",
    "content": "class Solution {\n    public int countVowelPermutation(int n) {\n        int mod=(int)Math.pow(10,9)+7;\n        int[]dp=new int[5];\n        for(int i=0;i<5;i++){\n            dp[i]=1;\n        }\n        for(int level=2;level<=n;level++){\n            int a= ((dp[1]+ dp[2])%mod +dp[4])%mod;\n            int e= (dp[0] + dp[2])%mod;\n            int i= (dp[1] + dp[3])%mod;\n            int o=dp[2];\n            int u=(dp[2]+ dp[3])%mod;\n            dp[0]=a;\n            dp[1]=e;\n            dp[2]=i;\n            dp[3]=o;\n            dp[4]=u;\n        }\n        return (((dp[0]+dp[1])%mod +(dp[2]+dp[3])%mod)%mod +dp[4])%mod;\n    }\n}"
  },
  {
    "path": "1220-count-vowels-permutation/NOTES.md",
    "content": "​"
  },
  {
    "path": "1220-count-vowels-permutation/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/count-vowels-permutation/\">1220. Count Vowels Permutation</a></h2><h3>Hard</h3><hr><div><p>Given an integer <code>n</code>, your task is to count how many strings of length <code>n</code> can be formed under the following rules:</p>\n\n<ul>\n\t<li>Each character is a lower case vowel&nbsp;(<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, <code>'u'</code>)</li>\n\t<li>Each vowel&nbsp;<code>'a'</code> may only be followed by an <code>'e'</code>.</li>\n\t<li>Each vowel&nbsp;<code>'e'</code> may only be followed by an <code>'a'</code>&nbsp;or an <code>'i'</code>.</li>\n\t<li>Each vowel&nbsp;<code>'i'</code> <strong>may not</strong> be followed by another <code>'i'</code>.</li>\n\t<li>Each vowel&nbsp;<code>'o'</code> may only be followed by an <code>'i'</code> or a&nbsp;<code>'u'</code>.</li>\n\t<li>Each vowel&nbsp;<code>'u'</code> may only be followed by an <code>'a'.</code></li>\n</ul>\n\n<p>Since the answer&nbsp;may be too large,&nbsp;return it modulo <code>10^9 + 7.</code></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 2\n<strong>Output:</strong> 10\n<strong>Explanation:</strong> All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".\n</pre>\n\n<p><strong>Example 3:&nbsp;</strong></p>\n\n<pre><strong>Input:</strong> n = 5\n<strong>Output:</strong> 68</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2 * 10^4</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1235-maximum-profit-in-job-scheduling/1235-maximum-profit-in-job-scheduling.java",
    "content": "class Solution {\n    class Job implements Comparable<Job>{\n        int start;\n        int end;\n        int profit;\n        Job(int start, int end, int profit) {\n            this.start = start;\n            this.end = end;\n            this.profit = profit;\n        }\n        public int compareTo(Job otherJob) {\n            return this.start - otherJob.start;\n        }\n    }\n    public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {\n        int n = startTime.length;\n        Job[] jobs = new Job[n];\n        for (int i=0; i<n; i++) {\n            jobs[i] = new Job(startTime[i], endTime[i], profit[i]);\n        }\n        Arrays.sort(jobs);\n        int[] dp = new int[n];\n        dp[n-1] = jobs[n-1].profit;\n        for (int i=n-2; i >=0; i--) {\n            dp[i] = Math.max(jobs[i].profit, dp[i+1]);\n            for (int j=i+1; j < n; j++) {\n                if (jobs[i].end <= jobs[j].start) {\n                    dp[i] = Math.max(dp[i], jobs[i].profit + dp[j]);\n                    break;\n                }\n            }\n        }\n        return dp[0];\n    }\n}"
  },
  {
    "path": "1235-maximum-profit-in-job-scheduling/NOTES.md",
    "content": "​"
  },
  {
    "path": "1235-maximum-profit-in-job-scheduling/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-profit-in-job-scheduling/\">1235. Maximum Profit in Job Scheduling</a></h2><h3>Hard</h3><hr><div><p>We have <code>n</code> jobs, where every job is scheduled to be done from <code>startTime[i]</code> to <code>endTime[i]</code>, obtaining a profit of <code>profit[i]</code>.</p>\n\n<p>You're given the <code>startTime</code>, <code>endTime</code> and <code>profit</code> arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.</p>\n\n<p>If you choose a job that ends at time <code>X</code> you will be able to start another job that starts at time <code>X</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<p><strong><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/10/10/sample1_1584.png\" style=\"width: 380px; height: 154px;\"></strong></p>\n\n<pre><strong>Input:</strong> startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]\n<strong>Output:</strong> 120\n<strong>Explanation:</strong> The subset chosen is the first and fourth job. \nTime range [1-3]+[3-6] , we get profit of 120 = 50 + 70.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<p><strong><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/10/10/sample22_1584.png\" style=\"width: 600px; height: 112px;\"> </strong></p>\n\n<pre><strong>Input:</strong> startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]\n<strong>Output:</strong> 150\n<strong>Explanation:</strong> The subset chosen is the first, fourth and fifth job. \nProfit obtained 150 = 20 + 70 + 60.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<p><strong><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/10/10/sample3_1584.png\" style=\"width: 400px; height: 112px;\"></strong></p>\n\n<pre><strong>Input:</strong> startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]\n<strong>Output:</strong> 6\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= startTime.length == endTime.length == profit.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= startTime[i] &lt; endTime[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>1 &lt;= profit[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1239-maximum-length-of-a-concatenated-string-with-unique-characters/1239-maximum-length-of-a-concatenated-string-with-unique-characters.java",
    "content": "class Solution {\n    public int solve(String strs[], int no, int a[], int index, int c) {\n        if(index==c)\n            return 0;\n        int x=no & a[index];\n        if(x==0)        \n            return Math.max(strs[index].length()+solve(strs,no^a[index],a,index+1,c),solve(strs,no,a,index+1,c));\n        else\n            return solve(strs,no,a,index+1,c);\n    }\n    public int maxLength(List<String> arr) {\n        int a[]=new int[arr.size()];int c=0;String strs[]=new String[a.length];\n        for(String s:arr) {\n            int x=0,fl=0;\n            for(char ch:s.toCharArray()) \n            {\n                int z=x|(1<<(ch-96));\n                if(x==z)\n                {\n                    fl=1;break;                \n                }\n                x=z;\n            }\n            if(fl==0)\n            {\n                a[c]=x;\n                strs[c++]=s;\n            }\n        }\n        return solve(strs,0,a,0,c);\n    }\n}"
  },
  {
    "path": "1239-maximum-length-of-a-concatenated-string-with-unique-characters/NOTES.md",
    "content": "​"
  },
  {
    "path": "1239-maximum-length-of-a-concatenated-string-with-unique-characters/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/\">1239. Maximum Length of a Concatenated String with Unique Characters</a></h2><h3>Medium</h3><hr><div><p>You are given an array of strings <code>arr</code>. A string <code>s</code> is formed by the <strong>concatenation</strong> of a <strong>subsequence</strong> of <code>arr</code> that has <strong>unique characters</strong>.</p>\n\n<p>Return <em>the <strong>maximum</strong> possible length</em> of <code>s</code>.</p>\n\n<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> arr = [\"un\",\"iq\",\"ue\"]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> arr = [\"cha\",\"r\",\"act\",\"ers\"]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> Possible longest valid concatenations are \"chaers\" (\"cha\" + \"ers\") and \"acters\" (\"act\" + \"ers\").\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> arr = [\"abcdefghijklmnopqrstuvwxyz\"]\n<strong>Output:</strong> 26\n<strong>Explanation:</strong> The only string in arr has all 26 characters.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= arr.length &lt;= 16</code></li>\n\t<li><code>1 &lt;= arr[i].length &lt;= 26</code></li>\n\t<li><code>arr[i]</code> contains only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "126-word-ladder-ii/126-word-ladder-ii.java",
    "content": "class Solution {\n    public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n        this.beginWord = beginWord;\n        this.endWord = endWord;\n        if (!sanityCheck(wordList)) {\n            return new ArrayList<>();\n        }\n        prepare(wordList);\n        minTrans();\n        return trans;\n    }\n\n    private String beginWord;\n    private String endWord;\n    private Map<String, String[]> w2p;\n    private Map<String, List<String>> p2w;\n\n    private void minTrans() {\n        Map<String, Integer> minLens = new HashMap<>();\n        Map<String, Set<String>> prev = new HashMap<>();\n        List<String> queue = new ArrayList<>();\n        int minLen = -1;\n\n        minLens.put(endWord, 0);\n        queue.add(endWord);\n        int count = 0;\n        while (count < queue.size()) {\n            String node = queue.get(count++);\n            int len = minLens.get(node) + 1;\n            if (minLen != -1 && len > minLen) {\n                break;\n            }\n\n            for (String pattern : w2p.get(node)) {\n                for (String word : p2w.get(pattern)) {\n                    if (!minLens.containsKey(word)) {\n                        minLens.put(word, len);\n                        queue.add(word);\n                        prev.put(word, new HashSet<>());\n                        if (word.equals(beginWord)) {\n                            minLen = len;\n                        }\n                    } else if (minLens.get(word) < len) {\n                        continue;\n                    }\n                    prev.get(word).add(node);\n                }\n            }\n        }\n\n        makeTrans(prev, minLens.getOrDefault(beginWord, -1));\n    }\n\n    private List<List<String>> trans;\n    private Map<String, Set<String>> paths;\n\n    private void makeTrans(Map<String, Set<String>> paths, int maxLen) {\n        this.trans = new ArrayList<>();\n        this.paths = paths;\n        if (maxLen == -1) {\n            return;\n        }\n        String[] path = new String[maxLen + 1];\n        path[0] = beginWord;\n        makeTransInternal(beginWord, 1, path);\n    }\n\n    void makeTransInternal(String start, int depth, String[] path) {\n        if (depth == path.length - 1) {\n            path[depth] = endWord;\n            List<String> result = new ArrayList<>();\n            for (String word : path) {\n                result.add(word);\n            }\n            this.trans.add(result);\n            return;\n        }\n        for (String word : paths.get(start)) {\n            path[depth] = word;\n            makeTransInternal(word, depth + 1, path);\n        }\n    }\n\n    private boolean sanityCheck(List<String> wordList) {\n        for (String word : wordList) {\n            if (word.equals(endWord)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    private void prepare(List<String> wordList) {\n        // Prepare a word -> patterns map.\n        w2p = new HashMap<>();\n        w2p.put(beginWord, getPatterns(beginWord));\n        for (String word : wordList) {\n            w2p.put(word, getPatterns(word));\n        }\n\n        // Prepare a pattern -> words map.\n        p2w = new HashMap<>();\n        for (String word : w2p.keySet()) {\n            for (String pattern : w2p.get(word)) {\n                if (!p2w.containsKey(pattern)) {\n                    p2w.put(pattern, new ArrayList<>());\n                }\n                p2w.get(pattern).add(word);\n            }\n        }\n    }\n\n    private String[] getPatterns(String word) {\n        char[] wc = word.toCharArray();\n        char original;\n        String[] patterns = new String[wc.length];\n        for (int i = 0; i < wc.length; ++i) {\n            original = wc[i];\n            wc[i] = '*';\n            patterns[i] = new String(wc);\n            wc[i] = original;\n        }\n        return patterns;\n    }\n}"
  },
  {
    "path": "126-word-ladder-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "126-word-ladder-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/word-ladder-ii/\">126. Word Ladder II</a></h2><h3>Hard</h3><hr><div><p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p>\n\n<ul>\n\t<li>Every adjacent pair of words differs by a single letter.</li>\n\t<li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li>\n\t<li><code>s<sub>k</sub> == endWord</code></li>\n</ul>\n\n<p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>all the <strong>shortest transformation sequences</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words </em><code>[beginWord, s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub>]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n<strong>Output:</strong> [[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]\n<strong>Explanation:</strong>&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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n<strong>Output:</strong> []\n<strong>Explanation:</strong> The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= beginWord.length &lt;= 5</code></li>\n\t<li><code>endWord.length == beginWord.length</code></li>\n\t<li><code>1 &lt;= wordList.length &lt;= 500</code></li>\n\t<li><code>wordList[i].length == beginWord.length</code></li>\n\t<li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li>\n\t<li><code>beginWord != endWord</code></li>\n\t<li>All the words in <code>wordList</code> are <strong>unique</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "1260-shift-2d-grid/1260-shift-2d-grid.java",
    "content": "class Solution {\n    public List<List<Integer>> shiftGrid(int[][] grid, int k) {\n        int rowCount = grid.length;// Number of rows in grid.\n        int colCount = grid[0].length;// Number of columns in grid.\n        int gridCount = rowCount * colCount;// Number of cells (i.e. values) in grid.\n        k = k % gridCount;// Limit k to max number of cells in grid. Avoid negatives in next lines.\n        int kCol = (gridCount - k) % colCount;// Column to start copying from.\n        int kRow = ((gridCount - k) % gridCount) / colCount;// Row to start copying from.\n        int[] innRow = grid[kRow];                          // Array for the row to start copying from.\n        int[][] result = new int[rowCount][colCount];       // Create result matrix, to hold shifted                                                                  values.\n        for (int r = 0; r < rowCount; r++) {  // Loop through \"to\" rows.\n            int[] outRow = result[r];// Get row array to copy into, so only                                                                    faster 1D reference in inner loop.\n            for (int c = 0; c < colCount; c++) {// Loop through \"to\" columns.\n                outRow[c] = innRow[kCol];                   // Copy value from grid to result, shifting                                                                by copying.\n                if (++kCol >= colCount) {                   // Next \"from\" column.  If at end of row...\n                    kCol = 0;                               // Then start \"from\" columns at first                                                                      column.\n                    if (++kRow >= rowCount)                 // When starting new column, next \"from\"                                                                  row.  If at end of grid...\n                        kRow = 0;                           // Then start \"from\" rows at first row.\n                    innRow = grid[kRow];                    // Get row array to copy from, so only                                                                    faster 1D reference when copying.\n                }\n            }\n        }\n        return (List)Arrays.asList(result);                 // Return result matrix, converting it to a                                                                List<List<Integer>>.\n    }\n}"
  },
  {
    "path": "1260-shift-2d-grid/NOTES.md",
    "content": "​"
  },
  {
    "path": "1260-shift-2d-grid/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/shift-2d-grid/\">1260. Shift 2D Grid</a></h2><h3>Easy</h3><hr><div><p>Given a 2D <code>grid</code> of size <code>m x n</code>&nbsp;and an integer <code>k</code>. You need to shift the <code>grid</code>&nbsp;<code>k</code> times.</p>\n\n<p>In one shift operation:</p>\n\n<ul>\n\t<li>Element at <code>grid[i][j]</code> moves to <code>grid[i][j + 1]</code>.</li>\n\t<li>Element at <code>grid[i][n - 1]</code> moves to <code>grid[i + 1][0]</code>.</li>\n\t<li>Element at <code>grid[m&nbsp;- 1][n - 1]</code> moves to <code>grid[0][0]</code>.</li>\n</ul>\n\n<p>Return the <em>2D grid</em> after applying shift operation <code>k</code> times.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/05/e1.png\" style=\"width: 400px; height: 178px;\">\n<pre><strong>Input:</strong> <code>grid</code> = [[1,2,3],[4,5,6],[7,8,9]], k = 1\n<strong>Output:</strong> [[9,1,2],[3,4,5],[6,7,8]]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/05/e2.png\" style=\"width: 400px; height: 166px;\">\n<pre><strong>Input:</strong> <code>grid</code> = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\n<strong>Output:</strong> [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> <code>grid</code> = [[1,2,3],[4,5,6],[7,8,9]], k = 9\n<strong>Output:</strong> [[1,2,3],[4,5,6],[7,8,9]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m ==&nbsp;grid.length</code></li>\n\t<li><code>n ==&nbsp;grid[i].length</code></li>\n\t<li><code>1 &lt;= m &lt;= 50</code></li>\n\t<li><code>1 &lt;= n &lt;= 50</code></li>\n\t<li><code>-1000 &lt;= grid[i][j] &lt;= 1000</code></li>\n\t<li><code>0 &lt;= k &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1268-search-suggestions-system/1268-search-suggestions-system.java",
    "content": "class Solution {\n    public List<List<String>> suggestedProducts(String[] products, String searchWord) {\n        List<List<String>> ret = new ArrayList();\n        Arrays.sort(products);\n        for(int i = 1; i <= searchWord.length(); i++) {\n            List<String> toAdd = new ArrayList();\n            String key = searchWord.substring(0,i);\n            for(String product : products) {\n                if(product.length() >= i && product.indexOf(key) == 0) {\n                    toAdd.add(product);\n                    if(toAdd.size() == 3) break;\n                }\n            }\n            ret.add(toAdd);\n        }\n        return ret;\n    }\n}"
  },
  {
    "path": "1268-search-suggestions-system/NOTES.md",
    "content": "​"
  },
  {
    "path": "1268-search-suggestions-system/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/search-suggestions-system/\">1268. Search Suggestions System</a></h2><h3>Medium</h3><hr><div><p>You are given an array of strings <code>products</code> and a string <code>searchWord</code>.</p>\n\n<p>Design a system that suggests at most three product names from <code>products</code> after each character of <code>searchWord</code> is typed. Suggested products should have common prefix with <code>searchWord</code>. If there are more than three products with a common prefix return the three lexicographically minimums products.</p>\n\n<p>Return <em>a list of lists of the suggested products after each character of </em><code>searchWord</code><em> is typed</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\n<strong>Output:</strong> [\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"]\n]\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> products = [\"havana\"], searchWord = \"havana\"\n<strong>Output:</strong> [[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> products = [\"bags\",\"baggage\",\"banner\",\"box\",\"cloths\"], searchWord = \"bags\"\n<strong>Output:</strong> [[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\"],[\"bags\"]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= products.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= products[i].length &lt;= 3000</code></li>\n\t<li><code>1 &lt;= sum(products[i].length) &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li>All the strings of <code>products</code> are <strong>unique</strong>.</li>\n\t<li><code>products[i]</code> consists of lowercase English letters.</li>\n\t<li><code>1 &lt;= searchWord.length &lt;= 1000</code></li>\n\t<li><code>searchWord</code> consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "128-longest-consecutive-sequence/128-longest-consecutive-sequence.java",
    "content": "class Solution {\n    public int longestConsecutive(int[] nums) {\n        Set<Integer> num_set = new HashSet<Integer>();\n        for (int num : nums) {\n            num_set.add(num);\n        }\n\n        int longestStreak = 0;\n\n        for (int num : nums) {\n            if (!num_set.contains(num-1)){\n                int currentNum = num;\n                int currentStreak = 1;\n\n                while (num_set.contains(currentNum+1)) {\n                    currentNum += 1;\n                    currentStreak += 1;\n                }\n\n                longestStreak = Math.max(longestStreak, currentStreak);\n            }\n        }\n\n        return longestStreak;\n    }\n}"
  },
  {
    "path": "128-longest-consecutive-sequence/NOTES.md",
    "content": "​"
  },
  {
    "path": "128-longest-consecutive-sequence/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-consecutive-sequence/\">128. Longest Consecutive Sequence</a></h2><h3>Medium</h3><hr><div><p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>\n\n<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [100,4,200,1,3,2]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]\n<strong>Output:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1293-shortest-path-in-a-grid-with-obstacles-elimination/1293-shortest-path-in-a-grid-with-obstacles-elimination.java",
    "content": "class Solution {\n    class Node {\n        int row;\n        int col;\n        int obstacles;\n\n        Node(int row, int col, int obstacles){\n            this.row = row;\n            this.col = col;\n            this.obstacles = obstacles;\n        }\n    }\n    \n    private int[][] directions = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}};\n    \n    public int shortestPath(int[][] grid, int k) {\n        int rows = grid.length;\n        int cols = grid[0].length;\n        int[][] visited = new int[rows][cols];\n        for(int i = 0; i < rows; i++) {\n            Arrays.fill(visited[i], Integer.MAX_VALUE);\n        }\n        \n        visited[0][0] = grid[0][0];\n        Queue<Node> queue = new LinkedList<>();\n        queue.add(new Node(0, 0, grid[0][0]));\n        int result = 0;\n        \n        while(!queue.isEmpty()) {\n            int size = queue.size();\n            for(int i = 0; i < size; i++) {\n                Node node = queue.poll();\n                if(node.row == rows-1 && node.col == cols-1) {\n                    return result;\n                }\n                for(int t = 0; t < directions.length; t++) {\n                    int newRow = node.row + directions[t][0];\n                    int newCol = node.col + directions[t][1];\n                    \n                    if(newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {\n\n                        int obstacles = node.obstacles + grid[newRow][newCol];\n                        if(obstacles > k) {\n                            continue;\n                        }\n                        if(visited[newRow][newCol] > obstacles) {\n                            visited[newRow][newCol] = obstacles;\n                            queue.add(new Node(newRow, newCol, obstacles));\n                        }\n                    }\n                }\n            }\n            result++;\n        }\n        return -1;\n    }\n}"
  },
  {
    "path": "1293-shortest-path-in-a-grid-with-obstacles-elimination/NOTES.md",
    "content": "​"
  },
  {
    "path": "1293-shortest-path-in-a-grid-with-obstacles-elimination/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/\">1293. Shortest Path in a Grid with Obstacles Elimination</a></h2><h3>Hard</h3><hr><div><p>You are given an <code>m x n</code> integer matrix <code>grid</code> where each cell is either <code>0</code> (empty) or <code>1</code> (obstacle). You can move up, down, left, or right from and to an empty cell in <strong>one step</strong>.</p>\n\n<p>Return <em>the minimum number of <strong>steps</strong> to walk from the upper left corner </em><code>(0, 0)</code><em> to the lower right corner </em><code>(m - 1, n - 1)</code><em> given that you can eliminate <strong>at most</strong> </em><code>k</code><em> obstacles</em>. If it is not possible to find such walk return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/09/30/short1-grid.jpg\" style=\"width: 244px; height: 405px;\">\n<pre><strong>Input:</strong> grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> \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; <strong>(3,2)</strong> -&gt; (4,2).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/09/30/short2-grid.jpg\" style=\"width: 244px; height: 245px;\">\n<pre><strong>Input:</strong> grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> We need to eliminate at least two obstacles to find such a walk.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 40</code></li>\n\t<li><code>1 &lt;= k &lt;= m * n</code></li>\n\t<li><code>grid[i][j]</code> is either <code>0</code> <strong>or</strong> <code>1</code>.</li>\n\t<li><code>grid[0][0] == grid[m - 1][n - 1] == 0</code></li>\n</ul>\n</div>"
  },
  {
    "path": "13-roman-to-integer/13-roman-to-integer.cpp",
    "content": "class Solution {\npublic:\n    int romanToInt(string s) {\n    unordered_map<char, int> mp{{'I',1},{'V',5},{'X',10},{'L',50},{'C',100,},{'D',500},{'M',1000}};\n        int ans = mp[s.back()];\n        for(int i=s.size()-2;i>=0;i--){\n            if(mp[s[i]] < mp[s[i+1]]) ans -= mp[s[i]];\n            else ans += mp[s[i]];\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "13-roman-to-integer/13-roman-to-integer.java",
    "content": "public class Solution {\n    public int romanToInt(String A) {\n        int ans=0;\n        int i=0;\n        while(i<A.length()){\n            if(i+1<A.length()){\n                if(getValue(A.charAt(i+1))>getValue(A.charAt(i))){\n                    ans+=getValue(A.charAt(i+1))-getValue(A.charAt(i));\n                    i+=2;\n                }else{\n                    ans+=getValue(A.charAt(i));\n                    i++;\n                }\n            }else{\n                ans+=getValue(A.charAt(i));\n                i++;\n            }\n        }\n        return ans;\n    }\n    int getValue(char ch){\n        switch(ch){\n            case 'I':\n                return 1;\n            case 'V':\n                return 5;\n            case 'X':\n                return 10;\n            case 'L':\n                return 50;\n            case 'C':\n                return 100;\n            case 'D':\n                return 500;\n            case 'M':\n                return 1000;\n            default:\n                return -1;\n        }\n    }\n}"
  },
  {
    "path": "13-roman-to-integer/NOTES.md",
    "content": "​"
  },
  {
    "path": "13-roman-to-integer/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/roman-to-integer/\">13. Roman to Integer</a></h2><h3>Easy</h3><hr><div><p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p>\n\n<pre><strong>Symbol</strong>       <strong>Value</strong>\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000</pre>\n\n<p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p>\n\n<p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p>\n\n<ul>\n\t<li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li>\n\t<li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li>\n\t<li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li>\n</ul>\n\n<p>Given a roman numeral, convert it to an integer.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"III\"\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> III = 3.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"LVIII\"\n<strong>Output:</strong> 58\n<strong>Explanation:</strong> L = 50, V= 5, III = 3.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"MCMXCIV\"\n<strong>Output:</strong> 1994\n<strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 15</code></li>\n\t<li><code>s</code> contains only&nbsp;the characters <code>('I', 'V', 'X', 'L', 'C', 'D', 'M')</code>.</li>\n\t<li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "1302-deepest-leaves-sum/1302-deepest-leaves-sum.java",
    "content": "class Solution {\n    int deepestLevel = 0;\n    int sum;\n    \n    public int deepestLeavesSum(TreeNode root) {\n        deepestLeavesSum(root, 0);\n        return sum;\n    }\n    \n    public void deepestLeavesSum(TreeNode root,int level) {\n        if (root == null) {\n            return;\n        }\n        \n        if (root.left == null && root.right == null && level == deepestLevel) {\n            sum = sum + root.val;\n        }\n        \n        if (root.left == null && root.right == null && level > deepestLevel) {\n            deepestLevel = level;\n            sum = root.val;\n        }\n        \n        deepestLeavesSum(root.left, level + 1);\n        deepestLeavesSum(root.right, level + 1);\n    }\n}"
  },
  {
    "path": "1302-deepest-leaves-sum/NOTES.md",
    "content": "​"
  },
  {
    "path": "1302-deepest-leaves-sum/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/deepest-leaves-sum/\">1302. Deepest Leaves Sum</a></h2><h3>Medium</h3><hr><div>Given the <code>root</code> of a binary tree, return <em>the sum of values of its deepest leaves</em>.\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png\" style=\"width: 273px; height: 265px;\">\n<pre><strong>Input:</strong> root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\n<strong>Output:</strong> 15\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\n<strong>Output:</strong> 19\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1323-maximum-69-number/1323-maximum-69-number.java",
    "content": "class Solution {\n    public int maximum69Number (int num) {\n        char[] arr=(String.valueOf(num)).toCharArray();\n        for(int i=0;i<arr.length;i++){\n            char c=arr[i];\n            if(c=='6'){\n                arr[i]='9';\n                break;\n            }\n        }\n        return Integer.parseInt(new String(arr));\n    }\n}"
  },
  {
    "path": "1323-maximum-69-number/NOTES.md",
    "content": "​"
  },
  {
    "path": "1323-maximum-69-number/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-69-number/\">1323. Maximum 69 Number</a></h2><h3>Easy</h3><hr><div><p>You are given a positive integer <code>num</code> consisting only of digits <code>6</code> and <code>9</code>.</p>\n\n<p>Return <em>the maximum number you can get by changing <strong>at most</strong> one digit (</em><code>6</code><em> becomes </em><code>9</code><em>, and </em><code>9</code><em> becomes </em><code>6</code><em>)</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> num = 9669\n<strong>Output:</strong> 9969\n<strong>Explanation:</strong> \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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> num = 9996\n<strong>Output:</strong> 9999\n<strong>Explanation:</strong> Changing the last digit 6 to 9 results in the maximum number.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> num = 9999\n<strong>Output:</strong> 9999\n<strong>Explanation:</strong> It is better not to apply any change.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt;= 10<sup>4</sup></code></li>\n\t<li><code>num</code>&nbsp;consists of only <code>6</code> and <code>9</code> digits.</li>\n</ul>\n</div>"
  },
  {
    "path": "1328-break-a-palindrome/1328-break-a-palindrome.java",
    "content": "class Solution {\n    public String breakPalindrome(String palindrome) {\n        if (palindrome.length() == 1){\n            return \"\";\n        }\n        else\n        {\n            char[] arr = palindrome.toCharArray();\n            for (int i=0; i<arr.length; i++)\n            {\n                if (arr[i] != 'a'){\n                    if (arr.length%2 == 1 && i == arr.length/2)\n                        continue;   \n                    arr[i]= 'a';\n                    return new String(arr);\n                }  \n            }\n            \n            arr[arr.length-1] = 'b';\n            return new String(arr);\n        }\n    }\n}"
  },
  {
    "path": "1328-break-a-palindrome/NOTES.md",
    "content": "​"
  },
  {
    "path": "1328-break-a-palindrome/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/break-a-palindrome/\">1328. Break a Palindrome</a></h2><h3>Medium</h3><hr><div><p>Given a palindromic string of lowercase English letters <code>palindrome</code>, replace <strong>exactly one</strong> character with any lowercase English letter so that the resulting string is <strong>not</strong> a palindrome and that it is the <strong>lexicographically smallest</strong> one possible.</p>\n\n<p>Return <em>the resulting string. If there is no way to replace a character to make it not a palindrome, return an <strong>empty string</strong>.</em></p>\n\n<p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly smaller than the corresponding character in <code>b</code>. For example, <code>\"abcc\"</code> is lexicographically smaller than <code>\"abcd\"</code> because the first position they differ is at the fourth character, and <code>'c'</code> is smaller than <code>'d'</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> palindrome = \"abccba\"\n<strong>Output:</strong> \"aaccba\"\n<strong>Explanation:</strong> There are many ways to make \"abccba\" not a palindrome, such as \"<u>z</u>bccba\", \"a<u>a</u>ccba\", and \"ab<u>a</u>cba\".\nOf all the ways, \"aaccba\" is the lexicographically smallest.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> palindrome = \"a\"\n<strong>Output:</strong> \"\"\n<strong>Explanation:</strong> There is no way to replace a single character to make \"a\" not a palindrome, so return an empty string.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= palindrome.length &lt;= 1000</code></li>\n\t<li><code>palindrome</code> consists of only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1329-sort-the-matrix-diagonally/1329-sort-the-matrix-diagonally.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> diagonalSort(vector<vector<int>>& mat) { \n\n// // Explanation\n// // A[i][j] on the same diagonal have same value of i - j\n// // For each diagonal,\n// // put its elements together, sort, and set them back.\n\n\n// // Complexity\n// // Time O(MNlogD), where D is the length of diagonal with D = min(M,N).\n// // Space O(MN)\n\n        // solving with priority queue, 20ms\n//         int n = mat.size(), m = mat[0].size();\n//         unordered_map<int, priority_queue<int, vector<int>, greater<int>>> mp;\n//         for(int i=0;i<n;i++){\n//             for(int j=0;j<m;j++){\n//                 mp[i-j].push(mat[i][j]);\n//             }\n//         }   \n//         for(int i=0;i<n;i++){\n//             for(int j=0;j<m;j++){\n//                 mat[i][j] = mp[i-j].top();\n//                 mp[i-j].pop();\n//             }\n//         }\n//         return mat;\n\n\n\n        // 2. solving with sorting techniques, 8ms \n        int r = mat.size(), c = mat[0].size();\n        int j,p,q;\n        // solving upper right triangle\n        for(int i=0;i<c;i++){\n            // extracting the values \n            p=0,q=i;\n            vector<int> t;\n            while(p < r and q < c){\n                t.push_back(mat[p][q]);\n                p++;q++;\n            }\n            sort(t.begin(), t.end());\n            // placing back\n            p=0,q=i,j=0;\n            while(p<r and q<c){\n                mat[p][q] = t[j];\n                p++;q++;j++;\n            }\n        }\n\n        // solving lower left triangle\n        for(int i=1;i<r;i++){\n            // extracting the values\n            vector<int> t;\n            p=i,q=0;\n            while(p<r and q<c){\n                t.push_back(mat[p][q]);\n                p++;q++;\n            }\n            sort(t.begin(),t.end());\n            // placing back\n            p=i,q=0,j=0;\n            while(p<r and q<c){\n                mat[p][q] = t[j];\n                p++;q++;j++;\n            }\n        }\n        return mat;\n    }\n};\n"
  },
  {
    "path": "1329-sort-the-matrix-diagonally/1329-sort-the-matrix-diagonally.java",
    "content": "class Solution {\n    public int[][] diagonalSort(int[][] mat) {\n      int m=mat.length,n=mat[0].length;\n      //row=0\n        for(int col=0;col<n;col++){\n            sort(mat,0,col,m,n);\n        }\n        //col=0\n        for(int row=0;row<m;row++){\n            sort(mat,row,0,m,n);\n        }\n        return mat;\n    }\n    public static void sort(int[][] mat,int row,int col,int m,int n){\n        int[] values=new int[101];//using count sort\n        int r=row,c=col;\n        while(r<m&&c<n){\n            values[mat[r][c]]++;\n            r++;\n            c++;\n        }\n        r=row;\n        c=col;\n        for(int i=1;i<101;i++){\n            if(values[i]>0){\n                int cnt=values[i];\n                while(cnt-->0){\n                    mat[r][c]=i;\n                    r++;c++;\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "1329-sort-the-matrix-diagonally/NOTES.md",
    "content": "​"
  },
  {
    "path": "1329-sort-the-matrix-diagonally/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/sort-the-matrix-diagonally/\">1329. Sort the Matrix Diagonally</a></h2><h3>Medium</h3><hr><div><p>A <strong>matrix diagonal</strong> 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 <strong>matrix diagonal</strong> starting from <code>mat[2][0]</code>, where <code>mat</code> is a <code>6 x 3</code> matrix, includes cells <code>mat[2][0]</code>, <code>mat[3][1]</code>, and <code>mat[4][2]</code>.</p>\n\n<p>Given an <code>m x n</code> matrix <code>mat</code> of integers, sort each <strong>matrix diagonal</strong> in ascending order and return <em>the resulting matrix</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png\" style=\"width: 500px; height: 198px;\">\n<pre><strong>Input:</strong> mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\n<strong>Output:</strong> [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> 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]]\n<strong>Output:</strong> [[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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == mat.length</code></li>\n\t<li><code>n == mat[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>1 &lt;= mat[i][j] &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1329-sort-the-matrix-diagonally/SolutionCode.cpp",
    "content": "class Solution {\npublic:\n    void sortIt(int r,int c,int m,int n,vector<vector<int>> &v){\n        int i = r, j = c;\n        vector<int> a;\n        while(i<m && j<n){\n            a.push_back(v[i][j]);\n            i++, j++;\n        }\n        \n        sort(a.begin(), a.end());\n        i = r, j= c;\n        int pos = 0;\n        while(i<m && j<n){\n            v[i][j] = a[pos++];\n            i++, j++;\n        }\n    }\n    vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {\n        if(mat.size()==1) return mat;\n        \n        int m = mat.size(), n = mat[0].size();\n        \n        //0 row\n        for(int col = 0;col<n;col++){\n            sortIt(0,col,m,n, mat);\n        }\n        \n        //0 col\n        for(int row = 1;row<m;row++){\n            sortIt(row,0,m,n, mat);\n        }\n        \n        return mat;\n    }\n};\n"
  },
  {
    "path": "1332-remove-palindromic-subsequences/1332-remove-palindromic-subsequences.java",
    "content": "class Solution {\n    public int removePalindromeSub(String s) {\n        int n=s.length();\n        if(n==0)return n;\n        if(isPal(s))return 1;\n        return 2;\n    }\n    public boolean isPal(String s){\n        int i=0;\n        int j=s.length()-1;\n        while(i<j){\n            if(s.charAt(i)!=s.charAt(j))return false;\n            i++;\n            j--;\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "1332-remove-palindromic-subsequences/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/remove-palindromic-subsequences/solution/\">1332. Remove Palindromic Subsequences</a></h2><h3>Easy</h3><hr><div><p>You are given a string <code>s</code> consisting <strong>only</strong> of letters <code>'a'</code> and <code>'b'</code>. In a single step you can remove one <strong>palindromic subsequence</strong> from <code>s</code>.</p>\n\n<p>Return <em>the <strong>minimum</strong> number of steps to make the given string empty</em>.</p>\n\n<p>A string is a <strong>subsequence</strong> 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 <strong>not</strong> necessarily need to be contiguous.</p>\n\n<p>A string is called <strong>palindrome</strong> if is one that reads the same backward as well as forward.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"ababa\"\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> s is already a palindrome, so its entirety can be removed in a single step.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"abb\"\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> \"<u>a</u>bb\" -&gt; \"<u>bb</u>\" -&gt; \"\". \nRemove palindromic subsequence \"a\" then \"bb\".\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"baabb\"\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> \"<u>baa</u>b<u>b</u>\" -&gt; \"<u>b</u>\" -&gt; \"\". \nRemove palindromic subsequence \"baab\" then \"b\".\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s[i]</code> is either <code>'a'</code> or <code>'b'</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "1335-minimum-difficulty-of-a-job-schedule/1335-minimum-difficulty-of-a-job-schedule.java",
    "content": "class Solution {\n    \n    Integer[][] dp;\n    int n;\n    \n    public int Helper(int idx, int[] arr, int d){\n        \n        if(idx == n && d == 0)    return 0;\n        if(n - idx < d)           return (int)1e5;          // only for optimization not necessary\n        if(d < 0)                 return (int)1e5;\n\t\t\n        if(dp[idx][d] != null)      return dp[idx][d];\n        \n        int max = 0;\n        int res = Integer.MAX_VALUE;\n        \n        for(int i = idx; i < n; ++i){\n            max = Math.max(arr[i], max);\n            res = Math.min(res, max + Helper(i + 1, arr, d - 1));\n        }\n    \n        return dp[idx][d] = res;\n    }\n    \n    public int minDifficulty(int[] jobDifficulty, int d) {\n        this.n = jobDifficulty.length;\n\t\tthis.dp = new Integer[n][d + 1]; \n\t\t\n        if(n < d)   return -1;\n       \n        return Helper(0, jobDifficulty, d);\n    }\n}"
  },
  {
    "path": "1335-minimum-difficulty-of-a-job-schedule/NOTES.md",
    "content": "​"
  },
  {
    "path": "1335-minimum-difficulty-of-a-job-schedule/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/\">1335. Minimum Difficulty of a Job Schedule</a></h2><h3>Hard</h3><hr><div><p>You want to schedule a list of jobs in <code>d</code> days. Jobs are dependent (i.e To work on the <code>i<sup>th</sup></code> job, you have to finish all the jobs <code>j</code> where <code>0 &lt;= j &lt; i</code>).</p>\n\n<p>You have to finish <strong>at least</strong> one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the <code>d</code> days. The difficulty of a day is the maximum difficulty of a job done on that day.</p>\n\n<p>You are given an integer array <code>jobDifficulty</code> and an integer <code>d</code>. The difficulty of the <code>i<sup>th</sup></code> job is <code>jobDifficulty[i]</code>.</p>\n\n<p>Return <em>the minimum difficulty of a job schedule</em>. If you cannot find a schedule for the jobs return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/01/16/untitled.png\" style=\"width: 365px; height: 370px;\">\n<pre><strong>Input:</strong> jobDifficulty = [6,5,4,3,2,1], d = 2\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> jobDifficulty = [9,9,9], d = 4\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> jobDifficulty = [1,1,1], d = 3\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The schedule is one job per day. total difficulty will be 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= jobDifficulty.length &lt;= 300</code></li>\n\t<li><code>0 &lt;= jobDifficulty[i] &lt;= 1000</code></li>\n\t<li><code>1 &lt;= d &lt;= 10</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.java",
    "content": "class Solution {\n    public int[] kWeakestRows(int[][] mat, int k) {\n        int[]ans=new int[k];\n        int[][]freq=new int[mat.length][2];\n        for(int i=0;i<mat.length;i++){\n            freq[i]=new int[]{count(mat,i),i};\n        }\n        Arrays.sort(freq,(o1,o2)->o1[0]-o2[0]);\n        for(int i=0;i<k;i++){\n            ans[i]=freq[i][1];\n        }\n        return ans;\n    }\n    public int count(int[][]mat,int i){\n        int ans=0;\n        for(int j=0;j<mat[i].length;j++){\n            if(mat[i][j]==0)break;\n            ans+=mat[i][j];\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "1337-the-k-weakest-rows-in-a-matrix/NOTES.md",
    "content": "​"
  },
  {
    "path": "1337-the-k-weakest-rows-in-a-matrix/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/\">1337. The K Weakest Rows in a Matrix</a></h2><h3>Easy</h3><hr><div><p>You are given an <code>m x n</code> binary matrix <code>mat</code> of <code>1</code>'s (representing soldiers) and <code>0</code>'s (representing civilians). The soldiers are positioned <strong>in front</strong> of the civilians. That is, all the <code>1</code>'s will appear to the <strong>left</strong> of all the <code>0</code>'s in each row.</p>\n\n<p>A row <code>i</code> is <strong>weaker</strong> than a row <code>j</code> if one of the following is true:</p>\n\n<ul>\n\t<li>The number of soldiers in row <code>i</code> is less than the number of soldiers in row <code>j</code>.</li>\n\t<li>Both rows have the same number of soldiers and <code>i &lt; j</code>.</li>\n</ul>\n\n<p>Return <em>the indices of the </em><code>k</code><em> <strong>weakest</strong> rows in the matrix ordered from weakest to strongest</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> 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\n<strong>Output:</strong> [2,0,3]\n<strong>Explanation:</strong> \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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2\n<strong>Output:</strong> [0,2]\n<strong>Explanation:</strong> \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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == mat.length</code></li>\n\t<li><code>n == mat[i].length</code></li>\n\t<li><code>2 &lt;= n, m &lt;= 100</code></li>\n\t<li><code>1 &lt;= k &lt;= m</code></li>\n\t<li><code>matrix[i][j]</code> is either 0 or 1.</li>\n</ul>\n</div>"
  },
  {
    "path": "1338-reduce-array-size-to-the-half/1338-reduce-array-size-to-the-half.cpp",
    "content": "int minSetSize(vector<int>& arr) {\n        map<int,int>mp;\n        \n        for(int i=0;i<arr.size();i++)\n        {\n            mp[arr[i]]++;\n        }\n        \n        priority_queue<pair<int,int>>pq;\n        \n        for(auto it:mp)\n        {\n            pq.push({it.second,it.first});\n        }\n        \n        int size=arr.size()/2;\n        int count=0;\n        \n        while(size>0 && !pq.empty())\n        {\n            if(size<pq.top().first)\n            {\n                size-=pq.top().first;\n                    count++;\n                break;\n            }\n            else\n            {\n               size-=pq.top().first;\n                count++;\n                pq.pop();\n            }\n        }\n        return count;\n    }\n"
  },
  {
    "path": "1338-reduce-array-size-to-the-half/1338-reduce-array-size-to-the-half.java",
    "content": "class Pair{\n    int num;\n    int freq;\n    Pair(int i,int j){\n        num=i;\n        freq=j;\n    }\n}\nclass Solution {\n    public int minSetSize(int[] arr) {\n        PriorityQueue<Pair> pq=new PriorityQueue<>((a,b)->b.freq-a.freq);\n        Map<Integer,Integer> map=new HashMap<>();\n        for(int i:arr){\n            map.put(i,map.getOrDefault(i,0)+1);\n        }\n        for(Map.Entry<Integer,Integer> entry : map.entrySet()){\n            pq.add(new Pair(entry.getKey(),entry.getValue()));\n        }\n        \n        int ans=0;\n        int size=arr.length;\n        int sz=arr.length;\n        while(sz>size/2){\n            ans++;\n            Pair p=pq.remove();\n            sz-=p.freq;\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "1338-reduce-array-size-to-the-half/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/reduce-array-size-to-the-half/\">1338. Reduce Array Size to The Half</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>arr</code>. You can choose a set of integers and remove all the occurrences of these integers in the array.</p>\n\n<p>Return <em>the minimum size of the set so that <strong>at least</strong> half of the integers of the array are removed</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> arr = [3,3,3,3,5,5,5,2,2,7]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> arr = [7,7,7,7,7,7]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The only possible set you can choose is {7}. This will make the new array empty.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= arr.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>arr.length</code> is even.</li>\n\t<li><code>1 &lt;= arr[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1339-maximum-product-of-splitted-binary-tree/1339-maximum-product-of-splitted-binary-tree.java",
    "content": "class Solution {\n    int mod = 1000000007;\n    long max = 0;\n    long total;\n    public int maxProduct(TreeNode root) {\n        this.total = dfs(root);\n        traverse(root);\n        return (int)(max%mod);\n    }\n    \n    private int dfs(TreeNode root)\n    {\n        if(root==null)\n            return 0;\n        return root.val += dfs(root.left) + dfs(root.right);\n    }\n    \n    private void traverse(TreeNode root)\n    {\n        if(root==null)\n            return;\n        max = Math.max(root.val*(total-root.val),max);\n        traverse(root.left);\n        traverse(root.right);\n    }\n}"
  },
  {
    "path": "1339-maximum-product-of-splitted-binary-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "1339-maximum-product-of-splitted-binary-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/\">1339. Maximum Product of Splitted Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> 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.</p>\n\n<p>Return <em>the maximum product of the sums of the two subtrees</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p><strong>Note</strong> that you need to maximize the answer before taking the mod and not after taking it.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/01/21/sample_1_1699.png\" style=\"width: 500px; height: 167px;\">\n<pre><strong>Input:</strong> root = [1,2,3,4,5,6]\n<strong>Output:</strong> 110\n<strong>Explanation:</strong> Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/01/21/sample_2_1699.png\" style=\"width: 500px; height: 211px;\">\n<pre><strong>Input:</strong> root = [1,null,2,3,4,null,null,5,6]\n<strong>Output:</strong> 90\n<strong>Explanation:</strong> Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 5 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1342-number-of-steps-to-reduce-a-number-to-zero/1342-number-of-steps-to-reduce-a-number-to-zero.java",
    "content": "class Solution {\n    public int numberOfSteps(int num) {\n        \n        int count = 1;\n        if(num == 0){return 0;}\n        if( num / 2== 0 || num - 1 == 0){return count;}\n        \n        if(num % 2 == 0){ return count + numberOfSteps(num/2);}\n        \n        return count + numberOfSteps(num-1);\n        \n    }\n}"
  },
  {
    "path": "1342-number-of-steps-to-reduce-a-number-to-zero/NOTES.md",
    "content": "​"
  },
  {
    "path": "1342-number-of-steps-to-reduce-a-number-to-zero/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/\">1342. Number of Steps to Reduce a Number to Zero</a></h2><h3>Easy</h3><hr><div><p>Given an integer <code>num</code>, return <em>the number of steps to reduce it to zero</em>.</p>\n\n<p>In one step, if the current number is even, you have to divide it by <code>2</code>, otherwise, you have to subtract <code>1</code> from it.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> num = 14\n<strong>Output:</strong> 6\n<strong>Explanation:</strong>&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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> num = 8\n<strong>Output:</strong> 4\n<strong>Explanation:</strong>&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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> num = 123\n<strong>Output:</strong> 12\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= num &lt;= 10<sup>6</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "135-candy/135-candy.java",
    "content": "public class Solution {\n    public int candy(int[] ratings) {\n        int[] candies = new int[ratings.length];\n        Arrays.fill(candies, 1);\n        for (int i = 1; i < ratings.length; i++) {\n            if (ratings[i] > ratings[i - 1]) {\n                candies[i] = candies[i - 1] + 1;\n            }\n        }\n        int sum = candies[ratings.length - 1];\n        for (int i = ratings.length - 2; i >= 0; i--) {\n            if (ratings[i] > ratings[i + 1]) {\n                candies[i] = Math.max(candies[i], candies[i + 1] + 1);\n            }\n            sum += candies[i];\n        }\n        return sum;\n    }\n}"
  },
  {
    "path": "135-candy/NOTES.md",
    "content": "​"
  },
  {
    "path": "135-candy/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/candy/\">135. Candy</a></h2><h3>Hard</h3><hr><div><p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>\n\n<p>You are giving candies to these children subjected to the following requirements:</p>\n\n<ul>\n\t<li>Each child must have at least one candy.</li>\n\t<li>Children with a higher rating get more candies than their neighbors.</li>\n</ul>\n\n<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> ratings = [1,0,2]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> ratings = [1,2,2]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == ratings.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= ratings[i] &lt;= 2 * 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1354-construct-target-array-with-multiple-sums/1354-construct-target-array-with-multiple-sums.java",
    "content": "class Solution {\n    public boolean isPossible(int[] target) {\n        long sum=0;\n        int n=target.length;\n        Queue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());\n        for(int i:target){\n            sum+=i;\n            pq.add(i);\n        }\n        while(sum!=n){\n            int largest=pq.remove();\n            sum-=largest;\n            if(sum==1 || largest==1)return true;\n            if(sum>largest || sum==0 || largest%sum==0)return false;\n            largest%=sum;\n            sum+=largest;\n            pq.add(largest);\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "1354-construct-target-array-with-multiple-sums/NOTES.md",
    "content": "​"
  },
  {
    "path": "1354-construct-target-array-with-multiple-sums/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/construct-target-array-with-multiple-sums/\">1354. Construct Target Array With Multiple Sums</a></h2><h3>Hard</h3><hr><div><p>You are given an array <code>target</code> of n integers. From a starting array <code>arr</code> consisting of <code>n</code> 1's, you may perform the following procedure :</p>\n\n<ul>\n\t<li>let <code>x</code> be the sum of all elements currently in your array.</li>\n\t<li>choose index <code>i</code>, such that <code>0 &lt;= i &lt; n</code> and set the value of <code>arr</code> at index <code>i</code> to <code>x</code>.</li>\n\t<li>You may repeat this procedure as many times as needed.</li>\n</ul>\n\n<p>Return <code>true</code> <em>if it is possible to construct the</em> <code>target</code> <em>array from</em> <code>arr</code><em>, otherwise, return</em> <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> target = [9,3,5]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> target = [1,1,1,2]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Impossible to create target array from [1,1,1,1].\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> target = [8,5]\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == target.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= target[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.java",
    "content": "/**\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    TreeNode ans;\n    TreeNode tar;\n    public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {\n        tar=target;\n        dfs(original,cloned);\n        return ans;\n    }\n    public void dfs(TreeNode a,TreeNode b){\n        if(a==null)return;\n        if(a==tar){\n            ans=b;\n            return;\n        }\n        dfs(a.left,b.left);\n        dfs(a.right,b.right);\n    }\n}"
  },
  {
    "path": "1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/\">1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree</a></h2><h3>Medium</h3><hr><div><p>Given two binary trees <code>original</code> and <code>cloned</code> and given a reference to a node <code>target</code> in the original tree.</p>\n\n<p>The <code>cloned</code> tree is a <strong>copy of</strong> the <code>original</code> tree.</p>\n\n<p>Return <em>a reference to the same node</em> in the <code>cloned</code> tree.</p>\n\n<p><strong>Note</strong> that you are <strong>not allowed</strong> to change any of the two trees or the <code>target</code> node and the answer <strong>must be</strong> a reference to a node in the <code>cloned</code> tree.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/21/e1.png\" style=\"width: 544px; height: 426px;\">\n<pre><strong>Input:</strong> tree = [7,4,3,null,null,6,19], target = 3\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/21/e2.png\" style=\"width: 221px; height: 159px;\">\n<pre><strong>Input:</strong> tree = [7], target =  7\n<strong>Output:</strong> 7\n</pre>\n\n<p><strong>Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/21/e3.png\" style=\"width: 459px; height: 486px;\">\n<pre><strong>Input:</strong> tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the <code>tree</code> is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li>The values of the nodes of the <code>tree</code> are unique.</li>\n\t<li><code>target</code> node is a node from the <code>original</code> tree and is not <code>null</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you solve the problem if repeated values on the tree are allowed?</p>\n</div>"
  },
  {
    "path": "1381. Design a Stack With Increment Operation/1381-Design-a-Stack-With-Increment-Operation.cpp",
    "content": "class CustomStack {\npublic:\n    \n    // 1.\n//     stack<int> st;\n//     int n;\n//     CustomStack(int maxSize){\n//         n = maxSize;\n//     }\n    \n//     void push(int x){\n//         if(st.size() < n){\n//             st.push(x);\n//         }\n//     }\n    \n//     int pop(){\n//         int t = -1;\n//         if(!st.empty()){\n//             t = st.top();\n//             st.pop();   \n//         }\n//         return t;\n//     }\n    \n//     void increment(int k, int val){\n//         stack<int> ts;\n//         int m;\n//         if(k < st.size()){\n//             m = st.size() - k;\n//             for(int i=0;i<m;i++){\n//                 ts.push(st.top());\n//                 st.pop();\n//             }\n//         }\n//         m = st.size();\n//         for(int i=0;i<m;i++){\n//             ts.push(st.top() + val);\n//             st.pop();\n//         }\n//         m = ts.size();\n//         for(int i=0;i<m;i++){\n//             st.push(ts.top());\n//             ts.pop();\n//         }\n//     }\n\n    \n    \n    \n    // 2. \n//     Explanation\n// Use an additional array to record the increment value.\n// inc[i] means for all elements stack[0] ~ stack[i],\n// we should plus inc[i] when popped from the stack.\n// Then inc[i-1]+=inc[i],\n// so that we can accumulate the increment inc[i]\n// for the bottom elements and the following pops.\n\n\n//     Complexity\n// C++/Python, initialization is O(1) time & space.\n// Java, initialization is O(N) time & space.\n// (We cam use ArrayList, but shrug)\n// push, pop, increment, all O(1) time and space.\n    \n    vector<int> stack, inc;\n    int n;\n    CustomStack(int maxSize) {\n        n = maxSize;\n    }\n\n    void push(int x) {\n        if (stack.size() == n) return;\n        stack.push_back(x);\n        inc.push_back(0);\n    }\n\n    // jo bhi ho raha hain pop function m ho raha hain\n    int pop() {\n        int i = stack.size() - 1;\n        if (i < 0) return -1; // if stack is empty\n        if (i > 0) inc[i - 1] += inc[i]; // here if we have added more to current then increment to the previous values too.\n        // like in case of 5, 100 and again 2, 100\n        // do dry run you will understand better.\n        int res = stack[i] + inc[i];\n        stack.pop_back();\n        inc.pop_back();\n        return res;\n    }\n\n    void increment(int k, int val) {\n        int i = min(k, (int)stack.size()) - 1;\n        if (i >= 0) inc[i] += val; // here comes the use of increment vector\n    }        \n};\n"
  },
  {
    "path": "1383 Maximum Performance of a Team lc hard.cpp",
    "content": "#include<bits.stdc++.h>\nusing namespace std;\n\nclass Solution {\n    // TC: O(N * (logN + logK)) \n// SC: O(N + K)\n// where N = total number of candidates & K = size of team\npublic:\n    int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {\n        int MOD = 1e9 + 7;\n        vector<pair<int, int>> candidates(n);\n        // building pair { efficiency, speed } to sort it later\n        for (int i = 0; i < n; i++) candidates[i] = { efficiency[i], speed[i] };\n        // sort candidates in dsc\n        sort(candidates.rbegin(), candidates.rend());\n        // Using Example 1: \n        // speed: [2, 10, 3, 1 ,5, 8] and efficiency: [5, 4, 3, 9, 7, 2]\n        // after sort, it becomes\n        // candidates: [{9, 1}, {7 ,5}, {5, 2}, {4, 10}, {3, 3}, {2, 8}]\n        long speedSum = 0, ans = 0;\n        // we use priority queue here with greater<int> to store the sum\n        // i.e min heap (the smallest element goes on the top)\n        priority_queue <int, vector<int>, greater<int>> pq;\n        // iterate each pair\n        for (auto& [e, s] : candidates) {\n            // put the speed to priority queue\n            pq.push(s);\n            // add to speedSum\n            speedSum += s;\n            // we only need to choose at most k engineers\n            // hence if the queue size is greater than k\n            // we need to remove a candidate\n            if (pq.size() > k) {\n                // who to remove? of course the one with smallest speed\n                speedSum -= pq.top();\n                pq.pop();\n            }\n            // a team is formed now, calculate the performance\n            ans = max(ans, speedSum * e);\n        }\n        return ans % MOD;\n    }\n};"
  },
  {
    "path": "1383-maximum-performance-of-a-team/1383-maximum-performance-of-a-team.java",
    "content": "class Solution {\n    public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {\n        int[][] players = new int[n][2];\n        for (int i=0; i<n; i++) {\n            players[i][0] = efficiency[i];\n            players[i][1] = speed[i];\n        }\n\t\t// Sort the players based on efficiency in decreasing order, as for each iteration, we'll consider only players with higher efficiency.\n        Arrays.sort(players, (p1, p2) -> (p2[0] - p1[0]));\n\n\t\t// Priority-Queue to maintain players with highest relative speeds with efficiencies greater than the one under iteration.\n        PriorityQueue<Integer> speedQueue = new PriorityQueue<>(k);\n        long teamPerformance = 0, teamSpeed = 0;\n\n        for (int i=0; i<n; i++) {\n\t\t\t// This is because a team can have atmost `k` players.\n            if (speedQueue.size() >= k) {\n                teamSpeed -= speedQueue.remove();\n            }\n            speedQueue.add(players[i][1]);\n            teamSpeed += players[i][1];\n\n            teamPerformance = Math.max(teamPerformance, teamSpeed * players[i][0]);\n        }\n        return (int) (teamPerformance % 1000000007);\n    }\n}"
  },
  {
    "path": "1383-maximum-performance-of-a-team/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-performance-of-a-team/\">1383. Maximum Performance of a Team</a></h2><h3>Hard</h3><hr><div><p>You are given two integers <code>n</code> and <code>k</code> and two integer arrays <code>speed</code> and <code>efficiency</code> both of length <code>n</code>. There are <code>n</code> engineers numbered from <code>1</code> to <code>n</code>. <code>speed[i]</code> and <code>efficiency[i]</code> represent the speed and efficiency of the <code>i<sup>th</sup></code> engineer respectively.</p>\n\n<p>Choose <strong>at most</strong> <code>k</code> different engineers out of the <code>n</code> engineers to form a team with the maximum <strong>performance</strong>.</p>\n\n<p>The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.</p>\n\n<p>Return <em>the maximum performance of this team</em>. Since the answer can be a huge number, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\n<strong>Output:</strong> 60\n<strong>Explanation:</strong> \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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\n<strong>Output:</strong> 68\n<strong>Explanation:\n</strong>This 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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\n<strong>Output:</strong> 72\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>speed.length == n</code></li>\n\t<li><code>efficiency.length == n</code></li>\n\t<li><code>1 &lt;= speed[i] &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= efficiency[i] &lt;= 10<sup>8</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1396-design-underground-system/1396-design-underground-system.java",
    "content": "class UndergroundSystem {\n    class Pair{\n        String place;\n        int time;\n        Pair(String p,int t){\n            place=p;\n            time=t;\n        }\n    }\n    Map<Integer,Pair> inMap;\n    Map<String,ArrayList<Integer>> map;\n    public UndergroundSystem() {\n        inMap=new HashMap<>();\n        map=new HashMap<>();\n    }\n    \n    public void checkIn(int id, String p, int t) {\n        inMap.put(id,new Pair(p,t));\n    }\n    \n    public void checkOut(int id, String stationName, int t) {\n        Pair pair=inMap.get(id);\n        String start=pair.place;\n        int inTime=pair.time;\n        String route=start+\"-\"+stationName;\n        int avgTime=t-inTime;\n        if(map.containsKey(route)){\n            ArrayList<Integer> arr=map.get(route);\n            arr.add(avgTime);\n            map.put(route,arr);\n        }else{\n            ArrayList<Integer> arr=new ArrayList<>();\n            arr.add(avgTime);\n            map.put(route,arr);\n        }\n    }\n    \n    public double getAverageTime(String start, String end) {\n        String route=start+\"-\"+end;\n        ArrayList<Integer> arr=map.get(route);\n        int len=arr.size();\n        double sum=0;\n        for(int i:arr){\n            sum+=i;\n        }\n        return sum/len;\n    }\n}\n\n/**\n * Your UndergroundSystem object will be instantiated and called as such:\n * UndergroundSystem obj = new UndergroundSystem();\n * obj.checkIn(id,stationName,t);\n * obj.checkOut(id,stationName,t);\n * double param_3 = obj.getAverageTime(startStation,endStation);\n */"
  },
  {
    "path": "1396-design-underground-system/NOTES.md",
    "content": "​"
  },
  {
    "path": "1396-design-underground-system/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/design-underground-system/\">1396. Design Underground System</a></h2><h3>Medium</h3><hr><div><p>An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.</p>\n\n<p>Implement the <code>UndergroundSystem</code> class:</p>\n\n<ul>\n\t<li><code>void checkIn(int id, string stationName, int t)</code>\n\n\t<ul>\n\t\t<li>A customer with a card ID equal to <code>id</code>, checks in at the station <code>stationName</code> at time <code>t</code>.</li>\n\t\t<li>A customer can only be checked into one place at a time.</li>\n\t</ul>\n\t</li>\n\t<li><code>void checkOut(int id, string stationName, int t)</code>\n\t<ul>\n\t\t<li>A customer with a card ID equal to <code>id</code>, checks out from the station <code>stationName</code> at time <code>t</code>.</li>\n\t</ul>\n\t</li>\n\t<li><code>double getAverageTime(string startStation, string endStation)</code>\n\t<ul>\n\t\t<li>Returns the average time it takes to travel from <code>startStation</code> to <code>endStation</code>.</li>\n\t\t<li>The average time is computed from all the previous traveling times from <code>startStation</code> to <code>endStation</code> that happened <strong>directly</strong>, meaning a check in at <code>startStation</code> followed by a check out from <code>endStation</code>.</li>\n\t\t<li>The time it takes to travel from <code>startStation</code> to <code>endStation</code> <strong>may be different</strong> from the time it takes to travel from <code>endStation</code> to <code>startStation</code>.</li>\n\t\t<li>There will be at least one customer that has traveled from <code>startStation</code> to <code>endStation</code> before <code>getAverageTime</code> is called.</li>\n\t</ul>\n\t</li>\n</ul>\n\n<p>You may assume all calls to the <code>checkIn</code> and <code>checkOut</code> methods are consistent. If a customer checks in at time <code>t<sub>1</sub></code> then checks out at time <code>t<sub>2</sub></code>, then <code>t<sub>1</sub> &lt; t<sub>2</sub></code>. All events happen in chronological order.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"UndergroundSystem\",\"checkIn\",\"checkIn\",\"checkIn\",\"checkOut\",\"checkOut\",\"checkOut\",\"getAverageTime\",\"getAverageTime\",\"checkIn\",\"getAverageTime\",\"checkOut\",\"getAverageTime\"]\n[[],[45,\"Leyton\",3],[32,\"Paradise\",8],[27,\"Leyton\",10],[45,\"Waterloo\",15],[27,\"Waterloo\",20],[32,\"Cambridge\",22],[\"Paradise\",\"Cambridge\"],[\"Leyton\",\"Waterloo\"],[10,\"Leyton\",24],[\"Leyton\",\"Waterloo\"],[10,\"Waterloo\",38],[\"Leyton\",\"Waterloo\"]]\n\n<strong>Output</strong>\n[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]\n\n<strong>Explanation</strong>\nUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(45, \"Leyton\", 3);\nundergroundSystem.checkIn(32, \"Paradise\", 8);\nundergroundSystem.checkIn(27, \"Leyton\", 10);\nundergroundSystem.checkOut(45, \"Waterloo\", 15);  // Customer 45 \"Leyton\" -&gt; \"Waterloo\" in 15-3 = 12\nundergroundSystem.checkOut(27, \"Waterloo\", 20);  // Customer 27 \"Leyton\" -&gt; \"Waterloo\" in 20-10 = 10\nundergroundSystem.checkOut(32, \"Cambridge\", 22); // Customer 32 \"Paradise\" -&gt; \"Cambridge\" in 22-8 = 14\nundergroundSystem.getAverageTime(\"Paradise\", \"Cambridge\"); // return 14.00000. One trip \"Paradise\" -&gt; \"Cambridge\", (14) / 1 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\");    // return 11.00000. Two trips \"Leyton\" -&gt; \"Waterloo\", (10 + 12) / 2 = 11\nundergroundSystem.checkIn(10, \"Leyton\", 24);\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\");    // return 11.00000\nundergroundSystem.checkOut(10, \"Waterloo\", 38);  // Customer 10 \"Leyton\" -&gt; \"Waterloo\" in 38-24 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\");    // return 12.00000. Three trips \"Leyton\" -&gt; \"Waterloo\", (10 + 12 + 14) / 3 = 12\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input</strong>\n[\"UndergroundSystem\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\"]\n[[],[10,\"Leyton\",3],[10,\"Paradise\",8],[\"Leyton\",\"Paradise\"],[5,\"Leyton\",10],[5,\"Paradise\",16],[\"Leyton\",\"Paradise\"],[2,\"Leyton\",21],[2,\"Paradise\",30],[\"Leyton\",\"Paradise\"]]\n\n<strong>Output</strong>\n[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]\n\n<strong>Explanation</strong>\nUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(10, \"Leyton\", 3);\nundergroundSystem.checkOut(10, \"Paradise\", 8); // Customer 10 \"Leyton\" -&gt; \"Paradise\" in 8-3 = 5\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.00000, (5) / 1 = 5\nundergroundSystem.checkIn(5, \"Leyton\", 10);\nundergroundSystem.checkOut(5, \"Paradise\", 16); // Customer 5 \"Leyton\" -&gt; \"Paradise\" in 16-10 = 6\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.50000, (5 + 6) / 2 = 5.5\nundergroundSystem.checkIn(2, \"Leyton\", 21);\nundergroundSystem.checkOut(2, \"Paradise\", 30); // Customer 2 \"Leyton\" -&gt; \"Paradise\" in 30-21 = 9\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= id, t &lt;= 10<sup>6</sup></code></li>\n\t<li><code>1 &lt;= stationName.length, startStation.length, endStation.length &lt;= 10</code></li>\n\t<li>All strings consist of uppercase and lowercase English letters and digits.</li>\n\t<li>There will be at most <code>2 * 10<sup>4</sup></code> calls <strong>in total</strong> to <code>checkIn</code>, <code>checkOut</code>, and <code>getAverageTime</code>.</li>\n\t<li>Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.</li>\n</ul>\n</div>"
  },
  {
    "path": "14. Longest Common Prefix.py",
    "content": "    def longestCommonPrefix(self, strs: List[str]) -> str:\n        sub = \"\"\n        counter = 0\n        for i in range(len(strs[0])):\n            for j in range(len(strs)):\n                if len(strs[j]) <= i:\n                    return sub\n                if strs[j][i] == strs[0][i]:\n                    counter += 1\n                    \n            if counter == len(strs):\n                sub += strs[0][i]\n                counter = 0\n            else:\n                return sub\n        return sub\n        \n        \n"
  },
  {
    "path": "1423-maximum-points-you-can-obtain-from-cards/1423-maximum-points-you-can-obtain-from-cards.java",
    "content": "class Solution {\n    public int maxScore(int[] cardPoints, int k) {\n        int n = cardPoints.length, l= 0, r = n - k ;\n        \n        int total = 0;\n        for (int i = r; i<n; i++) {\n            total += cardPoints[i];\n        }\n        int res = total;\n        while (r < n) {\n            total += (cardPoints[l] - cardPoints[r]);\n            res = Math.max(res, total);\n            l++;\n            r++;\n        }\n        return res;\n    }\n}"
  },
  {
    "path": "1423-maximum-points-you-can-obtain-from-cards/NOTES.md",
    "content": "​"
  },
  {
    "path": "1423-maximum-points-you-can-obtain-from-cards/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/\">1423. Maximum Points You Can Obtain from Cards</a></h2><h3>Medium</h3><hr><div><p>There are several cards <strong>arranged in a row</strong>, and each card has an associated number of points. The points are given in the integer array <code>cardPoints</code>.</p>\n\n<p>In one step, you can take one card from the beginning or from the end of the row. You have to take exactly <code>k</code> cards.</p>\n\n<p>Your score is the sum of the points of the cards you have taken.</p>\n\n<p>Given the integer array <code>cardPoints</code> and the integer <code>k</code>, return the <em>maximum score</em> you can obtain.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> cardPoints = [1,2,3,4,5,6,1], k = 3\n<strong>Output:</strong> 12\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> cardPoints = [2,2,2], k = 2\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Regardless of which two cards you take, your score will always be 4.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> cardPoints = [9,7,7,9,7,7,9], k = 7\n<strong>Output:</strong> 55\n<strong>Explanation:</strong> You have to take all the cards. Your score is the sum of points of all cards.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= cardPoints.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= cardPoints[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= cardPoints.length</code></li>\n</ul>\n</div>"
  },
  {
    "path": "143-Reorder List.java",
    "content": "// Runtime: 11 ms, faster than 10.15% of Java online submissions for Reorder List.\n// Memory Usage: 54.4 MB, less than 29.31% of Java online submissions for Reorder List.\nclass Solution {\n    public void reorderList(ListNode head) {\n        ListNode curr = head;\n        \n        Stack<ListNode> s = new Stack<>();\n\n        while(curr != null) {\n            s.push(curr);\n            curr = curr.next;\n        }\n        curr = head;\n        int n = s.size();\n        if(n<=2) return;\n        ListNode next;\n        for(int i = 0; i < n/2; i++) {\n            next = curr.next;\n            curr.next = s.peek();\n            s.pop();\n            curr = curr.next;\n            curr.next = next;\n            curr = curr.next;\n        }\n        curr.next = null;\n    }\n}\n"
  },
  {
    "path": "1443-minimum-time-to-collect-all-apples-in-a-tree/1443-minimum-time-to-collect-all-apples-in-a-tree.java",
    "content": "class Solution {\n    public int dfs(int node, int parent, Map<Integer, List<Integer>> adj,\n            List<Boolean> hasApple) {\n        if (!adj.containsKey(node))\n            return 0;\n\n        int totalTime = 0, childTime = 0;\n        for (int child : adj.get(node)) {\n            if (child == parent)\n                continue;\n            childTime = dfs(child, node, adj, hasApple);\n            // childTime > 0 indicates subtree of child has apples. Since the root node of the\n            // subtree does not contribute to the time, even if it has an apple, we have to check it\n            // independently.\n            if (childTime > 0 || hasApple.get(child))\n                totalTime += childTime + 2;\n        }\n        return totalTime;\n    }\n\n    public int minTime(int n, int[][] edges, List<Boolean> hasApple) {\n        Map<Integer, List<Integer>> adj = new HashMap<>();\n        for (int[] edge : edges) {\n            int a = edge[0], b = edge[1];\n            adj.computeIfAbsent(a, value -> new ArrayList<Integer>()).add(b);\n            adj.computeIfAbsent(b, value -> new ArrayList<Integer>()).add(a);\n        }\n        return dfs(0, -1, adj, hasApple);\n    }\n}"
  },
  {
    "path": "1443-minimum-time-to-collect-all-apples-in-a-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/\">1443. Minimum Time to Collect All Apples in a Tree</a></h2><h3>Medium</h3><hr><div><p>Given an undirected tree consisting of <code>n</code> vertices numbered from <code>0</code> to <code>n-1</code>, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. <em>Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at <strong>vertex 0</strong> and coming back to this vertex.</em></p>\n\n<p>The edges of the undirected tree are given in the array <code>edges</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> means that exists an edge connecting the vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code>. Additionally, there is a boolean array <code>hasApple</code>, where <code>hasApple[i] = true</code> means that vertex <code>i</code> has an apple; otherwise, it does not have any apple.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_1.png\" style=\"width: 300px; height: 212px;\">\n<pre><strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]\n<strong>Output:</strong> 8 \n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png\" style=\"width: 300px; height: 212px;\">\n<pre><strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>edges.length == n - 1</code></li>\n\t<li><code>edges[i].length == 2</code></li>\n\t<li><code>0 &lt;= a<sub>i</sub> &lt; b<sub>i</sub> &lt;= n - 1</code></li>\n\t<li><code>from<sub>i</sub> &lt; to<sub>i</sub></code></li>\n\t<li><code>hasApple.length == n</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1448-count-good-nodes-in-binary-tree/1448-count-good-nodes-in-binary-tree.java",
    "content": "/**\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 count;\n    public int goodNodes(TreeNode root) {\n        \n        if(root.left==null && root.right==null ){\n            return 1;\n        }\n        \n        count=0;\n        int curr=root.val;\n        \n        helper(root,curr);\n            \n        return count;\n    }\n    \n    public void helper(TreeNode root,int curr){\n        \n        if(root==null)\n            return;\n        \n        if(root.val>=curr){\n            count++;\n            curr=root.val;\n        }\n        \n        helper(root.left,curr);\n        helper(root.right,curr);\n    }\n}"
  },
  {
    "path": "1448-count-good-nodes-in-binary-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "1448-count-good-nodes-in-binary-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/count-good-nodes-in-binary-tree/\">1448. Count Good Nodes in Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given a binary tree <code>root</code>, a node <em>X</em> in the tree is named&nbsp;<strong>good</strong> if in the path from root to <em>X</em> there are no nodes with a value <em>greater than</em> X.</p>\n\n<p>Return the number of <strong>good</strong> nodes in the binary tree.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<p><strong><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png\" style=\"width: 263px; height: 156px;\"></strong></p>\n\n<pre><strong>Input:</strong> root = [3,1,4,3,null,1,5]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Nodes in blue are <strong>good</strong>.\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.</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<p><strong><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png\" style=\"width: 157px; height: 161px;\"></strong></p>\n\n<pre><strong>Input:</strong> root = [3,3,null,4,2]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Node 2 -&gt; (3, 3, 2) is not good, because \"3\" is higher than it.</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [1]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> Root is considered as <strong>good</strong>.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the binary tree is in the range&nbsp;<code>[1, 10^5]</code>.</li>\n\t<li>Each node's value is between <code>[-10^4, 10^4]</code>.</li>\n</ul></div>\n"
  },
  {
    "path": "1457 Pseudo-Palindromic Paths in a Binary Tree lc.cpp",
    "content": "class Solution {\npublic:\n    vector<int> a; //map count nodes with same value\n    int ans; // store ans\n    bool checkPalin(){\n        int cnt=0;\n        for(int i=1;i<10;i++){ \n            if(a[i]&1){\n                cnt++;\n            }\n        }\n        if(cnt>1) return false;\n        else return true;\n    }\n    void solve(TreeNode *root){\n        if(!root) return;\n        if(!root->left && !root->right){\n            a[root->val]++;\n            if(checkPalin()) ans++;\n            a[root->val]--;\n            \n            return ;\n        }\n        a[root->val]++;\n        solve(root->left);\n        solve(root->right);\n        a[root->val]--;\n    }\n    int pseudoPalindromicPaths (TreeNode* root) {\n        ans=0;\n        a.resize(10,0);\n        solve(root);\n        return ans;\n    }\n};"
  },
  {
    "path": "1457-pseudo-palindromic-paths-in-a-binary-tree/1457-pseudo-palindromic-paths-in-a-binary-tree.java",
    "content": "/**\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 ans;\n    public int pseudoPalindromicPaths (TreeNode root) {\n        int[] freq=new int[10];\n        ans=0;\n        dfs(root,freq);\n        return ans;\n    }\n    void dfs(TreeNode root,int[]freq){\n        if(root.left==null && root.right==null){\n            freq[root.val]++;\n            boolean odd=false;\n            for(int i=0;i<10;i++){\n                if(freq[i]%2!=0){\n                    if(!odd){\n                        odd=true;\n                    }else{\n                        freq[root.val]--;\n                        return;\n                    }\n                }\n            }\n            ans++;\n            freq[root.val]--;\n            return;\n        }\n        freq[root.val]++;\n        if(root.left!=null)dfs(root.left,freq);\n        if(root.right!=null)dfs(root.right,freq);\n        freq[root.val]--;\n    }\n}"
  },
  {
    "path": "1457-pseudo-palindromic-paths-in-a-binary-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/\">1457. Pseudo-Palindromic Paths in a Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be <strong>pseudo-palindromic</strong> if at least one permutation of the node values in the path is a palindrome.</p>\n\n<p><em>Return the number of <strong>pseudo-palindromic</strong> paths going from the root node to leaf nodes.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/05/06/palindromic_paths_1.png\" style=\"width: 300px; height: 201px;\"></p>\n\n<pre><strong>Input:</strong> root = [2,3,1,3,1,null,1]\n<strong>Output:</strong> 2 \n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<p><strong><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/05/07/palindromic_paths_2.png\" style=\"width: 300px; height: 314px;\"></strong></p>\n\n<pre><strong>Input:</strong> root = [2,1,1,1,3,null,null,null,null,null,1]\n<strong>Output:</strong> 1 \n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [9]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 9</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1461-check-if-a-string-contains-all-binary-codes-of-size-k/1461-check-if-a-string-contains-all-binary-codes-of-size-k.java",
    "content": "class Solution {\n    public static boolean hasAllCodes(String s, int k) {\n        int need = 1 << k;\n        boolean[] got = new boolean[need];\n        int allOne = need - 1;\n        int hashVal = 0;\n\n        for (int i = 0; i < s.length(); i++) {\n            // calculate hash for s.substr(i-k+1,i+1)\n            hashVal = ((hashVal << 1) & allOne) | (s.charAt(i) - '0');\n            // hash only available when i-k+1 > 0\n            if (i >= k - 1 && !got[hashVal]) {\n                got[hashVal] = true;\n                need--;\n                if (need == 0) {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "1461-check-if-a-string-contains-all-binary-codes-of-size-k/NOTES.md",
    "content": "​"
  },
  {
    "path": "1461-check-if-a-string-contains-all-binary-codes-of-size-k/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/\">1461. Check If a String Contains All Binary Codes of Size K</a></h2><h3>Medium</h3><hr><div><p>Given a binary string <code>s</code> and an integer <code>k</code>, return <code>true</code> <em>if every binary code of length</em> <code>k</code> <em>is a substring of</em> <code>s</code>. Otherwise, return <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"00110110\", k = 2\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"0110\", k = 1\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring. \n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"0110\", k = 2\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The binary code \"00\" is of length 2 and does not exist in the array.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>\n\t<li><code>1 &lt;= k &lt;= 20</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.java",
    "content": "class Solution {\n    public int maxArea(int h, int w, int[] hc, int[] vc) {\n        return (int)((getMax(h,hc)*getMax(w,vc))%1000000007);\n    }\n    public long getMax(int len,int[] cuts){\n        Arrays.sort(cuts);\n        long from=0,max=0;\n        for(int c:cuts){\n            max=Math.max(max,c-from);\n            from=c;\n        }\n        return Math.max(max,len-from);\n    }\n}"
  },
  {
    "path": "1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/NOTES.md",
    "content": "​"
  },
  {
    "path": "1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/\">1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts</a></h2><h3>Medium</h3><hr><div><p>You are given a rectangular cake of size <code>h x w</code> and two arrays of integers <code>horizontalCuts</code> and <code>verticalCuts</code> where:</p>\n\n<ul>\n\t<li><code>horizontalCuts[i]</code> is the distance from the top of the rectangular cake to the <code>i<sup>th</sup></code> horizontal cut and similarly, and</li>\n\t<li><code>verticalCuts[j]</code> is the distance from the left of the rectangular cake to the <code>j<sup>th</sup></code> vertical cut.</li>\n</ul>\n\n<p>Return <em>the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays</em> <code>horizontalCuts</code> <em>and</em> <code>verticalCuts</code>. Since the answer can be a large number, return this <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_2.png\" style=\"width: 225px; height: 240px;\">\n<pre><strong>Input:</strong> h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]\n<strong>Output:</strong> 4 \n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_3.png\" style=\"width: 225px; height: 240px;\">\n<pre><strong>Input:</strong> h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]\n<strong>Output:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= h, w &lt;= 10<sup>9</sup></code></li>\n\t<li><code>1 &lt;= horizontalCuts.length &lt;= min(h - 1, 10<sup>5</sup>)</code></li>\n\t<li><code>1 &lt;= verticalCuts.length &lt;= min(w - 1, 10<sup>5</sup>)</code></li>\n\t<li><code>1 &lt;= horizontalCuts[i] &lt; h</code></li>\n\t<li><code>1 &lt;= verticalCuts[i] &lt; w</code></li>\n\t<li>All the elements in <code>horizontalCuts</code> are distinct.</li>\n\t<li>All the elements in <code>verticalCuts</code> are distinct.</li>\n</ul>\n</div>"
  },
  {
    "path": "1473-paint-house-iii/1473-paint-house-iii.java",
    "content": "class Solution {\n    \n    static final int MAX_COST = 1000001;\n    \n    public int minCost(int[] houses, int[][] cost, int m, int n, int target) {\n        // dp(i, j, k): house, color, group\n        int[][][] dp = new int[m][n][target]; \n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                for (int k = 0; k < target; k++) {\n                    dp[i][j][k] = MAX_COST;\n                }\n            }\n        }\n         \n        if (houses[0] == 0) {\n            for (int j = 0; j < n; j++) {\n                dp[0][j][target - 1] = cost[0][j];\n            } \n        } else {\n            int j = houses[0] - 1;\n            dp[0][j][target - 1] = 0;\n        }\n        \n        \n        int lr = target - 1;\n        \n        for (int i = 1; i < m; i++) {\n            int hr = m - i;\n            if (hr >= target) {\n                hr = target - 1;\n            }\n            \n            if (houses[i] > 0) {\n                int j = houses[i] - 1;\n                for (int remaining = hr; remaining >= lr; remaining--) {\n                    // not change\n                    dp[i][j][remaining] = Math.min(dp[i][j][remaining], dp[i - 1][j][remaining]);\n                    \n                    // change\n                    if (houses[i - 1] > 0 && houses[i - 1] - 1 != j) {\n                        dp[i][j][remaining - 1] = Math.min(dp[i][j][remaining - 1], dp[i - 1][houses[i - 1] - 1][remaining]);\n                    } else {\n                        dp[i][j][remaining - 1] = Math.min(dp[i][j][remaining - 1], min(dp[i - 1], j, remaining));\n                    }\n                }\n                \n                if (lr == 1) {\n                    dp[i][j][0] = Math.min(dp[i][j][0], dp[i - 1][j][0]);\n                }\n            } else {\n                for (int j = 0; j < n; j++) {\n                    for (int remaining = hr; remaining >= lr; remaining--) {\n                        // not change\n                        int a = dp[i - 1][j][remaining];\n                        int b = cost[i][j];\n                        dp[i][j][remaining] = Math.min(dp[i][j][remaining], dp[i - 1][j][remaining] + cost[i][j]);\n\n                        // change\n                        if (houses[i - 1] > 0 && houses[i - 1] - 1 != j) {\n                            dp[i][j][remaining - 1] = Math.min(dp[i][j][remaining - 1], dp[i - 1][houses[i - 1] - 1][remaining] + cost[i][j]);\n                        } else {\n                            dp[i][j][remaining - 1] = Math.min(dp[i][j][remaining - 1], min(dp[i - 1], j, remaining) + cost[i][j]);\n                        }\n                    }\n\n                    if (lr == 1) {\n                        dp[i][j][0] = Math.min(dp[i][j][0], dp[i - 1][j][0] + cost[i][j]);\n                    }\n                }\n            }\n            \n            if (lr > 1) {\n                lr--;\n            }\n        }\n        \n        int min = dp[m - 1][0][0];\n        for (int j = 1; j < n; j++) {\n            if (dp[m - 1][j][0] < min) {\n                min = dp[m - 1][j][0];\n            }\n        }\n\n        return min < MAX_COST ? min : -1;\n    }\n    \n    private int min(int[][] minCost, int j, int remaining) {\n        int min = Integer.MAX_VALUE;\n        for (int k = 0; k < minCost.length; k++) {\n            if (k != j && minCost[k][remaining] < min) {\n                min = minCost[k][remaining];\n            }\n        }\n        \n        return min;\n    }\n    \n}"
  },
  {
    "path": "1473-paint-house-iii/NOTES.md",
    "content": "​"
  },
  {
    "path": "1473-paint-house-iii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/paint-house-iii/\">1473. Paint House III</a></h2><h3>Hard</h3><hr><div><p>There is a row of <code>m</code> houses in a small city, each house must be painted with one of the <code>n</code> colors (labeled from <code>1</code> to <code>n</code>), some houses that have been painted last summer should not be painted again.</p>\n\n<p>A neighborhood is a maximal group of continuous houses that are painted with the same color.</p>\n\n<ul>\n\t<li>For example: <code>houses = [1,2,2,3,3,2,1,1]</code> contains <code>5</code> neighborhoods <code>[{1}, {2,2}, {3,3}, {2}, {1,1}]</code>.</li>\n</ul>\n\n<p>Given an array <code>houses</code>, an <code>m x n</code> matrix <code>cost</code> and an integer <code>target</code> where:</p>\n\n<ul>\n\t<li><code>houses[i]</code>: is the color of the house <code>i</code>, and <code>0</code> if the house is not painted yet.</li>\n\t<li><code>cost[i][j]</code>: is the cost of paint the house <code>i</code> with the color <code>j + 1</code>.</li>\n</ul>\n\n<p>Return <em>the minimum cost of painting all the remaining houses in such a way that there are exactly</em> <code>target</code> <em>neighborhoods</em>. If it is not possible, return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\n<strong>Output:</strong> 9\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\n<strong>Output:</strong> 11\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == houses.length == cost.length</code></li>\n\t<li><code>n == cost[i].length</code></li>\n\t<li><code>1 &lt;= m &lt;= 100</code></li>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n\t<li><code>1 &lt;= target &lt;= m</code></li>\n\t<li><code>0 &lt;= houses[i] &lt;= n</code></li>\n\t<li><code>1 &lt;= cost[i][j] &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1480-running-sum-of-1d-array/1480-running-sum-of-1d-array.java",
    "content": "class Solution {\n    public int[] runningSum(int[] nums) {\n        for(int i=1;i<nums.length;i++){\n            nums[i]+=nums[i-1];\n        }\n        return nums;\n    }\n}"
  },
  {
    "path": "1480-running-sum-of-1d-array/NOTES.md",
    "content": "​"
  },
  {
    "path": "1480-running-sum-of-1d-array/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/running-sum-of-1d-array/\">1480. Running Sum of 1d Array</a></h2><h3>Easy</h3><hr><div><p>Given an array <code>nums</code>. We define a running sum of an array as&nbsp;<code>runningSum[i] = sum(nums[0]…nums[i])</code>.</p>\n\n<p>Return the running sum of <code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,4]\n<strong>Output:</strong> [1,3,6,10]\n<strong>Explanation:</strong> Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,1,1,1,1]\n<strong>Output:</strong> [1,2,3,4,5]\n<strong>Explanation:</strong> Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [3,1,2,10,1]\n<strong>Output:</strong> [3,4,6,16,17]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>-10^6&nbsp;&lt;= nums[i] &lt;=&nbsp;10^6</code></li>\n</ul></div>"
  },
  {
    "path": "15. 3Sum/SolutionCode.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> threeSum(vector<int>& nums) {\n        set<vector<int>> s;\n        \n        sort(nums.begin(), nums.end());\n        int n = nums.size();\n        \n        if(nums[0]==0 && nums[n-1]==0){\n            return {{0,0,0}};\n        }\n        \n        for(int i=0; i< n-2; i++){\n            int l = i + 1, r = n - 1;\n            \n            while(l < r){\n                int sum = nums[i] + nums[l] + nums[r];\n                \n                if(sum == 0){ \n                    s.insert({nums[i], nums[l], nums[r]});\n                    l++;\n                }else if(sum<0){\n                    l++;\n                }else{\n                    r--;\n                }\n            }\n        }\n        \n        vector<vector<int>> v;\n        \n        for(auto i = s.begin(); i!=s.end(); i++){\n            v.push_back(*i);\n        }\n        \n        return v;\n    }\n};\n\n\n// Second Better Approach : \n\nclass Solution {\npublic:\n    vector<vector<int>> threeSum(vector<int>& nums) {\n        sort(nums.begin(), nums.end());\n        vector<vector<int>> res;\n        for (unsigned int i=0; i<nums.size(); i++) {\n            if ((i>0) && (nums[i]==nums[i-1]))\n                continue;\n            int l = i+1, r = nums.size()-1;\n            while (l<r ) {\n                int s = nums[i]+nums[l]+nums[r];\n                if (s>0) r--;\n                else if (s<0) l++;\n                else {\n                    res.push_back(vector<int> {nums[i], nums[l], nums[r]});\n                    while (l < r && nums[l]==nums[l+1]) l++;\n                    while (l < r  && nums[r]==nums[r-1]) r--;\n                    l++; r--;\n                }\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "151. Reverse Words in a String.java",
    "content": "//151. Reverse Words in a String Leetcode\nclass Solution {\n    public String reverseWords(String s) {\n       int len = s.length();\n        String k = \"\", a = \"\";\n\n        for (int i = len - 1; i >= 0; i--) {\n            char currentChar = s.charAt(i);\n            if (currentChar != ' ' && currentChar != '.' && currentChar != ',') {\n                k = currentChar + k;\n            } else {\n                if (!k.isEmpty()) {\n                    a += (a.isEmpty() ? \"\" : \" \") + k;\n                    k = \"\";\n                }\n            }\n        }\n\n        if (!k.isEmpty()) {\n            a += (a.isEmpty() ? \"\" : \" \") + k;\n        }\n\n        return a;\n    }\n}\n"
  },
  {
    "path": "1519-number-of-nodes-in-the-sub-tree-with-the-same-label/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.java",
    "content": "class Solution {\n    public int[] dfs(int node, int parent, Map<Integer, List<Integer>> adj,\n            char[] labels, int[] ans) {\n        // Store count of all alphabets in the subtree of the node.\n        int[] nodeCounts = new int[26];\n        nodeCounts[labels[node] - 'a'] = 1;\n\n        if (!adj.containsKey(node))\n            return nodeCounts;\n        for (int child : adj.get(node)) {\n            if (child == parent) {\n                continue;\n            }\n            int[] childCounts = dfs(child, node, adj, labels, ans);\n            // Add frequencies of the child node in the parent node's frequency array.\n            for (int i = 0; i < 26; i++) {\n                nodeCounts[i] += childCounts[i];\n            }\n        }\n\n        ans[node] = nodeCounts[labels[node] - 'a'];\n        return nodeCounts;\n    }\n\n    public int[] countSubTrees(int n, int[][] edges, String labels) {\n        Map<Integer, List<Integer>> adj = new HashMap<>();\n        for (int[] edge : edges) {\n            int a = edge[0], b = edge[1];\n            adj.computeIfAbsent(a, value -> new ArrayList<Integer>()).add(b);\n            adj.computeIfAbsent(b, value -> new ArrayList<Integer>()).add(a);\n        }\n\n        int[] ans = new int[n];\n        char[] label = labels.toCharArray();\n        dfs(0, -1, adj, label, ans);\n        return ans;\n    }\n}"
  },
  {
    "path": "1519-number-of-nodes-in-the-sub-tree-with-the-same-label/NOTES.md",
    "content": "​"
  },
  {
    "path": "1519-number-of-nodes-in-the-sub-tree-with-the-same-label/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/\">1519. Number of Nodes in the Sub-Tree With the Same Label</a></h2><h3>Medium</h3><hr><div><p>You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code> and exactly <code>n - 1</code> <code>edges</code>. The <strong>root</strong> of the tree is the node <code>0</code>, and each node of the tree has <strong>a label</strong> which is a lower-case character given in the string <code>labels</code> (i.e. The node with the number <code>i</code> has the label <code>labels[i]</code>).</p>\n\n<p>The <code>edges</code> array is given on the form <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>, which means there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>\n\n<p>Return <em>an array of size <code>n</code></em> where <code>ans[i]</code> is the number of nodes in the subtree of the <code>i<sup>th</sup></code> node which have the same label as node <code>i</code>.</p>\n\n<p>A subtree of a tree <code>T</code> is the tree consisting of a node in <code>T</code> and all of its descendant nodes.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/07/01/q3e1.jpg\" style=\"width: 400px; height: 291px;\">\n<pre><strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = \"abaedcd\"\n<strong>Output:</strong> [2,1,1,1,1,1,1]\n<strong>Explanation:</strong> Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/07/01/q3e2.jpg\" style=\"width: 300px; height: 253px;\">\n<pre><strong>Input:</strong> n = 4, edges = [[0,1],[1,2],[0,3]], labels = \"bbbb\"\n<strong>Output:</strong> [4,2,1,1]\n<strong>Explanation:</strong> The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/07/01/q3e3.jpg\" style=\"width: 300px; height: 253px;\">\n<pre><strong>Input:</strong> n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = \"aabab\"\n<strong>Output:</strong> [3,2,1,1,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>edges.length == n - 1</code></li>\n\t<li><code>edges[i].length == 2</code></li>\n\t<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li><code>labels.length == n</code></li>\n\t<li><code>labels</code> is consisting of only of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1531-string-compression-ii/1531-string-compression-ii.java",
    "content": "/*\nWe define the state dp[i][j]: The best solution for the first i chars in the string after at most j chars\nbeing removed; i.e., the minimum length after at most j chars being removed from s.substring(0, i).\n\nFor each such substring, we can either delete or keep the last char, s[i - 1]\n- To delete, dp[i][j] = dp[i - 1][j - 1].\n- To keep, we delete at most j chars in s.substring(0, i) that are different from the last character.\n- We then take the min value of them for dp[i][j]\n*/\nclass Solution {\n    public int getLengthOfOptimalCompression(String s, int k) {\n        int n = s.length();\n        \n        // dp[i][j]: the minimum length for the first i chars after at most j chars being removed.\n        int[][] dp = new int[n + 1][k + 1];\n        // Initialize each cell of the dp 2-D array to n, the max value that each cell can have. This\n        // is OK, as each dp[i][j] will have the min value bewteen dp[i][j] and its calculate value.\n        // for (int[] i : dp) Arrays.fill(i, n); // this is a bit slower (100ms)\n        for (int i = 0; i <= n; i++) {\n            for (int j = 0; j <= k; j++) {\n                dp[i][j] = n;\n            }\n        }\n\t\t\n        // Minimum length of empty string after 0 removal is 0\n        dp[0][0] = 0;\n        \n        // iterate from 1 character substring to n-character substring\n        for(int i = 1; i <= n; i++) {\n            // We can delete at most i characters if i < k or k characters if i >= k.\n            // Using \"j <= k\" alone here is OK but \"j <= i && j <= k\" speeds up a lot\n            for(int j = 0; j <= i && j <= k; j++) {                \n                int count = 0;\n                int del = 0;\n                \n                // delete the last character of the substring (j has to be greater than 1 to delete 1 character)\n                if (j > 0) {\n                    dp[i][j] = dp[i - 1][j - 1];\n                }\n                \n                // Keep the last character of the substring, and starting from the end of the \n                // substring, count the same characters as the last character, and remove characters\n                // that are different.\n                char lastChar = s.charAt(i - 1);\n                for(int p = i; p >= 1; p--) { \n                    if (s.charAt(p - 1) == lastChar) {\n                        count++;\n                    } else {\n                        del++;\n                        \n                        // Bail out if no more removal is available\n                        if (del > j) {\n                            break;\n                        }\n                    }\n                    \n                    // After del number of removals from the end of substring we have \"p - 1\" characters left\n                    // in the substring and AT MOST \"j - del\" removals available\n                    dp[i][j] = Math.min(dp[i][j], dp[p - 1][j - del] + 1 + length(count));\n                }\n            }\n        }\n        \n        return dp[n][k];\n    }\n    \n    // Constraints is \"1 <= s.length <= 100\", then the max count is 100 when all 100 characters are the same\n    // Note we don't add '1' after single characters.\n    private int length(int count) {\n        return count == 100 ? 3 : count >= 10 ? 2 : count > 1 ? 1 : 0;\n    }\n}"
  },
  {
    "path": "1531-string-compression-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "1531-string-compression-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/string-compression-ii/\">1531. String Compression II</a></h2><h3>Hard</h3><hr><div><p><a href=\"http://en.wikipedia.org/wiki/Run-length_encoding\">Run-length encoding</a> 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;<code>\"aabccc\"</code>&nbsp;we replace <font face=\"monospace\"><code>\"aa\"</code></font>&nbsp;by&nbsp;<font face=\"monospace\"><code>\"a2\"</code></font>&nbsp;and replace <font face=\"monospace\"><code>\"ccc\"</code></font>&nbsp;by&nbsp;<font face=\"monospace\"><code>\"c3\"</code></font>. Thus the compressed string becomes <font face=\"monospace\"><code>\"a2bc3\"</code>.</font></p>\n\n<p>Notice that in this problem, we are not adding&nbsp;<code>'1'</code>&nbsp;after single characters.</p>\n\n<p>Given a&nbsp;string <code>s</code>&nbsp;and an integer <code>k</code>. You need to delete <strong>at most</strong>&nbsp;<code>k</code> characters from&nbsp;<code>s</code>&nbsp;such that the run-length encoded version of <code>s</code>&nbsp;has minimum length.</p>\n\n<p>Find the <em>minimum length of the run-length encoded&nbsp;version of </em><code>s</code><em> after deleting at most </em><code>k</code><em> characters</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"aaabcccd\", k = 2\n<strong>Output:</strong> 4\n<b>Explanation: </b>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.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"aabbaa\", k = 2\n<strong>Output:</strong> 2\n<b>Explanation: </b>If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"aaaaaaaaaaa\", k = 0\n<strong>Output:</strong> 3\n<strong>Explanation: </strong>Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= k &lt;= s.length</code></li>\n\t<li><code>s</code> contains only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1544-make-the-string-great/1544-make-the-string-great.java",
    "content": "class Solution {\n    public String makeGood(String s) {\n        Stack<Character> st=new Stack<>();\n        st.push(s.charAt(0));\n        for(int i=1;i<s.length();i++){\n            if(!st.isEmpty() && (st.peek()^32)==s.charAt(i)){\n                st.pop();\n            }else{\n                st.push(s.charAt(i));\n            }\n        }\n        StringBuilder sb=new StringBuilder();\n        while(!st.isEmpty()){\n            sb.append(st.pop());\n        }\n        return sb.reverse().toString();\n    }\n}"
  },
  {
    "path": "1544-make-the-string-great/NOTES.md",
    "content": "​"
  },
  {
    "path": "1544-make-the-string-great/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/make-the-string-great/\">1544. Make The String Great</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code> of lower and upper case English letters.</p>\n\n<p>A good string is a string which doesn't have <strong>two adjacent characters</strong> <code>s[i]</code> and <code>s[i + 1]</code> where:</p>\n\n<ul>\n\t<li><code>0 &lt;= i &lt;= s.length - 2</code></li>\n\t<li><code>s[i]</code> is a lower-case letter and <code>s[i + 1]</code> is the same letter but in upper-case or <strong>vice-versa</strong>.</li>\n</ul>\n\n<p>To make the string good, you can choose <strong>two adjacent</strong> characters that make the string bad and remove them. You can keep doing this until the string becomes good.</p>\n\n<p>Return <em>the string</em> after making it good. The answer is guaranteed to be unique under the given constraints.</p>\n\n<p><strong>Notice</strong> that an empty string is also good.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"leEeetcode\"\n<strong>Output:</strong> \"leetcode\"\n<strong>Explanation:</strong> In the first step, either you choose i = 1 or i = 2, both will result \"leEeetcode\" to be reduced to \"leetcode\".\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"abBAcC\"\n<strong>Output:</strong> \"\"\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"s\"\n<strong>Output:</strong> \"s\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s</code> contains only lower and upper case English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1578-minimum-time-to-make-rope-colorful/1578-minimum-time-to-make-rope-colorful.java",
    "content": "class Solution {\n    public int minCost(String colors, int[] neededTime) {\n        int prev = 0;\n        int res = 0;\n        char arr[] = colors.toCharArray();\n        for (int i = 1; i < arr.length; i++) {\n            if (arr[prev] != arr[i])\n               prev = i;\n            \n            else {\n                if (neededTime[prev] < neededTime[i]) {\n                    res += neededTime[prev];\n                    prev = i;\n                }\n                \n                else {\n                    res += neededTime[i];\n                }\n            }\n        }\n        return res;\n    }\n}"
  },
  {
    "path": "1578-minimum-time-to-make-rope-colorful/NOTES.md",
    "content": "​"
  },
  {
    "path": "1578-minimum-time-to-make-rope-colorful/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-time-to-make-rope-colorful/\">1578. Minimum Time to Make Rope Colorful</a></h2><h3>Medium</h3><hr><div><p>Alice has <code>n</code> balloons arranged on a rope. You are given a <strong>0-indexed</strong> string <code>colors</code> where <code>colors[i]</code> is the color of the <code>i<sup>th</sup></code> balloon.</p>\n\n<p>Alice wants the rope to be <strong>colorful</strong>. She does not want <strong>two consecutive balloons</strong> to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it <strong>colorful</strong>. You are given a <strong>0-indexed</strong> integer array <code>neededTime</code> where <code>neededTime[i]</code> is the time (in seconds) that Bob needs to remove the <code>i<sup>th</sup></code> balloon from the rope.</p>\n\n<p>Return <em>the <strong>minimum time</strong> Bob needs to make the rope <strong>colorful</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/12/13/ballon1.jpg\" style=\"width: 404px; height: 243px;\">\n<pre><strong>Input:</strong> colors = \"abaac\", neededTime = [1,2,3,4,5]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3.</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/12/13/balloon2.jpg\" style=\"width: 244px; height: 243px;\">\n<pre><strong>Input:</strong> colors = \"abc\", neededTime = [1,2,3]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The rope is already colorful. Bob does not need to remove any balloons from the rope.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/12/13/balloon3.jpg\" style=\"width: 404px; height: 243px;\">\n<pre><strong>Input:</strong> colors = \"aabaa\", neededTime = [1,2,3,4,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == colors.length == neededTime.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= neededTime[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>colors</code> contains only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1584-min-cost-to-connect-all-points/1584-min-cost-to-connect-all-points.java",
    "content": "class Solution {\n    public int minCostConnectPoints(int[][] points) {\n        int n = points.length;\n        \n        // Min-heap to store minimum weight edge at top.\n        PriorityQueue<Pair<Integer, Integer>> heap = new PriorityQueue<>((a, b) -> (a.getKey() - b.getKey()));;\n        \n        // Track nodes which are included in MST.\n        boolean[] inMST = new boolean[n];\n        \n        heap.add(new Pair(0, 0));\n        int mstCost = 0;\n        int edgesUsed = 0;\n        \n        while (edgesUsed < n) {\n            Pair<Integer, Integer> topElement = heap.poll();\n            \n            int weight = topElement.getKey();\n            int currNode = topElement.getValue();\n            \n            // If node was already included in MST we will discard this edge.\n            if (inMST[currNode]) {\n                continue;\n            }\n            \n            inMST[currNode] = true;\n            mstCost += weight;\n            edgesUsed++;\n            \n            for (int nextNode = 0; nextNode < n; ++nextNode) {\n                // If next node is not in MST, then edge from curr node\n                // to next node can be pushed in the priority queue.\n                if (!inMST[nextNode]){\n                    int nextWeight = Math.abs(points[currNode][0] - points[nextNode][0]) + Math.abs(points[currNode][1] - points[nextNode][1]);\n        \n                    heap.add(new Pair(nextWeight, nextNode));\n                }\n            }\n        }\n        return mstCost;\n    }\n}"
  },
  {
    "path": "1584-min-cost-to-connect-all-points/NOTES.md",
    "content": "​"
  },
  {
    "path": "1584-min-cost-to-connect-all-points/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/min-cost-to-connect-all-points/\">1584. Min Cost to Connect All Points</a></h2><h3>Medium</h3><hr><div><p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>\n\n<p>The cost of connecting two points <code>[x<sub>i</sub>, y<sub>i</sub>]</code> and <code>[x<sub>j</sub>, y<sub>j</sub>]</code> is the <strong>manhattan distance</strong> between them: <code>|x<sub>i</sub> - x<sub>j</sub>| + |y<sub>i</sub> - y<sub>j</sub>|</code>, where <code>|val|</code> denotes the absolute value of <code>val</code>.</p>\n\n<p>Return <em>the minimum cost to make all points connected.</em> All points are connected if there is <strong>exactly one</strong> simple path between any two points.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/26/d.png\" style=\"width: 214px; height: 268px;\">\n<pre><strong>Input:</strong> points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\n<strong>Output:</strong> 20\n<strong>Explanation:</strong> \n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/26/c.png\" style=\"width: 214px; height: 268px;\">\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> points = [[3,12],[-2,5],[-4,1]]\n<strong>Output:</strong> 18\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= points.length &lt;= 1000</code></li>\n\t<li><code>-10<sup>6</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>6</sup></code></li>\n\t<li>All pairs <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are distinct.</li>\n</ul>\n</div>"
  },
  {
    "path": "16-3sum-closest/16-3sum-closest.java",
    "content": "class Solution {\n    public int threeSumClosest(int[] nums, int target) {\n        Arrays.sort(nums);\n        int n = nums.length;\n        int minDiff = Integer.MAX_VALUE;\n        int result = Integer.MAX_VALUE;\n        \n        for(int i = 0; i < nums.length; i++) {\n            int start = i + 1;\n            int end = n - 1;\n            \n            while(start < end) {\n                \n                int sum = nums[i] + nums[start] + nums[end];\n                \n                if(sum == target) {\n                    return sum;\n                } \n            \n                int diff = Math.abs(target - sum);\n            \n                if(diff < minDiff) {\n                    minDiff = diff;\n                    result = sum;\n                }\n            \n                if(sum > target) {\n                    end--;\n                } else {\n                    start++;\n                }\n            }\n        }\n        \n        return result;\n    }\n}"
  },
  {
    "path": "16-3sum-closest/NOTES.md",
    "content": "​"
  },
  {
    "path": "16-3sum-closest/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/3sum-closest/\">16. 3Sum Closest</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p>\n\n<p>Return <em>the sum of the three integers</em>.</p>\n\n<p>You may assume that each input would have exactly one solution.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [-1,2,1,-4], target = 1\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [0,0,0], target = 1\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "16. 3Sum Closest - leetcode/SolutionCode.cpp",
    "content": "class Solution {\npublic:\n    int threeSumClosest(vector<int>& nums, int target) {\n        sort(nums.begin(), nums.end());\n        int closestSum = nums[0] + nums[1] + nums[2], n = nums.size();\n        \n        for(int i=0; i<n-2; i++){\n            int left = i+1, right = n-1;\n            while(left < right){\n                int tmpSum = nums[i] + nums[left] + nums[right];\n                int diff = abs(tmpSum - target);\n                \n                if(diff == 0) return tmpSum;\n                if(tmpSum < target) left++;\n                else right--;\n                \n                if(abs(closestSum - target) > diff) closestSum = tmpSum;\n            }\n        }\n        \n        return closestSum;\n    }\n};\n"
  },
  {
    "path": "160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.java",
    "content": "public class Solution {\n    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {\n        ListNode t1=headA;\n        ListNode t2=headB;\n        int n=0,m=0;\n        while(t1!=null){\n            m++;\n            t1=t1.next;\n        }\n        while(t2!=null){\n            n++;\n            t2=t2.next;\n        }\n        t1=headA;\n        t2=headB;\n        int t=m-n;\n        if(t>0){\n            m-=t;\n            while(t>0){\n                t1=t1.next;\n                t--;\n            }\n        }else{\n            t=-t;\n            n-=t;\n            while(t>0){\n                t2=t2.next;\n                t--;\n            }\n        }\n        \n        while(n>0){\n            if(t1==t2)\n                break;\n            n--;\n            t1=t1.next;\n            t2=t2.next;\n        }\n        return t1;\n        \n    }\n}"
  },
  {
    "path": "160-intersection-of-two-linked-lists/NOTES.md",
    "content": "​"
  },
  {
    "path": "160-intersection-of-two-linked-lists/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/intersection-of-two-linked-lists/\">160. Intersection of Two Linked Lists</a></h2><h3>Easy</h3><hr><div><p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p>\n\n<p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_statement.png\" style=\"width: 500px; height: 162px;\">\n<p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p>\n\n<p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p>\n\n<p><strong>Custom Judge:</strong></p>\n\n<p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p>\n\n<ul>\n\t<li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li>\n\t<li><code>listA</code> - The first linked list.</li>\n\t<li><code>listB</code> - The second linked list.</li>\n\t<li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li>\n\t<li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li>\n</ul>\n\n<p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code>&nbsp;to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png\" style=\"width: 500px; height: 162px;\">\n<pre><strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\n<strong>Output:</strong> Intersected at '8'\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png\" style=\"width: 500px; height: 194px;\">\n<pre><strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\n<strong>Output:</strong> Intersected at '2'\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png\" style=\"width: 300px; height: 189px;\">\n<pre><strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\n<strong>Output:</strong> No intersection\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li>\n\t<li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li>\n\t<li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= skipA &lt;&nbsp;m</code></li>\n\t<li><code>0 &lt;= skipB &lt;&nbsp;n</code></li>\n\t<li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li>\n\t<li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?</div>"
  },
  {
    "path": "1631-path-with-minimum-effort/1631-path-with-minimum-effort.java",
    "content": "class Solution {\n    public int minimumEffortPath(int[][] heights) {\n        int[][] dirs = new int[][]{{-1,0},{1,0},{0,1},{0,-1}};\n        int numR = heights.length; int numC = heights[0].length;\n        int[][] ans = new int[numR][numC];\n        for (int[] row : ans) {\n            Arrays.fill(row,Integer.MAX_VALUE);\n        }\n        PriorityQueue<int[]> queue = new PriorityQueue<>((a,b)->a[2]-b[2]);\n        queue.offer(new int[]{0,0,0});\n        ans[0][0] = 0;\n        while (!queue.isEmpty()) {\n            int[] curr = queue.poll();\n            if (curr[0]==numR-1 && curr[1]==numC-1) return curr[2];\n            for (int i=0; i<4; i++) {\n                int nextR = curr[0]+dirs[i][0];\n                int nextC = curr[1]+dirs[i][1];\n                if (nextR<0 || nextC<0 || nextR>=numR || nextC>=numC) continue;\n                int diff = Math.abs(heights[nextR][nextC]-heights[curr[0]][curr[1]]);\n                int max = Math.max(diff,curr[2]);\n                if (max<ans[nextR][nextC]) {\n                    ans[nextR][nextC] = max;\n                    queue.offer(new int[]{nextR,nextC,max});\n                }\n            }\n        }\n        return ans[numR-1][numC-1];\n    }\n}"
  },
  {
    "path": "1631-path-with-minimum-effort/NOTES.md",
    "content": "​"
  },
  {
    "path": "1631-path-with-minimum-effort/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/path-with-minimum-effort/\">1631. Path With Minimum Effort</a></h2><h3>Medium</h3><hr><div><p>You are a hiker preparing for an upcoming hike. You are given <code>heights</code>, a 2D array of size <code>rows x columns</code>, where <code>heights[row][col]</code> represents the height of cell <code>(row, col)</code>. You are situated in the top-left cell, <code>(0, 0)</code>, and you hope to travel to the bottom-right cell, <code>(rows-1, columns-1)</code> (i.e.,&nbsp;<strong>0-indexed</strong>). You can move <strong>up</strong>, <strong>down</strong>, <strong>left</strong>, or <strong>right</strong>, and you wish to find a route that requires the minimum <strong>effort</strong>.</p>\n\n<p>A route's <strong>effort</strong> is the <strong>maximum absolute difference</strong><strong> </strong>in heights between two consecutive cells of the route.</p>\n\n<p>Return <em>the minimum <strong>effort</strong> required to travel from the top-left cell to the bottom-right cell.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/04/ex1.png\" style=\"width: 300px; height: 300px;\"></p>\n\n<pre><strong>Input:</strong> heights = [[1,2,2],[3,8,2],[5,3,5]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/04/ex2.png\" style=\"width: 300px; height: 300px;\"></p>\n\n<pre><strong>Input:</strong> heights = [[1,2,3],[3,8,4],[5,3,5]]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/04/ex3.png\" style=\"width: 300px; height: 300px;\">\n<pre><strong>Input:</strong> 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]]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> This route does not require any effort.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>rows == heights.length</code></li>\n\t<li><code>columns == heights[i].length</code></li>\n\t<li><code>1 &lt;= rows, columns &lt;= 100</code></li>\n\t<li><code>1 &lt;= heights[i][j] &lt;= 10<sup>6</sup></code></li>\n</ul></div>"
  },
  {
    "path": "1641-count-sorted-vowel-strings/1641-count-sorted-vowel-strings.java",
    "content": "class Solution {\n    public int countVowelStrings(int n) {\n        int[] countOfEach = new int[] { 1, 1, 1, 1, 1 };\n        \n        for (int i = 0; i < n - 1; i++) {\n            for (int j = 1; j < countOfEach.length; j++) {\n                countOfEach[j] = countOfEach[j - 1] + countOfEach[j];\n             }  \n        }\n        \n        return sum(countOfEach);\n    }\n    \n    private int sum(int[] arr) {\n        int amount = 0;\n        for (int num : arr) {\n            amount += num;\n        }\n        return amount;\n    }\n}"
  },
  {
    "path": "1641-count-sorted-vowel-strings/NOTES.md",
    "content": "​"
  },
  {
    "path": "1641-count-sorted-vowel-strings/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/count-sorted-vowel-strings/\">1641. Count Sorted Vowel Strings</a></h2><h3>Medium</h3><hr><div><p>Given an integer <code>n</code>, return <em>the number of strings of length </em><code>n</code><em> that consist only of vowels (</em><code>a</code><em>, </em><code>e</code><em>, </em><code>i</code><em>, </em><code>o</code><em>, </em><code>u</code><em>) and are <strong>lexicographically sorted</strong>.</em></p>\n\n<p>A string <code>s</code> is <strong>lexicographically sorted</strong> if for all valid <code>i</code>, <code>s[i]</code> is the same as or comes before <code>s[i+1]</code> in the alphabet.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The 5 sorted strings that consist of vowels only are <code>[\"a\",\"e\",\"i\",\"o\",\"u\"].</code>\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 2\n<strong>Output:</strong> 15\n<strong>Explanation:</strong> The 15 sorted strings that consist of vowels only are\n[\"aa\",\"ae\",\"ai\",\"ao\",\"au\",\"ee\",\"ei\",\"eo\",\"eu\",\"ii\",\"io\",\"iu\",\"oo\",\"ou\",\"uu\"].\nNote that \"ea\" is not a valid string since 'e' comes after 'a' in the alphabet.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 33\n<strong>Output:</strong> 66045\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 50</code>&nbsp;</li>\n</ul>\n</div>"
  },
  {
    "path": "1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.java",
    "content": "class Solution {\n    public int furthestBuilding(int[] h, int bricks, int l) {\n        PriorityQueue<Integer> pq=new PriorityQueue<>();\n        int n=h.length;\n        for(int i=1;i<n;i++){\n            int diff=h[i]-h[i-1];\n            if(diff>0){\n                if(pq.size()<l){\n                    pq.add(diff);\n                }else{\n                    int br=diff;\n                    if(pq.size()>0 && pq.peek()<diff){\n                        br=pq.remove();\n                        pq.add(diff);\n                    }\n                    \n                    if(bricks>=br){\n                        bricks-=br;\n                    }else{\n                        return i-1;\n                    }\n                }\n            }\n        }\n        return n-1;\n    }\n}"
  },
  {
    "path": "1642-furthest-building-you-can-reach/NOTES.md",
    "content": "​"
  },
  {
    "path": "1642-furthest-building-you-can-reach/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/furthest-building-you-can-reach/\">1642. Furthest Building You Can Reach</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>heights</code> representing the heights of buildings, some <code>bricks</code>, and some <code>ladders</code>.</p>\n\n<p>You start your journey from building <code>0</code> and move to the next building by possibly using bricks or ladders.</p>\n\n<p>While moving from building <code>i</code> to building <code>i+1</code> (<strong>0-indexed</strong>),</p>\n\n<ul>\n\t<li>If the current building's height is <strong>greater than or equal</strong> to the next building's height, you do <strong>not</strong> need a ladder or bricks.</li>\n\t<li>If the current building's height is <b>less than</b> the next building's height, you can either use <strong>one ladder</strong> or <code>(h[i+1] - h[i])</code> <strong>bricks</strong>.</li>\n</ul>\n\n<p><em>Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/27/q4.gif\" style=\"width: 562px; height: 561px;\">\n<pre><strong>Input:</strong> heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Starting at building 0, you can follow these steps:\n- Go to building 1 without using ladders nor bricks since 4 &gt;= 2.\n- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 &lt; 7.\n- Go to building 3 without using ladders nor bricks since 7 &gt;= 6.\n- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 &lt; 9.\nIt is impossible to go beyond building 4 because you do not have any more bricks or ladders.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2\n<strong>Output:</strong> 7\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> heights = [14,3,19,3], bricks = 17, ladders = 0\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= heights[i] &lt;= 10<sup>6</sup></code></li>\n\t<li><code>0 &lt;= bricks &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= ladders &lt;= heights.length</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1647-minimum-deletions-to-make-character-frequencies-unique/1647-minimum-deletions-to-make-character-frequencies-unique.java",
    "content": "class Solution {\n    public int minDeletions(String s) {\n        Set<Integer> set = new HashSet<>();\n        int[] alpha = new int[26];\n        char[] arr =s.toCharArray();\n        for(char c:arr)\n        {\n            alpha[c-'a']++;\n        }\n        int count = 0;\n        for(int i=0;i<26;i++) {\n            if(alpha[i] != 0) {\n                while(set.contains(alpha[i]) && alpha[i]>0) {\n                    alpha[i]--;\n                    count++;\n                }\n                set.add(alpha[i]);\n            } \n        }\n        \n        return count;\n    }\n}"
  },
  {
    "path": "1647-minimum-deletions-to-make-character-frequencies-unique/NOTES.md",
    "content": "​"
  },
  {
    "path": "1647-minimum-deletions-to-make-character-frequencies-unique/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/\">1647. Minimum Deletions to Make Character Frequencies Unique</a></h2><h3>Medium</h3><hr><div><p>A string <code>s</code> is called <strong>good</strong> if there are no two different characters in <code>s</code> that have the same <strong>frequency</strong>.</p>\n\n<p>Given a string <code>s</code>, return<em> the <strong>minimum</strong> number of characters you need to delete to make </em><code>s</code><em> <strong>good</strong>.</em></p>\n\n<p>The <strong>frequency</strong> of a character in a string is the number of times it appears in the string. For example, in the string <code>\"aab\"</code>, the <strong>frequency</strong> of <code>'a'</code> is <code>2</code>, while the <strong>frequency</strong> of <code>'b'</code> is <code>1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"aab\"\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> <code>s</code> is already good.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"aaabbbcc\"\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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\".</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"ceabaacb\"\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code>&nbsp;contains only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1657-determine-if-two-strings-are-close/1657-determine-if-two-strings-are-close.java",
    "content": "class Solution {\n    public boolean closeStrings(String s1, String s2) {\n        \n        var freqs1 = new int[26];\n        for(var c1: s1.toCharArray()) {\n            freqs1[c1 - 'a']++;\n        }\n        var freqs2 = new int[26];\n        for(var c2: s2.toCharArray()) {\n            freqs2[c2 - 'a']++;\n        }\n        for(int i = 0; i < 26; i++) {\n            if(freqs1[i]  > 0 && freqs2[i] == 0) {\n                return false;\n            }\n            if(freqs1[i] == 0 && freqs2[i]  > 0) {\n                return false; \n            }\n        }\n        Arrays.sort(freqs1);\n        Arrays.sort(freqs2);\n        return Arrays.equals(freqs1, freqs2); \n    }\n}"
  },
  {
    "path": "1657-determine-if-two-strings-are-close/NOTES.md",
    "content": "​"
  },
  {
    "path": "1657-determine-if-two-strings-are-close/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/determine-if-two-strings-are-close/\">1657. Determine if Two Strings Are Close</a></h2><h3>Medium</h3><hr><div><p>Two strings are considered <strong>close</strong> if you can attain one from the other using the following operations:</p>\n\n<ul>\n\t<li>Operation 1: Swap any two <strong>existing</strong> characters.\n\n\t<ul>\n\t\t<li>For example, <code>a<u>b</u>cd<u>e</u> -&gt; a<u>e</u>cd<u>b</u></code></li>\n\t</ul>\n\t</li>\n\t<li>Operation 2: Transform <strong>every</strong> occurrence of one <strong>existing</strong> character into another <strong>existing</strong> character, and do the same with the other character.\n\t<ul>\n\t\t<li>For example, <code><u>aa</u>c<u>abb</u> -&gt; <u>bb</u>c<u>baa</u></code> (all <code>a</code>'s turn into <code>b</code>'s, and all <code>b</code>'s turn into <code>a</code>'s)</li>\n\t</ul>\n\t</li>\n</ul>\n\n<p>You can use the operations on either string as many times as necessary.</p>\n\n<p>Given two strings, <code>word1</code> and <code>word2</code>, return <code>true</code><em> if </em><code>word1</code><em> and </em><code>word2</code><em> are <strong>close</strong>, and </em><code>false</code><em> otherwise.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> word1 = \"abc\", word2 = \"bca\"\n<strong>Output:</strong> true\n<strong>Explanation:</strong> You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"a<u>bc</u>\" -&gt; \"a<u>cb</u>\"\nApply Operation 1: \"<u>a</u>c<u>b</u>\" -&gt; \"<u>b</u>c<u>a</u>\"\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> word1 = \"a\", word2 = \"aa\"\n<strong>Output:</strong> false\n<strong>Explanation: </strong>It is impossible to attain word2 from word1, or vice versa, in any number of operations.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> word1 = \"cabbba\", word2 = \"abbccc\"\n<strong>Output:</strong> true\n<strong>Explanation:</strong> You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"ca<u>b</u>bb<u>a</u>\" -&gt; \"ca<u>a</u>bb<u>b</u>\"\n<code>Apply Operation 2: \"</code><u>c</u>aa<u>bbb</u>\" -&gt; \"<u>b</u>aa<u>ccc</u>\"\nApply Operation 2: \"<u>baa</u>ccc\" -&gt; \"<u>abb</u>ccc\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word1.length, word2.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>word1</code> and <code>word2</code> contain&nbsp;only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1658-minimum-operations-to-reduce-x-to-zero/1658-minimum-operations-to-reduce-x-to-zero.java",
    "content": "class Solution {\n    public int minOperations(int[] nums, int x) {\n        \n        int k = 0;\n\t\tfor(int i = 0; i < nums.length; ++i)k  += nums[i];\n\t\tk -= x;\n\t\t\n\t\tint globalMax = -1;\n\t\tint windowSum = 0;\n\t\tint left = 0;\n\n\t\tfor (int i = 0; i < nums.length; i++) {\n\t\t\twindowSum += nums[i];\n\t\t\twhile (left <= i && windowSum > k) {\n\t\t\t\twindowSum -= nums[left];\n\t\t\t\t++left;\n\t\t\t}\n            if(windowSum == k)globalMax = Math.max(globalMax, i - left + 1);\n\t\t}\n\t\treturn globalMax==-1?-1:nums.length - globalMax;\n    }\n}"
  },
  {
    "path": "1658-minimum-operations-to-reduce-x-to-zero/NOTES.md",
    "content": "​"
  },
  {
    "path": "1658-minimum-operations-to-reduce-x-to-zero/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/\">1658. Minimum Operations to Reduce X to Zero</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>nums</code> and an integer <code>x</code>. In one operation, you can either remove the leftmost or the rightmost element from the array <code>nums</code> and subtract its value from <code>x</code>. Note that this <strong>modifies</strong> the array for future operations.</p>\n\n<p>Return <em>the <strong>minimum number</strong> of operations to reduce </em><code>x</code> <em>to <strong>exactly</strong></em> <code>0</code> <em>if it is possible</em><em>, otherwise, return </em><code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,1,4,2,3], x = 5\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The optimal solution is to remove the last two elements to reduce x to zero.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [5,6,7,8,9], x = 4\n<strong>Output:</strong> -1\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [3,2,20,1,1,3], x = 10\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= x &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1662-check-if-two-string-arrays-are-equivalent/1662-check-if-two-string-arrays-are-equivalent.java",
    "content": "class Solution {\n    public boolean arrayStringsAreEqual(String[] word1, String[] word2) {\n        StringBuilder s1 = new StringBuilder();\n        StringBuilder s2 = new StringBuilder();\n        \n        for(int i = 0 ; i < Math.max(word1.length , word2.length) ; i++){\n            if(i < word1.length){\n                s1.append(word1[i]);\n            }\n            if(i<word2.length){\n                s2.append(word2[i]);\n            }\n        }\n        \n        return (s1.toString()).equals(s2.toString());\n    }\n}"
  },
  {
    "path": "1662-check-if-two-string-arrays-are-equivalent/NOTES.md",
    "content": "​"
  },
  {
    "path": "1662-check-if-two-string-arrays-are-equivalent/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/\">1662. Check If Two String Arrays are Equivalent</a></h2><h3>Easy</h3><hr><div><p>Given two string arrays <code>word1</code> and <code>word2</code>, return<em> </em><code>true</code><em> if the two arrays <strong>represent</strong> the same string, and </em><code>false</code><em> otherwise.</em></p>\n\n<p>A string is <strong>represented</strong> by an array if the array elements concatenated <strong>in order</strong> forms the string.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> word1 = [\"ab\", \"c\"], word2 = [\"a\", \"bc\"]\n<strong>Output:</strong> true\n<strong>Explanation:</strong>\nword1 represents string \"ab\" + \"c\" -&gt; \"abc\"\nword2 represents string \"a\" + \"bc\" -&gt; \"abc\"\nThe strings are the same, so return true.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> word1  = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word1.length, word2.length &lt;= 10<sup>3</sup></code></li>\n\t<li><code>1 &lt;= word1[i].length, word2[i].length &lt;= 10<sup>3</sup></code></li>\n\t<li><code>1 &lt;= sum(word1[i].length), sum(word2[i].length) &lt;= 10<sup>3</sup></code></li>\n\t<li><code>word1[i]</code> and <code>word2[i]</code> consist of lowercase letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1663-smallest-string-with-a-given-numeric-value/1663-smallest-string-with-a-given-numeric-value.java",
    "content": "class Solution {\n    public String getSmallestString(int n, int k) {\n        char ch[]=new char[n];\n        int i=0;\n        while(i<n){\n            if(26*(n-i)>=k){\n                ch[i]='a';\n                i++;\n                k--;\n            }else{\n                break;\n            }\n        }\n        i--;\n        ch[i]=(char)(k%26+'a');\n        i++;\n        while(i<n)\n        {\n            ch[i]='z';\n            i++;\n        }\n        return String.valueOf(ch);\n    }\n}"
  },
  {
    "path": "1663-smallest-string-with-a-given-numeric-value/NOTES.md",
    "content": "​"
  },
  {
    "path": "1663-smallest-string-with-a-given-numeric-value/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/\">1663. Smallest String With A Given Numeric Value</a></h2><h3>Medium</h3><hr><div><p>The <strong>numeric value</strong> of a <strong>lowercase character</strong> is defined as its position <code>(1-indexed)</code> in the alphabet, so the numeric value of <code>a</code> is <code>1</code>, the numeric value of <code>b</code> is <code>2</code>, the numeric value of <code>c</code> is <code>3</code>, and so on.</p>\n\n<p>The <strong>numeric value</strong> of a <strong>string</strong> consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string <code>\"abe\"</code> is equal to <code>1 + 2 + 5 = 8</code>.</p>\n\n<p>You are given two integers <code>n</code> and <code>k</code>. Return <em>the <strong>lexicographically smallest string</strong> with <strong>length</strong> equal to <code>n</code> and <strong>numeric value</strong> equal to <code>k</code>.</em></p>\n\n<p>Note that a string <code>x</code> is lexicographically smaller than string <code>y</code> if <code>x</code> comes before <code>y</code> in dictionary order, that is, either <code>x</code> is a prefix of <code>y</code>, or if <code>i</code> is the first position such that <code>x[i] != y[i]</code>, then <code>x[i]</code> comes before <code>y[i]</code> in alphabetic order.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 3, k = 27\n<strong>Output:</strong> \"aay\"\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 5, k = 73\n<strong>Output:</strong> \"aaszz\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>n &lt;= k &lt;= 26 * n</code></li>\n</ul>\n</div>"
  },
  {
    "path": "167-two-sum-ii-input-array-is-sorted/167-two-sum-ii-input-array-is-sorted.java",
    "content": "class Solution {\n    public int[] twoSum(int[] numbers, int target) {\n        int left = 0;\n        int right = numbers.length - 1;\n        boolean targetLocated = false;\n        while (left < right && !targetLocated) {\n            int mid = left + (right - left) / 2;\n            int midVal = numbers[mid];\n            int curr = numbers[left] + numbers[right];\n            if(curr == target) {\n                targetLocated = true;\n            } else if (curr < target) {\n                if (midVal + numbers[right] < target) {\n                    left = mid + 1;\n                } else {\n                    left++;\n                }\n                \n            } else {\n                \n                if (midVal + numbers[left] > target) {\n                    right = mid - 1;\n                } else {\n                    right--;\n                }\n                \n                \n            }\n            \n        }\n        \n        int[] vals = new int[2];\n        vals[0] = left + 1;\n        vals[1] = right + 1;\n        \n        return vals;\n        \n    }\n}"
  },
  {
    "path": "167-two-sum-ii-input-array-is-sorted/NOTES.md",
    "content": "​"
  },
  {
    "path": "167-two-sum-ii-input-array-is-sorted/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/\">167. Two Sum II - Input Array Is Sorted</a></h2><h3>Medium</h3><hr><div><p>Given a <strong>1-indexed</strong> array of integers <code>numbers</code> that is already <strong><em>sorted in non-decreasing order</em></strong>, find two numbers such that they add up to a specific <code>target</code> number. Let these two numbers be <code>numbers[index<sub>1</sub>]</code> and <code>numbers[index<sub>2</sub>]</code> where <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p>\n\n<p>Return<em> the indices of the two numbers, </em><code>index<sub>1</sub></code><em> and </em><code>index<sub>2</sub></code><em>, <strong>added by one</strong> as an integer array </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> of length 2.</em></p>\n\n<p>The tests are generated such that there is <strong>exactly one solution</strong>. You <strong>may not</strong> use the same element twice.</p>\n\n<p>Your solution must use only constant extra space.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9\n<strong>Output:</strong> [1,2]\n<strong>Explanation:</strong> The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2].\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6\n<strong>Output:</strong> [1,3]\n<strong>Explanation:</strong> The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3].\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1\n<strong>Output:</strong> [1,2]\n<strong>Explanation:</strong> The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li>\n\t<li><code>numbers</code> is sorted in <strong>non-decreasing order</strong>.</li>\n\t<li><code>-1000 &lt;= target &lt;= 1000</code></li>\n\t<li>The tests are generated such that there is <strong>exactly one solution</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "1679-max-number-of-k-sum-pairs/1679-max-number-of-k-sum-pairs.java",
    "content": "class Solution {\n    public int maxOperations(int[] nums, int k) {\n        int ans=0;\n        Arrays.sort(nums);\n        int i=0;\n        int j=nums.length-1;\n        while(i<j){\n            int sum=nums[i]+nums[j];\n            if(sum==k){\n                ans++;\n                i++;\n                j--;\n            }else if(sum<k){\n                i++;\n            }else{\n                j--;\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "1679-max-number-of-k-sum-pairs/NOTES.md",
    "content": "​"
  },
  {
    "path": "1680 Concatenation of Consecutive Binary Numbers med s23.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;;\n\nclass Solution {\npublic:\n    // using bit manipulation TC: O(N), SC: O(1)\n    int concatenatedBinary(int n) {\n       int m = 1e9+7, l=0; // l is bit length to be shifted\n        long res =0;\n        for(int i =1; i<=n; i++){\n             if ((i & (i - 1)) == 0) l += 1;\n            res = ((res << l) | i) % m;\n        }\n        return res;\n        \n    }\n};"
  },
  {
    "path": "1680-concatenation-of-consecutive-binary-numbers/1680-concatenation-of-consecutive-binary-numbers.java",
    "content": "class Solution {\n    static String arr[] = new String[100001];\n\nstatic int ans[] = new int[100001];\n\npublic void build() {\n    for(int i=1; i<=100000; i++) {\n        arr[i] = Integer.toBinaryString(i);\n    }\n}\n\nint mod = 1000000007;\n\npublic int getVal(int n) {\n    int val = 0;\n    for(int i=1; i<=n; i++) {\n        for(int j=0; j<arr[i].length(); j++) {\n            int x = arr[i].charAt(j)-'0';\n            val = (val*2 + x)%mod;\n        }\n        ans[i] = val;\n    }\n    return val;\n}\n\npublic int concatenatedBinary(int n) {\n    if(arr[1]==null) {\n        build();\n        getVal(100000);\n    }\n    return ans[n];\n}\n}"
  },
  {
    "path": "1680-concatenation-of-consecutive-binary-numbers/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/\">1680. Concatenation of Consecutive Binary Numbers</a></h2><h3>Medium</h3><hr><div><p>Given an integer <code>n</code>, return <em>the <strong>decimal value</strong> of the binary string formed by concatenating the binary representations of </em><code>1</code><em> to </em><code>n</code><em> in order, <strong>modulo </strong></em><code>10<sup>9 </sup>+ 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n<strong>Explanation: </strong>\"1\" in binary corresponds to the decimal value 1. \n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 3\n<strong>Output:</strong> 27\n<strong>Explanation: </strong>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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 12\n<strong>Output:</strong> 505379714\n<strong>Explanation</strong>: The concatenation results in \"1101110010111011110001001101010111100\".\nThe decimal value of that is 118505380540.\nAfter modulo 10<sup>9</sup> + 7, the result is 505379714.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1689-partitioning-into-minimum-number-of-deci-binary-numbers/1689-partitioning-into-minimum-number-of-deci-binary-numbers.java",
    "content": "class Solution {\n    public int minPartitions(String n) {\n        for(int i=9; i>=1; i--) {\n            String ch = Integer.toString(i);\n            if( n.contains(ch) )return i;\n        }\n        return 0;\n        \n    }\n}"
  },
  {
    "path": "1689-partitioning-into-minimum-number-of-deci-binary-numbers/NOTES.md",
    "content": "​"
  },
  {
    "path": "1689-partitioning-into-minimum-number-of-deci-binary-numbers/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/\">1689. Partitioning Into Minimum Number Of Deci-Binary Numbers</a></h2><h3>Medium</h3><hr><div><p>A decimal number is called <strong>deci-binary</strong> if each of its digits is either <code>0</code> or <code>1</code> without any leading zeros. For example, <code>101</code> and <code>1100</code> are <strong>deci-binary</strong>, while <code>112</code> and <code>3001</code> are not.</p>\n\n<p>Given a string <code>n</code> that represents a positive decimal integer, return <em>the <strong>minimum</strong> number of positive <strong>deci-binary</strong> numbers needed so that they sum up to </em><code>n</code><em>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = \"32\"\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 10 + 11 + 11 = 32\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = \"82734\"\n<strong>Output:</strong> 8\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = \"27346209830709182346\"\n<strong>Output:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>n</code> consists of only digits.</li>\n\t<li><code>n</code> does not contain any leading zeros and represents a positive integer.</li>\n</ul>\n</div>"
  },
  {
    "path": "1695-maximum-erasure-value/1695-maximum-erasure-value.java",
    "content": "class Solution {\n    public int maximumUniqueSubarray(int[] arr) {\n        int res = 0;\n        boolean[] check = new boolean[10001];\n        int l = 0;\n        int r = 0;\n        int temp=0;\n        while(r<arr.length){\n            if(check[arr[r]] == true){\n                 res = Math.max(res, temp);\n                 while (arr[l] != arr[r]) {\n                     temp-=arr[l];\n                     check[arr[l]] = false;\n                     l++;\n                 }\n                 l++;\n            }else{\n                check[arr[r]] = true;\n                temp+= arr[r];\n            }\n            r++;\n            res = Math.max(res, temp);\n        }\n        return res;\n    }\n}"
  },
  {
    "path": "1695-maximum-erasure-value/NOTES.md",
    "content": "​"
  },
  {
    "path": "1695-maximum-erasure-value/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-erasure-value/\">1695. Maximum Erasure Value</a></h2><h3>Medium</h3><hr><div><p>You are given an array of positive integers <code>nums</code> and want to erase a subarray containing&nbsp;<strong>unique elements</strong>. The <strong>score</strong> you get by erasing the subarray is equal to the <strong>sum</strong> of its elements.</p>\n\n<p>Return <em>the <strong>maximum score</strong> you can get by erasing <strong>exactly one</strong> subarray.</em></p>\n\n<p>An array <code>b</code> is called to be a <span class=\"tex-font-style-it\">subarray</span> of <code>a</code> if it forms a contiguous subsequence of <code>a</code>, that is, if it is equal to <code>a[l],a[l+1],...,a[r]</code> for some <code>(l,r)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [4,2,4,5,6]\n<strong>Output:</strong> 17\n<strong>Explanation:</strong> The optimal subarray here is [2,4,5,6].\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [5,2,1,2,5,2,1,2,5]\n<strong>Output:</strong> 8\n<strong>Explanation:</strong> The optimal subarray here is [5,2,1] or [1,2,5].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1696-jump-game-vi/1696-jump-game-vi.java",
    "content": "class Solution {\n    public int maxResult(int[] nums, int k) {\n        \n        int n = nums.length;\n        int result = 0;\n        \n        if(k > n) {\n            k = n;\n        }\n        \n        if(k < 1) {\n            for(int i = 0; i < n; i++) {\n                result += nums[i];\n            }\n            return result;\n        }\n        \n        \n        int[] dp = new int[n];\n        \n        dp[0] = nums[0];\n        \n        for(int i = 1; i < n; i++) {\n            dp[i] = Integer.MIN_VALUE;\n        }\n        \n        int maxIndex = 0;\n        \n        for(int i = 1; i < n; i++) {\n            if(maxIndex < i - k) {\n                \n                int max = Integer.MIN_VALUE;\n                for(int j = maxIndex+1; j < n && j <= maxIndex+k; j++) {\n                    if(max <= dp[j]) {\n                        max = dp[j];\n                        maxIndex = j;\n                    }\n                }\n            }\n            \n            dp[i] = Math.max(nums[i] + dp[maxIndex], dp[i]);\n            if(dp[i] >= dp[maxIndex]) {\n                maxIndex = i;\n            }\n            \n        }\n        return dp[n-1];\n    }\n}"
  },
  {
    "path": "1696-jump-game-vi/NOTES.md",
    "content": "​"
  },
  {
    "path": "1696-jump-game-vi/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/jump-game-vi/\">1696. Jump Game VI</a></h2><h3>Medium</h3><hr><div><p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p>\n\n<p>You are initially standing at index <code>0</code>. In one move, you can jump at most <code>k</code> steps forward without going outside the boundaries of the array. That is, you can jump from index <code>i</code> to any index in the range <code>[i + 1, min(n - 1, i + k)]</code> <strong>inclusive</strong>.</p>\n\n<p>You want to reach the last index of the array (index <code>n - 1</code>). Your <strong>score</strong> is the <strong>sum</strong> of all <code>nums[j]</code> for each index <code>j</code> you visited in the array.</p>\n\n<p>Return <em>the <strong>maximum score</strong> you can get</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [<u>1</u>,<u>-1</u>,-2,<u>4</u>,-7,<u>3</u>], k = 2\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [<u>10</u>,-5,-2,<u>4</u>,0,<u>3</u>], k = 3\n<strong>Output:</strong> 17\n<strong>Explanation:</strong> You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length, k &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "17-letter-combinations-of-a-phone-number/17-letter-combinations-of-a-phone-number.java",
    "content": "class Solution {\n    public static String[] map = {\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n    public List<String> letterCombinations(String digits) {\n        List<String> res = new ArrayList<>();\n        if(digits == null || digits.length() == 0){\n            return res;\n        }\n        dfs(digits, 0, new StringBuilder(), res);\n        return res;\n    }\n    \n    public void dfs(String digits, int index, StringBuilder sb, List<String> res){\n        if(index == digits.length()){\n            res.add(sb.toString());\n            return;\n        }\n        \n        String str = map[digits.charAt(index) - '0'];\n        for(int i = 0; i < str.length(); i++){\n            sb.append(str.charAt(i));\n            dfs(digits, index + 1, sb, res);\n            sb.deleteCharAt(sb.length() - 1);\n        }\n    }\n}"
  },
  {
    "path": "17-letter-combinations-of-a-phone-number/NOTES.md",
    "content": "​"
  },
  {
    "path": "17-letter-combinations-of-a-phone-number/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/letter-combinations-of-a-phone-number/\">17. Letter Combinations of a Phone Number</a></h2><h3>Medium</h3><hr><div><p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p>\n\n<p>A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p>\n\n<p><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png\" style=\"width: 200px; height: 162px;\"></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> digits = \"23\"\n<strong>Output:</strong> [\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> digits = \"\"\n<strong>Output:</strong> []\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> digits = \"2\"\n<strong>Output:</strong> [\"a\",\"b\",\"c\"]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= digits.length &lt;= 4</code></li>\n\t<li><code>digits[i]</code> is a digit in the range <code>['2', '9']</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "1704-determine-if-string-halves-are-alike/1704-determine-if-string-halves-are-alike.java",
    "content": "class Solution {\n    public boolean halvesAreAlike(String s) {\n       char[] ch=s.toCharArray();\n       int len=s.length();\n       int mid=len/2;\n       int l=check(ch,0,mid-1);\n       int r=check(ch,mid,len-1);\n        if(l==r)\n        {\n            return true;\n        }\n        return false;\n        \n    }\n    public int check(char[] ch,int start,int end){\n        int count=0;\n        for(int i=start;i<=end;i++)\n        {\n            if(ch[i]=='a'||ch[i]=='e'||ch[i]=='i'||ch[i]=='o'||ch[i]=='u'||ch[i]=='A'||ch[i]=='E'||ch[i]=='I'||ch[i]=='O'||ch[i]=='U')\n            {\n               count++; \n            }\n         }\n        return count;\n    }\n}"
  },
  {
    "path": "1704-determine-if-string-halves-are-alike/NOTES.md",
    "content": "​"
  },
  {
    "path": "1704-determine-if-string-halves-are-alike/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/determine-if-string-halves-are-alike/\">1704. Determine if String Halves Are Alike</a></h2><h3>Easy</h3><hr><div><p>You are given a string <code>s</code> of even length. Split this string into two halves of equal lengths, and let <code>a</code> be the first half and <code>b</code> be the second half.</p>\n\n<p>Two strings are <strong>alike</strong> if they have the same number of vowels (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, <code>'u'</code>, <code>'A'</code>, <code>'E'</code>, <code>'I'</code>, <code>'O'</code>, <code>'U'</code>). Notice that <code>s</code> contains uppercase and lowercase letters.</p>\n\n<p>Return <code>true</code><em> if </em><code>a</code><em> and </em><code>b</code><em> are <strong>alike</strong></em>. Otherwise, return <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"book\"\n<strong>Output:</strong> true\n<strong>Explanation:</strong> a = \"b<u>o</u>\" and b = \"<u>o</u>k\". a has 1 vowel and b has 1 vowel. Therefore, they are alike.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"textbook\"\n<strong>Output:</strong> false\n<strong>Explanation:</strong> a = \"t<u>e</u>xt\" and b = \"b<u>oo</u>k\". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s.length</code> is even.</li>\n\t<li><code>s</code> consists of <strong>uppercase and lowercase</strong> letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1706-where-will-the-ball-fall/1706-where-will-the-ball-fall.java",
    "content": "class Solution {\n    public int[] findBall(int[][] grid) {\n        int result[] = new int[grid[0].length];\n        for (int i = 0; i < grid[0].length; i++) {\n            result[i] = findBallDropColumn(0, i, grid);\n        }\n        return result;\n    }\n\n    public int findBallDropColumn(int row, int col, int[][] grid) {\n        // base case; ball reached the last row\n        if (row == grid.length)\n            return col;\n        int nextColumn = col + grid[row][col];\n        if (nextColumn < 0 ||\n                nextColumn > grid[0].length - 1 ||\n                grid[row][col] != grid[row][nextColumn]) {\n            return -1;\n        }\n        return findBallDropColumn(row + 1, nextColumn, grid);\n    }\n}"
  },
  {
    "path": "1706-where-will-the-ball-fall/NOTES.md",
    "content": "​"
  },
  {
    "path": "1706-where-will-the-ball-fall/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/where-will-the-ball-fall/\">1706. Where Will the Ball Fall</a></h2><h3>Medium</h3><hr><div><p>You have a 2-D <code>grid</code> of size <code>m x n</code> representing a box, and you have <code>n</code> balls. The box is open on the top and bottom sides.</p>\n\n<p>Each 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.</p>\n\n<ul>\n\t<li>A 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 <code>1</code>.</li>\n\t<li>A 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 <code>-1</code>.</li>\n</ul>\n\n<p>We 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.</p>\n\n<p>Return <em>an array </em><code>answer</code><em> of size </em><code>n</code><em> where </em><code>answer[i]</code><em> is the column that the ball falls out of at the bottom after dropping the ball from the </em><code>i<sup>th</sup></code><em> column at the top, or <code>-1</code><em> if the ball gets stuck in the box</em>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<p><strong><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/09/26/ball.jpg\" style=\"width: 500px; height: 385px;\"></strong></p>\n\n<pre><strong>Input:</strong> 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]]\n<strong>Output:</strong> [1,-1,-1,-1,-1]\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> grid = [[-1]]\n<strong>Output:</strong> [-1]\n<strong>Explanation:</strong> The ball gets stuck against the left wall.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> 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]]\n<strong>Output:</strong> [0,1,2,3,4,-1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>grid[i][j]</code> is <code>1</code> or <code>-1</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "1710-maximum-units-on-a-truck/1710-maximum-units-on-a-truck.java",
    "content": "class Solution {\n    public int maximumUnits(int[][] boxTypes, int truckSize) {\n        int units = 0;\n        \n        int [] unitsVsBoxesCount = new int[1001];//value = number of boxes with i units per box\n        for(int [] boxType : boxTypes) { //O(N)\n            unitsVsBoxesCount[ boxType[1] ] += boxType[0];\n        }\n        for(int i = 1000; i > 0; i--) { //O(1001) = O(1)\n            if(unitsVsBoxesCount[i] > truckSize) {\n                units += (truckSize * i);\n                break;\n            } else if (unitsVsBoxesCount[i] > 0) {\n                units += (unitsVsBoxesCount[i] * i);\n                truckSize -= unitsVsBoxesCount[i];\n            }\n        }\n        return units;\n    }\n}"
  },
  {
    "path": "1710-maximum-units-on-a-truck/NOTES.md",
    "content": "​"
  },
  {
    "path": "1710-maximum-units-on-a-truck/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-units-on-a-truck/\">1710. Maximum Units on a Truck</a></h2><h3>Easy</h3><hr><div><p>You are assigned to put some amount of boxes onto <strong>one truck</strong>. You are given a 2D array <code>boxTypes</code>, where <code>boxTypes[i] = [numberOfBoxes<sub>i</sub>, numberOfUnitsPerBox<sub>i</sub>]</code>:</p>\n\n<ul>\n\t<li><code>numberOfBoxes<sub>i</sub></code> is the number of boxes of type <code>i</code>.</li>\n\t<li><code>numberOfUnitsPerBox<sub>i</sub></code><sub> </sub>is the number of units in each box of the type <code>i</code>.</li>\n</ul>\n\n<p>You are also given an integer <code>truckSize</code>, which is the <strong>maximum</strong> number of <strong>boxes</strong> that can be put on the truck. You can choose any boxes to put on the truck as long as the number&nbsp;of boxes does not exceed <code>truckSize</code>.</p>\n\n<p>Return <em>the <strong>maximum</strong> total number of <strong>units</strong> that can be put on the truck.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4\n<strong>Output:</strong> 8\n<strong>Explanation:</strong> There are:\n- 1 box of the first type that contains 3 units.\n- 2 boxes of the second type that contain 2 units each.\n- 3 boxes of the third type that contain 1 unit each.\nYou can take all the boxes of the first and second types, and one box of the third type.\nThe total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10\n<strong>Output:</strong> 91\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= boxTypes.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= numberOfBoxes<sub>i</sub>, numberOfUnitsPerBox<sub>i</sub> &lt;= 1000</code></li>\n\t<li><code>1 &lt;= truckSize &lt;= 10<sup>6</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1721-swapping-nodes-in-a-linked-list/1721-swapping-nodes-in-a-linked-list.java",
    "content": "/**\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 swapNodes(ListNode head, int k) {\n        \n        ListNode fast=head; \n        ListNode slow=head;  \n        int count=1;\n        while(fast !=null && count <k){ \n            fast=fast.next;\n            count++;\n        }\n\t\t//move fast k-1 time ahead of slow \n        ListNode fkth=fast;\n        while(fast.next !=null ){\n            fast=fast.next; \n            slow=slow.next;\n        }\n\t\t//fast.next=null\n\t\t//slow is equal to kth from end of the list\n        //swapping\n       int temp=fkth.val;\n       fkth.val=slow.val;\n       slow.val=temp;\n        \n        return head;\n    }\n}"
  },
  {
    "path": "1721-swapping-nodes-in-a-linked-list/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/swapping-nodes-in-a-linked-list/\">1721. Swapping Nodes in a Linked List</a></h2><h3>Medium</h3><hr><div><p>You are given the <code>head</code> of a linked list, and an integer <code>k</code>.</p>\n\n<p>Return <em>the head of the linked list after <strong>swapping</strong> the values of the </em><code>k<sup>th</sup></code> <em>node from the beginning and the </em><code>k<sup>th</sup></code> <em>node from the end (the list is <strong>1-indexed</strong>).</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg\" style=\"width: 400px; height: 112px;\">\n<pre><strong>Input:</strong> head = [1,2,3,4,5], k = 2\n<strong>Output:</strong> [1,4,3,2,5]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> head = [7,9,6,6,7,8,3,0,9,5], k = 5\n<strong>Output:</strong> [7,9,6,6,8,7,3,0,9,5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is <code>n</code>.</li>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "173-binary-search-tree-iterator/173-binary-search-tree-iterator.java",
    "content": "class BSTIterator {\n    \n    Deque<TreeNode> stack = new ArrayDeque<>();\n\n    public BSTIterator(TreeNode root) {\n        pushLeft(root);\n    }\n    \n    public int next() {\n        TreeNode node = stack.pollFirst();\n        pushLeft(node.right);\n        return node.val;\n    }\n    \n    public boolean hasNext() {\n        return !stack.isEmpty();\n    }\n    \n    private void pushLeft(TreeNode root) {\n        while (root != null) {\n            stack.addFirst(root);\n            root = root.left;\n        }\n    }\n}"
  },
  {
    "path": "173-binary-search-tree-iterator/NOTES.md",
    "content": "​"
  },
  {
    "path": "173-binary-search-tree-iterator/binary-search-tree-iterator.cpp",
    "content": "#include<bits/stdc++.h>\nclass BSTIterator {    \n//I use Stack to store directed left children from root.              \n// When next() be called, I just pop one element and process its right child as new root.\n    stack<TreeNode*> stack;\npublic:                    \n    BSTIterator(TreeNode* root) {\n        addElements(root);\n    }\n    \n    int next() {\n        TreeNode* temp = stack.top();\n        stack.pop();\n        addElements(temp->right);\n        return temp->val;\n    }\n    \n    bool hasNext() {\n        return !stack.empty();\n    }\nprivate:\n    void addElements(TreeNode* node){\n        for(;node != NULL; stack.push(node), node=node->left);\n    }\n};\n"
  },
  {
    "path": "1742. Maximum Number of Balls in a Box(leetcode)",
    "content": "class Solution {\n    public int countBalls(int lowLimit, int highLimit) {\n        Map<Integer,Integer>map=new HashMap<>();\n        int res=0;\n        for(int i=lowLimit;i<=highLimit;i++){\n            int d=digitSum(i);\n            map.put(d,map.getOrDefault(d,0)+1);\n            res=Math.max(res,map.get(d));\n        }return  res;\n    }\n        \n    public int digitSum(int num){\n        int sum=0;\n        while(num!=0){\n            sum=sum+(num%10);\n            num=num/10;\n        }return sum;\n    }\n}\n"
  },
  {
    "path": "1770 Maximum Score from Performing Multiplication Operations lc.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n     int m, n;\n    int dfs(vector<int>& nums, vector<int>& mult, vector<vector<int>>& dp, int i, int j) {\n        // i : *ptr at nums\n        // j : *ptr at mult\n        // if performed all oper, return 0\n        if (j == m) return 0;\n        // memoizated before - return the value here\n        if (dp[i][j] != INT_MIN) return dp[i][j];\n        return dp[i][j] = max(\n            mult[j] * nums[i] + dfs(nums, mult, dp, i + 1, j + 1),\n            mult[j] * nums[n - 1 - j + i] + dfs(nums, mult, dp, i, j + 1)\n        ); \n    }\n    int maximumScore(vector<int>& nums, vector<int>& multipliers) {\n        n = (int) nums.size(), m = (int) multipliers.size();\n\t\t// init values that couldn't be reached. -1 will cause TLE. -2 would pass but it's not supposed to pass.\n        vector<vector<int>> dp(m, vector<int>(m, INT_MIN));\n        // or u can return dp[0][0] after running dfs\n        return dfs(nums, multipliers, dp, 0, 0);\n    }\n};"
  },
  {
    "path": "1770-maximum-score-from-performing-multiplication-operations/1770-maximum-score-from-performing-multiplication-operations.java",
    "content": "class Solution {\n    public int maximumScore(int[] nums, int[] multipliers) {\n        // For Right Pointer\n        int n = nums.length;\n        // Number of Operations\n        int m = multipliers.length;\n        int[][] dp = new int[m + 1][m + 1];\n        \n        for (int op = m - 1; op >= 0; op--) {\n            for (int left = op; left >= 0; left--) {\n                dp[op][left] = Math.max(multipliers[op] * nums[left] + dp[op + 1][left + 1],\n                                   multipliers[op] * nums[n - 1 - (op - left)] + dp[op + 1][left]);\n            }\n        }\n        \n        return dp[0][0];\n    }\n}"
  },
  {
    "path": "1770-maximum-score-from-performing-multiplication-operations/NOTES.md",
    "content": "​"
  },
  {
    "path": "1770-maximum-score-from-performing-multiplication-operations/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/\">1770. Maximum Score from Performing Multiplication Operations</a></h2><h3>Medium</h3><hr><div><p>You are given two integer arrays <code>nums</code> and <code>multipliers</code><strong> </strong>of size <code>n</code> and <code>m</code> respectively, where <code>n &gt;= m</code>. The arrays are <strong>1-indexed</strong>.</p>\n\n<p>You begin with a score of <code>0</code>. You want to perform <strong>exactly</strong> <code>m</code> operations. On the <code>i<sup>th</sup></code> operation <strong>(1-indexed)</strong>, you will:</p>\n\n<ul>\n\t<li>Choose one integer <code>x</code> from <strong>either the start or the end </strong>of the array <code>nums</code>.</li>\n\t<li>Add <code>multipliers[i] * x</code> to your score.</li>\n\t<li>Remove <code>x</code> from the array <code>nums</code>.</li>\n</ul>\n\n<p>Return <em>the <strong>maximum</strong> score after performing </em><code>m</code> <em>operations.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3], multipliers = [3,2,1]\n<strong>Output:</strong> 14\n<strong>Explanation:</strong>&nbsp;An optimal solution is as follows:\n- Choose from the end, [1,2,<strong><u>3</u></strong>], adding 3 * 3 = 9 to the score.\n- Choose from the end, [1,<strong><u>2</u></strong>], adding 2 * 2 = 4 to the score.\n- Choose from the end, [<strong><u>1</u></strong>], adding 1 * 1 = 1 to the score.\nThe total score is 9 + 4 + 1 = 14.</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]\n<strong>Output:</strong> 102\n<strong>Explanation: </strong>An optimal solution is as follows:\n- Choose from the start, [<u><strong>-5</strong></u>,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.\n- Choose from the start, [<strong><u>-3</u></strong>,-3,-2,7,1], adding -3 * -5 = 15 to the score.\n- Choose from the start, [<strong><u>-3</u></strong>,-2,7,1], adding -3 * 3 = -9 to the score.\n- Choose from the end, [-2,7,<strong><u>1</u></strong>], adding 1 * 4 = 4 to the score.\n- Choose from the end, [-2,<strong><u>7</u></strong>], adding 7 * 6 = 42 to the score. \nThe total score is 50 + 15 - 9 + 4 + 42 = 102.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>m == multipliers.length</code></li>\n\t<li><code>1 &lt;= m &lt;= 10<sup>3</sup></code></li>\n\t<li><code>m &lt;= n &lt;= 10<sup>5</sup></code><code> </code></li>\n\t<li><code>-1000 &lt;= nums[i], multipliers[i] &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "179-Largest Number.java",
    "content": "// Heres the simple solution:\n\n// Runtime: 6ms\n// Memory: 42 MB\n// Faster than: 81.48%\n\nclass Solution {\n    public String largestNumber(int[] nums) {\n        int n= nums.length;\n        String [] s = new String[n];\n        for(int i = 0; i < n; i++)\n            s[i] = \"\"+nums[i];\n        \n        Arrays.sort(s, (a, b) -> (b+a).compareTo(a+b));\n        \n        StringBuilder sb = new StringBuilder();\n        for(String str: s)\n            sb.append(str);\n        \n        String result = sb+\"\";\n        return result.startsWith(\"0\")? \"0\" : result;\n    }\n}\n"
  },
  {
    "path": "1791. Find Center of Star Graph.java",
    "content": "class Solution {\n    public int findCenter(int[][] edges) {\n        int n=edges.length;\n        List<List<Integer>> adj=new ArrayList<>();\n        \n        for(int i=0;i<=n+1;i++){\n            ArrayList<Integer> list=new ArrayList<>();\n            adj.add(list);\n        }\n        \n        for(int i=0;i<n;i++){\n            adj.get(edges[i][0]).add(edges[i][1]);\n            adj.get(edges[i][1]).add(edges[i][0]);\n        }\n        \n        int ans=0;\n        for(int i=0;i<adj.size();i++){\n            if(adj.get(i).size()==n){\n                ans = i;\n                break;\n            }\n        }\n        \n        return ans;\n    }\n}\n"
  },
  {
    "path": "1832-check-if-the-sentence-is-pangram/1832-check-if-the-sentence-is-pangram.java",
    "content": "class Solution {\n    public boolean checkIfPangram(String sentence) {\n        for(int i=0;i<26;i++){\n            int c=(char)('a'+i);\n            if(sentence.indexOf(c)==-1){\n                return false;\n            }\n        }return true;\n    }\n}"
  },
  {
    "path": "1832-check-if-the-sentence-is-pangram/NOTES.md",
    "content": "​"
  },
  {
    "path": "1832-check-if-the-sentence-is-pangram/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/check-if-the-sentence-is-pangram/\">1832. Check if the Sentence Is Pangram</a></h2><h3>Easy</h3><hr><div><p>A <strong>pangram</strong> is a sentence where every letter of the English alphabet appears at least once.</p>\n\n<p>Given a string <code>sentence</code> containing only lowercase English letters, return<em> </em><code>true</code><em> if </em><code>sentence</code><em> is a <strong>pangram</strong>, or </em><code>false</code><em> otherwise.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> sentence = \"thequickbrownfoxjumpsoverthelazydog\"\n<strong>Output:</strong> true\n<strong>Explanation:</strong> sentence contains at least one of every letter of the English alphabet.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> sentence = \"leetcode\"\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= sentence.length &lt;= 1000</code></li>\n\t<li><code>sentence</code> consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "1833-maximum-ice-cream-bars/1833-maximum-ice-cream-bars.java",
    "content": "class Solution {\n    public int maxIceCream(int[] costs, int coins) {\n        int maxCost = 0;\n\n        for (int cost : costs) {\n            if (cost > maxCost) {\n                maxCost = cost;\n            }\n        }\n\n        int[] numOfCosts = new int[maxCost + 1];\n\n        for (int cost : costs) {\n            numOfCosts[cost]++;\n        }\n\n        int iceCreamBars = 0;\n\n        for (int cost = 1; cost <= maxCost; cost++) {\n            if (numOfCosts[cost] == 0) {\n                continue;\n            }\n\n            if (coins < cost) {\n                break;\n            }\n\n            int count = Math.min(numOfCosts[cost], coins / cost);\n            coins -= count * cost;\n            iceCreamBars += count;\n        }\n\n        return iceCreamBars;\n    }\n}"
  },
  {
    "path": "1833-maximum-ice-cream-bars/NOTES.md",
    "content": "​"
  },
  {
    "path": "1833-maximum-ice-cream-bars/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-ice-cream-bars/\">1833. Maximum Ice Cream Bars</a></h2><h3>Medium</h3><hr><div><p>It is a sweltering summer day, and a boy wants to buy some ice cream bars.</p>\n\n<p>At the store, there are <code>n</code> ice cream bars. You are given an array <code>costs</code> of length <code>n</code>, where <code>costs[i]</code> is the price of the <code>i<sup>th</sup></code> ice cream bar in coins. The boy initially has <code>coins</code> coins to spend, and he wants to buy as many ice cream bars as possible.&nbsp;</p>\n\n<p>Return <em>the <strong>maximum</strong> number of ice cream bars the boy can buy with </em><code>coins</code><em> coins.</em></p>\n\n<p><strong>Note:</strong> The boy can buy the ice cream bars in any order.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> costs = [1,3,2,4,1], coins = 7\n<strong>Output:</strong> 4\n<strong>Explanation: </strong>The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> costs = [10,6,8,7,7,8], coins = 5\n<strong>Output:</strong> 0\n<strong>Explanation: </strong>The boy cannot afford any of the ice cream bars.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> costs = [1,6,3,1,2,5], coins = 20\n<strong>Output:</strong> 6\n<strong>Explanation: </strong>The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>costs.length == n</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= costs[i] &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= coins &lt;= 10<sup>8</sup></code></li>\n</ul></div>"
  },
  {
    "path": "1834-single-threaded-cpu/1834-single-threaded-cpu.java",
    "content": "class Solution {\n    public int[] getOrder(int[][] tasks) {\n        \n        // Sort based on min task processing time or min task index.\n        // Store enqueue time, processing time, task index.\n        PriorityQueue<int[]> nextTask = new PriorityQueue<int[]>((a, b) -> (a[1] != b[1] ? (a[1] - b[1]) : (a[2] - b[2])));\n        \n        // Store task enqueue time, processing time, index.\n        int sortedTasks[][] = new int[tasks.length][3];\n        for (int i = 0; i < tasks.length; ++i) {\n            sortedTasks[i][0] = tasks[i][0];\n            sortedTasks[i][1] = tasks[i][1];\n            sortedTasks[i][2] = i;\n        }\n        \n        Arrays.sort(sortedTasks, (a, b) -> Integer.compare(a[0], b[0]));\n        int tasksProcessingOrder[] = new int[tasks.length];\n        \n        long currTime = 0;\n        int taskIndex = 0;\n        int ansIndex = 0;\n        \n        // Stop when no tasks are left in array and heap.\n        while (taskIndex < tasks.length || !nextTask.isEmpty()) {\n            if (nextTask.isEmpty() && currTime < sortedTasks[taskIndex][0]) {\n                // When the heap is empty, try updating currTime to next task's enqueue time. \n                currTime = sortedTasks[taskIndex][0];\n            }\n            \n            // Push all the tasks whose enqueueTime <= currtTime into the heap.\n            while (taskIndex < tasks.length && currTime >= sortedTasks[taskIndex][0]) { \n                nextTask.add(sortedTasks[taskIndex]);\n                ++taskIndex;\n            }\n            \n            int processTime = nextTask.peek()[1];\n            int index = nextTask.peek()[2];\n            nextTask.remove();\n            \n            // Complete this task and increment currTime.\n            currTime += processTime; \n            tasksProcessingOrder[ansIndex++] = index;\n        }\n        \n        return tasksProcessingOrder;\n    }\n}"
  },
  {
    "path": "1834-single-threaded-cpu/NOTES.md",
    "content": "​"
  },
  {
    "path": "1834-single-threaded-cpu/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/single-threaded-cpu/\">1834. Single-Threaded CPU</a></h2><h3>Medium</h3><hr><div><p>You are given <code>n</code>​​​​​​ tasks labeled from <code>0</code> to <code>n - 1</code> represented by a 2D integer array <code>tasks</code>, where <code>tasks[i] = [enqueueTime<sub>i</sub>, processingTime<sub>i</sub>]</code> means that the <code>i<sup>​​​​​​th</sup></code>​​​​ task will be available to process at <code>enqueueTime<sub>i</sub></code> and will take <code>processingTime<sub>i</sub></code><sub> </sub>to finish processing.</p>\n\n<p>You have a single-threaded CPU that can process <strong>at most one</strong> task at a time and will act in the following way:</p>\n\n<ul>\n\t<li>If the CPU is idle and there are no available tasks to process, the CPU remains idle.</li>\n\t<li>If the CPU is idle and there are available tasks, the CPU will choose the one with the <strong>shortest processing time</strong>. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.</li>\n\t<li>Once a task is started, the CPU will <strong>process the entire task</strong> without stopping.</li>\n\t<li>The CPU can finish a task then start a new one instantly.</li>\n</ul>\n\n<p>Return <em>the order in which the CPU will process the tasks.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> tasks = [[1,2],[2,4],[3,2],[4,1]]\n<strong>Output:</strong> [0,2,3,1]\n<strong>Explanation: </strong>The events go as follows: \n- At time = 1, task 0 is available to process. Available tasks = {0}.\n- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.\n- At time = 2, task 1 is available to process. Available tasks = {1}.\n- At time = 3, task 2 is available to process. Available tasks = {1, 2}.\n- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.\n- At time = 4, task 3 is available to process. Available tasks = {1, 3}.\n- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.\n- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.\n- At time = 10, the CPU finishes task 1 and becomes idle.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]\n<strong>Output:</strong> [4,3,2,0,1]\n<strong>Explanation</strong><strong>: </strong>The events go as follows:\n- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.\n- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.\n- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.\n- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.\n- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.\n- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.\n- At time = 40, the CPU finishes task 1 and becomes idle.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>tasks.length == n</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= enqueueTime<sub>i</sub>, processingTime<sub>i</sub> &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "188-best-time-to-buy-and-sell-stock-iv/188-best-time-to-buy-and-sell-stock-iv.java",
    "content": "class Solution {\n \n            \n     public int maxProfit(int k, int[] prices) {\n        return DP(prices, k);\n    }\n    \n    private int DP(int[] prices, int k) {\n        int[] costs = new int[k+1];\n        int[] profits = new int[k+1];\n        //costs[0] = prices[0];\n        Arrays.fill(costs, Integer.MAX_VALUE);\n        \n        for (int currentPrice : prices) {\n            for (int i = 0; i < k; i++) {\n                costs[i+1] = Math.min(costs[i+1], currentPrice - profits[i]);\n                profits[i+1] = Math.max(profits[i+1], currentPrice - costs[i+1]);\n            }\n        }\n        \n        return profits[k];\n            \n    }\n}"
  },
  {
    "path": "188-best-time-to-buy-and-sell-stock-iv/NOTES.md",
    "content": "​"
  },
  {
    "path": "188-best-time-to-buy-and-sell-stock-iv/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/\">188. Best Time to Buy and Sell Stock IV</a></h2><h3>Hard</h3><hr><div><p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p>\n\n<p>Find the maximum profit you can achieve. You may complete at most <code>k</code> transactions.</p>\n\n<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> k = 2, prices = [2,4,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> k = 2, prices = [3,2,6,5,0,3]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= k &lt;= 100</code></li>\n\t<li><code>0 &lt;= prices.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "188. Best Time to Buy and Sell Stock IV.cpp",
    "content": "class Solution {\npublic:\n    int maxProfit(int k, vector<int>& prices) {\n        if(k==0) return 0; // no transaction no profit        \n        vector<vector<int>> dp(k+1, vector<int>(2));\n        // initialise\n        // dp[k][0] - min cost that you need to spend on a stock\n        // dp[k][1] - max profit that you can gain from a stock\n        for(int i=0;i<=k;i++) dp[i][0] = INT_MAX;\n        for(auto &price : prices){\n            for(int i=1;i<=k;i++){\n                // price - dp[i - 1][1] is how much you need to spend\n                // i.e use the profit you earned from previous transaction to buy the stock\n                // we want to minimize it\n                dp[i][0] = min(dp[i][0], price - dp[i-1][1]);\n                // price - dp[i][0] is how much you can achieve from previous min cost\n                // we want to maximize it\n                dp[i][1] = max(dp[i][1], price - dp[i][0]);\n            }\n        }\n         // return max profit at most k transactions\n        // or you can use `return dp.back()[1];\n        return dp[k][1];\n    }\n};\n"
  },
  {
    "path": "19-remove-nth-node-from-end-of-list/19-remove-nth-node-from-end-of-list.java",
    "content": "/**\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 removeNthFromEnd(ListNode head, int n) {\n        if(head.next==null && n==1)return null;\n        ListNode temp=head;\n        int length=0;\n        while(temp!=null){\n            length++;\n            temp=temp.next;\n        }\n        if(length==n)return head.next;\n        ListNode tem=head;\n        for(int i=1;i<length-n;i++){\n            tem=tem.next;\n        }\n        tem.next=tem.next.next;\n        return head;\n    }\n}"
  },
  {
    "path": "19-remove-nth-node-from-end-of-list/NOTES.md",
    "content": "​"
  },
  {
    "path": "19-remove-nth-node-from-end-of-list/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/remove-nth-node-from-end-of-list/\">19. Remove Nth Node From End of List</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg\" style=\"width: 542px; height: 222px;\">\n<pre><strong>Input:</strong> head = [1,2,3,4,5], n = 2\n<strong>Output:</strong> [1,2,3,5]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> head = [1], n = 1\n<strong>Output:</strong> []\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> head = [1,2], n = 1\n<strong>Output:</strong> [1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is <code>sz</code>.</li>\n\t<li><code>1 &lt;= sz &lt;= 30</code></li>\n\t<li><code>0 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>1 &lt;= n &lt;= sz</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you do this in one pass?</p>\n</div>"
  },
  {
    "path": "191-number-of-1-bits/191-number-of-1-bits.java",
    "content": "public class Solution {\n    public int hammingWeight(int n) {   \n        int count = 0;\n        while (n != 0) {\n            n=n&(n-1);\n            count++;\n        }\n        return count;\n    }\n}"
  },
  {
    "path": "191-number-of-1-bits/NOTES.md",
    "content": "​"
  },
  {
    "path": "191-number-of-1-bits/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/number-of-1-bits/\">191. Number of 1 Bits</a></h2><h3>Easy</h3><hr><div><p>Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the <a href=\"http://en.wikipedia.org/wiki/Hamming_weight\" target=\"_blank\">Hamming weight</a>).</p>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n\t<li>Note 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.</li>\n\t<li>In Java, the compiler represents the signed integers using <a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" target=\"_blank\">2's complement notation</a>. Therefore, in <strong>Example 3</strong>, the input represents the signed integer. <code>-3</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 00000000000000000000000000001011\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The input binary string <strong>00000000000000000000000000001011</strong> has a total of three '1' bits.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 00000000000000000000000010000000\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The input binary string <strong>00000000000000000000000010000000</strong> has a total of one '1' bit.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 11111111111111111111111111111101\n<strong>Output:</strong> 31\n<strong>Explanation:</strong> The input binary string <strong>11111111111111111111111111111101</strong> has a total of thirty one '1' bits.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The input must be a <strong>binary string</strong> of length <code>32</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> If this function is called many times, how would you optimize it?</div>"
  },
  {
    "path": "1926-nearest-exit-from-entrance-in-maze/1926-nearest-exit-from-entrance-in-maze.java",
    "content": "class Solution {\n    public int nearestExit(char[][] maze, int[] entrance) {\n        int m = maze.length;\n        int n = maze[0].length;\n        \n        Queue<int[]> q = new LinkedList<>();\n        int ei = entrance[0];\n        int ej = entrance[1];\n        int[][] dvs = new int[][] {\n            {1, 0}, {0, 1}, {-1, 0}, {0, -1}    \n        };\n        \n        maze[ei][ej] = '+';\n        q.add(new int[] {ei, ej, 0});\n        \n        while(!q.isEmpty()) {\n            int[] val = q.poll();\n            \n            for (int[] d: dvs) {\n                int i1 = val[0] + d[0];\n                int j1 = val[1] + d[1];\n                \n                if (i1 < 0 || j1 < 0 || i1 >= m || j1 >= n) {\n                    if (val[0] == ei && val[1] == ej) continue;\n                    return val[2];\n                }\n                \n                if (maze[i1][j1] == '.') {\n                    q.add(new int[] {i1, j1, val[2] + 1});\n                    maze[i1][j1] = '+';\n                }\n            }\n        }\n        \n        return -1;\n    }\n}"
  },
  {
    "path": "1926-nearest-exit-from-entrance-in-maze/NOTES.md",
    "content": "​"
  },
  {
    "path": "1926-nearest-exit-from-entrance-in-maze/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/\">1926. Nearest Exit from Entrance in Maze</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>m x n</code> matrix <code>maze</code> (<strong>0-indexed</strong>) with empty cells (represented as <code>'.'</code>) and walls (represented as <code>'+'</code>). You are also given the <code>entrance</code> of the maze, where <code>entrance = [entrance<sub>row</sub>, entrance<sub>col</sub>]</code> denotes the row and column of the cell you are initially standing at.</p>\n\n<p>In one step, you can move one cell <strong>up</strong>, <strong>down</strong>, <strong>left</strong>, or <strong>right</strong>. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the <strong>nearest exit</strong> from the <code>entrance</code>. An <strong>exit</strong> is defined as an <strong>empty cell</strong> that is at the <strong>border</strong> of the <code>maze</code>. The <code>entrance</code> <strong>does not count</strong> as an exit.</p>\n\n<p>Return <em>the <strong>number of steps</strong> in the shortest path from the </em><code>entrance</code><em> to the nearest exit, or </em><code>-1</code><em> if no such path exists</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg\" style=\"width: 333px; height: 253px;\">\n<pre><strong>Input:</strong> maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg\" style=\"width: 253px; height: 253px;\">\n<pre><strong>Input:</strong> maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg\" style=\"width: 173px; height: 93px;\">\n<pre><strong>Input:</strong> maze = [[\".\",\"+\"]], entrance = [0,0]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> There are no exits in this maze.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>maze.length == m</code></li>\n\t<li><code>maze[i].length == n</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>maze[i][j]</code> is either <code>'.'</code> or <code>'+'</code>.</li>\n\t<li><code>entrance.length == 2</code></li>\n\t<li><code>0 &lt;= entrance<sub>row</sub> &lt; m</code></li>\n\t<li><code>0 &lt;= entrance<sub>col</sub> &lt; n</code></li>\n\t<li><code>entrance</code> will always be an empty cell.</li>\n</ul>\n</div>"
  },
  {
    "path": "1962-remove-stones-to-minimize-the-total/1962-remove-stones-to-minimize-the-total.java",
    "content": "public class Solution {\n    public int minStoneSum(int[] piles, int k) {\n        int sum = 0;\n        int a[] = new int[10001];\n        for (int i : piles) {\n            sum += i;\n            a[i]++;\n        }\n        for (int i = 10000; i > 0 && k > 0; i--) {\n            if (a[i] > 0) {\n                int b = i / 2;\n                sum -= Math.min(k, a[i]) * b;\n                a[i - i / 2] += a[i];\n                k -= a[i];\n            }\n        }\n        return sum;\n\n    }\n}"
  },
  {
    "path": "1962-remove-stones-to-minimize-the-total/NOTES.md",
    "content": "​"
  },
  {
    "path": "1962-remove-stones-to-minimize-the-total/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/remove-stones-to-minimize-the-total/\">1962. Remove Stones to Minimize the Total</a></h2><h3>Medium</h3><hr><div><p>You are given a <strong>0-indexed</strong> integer array <code>piles</code>, where <code>piles[i]</code> represents the number of stones in the <code>i<sup>th</sup></code> pile, and an integer <code>k</code>. You should apply the following operation <strong>exactly</strong> <code>k</code> times:</p>\n\n<ul>\n\t<li>Choose any <code>piles[i]</code> and <strong>remove</strong> <code>floor(piles[i] / 2)</code> stones from it.</li>\n</ul>\n\n<p><strong>Notice</strong> that you can apply the operation on the <strong>same</strong> pile more than once.</p>\n\n<p>Return <em>the <strong>minimum</strong> possible total number of stones remaining after applying the </em><code>k</code><em> operations</em>.</p>\n\n<p><code>floor(x)</code> is the <b>greatest</b> integer that is <strong>smaller</strong> than or <strong>equal</strong> to <code>x</code> (i.e., rounds <code>x</code> down).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> piles = [5,4,9], k = 2\n<strong>Output:</strong> 12\n<strong>Explanation:</strong>&nbsp;Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,<u>5</u>].\n- Apply the operation on pile 0. The resulting piles are [<u>3</u>,4,5].\nThe total number of stones in [3,4,5] is 12.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> piles = [4,3,6,7], k = 3\n<strong>Output:</strong> 12\n<strong>Explanation:</strong>&nbsp;Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,<u>3</u>,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,<u>4</u>].\n- Apply the operation on pile 0. The resulting piles are [<u>2</u>,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= piles.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= piles[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "1971-find-if-path-exists-in-graph/1971-find-if-path-exists-in-graph.java",
    "content": "class Solution {\n    public boolean validPath(int n, int[][] edges, int start, int end) {\n        boolean[] visited = new boolean[n];\n        visited[start] = true;\n        \n        boolean newVisited = true;\n         \n        while(!visited[end] && newVisited) {\n            newVisited = false;\n            for (int i = edges.length - 1; i > -1; i--) {\n                if (visited[edges[i][0]]) {\n                    if (!visited[edges[i][1]]) {\n                        newVisited = visited[edges[i][1]] = true;\n                    }\n                } else if (visited[edges[i][1]]){\n                    newVisited = visited[edges[i][0]] = true;\n                }\n            }\n        }\n        \n        return visited[end];\n    }\n}"
  },
  {
    "path": "1971-find-if-path-exists-in-graph/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-if-path-exists-in-graph/\">1971. Find if Path Exists in Graph</a></h2><h3>Easy</h3><hr><div><p>There is a <strong>bi-directional</strong> graph with <code>n</code> vertices, where each vertex is labeled from <code>0</code> to <code>n - 1</code> (<strong>inclusive</strong>). The edges in the graph are represented as a 2D integer array <code>edges</code>, where each <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes a bi-directional edge between vertex <code>u<sub>i</sub></code> and vertex <code>v<sub>i</sub></code>. Every vertex pair is connected by <strong>at most one</strong> edge, and no vertex has an edge to itself.</p>\n\n<p>You want to determine if there is a <strong>valid path</strong> that exists from vertex <code>source</code> to vertex <code>destination</code>.</p>\n\n<p>Given <code>edges</code> and the integers <code>n</code>, <code>source</code>, and <code>destination</code>, return <code>true</code><em> if there is a <strong>valid path</strong> from </em><code>source</code><em> to </em><code>destination</code><em>, or </em><code>false</code><em> otherwise</em><em>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/08/14/validpath-ex1.png\" style=\"width: 141px; height: 121px;\">\n<pre><strong>Input:</strong> n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2\n<strong>Output:</strong> true\n<strong>Explanation:</strong> There are two paths from vertex 0 to vertex 2:\n- 0 → 1 → 2\n- 0 → 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/08/14/validpath-ex2.png\" style=\"width: 281px; height: 141px;\">\n<pre><strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There is no path from vertex 0 to vertex 5.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= edges.length &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>edges[i].length == 2</code></li>\n\t<li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n - 1</code></li>\n\t<li><code>u<sub>i</sub> != v<sub>i</sub></code></li>\n\t<li><code>0 &lt;= source, destination &lt;= n - 1</code></li>\n\t<li>There are no duplicate edges.</li>\n\t<li>There are no self edges.</li>\n</ul>\n</div>"
  },
  {
    "path": "199-binary-tree-right-side-view/199-binary-tree-right-side-view.java",
    "content": "/**\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<Integer> rightSideView(TreeNode root) {\n        List<Integer> list=new ArrayList<>();\n        int level=0;\n        rightView(root,list,level);\n        return list;\n    }\n    void rightView(TreeNode root,List<Integer> list,int level){\n        if(root==null)return;\n        \n        if(level==list.size()){\n            list.add(root.val);\n        }\n        \n        rightView(root.right,list,level+1);\n        rightView(root.left,list,level+1);\n    }  \n}"
  },
  {
    "path": "199-binary-tree-right-side-view/NOTES.md",
    "content": "​"
  },
  {
    "path": "199-binary-tree-right-side-view/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-tree-right-side-view/\">199. Binary Tree Right Side View</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/14/tree.jpg\" style=\"width: 401px; height: 301px;\">\n<pre><strong>Input:</strong> root = [1,2,3,null,5,null,4]\n<strong>Output:</strong> [1,3,4]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = [1,null,3]\n<strong>Output:</strong> [1,3]\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "1991-find-the-middle-index-in-array/1991-find-the-middle-index-in-array.java",
    "content": "class Solution {\n    public int findMiddleIndex(int[] nums) {\n        int sum=0;\n        for(int n:nums){\n            sum+=n;\n        }\n        int left=0;\n        for(int i=0;i<nums.length;i++){\n            sum -=nums[i];\n            if(left==sum){\n                return i;\n            }\n            left +=nums[i];\n        }\n        return -1;\n    }\n}"
  },
  {
    "path": "1991-find-the-middle-index-in-array/NOTES.md",
    "content": "​"
  },
  {
    "path": "1991-find-the-middle-index-in-array/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-the-middle-index-in-array/\">1991. Find the Middle Index in Array</a></h2><h3>Easy</h3><hr><div><p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, find the <strong>leftmost</strong> <code>middleIndex</code> (i.e., the smallest amongst all the possible ones).</p>\n\n<p>A <code>middleIndex</code> is an index where <code>nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]</code>.</p>\n\n<p>If <code>middleIndex == 0</code>, the left side sum is considered to be <code>0</code>. Similarly, if <code>middleIndex == nums.length - 1</code>, the right side sum is considered to be <code>0</code>.</p>\n\n<p>Return <em>the <strong>leftmost</strong> </em><code>middleIndex</code><em> that satisfies the condition, or </em><code>-1</code><em> if there is no such index</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,3,-1,<u>8</u>,4]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,-1,<u>4</u>]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,5]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> There is no valid middleIndex.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as&nbsp;724:&nbsp;<a href=\"https://leetcode.com/problems/find-pivot-index/\" target=\"_blank\">https://leetcode.com/problems/find-pivot-index/</a></p>\n</div>"
  },
  {
    "path": "1996-the-number-of-weak-characters-in-the-game/1996-the-number-of-weak-characters-in-the-game.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution{\n    public:\n    // using hash_map + STL\n    // approach\n    /*\n    rearrange order of attach in asc order\n    count weak chars(those defense less than curr maxi defense)\n    update maxidefense\n    */\n   int numberOfWeakCharacters(vector<vector<int>>& properties){\n    int WC =0; // final res to be returned, WC = weak chars\n    // return maxiDefense since 1 <= defense[i] <= 10^5, set inti value to x sinec x <1\n    int maxiDefense =0;\n    // using hash_map to map the attack and defense with greater<int> as a key compare\n    map<int, vector<int>, greater<int>> mp;\n    for(auto x : properties) mp[x[0]].push_back(x[1]);\n    // foreach attack\n    for(auto x : mp){\n        // count num of weakchar and add it to WC, count_if() returns the number of elements in the given sequence for which the comparator function (third parameter) returns true.\n        // STL iterator ==> x.second.begin() => __first, x.second.end() => __last,  [&](int currDefense) => predicate \n        WC+= count_if(x.second.begin(), x.second.end(), [&](int currDefense){\n            return currDefense < maxiDefense;\n        });\n        // update maxidefense which is the maxi value of currdefense\n        maxiDefense = max(maxiDefense, *max_element(x.second.begin(), x.second.end()));\n\n    }\n    return WC;\n\n\n   }\n};\n"
  },
  {
    "path": "1996-the-number-of-weak-characters-in-the-game/1996-the-number-of-weak-characters-in-the-game.java",
    "content": "class Solution {\n    public int numberOfWeakCharacters(int[][] prop) {\n        \n        /** Solution\n        1. here we sort the array in the increasing order of attack\n         1.1 if two attack has a same value then we sort the decreasing order of defense\n        \n        2. compare the defense value and increasing answer count\n         2.1 chnage the defense value if it is greater\n        \n        \n        */\n                                       //if attack same then  decreasing order of defense else increasing order of attack\n        Arrays.sort(prop,(a,b)->  a[0]==b[0]? b[1]-a[1] : a[0]-b[0]);\n        \n        int min=Integer.MIN_VALUE;\n        int ans=0;\n        \n        for(int i=prop.length-1;i>=0;i--){\n            int[] arr=prop[i];\n            int att=arr[0];\n            int def=arr[1];\n            \n             if(def<min){\n                ans++;\n            }\n            \n            min=Math.max(def,min);\n        }\n        \n        return ans;\n        \n    }\n}\n\n\n//dp\nclass Solution {\n    public int numberOfWeakCharacters(int[][] properties) {\n        int maxAttack = 0;\n        // Find the maximum attack value\n        for (int[] property : properties) {\n            int attack = property[0];\n            maxAttack = Math.max(maxAttack, attack);\n        }\n        \n        int maxDefense[] = new int[maxAttack + 2];\n        // Store the maximum defense for an attack value\n        for (int[] property : properties) {\n            int attack = property[0];\n            int defense = property[1];\n            \n            maxDefense[attack] = Math.max(maxDefense[attack], defense);\n        }\n\n        // Store the maximum defense for attack greater than or equal to a value\n        for (int i = maxAttack - 1; i >= 0; i--) {\n            maxDefense[i] = Math.max(maxDefense[i], maxDefense[i + 1]);\n        }\n        \n        int weakCharacters = 0;\n        for (int[] property : properties) {\n            int attack = property[0];\n            int defense = property[1];\n            \n            // If their is a greater defense for properties with greater attack\n            if (defense < maxDefense[attack + 1]) {\n                weakCharacters++;\n            }\n        }\n        \n        return weakCharacters;\n    }\n}\n"
  },
  {
    "path": "1996-the-number-of-weak-characters-in-the-game/NOTES.md",
    "content": "​"
  },
  {
    "path": "1996-the-number-of-weak-characters-in-the-game/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/\">1996. The Number of Weak Characters in the Game</a></h2><h3>Medium</h3><hr><div><p>You are playing a game that contains multiple characters, and each of the characters has <strong>two</strong> main properties: <strong>attack</strong> and <strong>defense</strong>. You are given a 2D integer array <code>properties</code> where <code>properties[i] = [attack<sub>i</sub>, defense<sub>i</sub>]</code> represents the properties of the <code>i<sup>th</sup></code> character in the game.</p>\n\n<p>A character is said to be <strong>weak</strong> if any other character has <strong>both</strong> attack and defense levels <strong>strictly greater</strong> than this character's attack and defense levels. More formally, a character <code>i</code> is said to be <strong>weak</strong> if there exists another character <code>j</code> where <code>attack<sub>j</sub> &gt; attack<sub>i</sub></code> and <code>defense<sub>j</sub> &gt; defense<sub>i</sub></code>.</p>\n\n<p>Return <em>the number of <strong>weak</strong> characters</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> properties = [[5,5],[6,3],[3,6]]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> No character has strictly greater attack and defense than the other.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> properties = [[2,2],[3,3]]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The first character is weak because the second character has a strictly greater attack and defense.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> properties = [[1,5],[10,4],[4,3]]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The third character is weak because the second character has a strictly greater attack and defense.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= properties.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>properties[i].length == 2</code></li>\n\t<li><code>1 &lt;= attack<sub>i</sub>, defense<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "200-number-of-islands/200-number-of-islands.java",
    "content": "class Solution {\n    public int numIslands(char[][] grid) {\n        int ans=0;\n        int n=grid.length;\n        int m=grid[0].length;\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(grid[i][j]=='1'){\n                    ans++;\n                    dfs(grid,i,j);\n                }\n            }\n        }\n        return ans;\n    }\n    public void dfs(char[][]grid,int i,int j){\n        if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == '0') return;\n        grid[i][j] = '0';\n        dfs(grid,i+1,j);\n        dfs(grid,i-1,j);\n        dfs(grid,i,j+1);\n        dfs(grid,i,j-1);\n    }\n}"
  },
  {
    "path": "200-number-of-islands/NOTES.md",
    "content": "​"
  },
  {
    "path": "200-number-of-islands/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/number-of-islands/\">200. Number of Islands</a></h2><h3>Medium</h3><hr><div><p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>'1'</code>s (land) and <code>'0'</code>s (water), return <em>the number of islands</em>.</p>\n\n<p>An <strong>island</strong> 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.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> 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]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> 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]\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 300</code></li>\n\t<li><code>grid[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "2007 Find Original Array From Doubled Array lc.cpp",
    "content": "class Solution {\npublic:\n    vector<int> findOriginalArray(vector<int>& changed) {\n//         hashmap approach\n//         if the len of i/p is odd return {}, because double array must have even len\n        \n            if(changed.size() & 1) return {};\n//         count the freq of each number\n        unordered_map<int, int>mp;\n        for(auto x : changed) mp[x]++;\n        vector<int> res;\n//         sort in asc\n        sort(changed.begin(), changed.end());\n//         keep the unique elements only in changed \n        changed.erase(unique(changed.begin(), changed.end()), changed.end());\n//         so that we can iterate from smallest to largest\n        for(auto x : changed){\n//             if the numb of x is greater than mp[x*2], there'd be some mp[x] left therefore return {} here as a changed isn't a double array\n            if(mp[x] >mp[x*2]) return {};\n            for(int i =0; i<mp[x]; i++){\n//                 otherwise we put the ele `x` mp[x] to res\n                res.push_back(x);\n//                 at same time we decrease the count of mp[x*2] by 1\n//                 we don't need to decrease m[x] by 1 as we won't use it again\n                mp[x*2] -= 1;\n                \n                \n            }\n            \n        }\n        return res;\n    }\n};"
  },
  {
    "path": "2007-find-original-array-from-doubled-array/2007-find-original-array-from-doubled-array.java",
    "content": "/**\n    Solution:\n    \n    1. Sort the array\n    2. Make the queue\n    3. Now we know that the answer array is half size of the change array\n    4. Now traverse the change array and if queue is not empty and curr element is same as queue.peek then \n    add the half of num/2 to ans\n    5. else add that 2*num to queue\n    \n    TC: O(nlogn) SC:O(n)\n*/\n\n\nclass Solution {\n    public int[] findOriginalArray(int[] c) {\n        \n        int n=c.length;\n        Deque<Integer> q=new LinkedList<>();\n        Arrays.sort(c);\n        \n        int i=0;\n        int j=0;\n        int[] ans=new int[n/2];\n        \n        while(i<n){\n            int num=c[i];\n            if(q.size()>0 && q.peek()==num){\n                ans[j++]=q.poll()/2;\n            }else{\n                q.add(2*num);\n            }\n            i++;\n        }\n        \n        return q.size()>0?new int[]{}:ans;\n        \n    }\n}\n\n\n//without sorting\n\nclass Solution {\n    public int[] findOriginalArray(int[] changed) {\n        if(changed.length%2 != 0) return new int[0];\n        int max = Integer.MIN_VALUE;\n        for(int num : changed) max = Math.max(max, num);\n        if(max%2 != 0) return new int[0];\n        \n        int[] cnts = new int[max+1];\n        for(int num : changed) cnts[num]++;\n        \n        int[] res = new int[changed.length/2];\n        if(cnts[0] % 2 != 0) return new int[0];\n        int idx = cnts[0]/2;\n        for(int i = 1; i < cnts.length; i++) {\n            if(cnts[i] == 0) continue;\n            if(2*i > max || cnts[i] > cnts[2*i]) return new int[0];\n            int cnt = cnts[i];\n            cnts[2*i] -= cnt;\n            while(cnt-- > 0) res[idx++] = i;\n        }\n        \n        return res;\n    }\n}class Solution {\n    public int[] findOriginalArray(int[] changed) {\n        if(changed.length%2 != 0) return new int[0];\n        int max = Integer.MIN_VALUE;\n        for(int num : changed) max = Math.max(max, num);\n        if(max%2 != 0) return new int[0];\n        \n        int[] cnts = new int[max+1];\n        for(int num : changed) cnts[num]++;\n        \n        int[] res = new int[changed.length/2];\n        if(cnts[0] % 2 != 0) return new int[0];\n        int idx = cnts[0]/2;\n        for(int i = 1; i < cnts.length; i++) {\n            if(cnts[i] == 0) continue;\n            if(2*i > max || cnts[i] > cnts[2*i]) return new int[0];\n            int cnt = cnts[i];\n            cnts[2*i] -= cnt;\n            while(cnt-- > 0) res[idx++] = i;\n        }\n        \n        return res;\n    }\n}\n"
  },
  {
    "path": "2007-find-original-array-from-doubled-array/NOTES.md",
    "content": "​"
  },
  {
    "path": "2007-find-original-array-from-doubled-array/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-original-array-from-doubled-array/\">2007. Find Original Array From Doubled Array</a></h2><h3>Medium</h3><hr><div><p>An integer array <code>original</code> is transformed into a <strong>doubled</strong> array <code>changed</code> by appending <strong>twice the value</strong> of every element in <code>original</code>, and then randomly <strong>shuffling</strong> the resulting array.</p>\n\n<p>Given an array <code>changed</code>, return <code>original</code><em> if </em><code>changed</code><em> is a <strong>doubled</strong> array. If </em><code>changed</code><em> is not a <strong>doubled</strong> array, return an empty array. The elements in</em> <code>original</code> <em>may be returned in <strong>any</strong> order</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> changed = [1,3,4,2,6,8]\n<strong>Output:</strong> [1,3,4]\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> changed = [6,3,0,1]\n<strong>Output:</strong> []\n<strong>Explanation:</strong> changed is not a doubled array.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> changed = [1]\n<strong>Output:</strong> []\n<strong>Explanation:</strong> changed is not a doubled array.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= changed.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= changed[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "2095-delete-the-middle-node-of-a-linked-list/2095-delete-the-middle-node-of-a-linked-list.java",
    "content": "/**\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 deleteMiddle(ListNode head) {\n        if(head.next==null)return null;\n        ListNode prev=null;\n        ListNode slow=head;\n        ListNode fast=head;\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}"
  },
  {
    "path": "2095-delete-the-middle-node-of-a-linked-list/NOTES.md",
    "content": "​"
  },
  {
    "path": "2131-longest-palindrome-by-concatenating-two-letter-words/2131-longest-palindrome-by-concatenating-two-letter-words.java",
    "content": "class Solution {\n    public int longestPalindrome(String[] words) {\n        int result=0;\n        int[][]freq=new int[26][26];\n        \n        for(String s:words){\n            int i=s.charAt(0)-'a';\n            int j=s.charAt(1)-'a';\n            if(freq[j][i]>0){\n                freq[j][i]--;\n                result+=4;\n            }else{\n                freq[i][j]++;\n            }\n        }\n        \n        for(int i=0;i<26;i++){\n            if(freq[i][i]>0){\n                result+=2;\n                break;\n            }\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "2131-longest-palindrome-by-concatenating-two-letter-words/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/\">2131. Longest Palindrome by Concatenating Two Letter Words</a></h2><h3>Medium</h3><hr><div><p>You are given an array of strings <code>words</code>. Each element of <code>words</code> consists of <strong>two</strong> lowercase English letters.</p>\n\n<p>Create the <strong>longest possible palindrome</strong> by selecting some elements from <code>words</code> and concatenating them in <strong>any order</strong>. Each element can be selected <strong>at most once</strong>.</p>\n\n<p>Return <em>the <strong>length</strong> of the longest palindrome that you can create</em>. If it is impossible to create any palindrome, return <code>0</code>.</p>\n\n<p>A <strong>palindrome</strong> is a string that reads the same forward and backward.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"lc\",\"cl\",\"gg\"]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\nNote that \"clgglc\" is another longest palindrome that can be created.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]\n<strong>Output:</strong> 8\n<strong>Explanation:</strong> One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\nNote that \"lcyttycl\" is another longest palindrome that can be created.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"cc\",\"ll\",\"xx\"]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> One longest palindrome is \"cc\", of length 2.\nNote that \"ll\" is another longest palindrome that can be created, and so is \"xx\".\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>words[i].length == 2</code></li>\n\t<li><code>words[i]</code> consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "2136-earliest-possible-day-of-full-bloom/2136-earliest-possible-day-of-full-bloom.java",
    "content": "class Solution {\n    class Pair{\n        int plantTime;\n        int growTime;\n        Pair(int a,int b){\n            plantTime=a;\n            growTime=b;\n        }\n    }\n    public int earliestFullBloom(int[] plantTime, int[] growTime) {\n        PriorityQueue<Pair> pq=new PriorityQueue<>((a,b)->b.growTime-a.growTime);\n        for(int i=0;i<plantTime.length;i++){\n            pq.add(new Pair(plantTime[i],growTime[i]));\n        }\n        int ans=0;\n        int currTime=0;\n        while(!pq.isEmpty()){\n            Pair p=pq.remove();\n            int time=currTime+p.plantTime + p.growTime;\n            ans=Math.max(ans,time);\n            currTime+=p.plantTime;\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "2136-earliest-possible-day-of-full-bloom/NOTES.md",
    "content": "​"
  },
  {
    "path": "215-kth-largest-element-in-an-array/215-kth-largest-element-in-an-array.java",
    "content": "class Solution {\n    public int findKthLargest(int[] nums, int k) {\n        Arrays.sort(nums);\n        return nums[nums.length-k];\n    }\n}"
  },
  {
    "path": "215-kth-largest-element-in-an-array/NOTES.md",
    "content": "​"
  },
  {
    "path": "216-combination-sum-iii/216-combination-sum-iii.java",
    "content": "class Solution {\n    public List<List<Integer>> combinationSum3(int k, int n) {\n      List<List<Integer>> res = new ArrayList<>();\n        List out = new ArrayList<>();\n        back(res,out,k,n,1);\n        return res;\n    }\n    void back(List<List<Integer>> res,List<Integer> out,int currSize,int n,int limit)\n    {\n        if(out.size()==currSize && n ==0)\n        {\n            res.add(new ArrayList<>(out));\n            return ;\n        }\n        if(limit>9)\n        {\n            return ;\n        }\n            \n        if(out.size()>currSize)\n        {\n            return ;\n        }\n        if(n<0)\n        {\n            return ;\n        }\n        out.add(limit);\n        back(res,out,currSize,n-limit,limit+1);\n        out.remove(out.size()-1);\n        back(res,out,currSize,n,limit+1);\n    }\n}"
  },
  {
    "path": "216-combination-sum-iii/NOTES.md",
    "content": "​"
  },
  {
    "path": "216-combination-sum-iii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/combination-sum-iii/\">216. Combination Sum III</a></h2><h3>Medium</h3><hr><div><p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p>\n\n<ul>\n\t<li>Only numbers <code>1</code> through <code>9</code> are used.</li>\n\t<li>Each number is used <strong>at most once</strong>.</li>\n</ul>\n\n<p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> k = 3, n = 7\n<strong>Output:</strong> [[1,2,4]]\n<strong>Explanation:</strong>\n1 + 2 + 4 = 7\nThere are no other valid combinations.</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> k = 3, n = 9\n<strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]]\n<strong>Explanation:</strong>\n1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> k = 4, n = 1\n<strong>Output:</strong> []\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= k &lt;= 9</code></li>\n\t<li><code>1 &lt;= n &lt;= 60</code></li>\n</ul>\n</div>"
  },
  {
    "path": "218-the-skyline-problem/218-the-skyline-problem.java",
    "content": "class Solution {\n    class KeyPoint {\n        public int key;\n        public int height;\n        public KeyPoint next = null;\n\n        public KeyPoint(int key, int height) {\n            this.key = key;\n            this.height = height;\n        }\n    }\n\n    public List<List<Integer>> getSkyline(int[][] buildings) {\n        List<List<Integer>> res = new ArrayList<>();\n        KeyPoint dummy = new KeyPoint(-1, 0); // dummy head\n        KeyPoint pre = dummy;\n\n        for (int[] bd : buildings) {\n            int L = bd[0];\n            int R = bd[1];\n            int H = bd[2];\n\n            while (pre.next != null && pre.next.key <= L)\n                pre = pre.next;\n\n            int preH = pre.height;\n\n            if (pre.key == L)\n                pre.height = Math.max(pre.height, H);\n            else if (pre.height < H) {\n                KeyPoint next = pre.next;\n                pre.next = new KeyPoint(L, H);\n                pre = pre.next;\n                pre.next = next;\n            }\n\n            KeyPoint preIter = pre;\n            KeyPoint curIter = pre.next;\n            while (curIter != null && curIter.key < R) {\n                preH = curIter.height;\n                curIter.height = Math.max(curIter.height, H);\n\n                if (curIter.height == preIter.height)\n                    preIter.next = curIter.next;\n                else\n                    preIter = curIter;\n\n                curIter = curIter.next;\n            }\n\n            if (preIter.height != preH && preIter.key != R && (curIter == null || curIter.key != R)) {\n                KeyPoint next = preIter.next;\n                preIter.next = new KeyPoint(R, preH);\n                preIter.next.next = next;\n            }\n        }\n\n        KeyPoint first = dummy;\n        KeyPoint second = dummy.next;\n        while (second != null) {\n            if (second.height != first.height)\n                res.add(Arrays.asList(second.key, second.height));\n            first = first.next;\n            second = second.next;\n        }\n        return res;\n    }\n}"
  },
  {
    "path": "218-the-skyline-problem/NOTES.md",
    "content": "​"
  },
  {
    "path": "218-the-skyline-problem/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/the-skyline-problem/\">218. The Skyline Problem</a></h2><h3>Hard</h3><hr><div><p>A city's <strong>skyline</strong> 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 <em>the <strong>skyline</strong> formed by these buildings collectively</em>.</p>\n\n<p>The geometric information of each building is given in the array <code>buildings</code> where <code>buildings[i] = [left<sub>i</sub>, right<sub>i</sub>, height<sub>i</sub>]</code>:</p>\n\n<ul>\n\t<li><code>left<sub>i</sub></code> is the x coordinate of the left edge of the <code>i<sup>th</sup></code> building.</li>\n\t<li><code>right<sub>i</sub></code> is the x coordinate of the right edge of the <code>i<sup>th</sup></code> building.</li>\n\t<li><code>height<sub>i</sub></code> is the height of the <code>i<sup>th</sup></code> building.</li>\n</ul>\n\n<p>You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height <code>0</code>.</p>\n\n<p>The <strong>skyline</strong> should be represented as a list of \"key points\" <strong>sorted by their x-coordinate</strong> in the form <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code>. 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 <code>0</code> 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.</p>\n\n<p><b>Note:</b> There must be no consecutive horizontal lines of equal height in the output skyline. For instance, <code>[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]</code> is not acceptable; the three lines of height 5 should be merged into one in the final output as such: <code>[...,[2 3],[4 5],[12 7],...]</code></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/01/merged.jpg\" style=\"width: 800px; height: 331px;\">\n<pre><strong>Input:</strong> buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\n<strong>Output:</strong> [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> buildings = [[0,2,3],[2,5,3]]\n<strong>Output:</strong> [[0,3],[5,0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= buildings.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= height<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>buildings</code> is sorted by <code>left<sub>i</sub></code> in&nbsp;non-decreasing order.</li>\n</ul>\n</div>"
  },
  {
    "path": "2225-find-players-with-zero-or-one-losses/2225-find-players-with-zero-or-one-losses.java",
    "content": "class Solution {\n    public List<List<Integer>> findWinners(int[][] matches) {\n        Map<Integer,Integer> p=new HashMap<>();\n        int n=matches.length;\n        int maxEle=0;\n        for(int[] match:matches){\n            p.putIfAbsent(match[0],0);\n            p.putIfAbsent(match[1],0);\n            p.put(match[1],p.get(match[1])+1);\n            maxEle=Math.max(maxEle,Math.max(match[0],match[1]));\n        }\n        List<Integer> zeroes=new ArrayList<>();\n        List<Integer> ones=new ArrayList<>();\n        for(int i=1;i<=maxEle;i++){\n            if(!p.containsKey(i))continue;\n            if(p.get(i)==0){\n                zeroes.add(i);\n            }else if(p.get(i)==1){\n                ones.add(i);\n            }\n        }\n        List<List<Integer>> ans=new ArrayList<>();\n        ans.add(zeroes);\n        ans.add(ones);\n        return ans;\n    }\n}"
  },
  {
    "path": "2225-find-players-with-zero-or-one-losses/NOTES.md",
    "content": "​"
  },
  {
    "path": "2225-find-players-with-zero-or-one-losses/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-players-with-zero-or-one-losses/\">2225. Find Players With Zero or One Losses</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>matches</code> where <code>matches[i] = [winner<sub>i</sub>, loser<sub>i</sub>]</code> indicates that the player <code>winner<sub>i</sub></code> defeated player <code>loser<sub>i</sub></code> in a match.</p>\n\n<p>Return <em>a list </em><code>answer</code><em> of size </em><code>2</code><em> where:</em></p>\n\n<ul>\n\t<li><code>answer[0]</code> is a list of all players that have <strong>not</strong> lost any matches.</li>\n\t<li><code>answer[1]</code> is a list of all players that have lost exactly <strong>one</strong> match.</li>\n</ul>\n\n<p>The values in the two lists should be returned in <strong>increasing</strong> order.</p>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n\t<li>You should only consider the players that have played <strong>at least one</strong> match.</li>\n\t<li>The testcases will be generated such that <strong>no</strong> two matches will have the <strong>same</strong> outcome.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]\n<strong>Output:</strong> [[1,2,10],[4,5,7,8]]\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> matches = [[2,3],[1,3],[5,4],[6,4]]\n<strong>Output:</strong> [[1,2,5,6],[]]\n<strong>Explanation:</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= matches.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>matches[i].length == 2</code></li>\n\t<li><code>1 &lt;= winner<sub>i</sub>, loser<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n\t<li><code>winner<sub>i</sub> != loser<sub>i</sub></code></li>\n\t<li>All <code>matches[i]</code> are <strong>unique</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "2244-minimum-rounds-to-complete-all-tasks/2244-minimum-rounds-to-complete-all-tasks.java",
    "content": "class Solution {\n    public int minimumRounds(int[] tasks) {\n        Map<Integer, Integer> freq = new HashMap();\n        // Store the frequencies in the map.\n        for (int task : tasks) {\n            freq.put(task, freq.getOrDefault(task, 0) + 1);\n        }\n\n        int minimumRounds = 0;\n        // Iterate over the task's frequencies.\n        for (int count : freq.values()) {\n            // If the frequency is 1, it's not possible to complete tasks.\n            if (count == 1) {\n                return - 1;\n            }\n\n            if (count % 3 == 0) {\n                // Group all the task in triplets.\n                minimumRounds += count / 3;\n            } else {\n                // If count % 3 = 1; (count / 3 - 1) groups of triplets and 2 pairs.\n                // If count % 3 = 2; (count / 3) groups of triplets and 1 pair.\n                minimumRounds += count / 3 + 1;\n            }\n        }\n\n        return minimumRounds;\n    }\n}"
  },
  {
    "path": "2244-minimum-rounds-to-complete-all-tasks/NOTES.md",
    "content": "​"
  },
  {
    "path": "2244-minimum-rounds-to-complete-all-tasks/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/\">2244. Minimum Rounds to Complete All Tasks</a></h2><h3>Medium</h3><hr><div><p>You are given a <strong>0-indexed</strong> integer array <code>tasks</code>, where <code>tasks[i]</code> represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the <strong>same difficulty level</strong>.</p>\n\n<p>Return <em>the <strong>minimum</strong> rounds required to complete all the tasks, or </em><code>-1</code><em> if it is not possible to complete all the tasks.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> tasks = [2,2,3,3,2,4,4,4,4,4]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> tasks = [2,3,3]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= tasks[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "2246-longest-path-with-different-adjacent-characters/2246-longest-path-with-different-adjacent-characters.java",
    "content": "class Solution {\n    private int longestPath = 1;\n\n    public int dfs(int currentNode, Map<Integer, List<Integer>> children, String s) {\n        // If the node is the only child, return 1 for the currentNode itself.\n        if (!children.containsKey(currentNode)) {\n            return 1;\n        }\n\n        // Longest and second longest path starting from currentNode (does not count the\n        // currentNode itself).\n        int longestChain = 0, secondLongestChain = 0;\n        for (int child : children.get(currentNode)) {\n            // Get the number of nodes in the longest chain starting from the child,\n            // including the child.\n            int longestChainStartingFromChild = dfs(child, children, s);\n            // We won't move to the child if it has the same character as the currentNode.\n            if (s.charAt(currentNode) == s.charAt(child)) {\n                continue;\n            }\n            // Modify the longestChain and secondLongestChain if longestChainStartingFromChild\n            // is bigger.\n            if (longestChainStartingFromChild > longestChain) {\n                secondLongestChain = longestChain;\n                longestChain = longestChainStartingFromChild;\n            } else if (longestChainStartingFromChild > secondLongestChain) {\n                secondLongestChain = longestChainStartingFromChild;\n            }\n        }\n\n        // Add \"1\" for the node itself.\n        longestPath = Math.max(longestPath, longestChain + secondLongestChain + 1);\n        return longestChain + 1;\n    }\n\n    public int longestPath(int[] parent, String s) {\n        int n = parent.length;\n        Map<Integer, List<Integer>> children = new HashMap<>();\n        // Start from node 1, since root node 0 does not have a parent.\n        for (int i = 1; i < n; i++) {\n            children.computeIfAbsent(parent[i], value -> new ArrayList<Integer>()).add(i);\n        }\n\n        dfs(0, children, s);\n\n        return longestPath;\n    }\n}"
  },
  {
    "path": "2246-longest-path-with-different-adjacent-characters/NOTES.md",
    "content": "​"
  },
  {
    "path": "2246-longest-path-with-different-adjacent-characters/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-path-with-different-adjacent-characters/\">2246. Longest Path With Different Adjacent Characters</a></h2><h3>Hard</h3><hr><div><p>You are given a <strong>tree</strong> (i.e. a connected, undirected graph that has no cycles) <strong>rooted</strong> at node <code>0</code> consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by a <strong>0-indexed</strong> array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node <code>0</code> is the root, <code>parent[0] == -1</code>.</p>\n\n<p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p>\n\n<p>Return <em>the length of the <strong>longest path</strong> in the tree such that no pair of <strong>adjacent</strong> nodes on the path have the same character assigned to them.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/03/25/testingdrawio.png\" style=\"width: 201px; height: 241px;\">\n<pre><strong>Input:</strong> parent = [-1,0,0,1,1,2], s = \"abacbe\"\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -&gt; 1 -&gt; 3. The length of this path is 3, so 3 is returned.\nIt can be proven that there is no longer path that satisfies the conditions. \n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/03/25/graph2drawio.png\" style=\"width: 201px; height: 221px;\">\n<pre><strong>Input:</strong> parent = [-1,0,0,0], s = \"aabc\"\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The longest path where each two adjacent nodes have different characters is the path: 2 -&gt; 0 -&gt; 3. The length of this path is 3, so 3 is returned.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == parent.length == s.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code></li>\n\t<li><code>parent[0] == -1</code></li>\n\t<li><code>parent</code> represents a valid tree.</li>\n\t<li><code>s</code> consists of only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "225-implement-stack-using-queues/225-implement-stack-using-queues.java",
    "content": "class MyStack {\n    Queue<Integer> q1,q2;\n    boolean fis;\n    public MyStack() {\n        q1=new LinkedList<>();\n        q2=new LinkedList<>();\n        fis=true;\n    }\n    \n    public void push(int x) {\n        if(fis){\n            q1.add(x);\n        }else{\n            q2.add(x);\n        }\n    }\n    \n    public int pop() {\n        if(fis){\n            fis=false;\n            while(q1.size()>1){\n                q2.add(q1.remove());\n            }\n            int ele=q1.remove();\n            return ele;\n        }else{\n            fis=true;\n            while(q2.size()>1){\n                q1.add(q2.remove());\n            }\n            int ele=q2.remove();\n            return ele;\n        }\n    }\n    \n    public int top() {\n        if(fis){\n            fis=false;\n            while(q1.size()>1){\n                q2.add(q1.remove());\n            }\n            int ele=q1.peek();\n            q2.add(q1.remove());\n            return ele;\n        }else{\n            fis=true;\n            while(q2.size()>1){\n                q1.add(q2.remove());\n            }\n            int ele=q2.peek();\n            q1.add(q2.remove());\n            return ele;\n        }\n    }\n    \n    public boolean empty() {\n        return q1.isEmpty() && q2.isEmpty();\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 * boolean param_4 = obj.empty();\n */"
  },
  {
    "path": "225-implement-stack-using-queues/NOTES.md",
    "content": "​"
  },
  {
    "path": "2256-minimum-average-difference/2256-minimum-average-difference.java",
    "content": "class Solution {\n    public int minimumAverageDifference(int[] nums) {\n        int n=nums.length;\n        long left=0;\n        long right=0;\n        long minDiff=Integer.MAX_VALUE;\n        int idx=-1;\n        for(int i:nums)right+=i;\n        for(int i=0;i<n;i++){\n            left+=nums[i];\n            right-=nums[i];\n            int leftEle=i+1;\n            int rightEle=n-leftEle;\n            if(rightEle==0)rightEle=1;\n            long currDiff=Math.abs((left/leftEle)-(right/rightEle));\n            if(currDiff<minDiff){\n                minDiff=currDiff;\n                idx=i;\n            }\n        }\n        return idx;\n    }\n}"
  },
  {
    "path": "2256-minimum-average-difference/NOTES.md",
    "content": "​"
  },
  {
    "path": "2256-minimum-average-difference/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-average-difference/\">2256. Minimum Average Difference</a></h2><h3>Medium</h3><hr><div><p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p>\n\n<p>The <strong>average difference</strong> of the index <code>i</code> is the <strong>absolute</strong> <strong>difference</strong> between the average of the <strong>first</strong> <code>i + 1</code> elements of <code>nums</code> and the average of the <strong>last</strong> <code>n - i - 1</code> elements. Both averages should be <strong>rounded down</strong> to the nearest integer.</p>\n\n<p>Return<em> the index with the <strong>minimum average difference</strong></em>. If there are multiple such indices, return the <strong>smallest</strong> one.</p>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n\t<li>The <strong>absolute difference</strong> of two numbers is the absolute value of their difference.</li>\n\t<li>The <strong>average</strong> of <code>n</code> elements is the <strong>sum</strong> of the <code>n</code> elements divided (<strong>integer division</strong>) by <code>n</code>.</li>\n\t<li>The average of <code>0</code> elements is considered to be <code>0</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,5,3,9,5,3]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [0]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong>\nThe only index is 0 so return 0.\nThe average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "2279-maximum-bags-with-full-capacity-of-rocks/2279-maximum-bags-with-full-capacity-of-rocks.java",
    "content": "class Solution {\n    public int maximumBags(int[] capacity, int[] rocks, int x) {\n        int n=rocks.length;\n        int[]diff=new int[n];\n        for(int i=0;i<n;i++){\n            diff[i]=capacity[i]-rocks[i];\n        }\n        Arrays.sort(diff);\n        int i=0;\n        while(x>0){\n            if(i<n && x>=diff[i]){\n                x-=diff[i];\n                i++;    \n            }else{\n                break;\n            }\n        }\n        return i;\n    }\n}"
  },
  {
    "path": "2279-maximum-bags-with-full-capacity-of-rocks/NOTES.md",
    "content": "​"
  },
  {
    "path": "2279-maximum-bags-with-full-capacity-of-rocks/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/\">2279. Maximum Bags With Full Capacity of Rocks</a></h2><h3>Medium</h3><hr><div><p>You have <code>n</code> bags numbered from <code>0</code> to <code>n - 1</code>. You are given two <strong>0-indexed</strong> integer arrays <code>capacity</code> and <code>rocks</code>. The <code>i<sup>th</sup></code> bag can hold a maximum of <code>capacity[i]</code> rocks and currently contains <code>rocks[i]</code> rocks. You are also given an integer <code>additionalRocks</code>, the number of additional rocks you can place in <strong>any</strong> of the bags.</p>\n\n<p>Return<em> the <strong>maximum</strong> number of bags that could have full capacity after placing the additional rocks in some bags.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\nPlace 1 rock in bag 0 and 1 rock in bag 1.\nThe number of rocks in each bag are now [2,3,4,4].\nBags 0, 1, and 2 have full capacity.\nThere are 3 bags at full capacity, so we return 3.\nIt can be shown that it is not possible to have more than 3 bags at full capacity.\nNote that there may be other ways of placing the rocks that result in an answer of 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\nPlace 8 rocks in bag 0 and 2 rocks in bag 2.\nThe number of rocks in each bag are now [10,2,2].\nBags 0, 1, and 2 have full capacity.\nThere are 3 bags at full capacity, so we return 3.\nIt can be shown that it is not possible to have more than 3 bags at full capacity.\nNote that we did not use all of the additional rocks.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == capacity.length == rocks.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= capacity[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= rocks[i] &lt;= capacity[i]</code></li>\n\t<li><code>1 &lt;= additionalRocks &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "23-Merge-k-Sorted-Lists/23-Merge-k-Sorted-Lists.cpp",
    "content": "class Solution {\r\npublic:\r\n    ListNode* mergeKLists(vector<ListNode*>& lists) {\r\n        //pushing all list values into min heap\r\n        priority_queue<int, vector<int>, greater<int> > mh;\r\n        for(auto head : lists){\r\n            while(head){\r\n                mh.push(head -> val);\r\n                head = head -> next;\r\n            }\r\n        }\r\n        \r\n        //if there is no element in lists\r\n        if(mh.size() == 0) return NULL;\r\n        \r\n        //creating head node of resultant list\r\n        ListNode * head = new ListNode(mh.top());\r\n        mh.pop();\r\n        //we will traverse the head so storing it for returning\r\n        ListNode * ans_head = head;\r\n        \r\n        //creating final list and poping the min heap\r\n        int n = mh.size();\r\n        while(n--){\r\n            head -> next = new ListNode(mh.top());\r\n            mh.pop();\r\n            head = head -> next;\r\n        }\r\n        \r\n        return ans_head;\r\n    }\r\n};"
  },
  {
    "path": "23-Merge-k-Sorted-Lists/NOTES.md",
    "content": ""
  },
  {
    "path": "23-Merge-k-Sorted-Lists/README.md",
    "content": "<h2>\r\n<a href=\"https://leetcode.com/problems/reverse-nodes-in-k-group/\"> 23. Merge k Sorted Lists </a> \r\n</h2>\r\n<h3>Hard</h3>\r\n<hr>\r\nYou are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order.\r\n\r\n*Merge all the linked-lists into one sorted linked-list and return it.*\r\n\r\n**Example 1:**\r\n\r\n**Input:** lists = [[1,4,5],[1,3,4],[2,6]]\r\n<br>\r\n**Output:** [1,1,2,3,4,4,5,6]\r\n<br>\r\n**Explanation:** The linked-lists are:\r\n[\r\n  1->4->5,\r\n  1->3->4,\r\n  2->6\r\n]\r\nmerging them into one sorted list:\r\n1->1->2->3->4->4->5->6\r\n\r\n**Example 2:**\r\n\r\n**Input:** lists = []\r\n**Output:** []\r\n\r\n**Example 3:**\r\n\r\n**Input:** lists = [[]]\r\n**Output:** []\r\n\r\n**Constraints:**\r\n\r\n-   `k == lists.length`\r\n-   `0 <= k <= 10^4^`\r\n-   `0 <= lists[i].length <= 500`\r\n-   `-10^4^ <= lists[i][j] <= 10^4^`\r\n-   `lists[i]` is sorted in **ascending order**.\r\n-   The sum of `lists[i].length` will not exceed `10^4^`.\r\n"
  },
  {
    "path": "230-kth-smallest-element-in-a-bst/230-kth-smallest-element-in-a-bst.java",
    "content": "/**\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 count=0;\n    int ans=-1;\n    public int kthSmallest(TreeNode root, int k) {\n        dfs(root,k);\n        return ans;\n    }\n    public void dfs(TreeNode root,int k){\n        if(root==null)return;\n        dfs(root.left,k);\n        count++;\n        if(count==k){\n            ans=root.val;\n            return;\n        }\n        dfs(root.right,k);\n        return;\n    }\n}"
  },
  {
    "path": "230-kth-smallest-element-in-a-bst/NOTES.md",
    "content": "​"
  },
  {
    "path": "234-palindrome-linked-list/234-palindrome-linked-list.java",
    "content": "/**\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 boolean isPalindrome(ListNode head) {\n        ListNode node=head;\n        int sz=0;\n        while(node!=null){\n            node=node.next;\n            sz++;\n        }\n        if(sz==1)return true;\n        ListNode curr=head;\n        ListNode prev=null;\n        for(int i=0;i<sz/2;i++){\n            ListNode next=curr.next;\n            curr.next=prev;\n            prev=curr;\n            curr=next;\n        }\n        if(sz%2!=0){\n            curr=curr.next;\n        }\n        while(prev!=null || curr!=null){\n            if(prev.val!=curr.val)return false;\n            prev=prev.next;\n            curr=curr.next;\n        }\n        if(curr==null && prev==null)return true;\n        return false;\n    }\n}"
  },
  {
    "path": "234-palindrome-linked-list/234-palindrome-linked-list.py",
    "content": "# 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 isPalindrome(self, head: Optional[ListNode]) -> bool:\n        if head is None:\n            return True\n        slow = head\n        fast = head\n        while fast.next is not None and fast.next.next is not None:\n            slow = slow.next\n            fast = fast.next.next\n        mid = slow.next\n        slow.next = None\n        prev = None\n        while mid is not None:\n            temp = mid.next\n            mid.next = prev\n            prev = mid\n            mid = temp\n        while prev is not None and head is not None:\n            if prev.val != head.val:\n                return False\n            prev = prev.next\n            head = head.next\n        return True"
  },
  {
    "path": "234-palindrome-linked-list/NOTES.md",
    "content": "​"
  },
  {
    "path": "234-palindrome-linked-list/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/palindrome-linked-list/\">234. Palindrome Linked List</a></h2><h3>Easy</h3><hr><div><p>Given the <code>head</code> of a singly linked list, return <code>true</code> if it is a palindrome.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg\" style=\"width: 422px; height: 62px;\">\n<pre><strong>Input:</strong> head = [1,2,2,1]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg\" style=\"width: 182px; height: 62px;\">\n<pre><strong>Input:</strong> head = [1,2]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 9</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?</div>"
  },
  {
    "path": "234-palindrome-linked-list/palindrome-linked-list.cpp",
    "content": "class Solution {\npublic:\n    bool isPalindrome(ListNode* head) {\n        ListNode* slow = head, *fast = head;\n        while(fast and fast->next){\n            slow=slow->next;\n            fast=fast->next->next;\n        }\n        \n        // reverse half of linkedlist\n        ListNode* nextNode, *prev = NULL;\n        while(slow){\n            nextNode = slow->next;\n            slow->next = prev;\n            prev = slow;\n            slow = nextNode;\n        }\n        \n        while(prev){\n            if(prev->val != head->val) return false;\n            prev = prev->next;\n            head = head->next;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "234. Palindrome Linked List/SolutionCode.cpp",
    "content": "/*\n  Approach : \n    1. Find mid point of linked list.Divide the LL into two respective LL's.\n    2. Now reverse either one of the LL.\n    3. Traverse both LL's simulatenously and if at any instant their data doesn't match -> return false;\n*/\n\nclass Solution {\npublic:\nListNode* reverseNode(ListNode* head){\n    if(!head) return head;\n    \n    ListNode* nx = head->next, *prev = NULL, *curr = head;\n    \n    while(curr){\n        nx = curr->next;\n        curr->next = prev;\n        prev = curr;\n        curr = nx;\n    }\n    return prev;\n}\n    bool isPalindrome(ListNode* head) {\n        if(!head) return true;\n        \n        \n        ListNode *slow = head, *fast = head->next;\n        \n        while(fast && fast->next){\n            slow = slow->next;\n            fast = fast->next;\n            if(fast){\n                fast = fast->next;\n            }\n        }\n        \n        ListNode* tmp = slow->next;\n        slow->next = NULL;\n      \n        ListNode* rev = reverseNode(tmp);\n \n        while(rev && head){\n            if(rev->val != head->val) return false;\n            \n            rev = rev->next;\n            head = head->next;\n        }\n        \n        return true;\n    }\n};\n\n\n"
  },
  {
    "path": "235-lowest-common-ancestor-of-a-binary-search-tree/235-lowest-common-ancestor-of-a-binary-search-tree.java",
    "content": "class Solution {\n    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n        if(p.val<root.val && q.val<root.val) \n            return lowestCommonAncestor(root.left,p,q);\n        else if(p.val>root.val && q.val>root.val)\n            return lowestCommonAncestor(root.right,p,q);\n        else\n            return root;\n    }\n}"
  },
  {
    "path": "235-lowest-common-ancestor-of-a-binary-search-tree/235-lowest-common-ancestor-of-a-binary-search-tree.py",
    "content": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.left = None\n#         self.right = None\n\nclass Solution:\n    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n        \n        \n        # Using Recursion\n        if (root == p or root == q or not root): return root\n        \n        left = self.lowestCommonAncestor(root.left, p, q)\n        right = self.lowestCommonAncestor(root.right, p , q)\n        \n        if left and right : return root  #Found common ancestor\n        \n        elif left: return left\n        elif right: return right\n"
  },
  {
    "path": "235-lowest-common-ancestor-of-a-binary-search-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "235-lowest-common-ancestor-of-a-binary-search-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/\">235. Lowest Common Ancestor of a Binary Search Tree</a></h2><h3>Easy</h3><hr><div><p>Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.</p>\n\n<p>According to the <a href=\"https://en.wikipedia.org/wiki/Lowest_common_ancestor\" target=\"_blank\">definition of LCA on Wikipedia</a>: “The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).”</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png\" style=\"width: 200px; height: 190px;\">\n<pre><strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The LCA of nodes 2 and 8 is 6.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png\" style=\"width: 200px; height: 190px;\">\n<pre><strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [2,1], p = 2, q = 1\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li>\n\t<li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li>\n\t<li>All <code>Node.val</code> are <strong>unique</strong>.</li>\n\t<li><code>p != q</code></li>\n\t<li><code>p</code> and <code>q</code> will exist in the BST.</li>\n</ul>\n</div>"
  },
  {
    "path": "2359-find-closest-node-to-given-two-nodes/NOTES.md",
    "content": "​"
  },
  {
    "path": "2359-find-closest-node-to-given-two-nodes/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-closest-node-to-given-two-nodes/\">2359. Find Closest Node to Given Two Nodes</a></h2><h3>Medium</h3><hr><div><p>You are given a <strong>directed</strong> graph of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>, where each node has <strong>at most one</strong> outgoing edge.</p>\n\n<p>The graph is represented with a given <strong>0-indexed</strong> array <code>edges</code> of size <code>n</code>, indicating that there is a directed edge from node <code>i</code> to node <code>edges[i]</code>. If there is no outgoing edge from <code>i</code>, then <code>edges[i] == -1</code>.</p>\n\n<p>You are also given two integers <code>node1</code> and <code>node2</code>.</p>\n\n<p>Return <em>the <strong>index</strong> of the node that can be reached from both </em><code>node1</code><em> and </em><code>node2</code><em>, such that the <strong>maximum</strong> between the distance from </em><code>node1</code><em> to that node, and from </em><code>node2</code><em> to that node is <strong>minimized</strong></em>. If there are multiple answers, return the node with the <strong>smallest</strong> index, and if no possible answer exists, return <code>-1</code>.</p>\n\n<p>Note that <code>edges</code> may contain cycles.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-2.png\" style=\"width: 321px; height: 161px;\">\n<pre><strong>Input:</strong> edges = [2,2,3,-1], node1 = 0, node2 = 1\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.\nThe maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-4.png\" style=\"width: 195px; height: 161px;\">\n<pre><strong>Input:</strong> edges = [1,2,-1], node1 = 0, node2 = 2\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.\nThe maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == edges.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-1 &lt;= edges[i] &lt; n</code></li>\n\t<li><code>edges[i] != i</code></li>\n\t<li><code>0 &lt;= node1, node2 &lt; n</code></li>\n</ul>\n</div>"
  },
  {
    "path": "236-lowest-common-ancestor-of-a-binary-tree/236-lowest-common-ancestor-of-a-binary-tree.java",
    "content": "class Solution {\n    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n        if (root == null || root == p || root == q) return root;\n        TreeNode left = lowestCommonAncestor(root.left, p, q);\n        TreeNode right = lowestCommonAncestor(root.right, p, q);\n        if (left != null && right != null) return root;\n        return left != null ? left : right;\n    }\n}"
  },
  {
    "path": "236-lowest-common-ancestor-of-a-binary-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.java",
    "content": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n *     int val;\n *     ListNode next;\n *     ListNode(int x) { val = x; }\n * }\n */\nclass Solution {\n    public void deleteNode(ListNode node) {\n        node.val = node.next.val;\n        node.next = node.next.next;\n        return;\n    }\n}"
  },
  {
    "path": "237-delete-node-in-a-linked-list/NOTES.md",
    "content": ""
  },
  {
    "path": "2389-longest-subsequence-with-limited-sum/2389-longest-subsequence-with-limited-sum.java",
    "content": "class Solution {\n    public int[] answerQueries(int[] nums, int[] queries) {\n        Arrays.sort(nums);\n        int n=queries.length;\n        int[]ans=new int[n];\n        for(int i=0;i<n;i++){\n            int sum=0;\n            int j=0;\n            for(;j<nums.length;j++){\n                if(sum+nums[j]>queries[i])break;\n                sum+=nums[j];\n            }\n            ans[i]=j;\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "2389-longest-subsequence-with-limited-sum/NOTES.md",
    "content": "​"
  },
  {
    "path": "2389-longest-subsequence-with-limited-sum/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-subsequence-with-limited-sum/\">2389. Longest Subsequence With Limited Sum</a></h2><h3>Easy</h3><hr><div><p>You are given an integer array <code>nums</code> of length <code>n</code>, and an integer array <code>queries</code> of length <code>m</code>.</p>\n\n<p>Return <em>an array </em><code>answer</code><em> of length </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>maximum</strong> size of a <strong>subsequence</strong> that you can take from </em><code>nums</code><em> such that the <strong>sum</strong> of its elements is less than or equal to </em><code>queries[i]</code>.</p>\n\n<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [4,5,2,1], queries = [3,10,21]\n<strong>Output:</strong> [2,3,4]\n<strong>Explanation:</strong> We answer the queries as follows:\n- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.\n- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.\n- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,3,4,5], queries = [1]\n<strong>Output:</strong> [0]\n<strong>Explanation:</strong> The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>m == queries.length</code></li>\n\t<li><code>1 &lt;= n, m &lt;= 1000</code></li>\n\t<li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>6</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "2389_longest_subsequence_with_limited_sum.cpp",
    "content": "class Solution {\npublic:\n    vector<int> answerQueries(vector<int>& n, vector<int>& q) {\n        vector<int> v;\n        sort(n.begin(),n.end());\n        for(int i =0;i<q.size();i++){\n            int x = q[i];\n            int sum =0;\n            int count =0;\n            for(int j = 0;j<n.size();j++){\n                sum+=n[j];\n                if(sum<=x){\n                    count++;\n                }\n            }\n            v.push_back(count);\n        }\n        return v;\n    }\n};\n"
  },
  {
    "path": "2390_removing_stars_from_a_string.cpp",
    "content": "class Solution {\npublic:\n    string removeStars(string s) {\n        int i =0;\n        for(auto it: s){\n            if(it=='*'){\n                i--;\n            }\n            else{\n                s[i++]=it;\n            }\n        }\n        return s.substr(0,i);\n    }\n};\n"
  },
  {
    "path": "2395_Find_Subarrays_With_Equal_Sum.cpp",
    "content": "class Solution {\npublic:\n    bool findSubarrays(vector<int>& nums) {\n        set<int> s;\n        for(int i =0;i<nums.size()-1;i++){\n            s.insert(nums[i]+nums[i+1]);\n        }\n        if(s.size()==nums.size()-1){\n            return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "240-search-a-2d-matrix-ii/240-search-a-2d-matrix-ii.java",
    "content": "class Solution {\n    public boolean searchMatrix(int[][] matrix, int target) {\n        int i = 0;\n        int j = matrix[0].length - 1;\n        \n        while(i >= 0 && i < matrix.length && j >= 0 && j < matrix[0].length){\n            if(matrix[i][j] == target) return true;\n            else if(matrix[i][j] > target) j--;\n            else if(matrix[i][j] < target) i++;\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "240-search-a-2d-matrix-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "240-search-a-2d-matrix-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/search-a-2d-matrix-ii/\">240. Search a 2D Matrix II</a></h2><h3>Medium</h3><hr><div><p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p>\n\n<ul>\n\t<li>Integers in each row are sorted in ascending from left to right.</li>\n\t<li>Integers in each column are sorted in ascending from top to bottom.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg\" style=\"width: 300px; height: 300px;\">\n<pre><strong>Input:</strong> 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\n<strong>Output:</strong> true\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg\" style=\"width: 300px; height: 300px;\">\n<pre><strong>Input:</strong> 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\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= n, m &lt;= 300</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li>\n\t<li>All the integers in each row are <strong>sorted</strong> in ascending order.</li>\n\t<li>All the integers in each column are <strong>sorted</strong> in ascending order.</li>\n\t<li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "242-valid-anagram/242-valid-anagram.java",
    "content": "class Solution {\n    public boolean isAnagram(String s, String t) {\n        var freqs = new int[26];\n        var freqt = new int[26];\n        \n        for (var c : s.toCharArray()) {\n            freqs[c - 'a']++;\n        }\n        \n        for (var c : t.toCharArray()) {\n            freqt[c - 'a']++;\n        }\n        \n        for (int i = 0; i != 26; ++i) {\n            if (freqs[i] != freqt[i]) {\n                return false;\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "242-valid-anagram/NOTES.md",
    "content": "​"
  },
  {
    "path": "242-valid-anagram/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/valid-anagram/\">242. Valid Anagram</a></h2><h3>Easy</h3><hr><div><p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> <em>if</em> <code>t</code> <em>is an anagram of</em> <code>s</code><em>, and</em> <code>false</code> <em>otherwise</em>.</p>\n\n<p>An <strong>Anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"anagram\", t = \"nagaram\"\n<strong>Output:</strong> true\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"rat\", t = \"car\"\n<strong>Output:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>\n</div>"
  },
  {
    "path": "2421-number-of-good-paths/2421-number-of-good-paths.java",
    "content": "class UnionFind {\n    int[] parent;\n    int[] rank;\n\n    public UnionFind(int size) {\n        parent = new int[size];\n        for (int i = 0; i < size; i++)\n            parent[i] = i;\n        rank = new int[size];\n    }\n\n    public int find(int x) {\n        if (parent[x] != x)\n            parent[x] = find(parent[x]);\n        return parent[x];\n    }\n\n    public void union_set(int x, int y) {\n        int xset = find(x), yset = find(y);\n        if (xset == yset) {\n            return;\n        } else if (rank[xset] < rank[yset]) {\n            parent[xset] = yset;\n        } else if (rank[xset] > rank[yset]) {\n            parent[yset] = xset;\n        } else {\n            parent[yset] = xset;\n            rank[xset]++;\n        }\n    }\n}\n\nclass Solution {\n    public int numberOfGoodPaths(int[] vals, int[][] edges) {\n        Map<Integer, List<Integer>> adj = new HashMap<>();\n        for (int[] edge : edges) {\n            int a = edge[0], b = edge[1];\n            adj.computeIfAbsent(a, value -> new ArrayList<Integer>()).add(b);\n            adj.computeIfAbsent(b, value -> new ArrayList<Integer>()).add(a);\n        }\n\n        int n = vals.length;\n        // Mapping from value to all the nodes having the same value in sorted order of\n        // values.\n        TreeMap<Integer, List<Integer>> valuesToNodes = new TreeMap<>();\n        for (int i = 0; i < n; i++) {\n            valuesToNodes.computeIfAbsent(vals[i], value -> new ArrayList<Integer>()).add(i);\n        }\n\n        UnionFind dsu = new UnionFind(n);\n        int goodPaths = 0;\n\n        // Iterate over all the nodes with the same value in sorted order, starting from\n        // the lowest value.\n        for (int value : valuesToNodes.keySet()) {\n            // For every node in nodes, combine the sets of the node and its neighbors into\n            // one set.\n            for (int node : valuesToNodes.get(value)) {\n                if (!adj.containsKey(node))\n                    continue;\n                for (int neighbor : adj.get(node)) {\n                    // Only choose neighbors with a smaller value, as there is no point in\n                    // traversing to other neighbors.\n                    if (vals[node] >= vals[neighbor]) {\n                        dsu.union_set(node, neighbor);\n                    }\n                }\n            }\n            // Map to compute the number of nodes under observation (with the same values)\n            // in each of the sets.\n            Map<Integer, Integer> group = new HashMap<>();\n            // Iterate over all the nodes. Get the set of each node and increase the count\n            // of the set by 1.\n            for (int u : valuesToNodes.get(value)) {\n                group.put(dsu.find(u), group.getOrDefault(dsu.find(u), 0) + 1);\n            }\n            // For each set of \"size\", add size * (size + 1) / 2 to the number of goodPaths.\n            for (int key : group.keySet()) {\n                int size = group.get(key);\n                goodPaths += size * (size + 1) / 2;\n            }\n        }\n        return goodPaths;\n    }\n}"
  },
  {
    "path": "2421-number-of-good-paths/NOTES.md",
    "content": "​"
  },
  {
    "path": "2429-minimize-xor/2429-minimize-xor.cpp",
    "content": "class Solution\n{\npublic:\n    int minimizeXor(int num1, int num2)\n    {\n        int c1 = __builtin_popcount(num1);\n        int c2 = __builtin_popcount(num2);\n\n        int ans = 0;\n\n        for (int i = 31; i >= 0; i--)\n        {\n            if ((1 << i) & num1)\n            {\n                ans |= (1 << i);\n                c2--;\n\n                if (c2 == 0) break;\n            }\n        }\n\n        if (c2 > 0)\n        {\n            for (int i = 0; i < 32; i++)\n            {\n                if (((1 << i) & num1) == 0)\n                {\n                    ans |= 1 << i;\n                    c2--;\n                }\n\n                if (c2 == 0) break;\n            }\n        }\n\n        return ans;\n    }\n};"
  },
  {
    "path": "2429-minimize-xor/Notes.md",
    "content": ""
  },
  {
    "path": "2429-minimize-xor/Readme.md",
    "content": "## 2429. Minimize XOR\n\n**Difficulty - Medium**\n\nGiven two positive integers num1 and num2, find the integer x such that:\n\n- x has the same number of set bits as num2, and\n- The value x XOR num1 is minimal.  \n  Note that XOR is the bitwise XOR operation.\n\nReturn the integer x. The test cases are generated such that x is uniquely determined.\n\nThe number of set bits of an integer is the number of 1's in its binary representation.\n\n## Example 1\n\n**Input:** num1 = 3, num2 = 5  \n**Output:** 3  \n**Explanation:**  \nThe binary representations of num1 and num2 are 0011 and 0101, respectively.\nThe integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal.\n\n## Example 2\n\n**Input:** num1 = 1, num2 = 12  \n**Output:** 3  \n**Explanation:**  \nThe binary representations of num1 and num2 are 0001 and 1100, respectively.\nThe integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal.\n\n## Contraints\n\n- 1 <= num1, num2 <= 109\n"
  },
  {
    "path": "2453-destroy-sequential-targets/2453-destroy-sequential-targets.java",
    "content": "class Solution {\n    public int destroyTargets(int[] nums, int space) {\n        HashMap<Integer, Integer> remCount  = new HashMap<>();\n        HashMap<Integer, Integer> remNum = new HashMap<>();\n        for(int e : nums){\n            int rem = e%space;\n\n            remNum.put(rem, Math.min(e,remNum.getOrDefault(rem, Integer.MAX_VALUE) ));\n            remCount.put(rem, remCount.getOrDefault(rem,0)+1);\n        }\n\n        int max = -1; int remMax=-1; int re = -1;\n        for(int rem : remCount.keySet()){\n            if(remCount.get(rem)>max){\n                remMax = rem; max = remCount.get(rem);\n                re = remNum.get(remMax);\n            }\n        }\n\n        int result = Integer.MAX_VALUE;\n        for(int key :  remNum.keySet()){\n            if(remCount.get(key)==max){\n                result = Math.min(remNum.get(key), result);\n            }\n        }\n\n        return result;\n    }\n}"
  },
  {
    "path": "2453-destroy-sequential-targets/NOTES.md",
    "content": "​"
  },
  {
    "path": "268-missing-number/268-missing-number.java",
    "content": "class Solution {\n    public int missingNumber(int[] nums) {\n        int num=nums.length;\n        for(int i=0;i<nums.length;i++){\n            num=num^nums[i];\n            num=num^i;\n        }\n        return num;\n    }\n}"
  },
  {
    "path": "268-missing-number/NOTES.md",
    "content": "​"
  },
  {
    "path": "268-missing-number/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/missing-number/\">268. Missing Number</a></h2><h3>Easy</h3><hr><div><p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [3,0,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [0,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [9,6,4,2,3,5,7,0,1]\n<strong>Output:</strong> 8\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= n</code></li>\n\t<li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>\n</div>"
  },
  {
    "path": "284-peeking-iterator/284-peeking-iterator.java",
    "content": "// Java Iterator interface reference:\n// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html\n\nclass PeekingIterator implements Iterator<Integer> {\n    int i;\n    ArrayList<Integer> arr;\n\tpublic PeekingIterator(Iterator<Integer> iterator) {\n\t    // initialize any member here.\n\t    arr=new ArrayList<>();\n        while(iterator.hasNext()){\n            arr.add(iterator.next());\n        }\n        i=0;\n\t}\n\t\n    // Returns the next element in the iteration without advancing the iterator.\n\tpublic Integer peek() {\n        return arr.get(i);\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    int val=arr.get(i);\n        i++;\n        return val;\n\t}\n\t\n\t@Override\n\tpublic boolean hasNext() {\n\t    return i<arr.size();\n\t}\n}"
  },
  {
    "path": "284-peeking-iterator/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/peeking-iterator/\">284. Peeking Iterator</a></h2><h3>Medium</h3><hr><div><p>Design an iterator that supports the <code>peek</code> operation on an existing iterator in addition to the <code>hasNext</code> and the <code>next</code> operations.</p>\n\n<p>Implement the <code>PeekingIterator</code> class:</p>\n\n<ul>\n\t<li><code>PeekingIterator(Iterator&lt;int&gt; nums)</code> Initializes the object with the given integer iterator <code>iterator</code>.</li>\n\t<li><code>int next()</code> Returns the next element in the array and moves the pointer to the next element.</li>\n\t<li><code>boolean hasNext()</code> Returns <code>true</code> if there are still elements in the array.</li>\n\t<li><code>int peek()</code> Returns the next element in the array <strong>without</strong> moving the pointer.</li>\n</ul>\n\n<p><strong>Note:</strong> Each language may have a different implementation of the constructor and <code>Iterator</code>, but they all support the <code>int next()</code> and <code>boolean hasNext()</code> functions.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"PeekingIterator\", \"next\", \"peek\", \"next\", \"next\", \"hasNext\"]\n[[[1, 2, 3]], [], [], [], [], []]\n<strong>Output</strong>\n[null, 1, 2, 2, 3, false]\n\n<strong>Explanation</strong>\nPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [<u><strong>1</strong></u>,2,3]\npeekingIterator.next();    // return 1, the pointer moves to the next element [1,<u><strong>2</strong></u>,3].\npeekingIterator.peek();    // return 2, the pointer does not move [1,<u><strong>2</strong></u>,3].\npeekingIterator.next();    // return 2, the pointer moves to the next element [1,2,<u><strong>3</strong></u>]\npeekingIterator.next();    // return 3, the pointer moves to the next element [1,2,3]\npeekingIterator.hasNext(); // return False\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>All the calls to <code>next</code> and <code>peek</code> are valid.</li>\n\t<li>At most <code>1000</code> calls will be made to <code>next</code>, <code>hasNext</code>, and <code>peek</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> How would you extend your design to be generic and work with all types, not just integer?</div>"
  },
  {
    "path": "287-find-the-duplicate-number/287-find-the-duplicate-number.java",
    "content": "class Solution {\n    public int findDuplicate(int[] nums) {\n        int fast=0,slow=0;\n        while(true){\n            slow=nums[slow];\n            fast=nums[nums[fast]];\n            if(slow==fast)break;\n        }\n        int slow2=0;\n        while(true){\n            slow=nums[slow];\n            slow2=nums[slow2];\n            if(slow==slow2)break;\n        }\n        return slow;\n    }\n}"
  },
  {
    "path": "287-find-the-duplicate-number/NOTES.md",
    "content": "​"
  },
  {
    "path": "287-find-the-duplicate-number/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-the-duplicate-number/\">287. Find the Duplicate Number</a></h2><h3>Medium</h3><hr><div><p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p>\n\n<p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p>\n\n<p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and uses only constant extra space.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,3,4,2,2]\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [3,1,3,4,2]\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>nums.length == n + 1</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= n</code></li>\n\t<li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><b>Follow up:</b></p>\n\n<ul>\n\t<li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li>\n\t<li>Can you solve the problem in linear runtime complexity?</li>\n</ul>\n</div>"
  },
  {
    "path": "289-game-of-life/289-game-of-life.java",
    "content": "class Solution {\n    public void gameOfLife(int[][] board) {\n        int n=board.length;\n        int m=board[0].length;\n        int[][] ans=new int[n][m];\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(board[i][j]==1)ans[i][j]=1;\n                int ones=getNebs(board,i,j);\n                if(ones<2 && board[i][j]==1){\n                    ans[i][j]=0;\n                }else if((ones==2 || ones==3) && board[i][j]==1){\n                    ans[i][j]=1;\n                }else if(board[i][j]==1 && ones>3){\n                    ans[i][j]=0;\n                }else if(board[i][j]==0 && ones==3){\n                    ans[i][j]=1;\n                }\n            }\n        }\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                board[i][j]=ans[i][j];\n            }\n        }\n    }\n    public int getNebs(int[][]mat,int i,int j){\n        int ans=0;\n        int n=mat.length;\n        int m=mat[0].length;\n        if(i>0){\n            ans+=mat[i-1][j];\n        }\n        if(j>0){\n            ans+=mat[i][j-1];\n        }\n        if(i>0 && j>0){\n            ans+=mat[i-1][j-1];\n        }\n        if(j<m-1){\n            ans+=mat[i][j+1];\n        }\n        if(i>0 && j<m-1){\n            ans+=mat[i-1][j+1];\n        }\n        if(i<n-1){\n            ans+=mat[i+1][j];\n        }\n        if(j>0 && i<n-1){\n            ans+=mat[i+1][j-1];\n        }\n        if(j<m-1 && i<n-1){\n            ans+=mat[i+1][j+1];\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "289-game-of-life/NOTES.md",
    "content": "​"
  },
  {
    "path": "289-game-of-life/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/game-of-life/\">289. Game of Life</a></h2><h3>Medium</h3><hr><div><p>According to&nbsp;<a href=\"https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life\" target=\"_blank\">Wikipedia's article</a>: \"The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\"</p>\n\n<p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href=\"https://en.wikipedia.org/wiki/Moore_neighborhood\" target=\"_blank\">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p>\n\n<ol>\n\t<li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li>\n\t<li>Any live cell with two or three live neighbors lives on to the next generation.</li>\n\t<li>Any live cell with more than three live neighbors dies, as if by over-population.</li>\n\t<li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li>\n</ol>\n\n<p><span>The 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 <code>m x n</code> grid <code>board</code>, return <em>the next state</em>.</span></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg\" style=\"width: 562px; height: 322px;\">\n<pre><strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\n<strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg\" style=\"width: 402px; height: 162px;\">\n<pre><strong>Input:</strong> board = [[1,1],[1,0]]\n<strong>Output:</strong> [[1,1],[1,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 25</code></li>\n\t<li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>Could 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.</li>\n\t<li>In 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?</li>\n</ul>\n</div>"
  },
  {
    "path": "29-divide-two-integers/29-divide-two-integers.java",
    "content": "class Solution {\n    public int divide(int dividend, int divisor) {\n    //the special situation\n        if (dividend == 0) {\n          return 0;\n        }\n        if (dividend == Integer.MIN_VALUE && divisor == -1) {\n          return Integer.MAX_VALUE;\n        }\n        //mark the different situation\n        boolean sign = true;\n        if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {\n            sign = false;\n        }\n        //change them both into negative number\n        dividend = dividend > 0 ? -dividend : dividend;\n        divisor = divisor > 0 ? -divisor : divisor;\n        //if there are different,so it must be a negative number,just 0 minus the result\n        return sign == false ? 0 - count(dividend, divisor) : count(dividend, divisor);\n     }\n\n  /**\n   * This recursion main code is while,it just likes optimization of subtraction\n   */\n      private int count(int a, int b) {\n        //if 3*n==7 just plus 1,or 3*n>7 just plus 0\n        if (a >= b) {\n          return a > b ? 0 : 1;\n        }\n        //the default number is 1,and 2,4,8...doubling\n        int n = 1;\n        int result = 0;\n        int temp = b;\n        while (a <= temp && temp < 0) {\n          a -= temp;\n          result += n;\n          temp += temp;\n          n += n;\n        }\n        return result + count(a, b);\n      }\n}"
  },
  {
    "path": "29-divide-two-integers/NOTES.md",
    "content": "​"
  },
  {
    "path": "3-longest-substring-without-repeating-characters/3-longest-substring-without-repeating-characters.java",
    "content": "class Solution {\n    public int lengthOfLongestSubstring(String s) {\n        if(s.length() < 2) return s.length();\n        int max = 0;\n        char[] split = s.toCharArray();\n        int[] map = new int[256];\n        for(int i = 0, j = 0; i < split.length; i++) {\n            char c = split[i]; \n            j = Math.max(j, map[c]);\n            map[c] = i + 1;\n            max = Math.max(max, i - j + 1);\n        }\n        return max;\n    }\n}"
  },
  {
    "path": "3-longest-substring-without-repeating-characters/NOTES.md",
    "content": "​"
  },
  {
    "path": "3-longest-substring-without-repeating-characters/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-substring-without-repeating-characters/\">3. Longest Substring Without Repeating Characters</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, find the length of the <strong>longest substring</strong> without repeating characters.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"abcabcbb\"\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The answer is \"abc\", with the length of 3.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"bbbbb\"\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The answer is \"b\", with the length of 1.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"pwwkew\"\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of English letters, digits, symbols and spaces.</li>\n</ul>\n</div>"
  },
  {
    "path": "30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.java",
    "content": "class Solution {\n    public List<Integer> findSubstring(String str, String[] words) {\n        if(str == null || str.length() == 0 || words == null || words.length == 0) {\n          return new ArrayList<>();\n        }\n\n        Map<String, Integer> frequencyMap = new HashMap<>();\n\n        for(String word: words) {\n          frequencyMap.put(word, frequencyMap.getOrDefault(word, 0) + 1);\n        }\n\n        int eachWordLength = words[0].length();\n        int totalWords = words.length;\n        List<Integer> result = new ArrayList<>();\n\n        for (int i = 0; i <= str.length() - (totalWords * eachWordLength); i++) {\n\n          Map<String, Integer> seenWords = new HashMap<>();\n\n          for (int j = 0; j < totalWords; j++) {\n            int wordIndex = i + j * eachWordLength;\n\n            String word = str.substring(wordIndex, wordIndex + eachWordLength);\n\n            if(!frequencyMap.containsKey(word)) {\n              break;\n            }\n\n            seenWords.put(word, seenWords.getOrDefault(word, 0) + 1);\n\n            if(seenWords.get(word) > frequencyMap.get(word)) {\n              break;\n            }\n\n            if(j + 1 == totalWords)   {\n              result.add(i);\n            }\n          }\n        }\n\n        return result;\n    }\n}"
  },
  {
    "path": "30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.py",
    "content": "class Solution:\n    def findSubstring(self, s: str, words: List[str]) -> List[int]:\n\n        words_counter = Counter(words)\n        WORDLEN = len(words[0])\n        MATCHLEN = (len(words) - 1) * WORDLEN\n\n        res = []\n        stack = deque()\n        \n        for offset in range(WORDLEN):\n            counter = words_counter.copy()\n            for i in range(offset, len(s), WORDLEN):\n                word = s[i: i + WORDLEN]\n                while len(stack) and word not in counter:\n                    prev = stack.popleft()\n                    if prev == word:\n                        stack.append(word)\n                        break\n                    counter[prev] += 1\n                \n                if word in counter:\n                    counter[word] -= 1\n                    stack.append(word)\n                    if counter[word] == 0:\n                        del counter[word]\n                    \n                if len(counter) == 0:\n                    res.append(i - MATCHLEN)\n                    \n            stack.clear() # Clears stack in the cases there are left overs from previous offset\n                \n        return res\n"
  },
  {
    "path": "30-substring-with-concatenation-of-all-words/NOTES.md",
    "content": "​"
  },
  {
    "path": "30-substring-with-concatenation-of-all-words/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/substring-with-concatenation-of-all-words/\">30. Substring with Concatenation of All Words</a></h2><h3>Hard</h3><hr><div><p>You are given a string <code>s</code> and an array of strings <code>words</code> of <strong>the same length</strong>. Return&nbsp;all starting indices of substring(s) in <code>s</code>&nbsp;that is a concatenation of each word in <code>words</code> <strong>exactly once</strong>, <strong>in any order</strong>,&nbsp;and <strong>without any intervening characters</strong>.</p>\n\n<p>You can return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\n<strong>Output:</strong> [0,9]\n<strong>Explanation:</strong> Substrings starting at index 0 and 9 are \"barfoo\" and \"foobar\" respectively.\nThe output order does not matter, returning [9,0] is fine too.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]\n<strong>Output:</strong> []\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]\n<strong>Output:</strong> [6,9,12]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words.length &lt;= 5000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 30</code></li>\n\t<li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "300-longest-increasing-subsequence/300-longest-increasing-subsequence.java",
    "content": "class Solution {\n    public int lengthOfLIS(int[] nums) {\n        int[]dp=new int[nums.length];\n        Arrays.fill(dp,1);\n        for(int i=nums.length-2;i>=0;i--){\n            for(int j=i+1;j<nums.length;j++){\n                if(nums[i]<nums[j]){\n                    dp[i]=Math.max(dp[i],1+dp[j]);\n                }\n            }\n        }\n        int ans=0;\n        for(int i:dp)ans=Math.max(ans,i);\n        return ans;\n    }\n}"
  },
  {
    "path": "300-longest-increasing-subsequence/NOTES.md",
    "content": "​"
  },
  {
    "path": "300-longest-increasing-subsequence/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-increasing-subsequence/\">300. Longest Increasing Subsequence</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, return the length of the longest strictly increasing subsequence.</p>\n\n<p>A <strong>subsequence</strong> 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, <code>[3,6,2,7]</code> is a subsequence of the array <code>[0,3,1,6,2,2,7]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [10,9,2,5,3,7,101,18]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The longest increasing subsequence is [2,3,7,101], therefore the length is 4.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [0,1,0,3,2,3]\n<strong>Output:</strong> 4\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [7,7,7,7,7,7,7]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2500</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><b>Follow up:</b>&nbsp;Can you come up with an algorithm that runs in&nbsp;<code>O(n log(n))</code> time complexity?</p>\n</div>"
  },
  {
    "path": "304-range-sum-query-2d-immutable/304-range-sum-query-2d-immutable.java",
    "content": "class NumMatrix {\n    int[][]mat;\n    int[][]sum;\n    public NumMatrix(int[][] matrix) {\n        mat=matrix;\n        int n=matrix.length;\n        int m=matrix[0].length;\n        sum=new int[n][m];\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(j==0){\n                    sum[i][j]=mat[i][j];\n                }else{\n                    sum[i][j]=mat[i][j]+sum[i][j-1];\n                }\n            }\n        }\n    }\n    \n    public int sumRegion(int row1, int col1, int row2, int col2) {\n        int ans=0;\n        if(col1==0){\n            while(row1<=row2){\n                ans+=sum[row1][col2];\n                row1++;\n            }\n        }else{\n            while(row1<=row2){\n                ans+=sum[row1][col2]-sum[row1][col1-1];\n                row1++;\n            }\n        }\n        return ans;\n    }\n}\n\n/**\n * Your NumMatrix object will be instantiated and called as such:\n * NumMatrix obj = new NumMatrix(matrix);\n * int param_1 = obj.sumRegion(row1,col1,row2,col2);\n */"
  },
  {
    "path": "304-range-sum-query-2d-immutable/NOTES.md",
    "content": "​"
  },
  {
    "path": "304-range-sum-query-2d-immutable/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/range-sum-query-2d-immutable/\">304. Range Sum Query 2D - Immutable</a></h2><h3>Medium</h3><hr><div><p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p>\n\n<ul>\n\t<li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>\n</ul>\n\n<p>Implement the NumMatrix class:</p>\n\n<ul>\n\t<li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li>\n\t<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg\" style=\"width: 415px; height: 415px;\">\n<pre><strong>Input</strong>\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]]\n<strong>Output</strong>\n[null, 8, 11, 12]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= matrix[i][j] &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= row1 &lt;= row2 &lt; m</code></li>\n\t<li><code>0 &lt;= col1 &lt;= col2 &lt; n</code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "307-range-sum-query-mutable/307-range-sum-query-mutable.java",
    "content": "class NumArray {\n    class SegmentTreeNode {\n        int start, end;\n        SegmentTreeNode left, right;\n        int sum;\n\n        public SegmentTreeNode(int start, int end) {\n            this.start = start;\n            this.end = end;\n            this.left = null;\n            this.right = null;\n            this.sum = 0;\n        }\n    }\n      \n    SegmentTreeNode root = null;\n   \n    public NumArray(int[] nums) {\n        root = buildTree(nums, 0, nums.length-1);\n    }\n\n    private SegmentTreeNode buildTree(int[] nums, int start, int end) {\n        if (start > end) {\n            return null;\n        } else {\n            SegmentTreeNode ret = new SegmentTreeNode(start, end);\n            if (start == end) {\n                ret.sum = nums[start];\n            } else {\n                int mid = start  + (end - start) / 2;             \n                ret.left = buildTree(nums, start, mid);\n                ret.right = buildTree(nums, mid + 1, end);\n                ret.sum = ret.left.sum + ret.right.sum;\n            }         \n            return ret;\n        }\n    }\n   \n    void update(int i, int val) {\n        update(root, i, val);\n    }\n   \n    void update(SegmentTreeNode root, int pos, int val) {\n        if (root.start == root.end) {\n           root.sum = val;\n        } else {\n            int mid = root.start + (root.end - root.start) / 2;\n            if (pos <= mid) {\n                 update(root.left, pos, val);\n            } else {\n                 update(root.right, pos, val);\n            }\n            root.sum = root.left.sum + root.right.sum;\n        }\n    }\n\n    public int sumRange(int i, int j) {\n        return sumRange(root, i, j);\n    }\n    \n    public int sumRange(SegmentTreeNode root, int start, int end) {\n        if (root.end == end && root.start == start) {\n            return root.sum;\n        } else {\n            int mid = root.start + (root.end - root.start) / 2;\n            if (end <= mid) {\n                return sumRange(root.left, start, end);\n            } else if (start >= mid+1) {\n                return sumRange(root.right, start, end);\n            }  else {    \n                return sumRange(root.right, mid+1, end) + sumRange(root.left, start, mid);\n            }\n        }\n    }\n}\n\n/**\n * Your NumArray object will be instantiated and called as such:\n * NumArray obj = new NumArray(nums);\n * obj.update(index,val);\n * int param_2 = obj.sumRange(left,right);\n */"
  },
  {
    "path": "307-range-sum-query-mutable/NOTES.md",
    "content": "​"
  },
  {
    "path": "307-range-sum-query-mutable/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/range-sum-query-mutable/\">307. Range Sum Query - Mutable</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, handle multiple queries of the following types:</p>\n\n<ol>\n\t<li><strong>Update</strong> the value of an element in <code>nums</code>.</li>\n\t<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li>\n</ol>\n\n<p>Implement the <code>NumArray</code> class:</p>\n\n<ul>\n\t<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>\n\t<li><code>void update(int index, int val)</code> <strong>Updates</strong> the value of <code>nums[index]</code> to be <code>val</code>.</li>\n\t<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]\n<strong>Output</strong>\n[null, 9, null, 8]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n\t<li><code>0 &lt;= index &lt; nums.length</code></li>\n\t<li><code>-100 &lt;= val &lt;= 100</code></li>\n\t<li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li>\n\t<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>update</code> and <code>sumRange</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "31-next-permutation/31-next-permutation.java",
    "content": "class Solution {\n    public void nextPermutation(int[] a) {\n        int N=a.length;\n        int k=-1;\n        for(int i=0;i<N-1;i++){\n            if(a[i]<a[i+1]){\n                k=i;\n            }\n        }\n        if(k==-1){\n            reverse(a,0,N-1);\n            return;\n        }\n        int l=k+1;\n        for(int i=k+1;i<N;i++){\n            if(a[i]>a[k]){\n                l=i;\n            }\n        }\n        int temp=a[k];\n        a[k]=a[l];\n        a[l]=temp;\n        reverse(a,k+1,N-1);\n    }\n    public void reverse(int[]a,int i,int j){\n        while(i<=j-1){\n            int temp=a[i];\n            a[i]=a[j];\n            a[j]=temp;\n            i++;\n            j--;\n        }\n    }\n}"
  },
  {
    "path": "31-next-permutation/NOTES.md",
    "content": "​"
  },
  {
    "path": "31-next-permutation/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/next-permutation/\">31. Next Permutation</a></h2><h3>Medium</h3><hr><div><p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p>\n\n<ul>\n\t<li>For example, for <code>arr = [1,2,3]</code>, the following are considered permutations of <code>arr</code>: <code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[3,1,2]</code>, <code>[2,3,1]</code>.</li>\n</ul>\n\n<p>The <strong>next permutation</strong> 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 <strong>next permutation</strong> 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).</p>\n\n<ul>\n\t<li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li>\n\t<li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li>\n\t<li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li>\n</ul>\n\n<p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p>\n\n<p>The replacement must be <strong><a href=\"http://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in place</a></strong> and use only constant extra memory.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> [1,3,2]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [3,2,1]\n<strong>Output:</strong> [1,2,3]\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,1,5]\n<strong>Output:</strong> [1,5,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "31-next-permutation/nextPurmutation.cpp",
    "content": "/*\nApproach: \nThere may be three possibilities for the given sequence, it could be in ascending, descending or mixed Order.\nBased upon that three subcases will be applied\n1. Descending Order : For this we simply need to return a series in acending order i.e. a Sorted Array\n2. Ascending Order : By just swapping last two unequal numbers of array, we could get a Required next Permutation.\n3. Mixed Order : For this we need to find the right most local maxima, after that is find further two cases may arise: \n      i) If a number exists in right of this local maxima which is less than this maxima and greater than element before maxima(let say that as midVal)\n          In that cases swapping midVal with element just before local maxima will give, next premutaion, as that would be more close.\n      ii) In case if no such Element Exists, in that case directly swapping local maxima with element before than will be right.\n      \n After doing any of i or ii, we need to sort remainning right array in ascending order.     \n\n*/\n\n// Code : \n\nclass Solution {\npublic:\nint findIfMidExists(vector<int>& nums, int t){\n    int ans = -1;\n    for(int i=t+1;i<nums.size();i++){\n        if(nums[i]<nums[t] &&  nums[i]>nums[t-1]){\n            ans = i;\n        }\n    }\n    return ans;\n}    \n    void nextPermutation(vector<int>& nums) {\n        if(nums.size()==1) return ;\n        if(nums.size()==2){\n            swap(nums[0], nums[1]);\n            return;\n        }\n        int n = nums.size(), mx = n-1, i=n-1;\n        for(;i>=0;i--){\n            if(i==n-1 && nums[i]>nums[i-1]){ \n                mx = n-1;\n                break;}\n            else if(i>0 && nums[i]>nums[i-1] && nums[i]>=nums[i+1]){ \n                mx = i;\n                break;\n            }\n        }\n      // If Given series is in descending Order\n        if(i<0){\n            sort(nums.begin(), nums.end());\n            return;\n        }\n        \n        int midVal = findIfMidExists(nums,mx);\n        if(midVal != -1){\n            swap(nums[mx-1], nums[midVal]);\n            sort(nums.begin()+mx, nums.end());\n            return;\n        }\n        swap(nums[mx-1], nums[mx]);\n        sort(nums.begin() + mx, nums.end());\n    }\n};\n"
  },
  {
    "path": "315-count-of-smaller-numbers-after-self/315-count-of-smaller-numbers-after-self.java",
    "content": "class Solution {\n    public List<Integer> countSmaller(int[] nums) {\n        int n=nums.length;\n        Integer[] ans=new Integer[n];\n        ans[n-1]=0;\n        int ii=n-2;\n        List<Integer> arr=new ArrayList<>();\n        arr.add(nums[n-1]);\n        for(int i=n-2;i>=0;i--){\n            int idx=dfs(arr,nums[i]);\n            arr.add(idx,nums[i]);\n            ans[ii]=idx;\n            ii--;\n        }\n        return Arrays.asList(ans);\n    }\n    int dfs(List<Integer> arr,int ele){\n        int l=0;\n        int h=arr.size()-1;\n        while(l<=h){\n            int mid=l+(h-l)/2;\n            if(ele<=arr.get(mid)){\n                h=mid-1;\n            }else{\n                l=mid+1;\n            }\n        }\n        return l;\n    }\n}"
  },
  {
    "path": "315-count-of-smaller-numbers-after-self/NOTES.md",
    "content": "​"
  },
  {
    "path": "315-count-of-smaller-numbers-after-self/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/count-of-smaller-numbers-after-self/\">315. Count of Smaller Numbers After Self</a></h2><h3>Hard</h3><hr><div><p>You are given an integer array <code>nums</code> and you have to return a new <code>counts</code> array. The <code>counts</code> array has the property where <code>counts[i]</code> is the number of smaller elements to the right of <code>nums[i]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [5,2,6,1]\n<strong>Output:</strong> [2,1,1,0]\n<strong>Explanation:</strong>\nTo the right of 5 there are <b>2</b> smaller elements (2 and 1).\nTo the right of 2 there is only <b>1</b> smaller element (1).\nTo the right of 6 there is <b>1</b> smaller element (1).\nTo the right of 1 there is <b>0</b> smaller element.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [-1]\n<strong>Output:</strong> [0]\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [-1,-1]\n<strong>Output:</strong> [0,0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "316-remove-duplicate-letters/316-remove-duplicate-letters.java",
    "content": "class Solution {\n    public String removeDuplicateLetters(String s) {\n        int[]freq=new int[26];\n        int[]done=new int[26];\n        for(char c:s.toCharArray()){\n            freq[c-97]++;\n        }\n        Deque<Character> stack=new ArrayDeque<>();\n        for(int i=0;i<s.length();i++){\n            char ch=s.charAt(i);\n            if(done[ch-97]==0){\n                while(stack.size()>0 && stack.peek()>ch){\n                    if(freq[stack.peek()-97]>0){\n                        char out=stack.pop();\n                        done[out-97]=0;\n                    }else{\n                        break;\n                    }\n                }\n                done[ch-97]=1;\n                stack.push(ch);\n            }\n            freq[ch-97]--;\n        }\n        StringBuilder sb=new StringBuilder();\n        while(stack.size()>0){\n            sb.append(stack.pop());\n        }\n        return sb.reverse().toString();\n    }\n}"
  },
  {
    "path": "316-remove-duplicate-letters/NOTES.md",
    "content": "​"
  },
  {
    "path": "316-remove-duplicate-letters/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/remove-duplicate-letters/\">316. Remove Duplicate Letters</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, remove duplicate letters so that every letter appears once and only once. You must make sure your result is <strong>the smallest in lexicographical order</strong> among all possible results.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"bcabc\"\n<strong>Output:</strong> \"abc\"\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"cbacdcbc\"\n<strong>Output:</strong> \"acdb\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as 1081: <a href=\"https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/\" target=\"_blank\">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>\n</div>"
  },
  {
    "path": "318-maximum-product-of-word-lengths/318-maximum-product-of-word-lengths.java",
    "content": "class Solution {\n    public int maxProduct(String[] words) {\n        int n=words.length;\n        int[] mask=new int[n];\n        for(int i=0; i<n; i++){\n            for(char c: words[i].toCharArray()){\n                mask[i]|=1<<(c-'a');\n            }\n        }\n        int max=0;\n        for(int i=0; i<n; i++){\n            for(int j=i+1; j<n; j++){\n                if((mask[i] & mask[j])==0) max=Math.max(max, words[i].length()*words[j].length());\n            }\n        }\n        \n        return max;\n    }\n}"
  },
  {
    "path": "318-maximum-product-of-word-lengths/NOTES.md",
    "content": "​"
  },
  {
    "path": "318-maximum-product-of-word-lengths/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-product-of-word-lengths/\">318. Maximum Product of Word Lengths</a></h2><h3>Medium</h3><hr><div><p>Given a string array <code>words</code>, return <em>the maximum value of</em> <code>length(word[i]) * length(word[j])</code> <em>where the two words do not share common letters</em>. If no such two words exist, return <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"abcw\",\"baz\",\"foo\",\"bar\",\"xtfn\",\"abcdef\"]\n<strong>Output:</strong> 16\n<strong>Explanation:</strong> The two words can be \"abcw\", \"xtfn\".\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"a\",\"ab\",\"abc\",\"d\",\"cd\",\"bcd\",\"abcd\"]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The two words can be \"ab\", \"cd\".\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> No such pair of words.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= words.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 1000</code></li>\n\t<li><code>words[i]</code> consists only of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "32-longest-valid-parentheses/32-longest-valid-parentheses.java",
    "content": "public class Solution {\n    public int longestValidParentheses(String s) {\n        int left = 0, right = 0, maxlength = 0;\n        for (int i = 0; i < s.length(); i++) {\n            if (s.charAt(i) == '(') {\n                left++;\n            } else {\n                right++;\n            }\n            if (left == right) {\n                maxlength = Math.max(maxlength, 2 * right);\n            } else if (right >= left) {\n                left = right = 0;\n            }\n        }\n        left = right = 0;\n        for (int i = s.length() - 1; i >= 0; i--) {\n            if (s.charAt(i) == '(') {\n                left++;\n            } else {\n                right++;\n            }\n            if (left == right) {\n                maxlength = Math.max(maxlength, 2 * left);\n            } else if (left >= right) {\n                left = right = 0;\n            }\n        }\n        return maxlength;\n    }\n}"
  },
  {
    "path": "32-longest-valid-parentheses/NOTES.md",
    "content": "​"
  },
  {
    "path": "32-longest-valid-parentheses/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-valid-parentheses/\">32. Longest Valid Parentheses</a></h2><h3>Hard</h3><hr><div><p>Given a string containing just the characters <code>'('</code> and <code>')'</code>, find the length of the longest valid (well-formed) parentheses substring.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"(()\"\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The longest valid parentheses substring is \"()\".\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \")()())\"\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The longest valid parentheses substring is \"()()\".\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"\"\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>s[i]</code> is <code>'('</code>, or <code>')'</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "322-coin-change/322-coin-change.java",
    "content": "class Solution {\n    public int coinChange(int[] coins, int amount) {\n        int dp[]=new int[amount+1];\n        Arrays.fill(dp,amount+1);\n        dp[0]=0;\n        for(int coin:coins){\n            for(int i=coin;i<=amount;i++){//<dp.length\n                dp[i]=Math.min(dp[i],dp[i-coin]+1);\n            }\n        }\n        return dp[amount]<=amount? dp[amount] : -1;\n    }\n}"
  },
  {
    "path": "322-coin-change/NOTES.md",
    "content": "​"
  },
  {
    "path": "322-coin-change/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/coin-change/\">322. Coin Change</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>\n\n<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>\n\n<p>You may assume that you have an infinite number of each kind of coin.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> coins = [1,2,5], amount = 11\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 11 = 5 + 5 + 1\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> coins = [2], amount = 3\n<strong>Output:</strong> -1\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> coins = [1], amount = 0\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= coins.length &lt;= 12</code></li>\n\t<li><code>1 &lt;= coins[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>0 &lt;= amount &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "326-power-of-three/326-power-of-three.java",
    "content": "public class Solution {\n    public boolean isPowerOfThree(int n) {\n        return n > 0 && 1162261467 % n == 0;\n    }\n}"
  },
  {
    "path": "326-power-of-three/326_Power_of_three.cpp",
    "content": "class Solution {\npublic:\n    bool isPowerOfThree(int n) {\n        while(n>=3)\n        {\n            if(n%3 != 0)\n                return false;\n            n/=3;\n        }\n        return n==1;\n    }\n};\n"
  },
  {
    "path": "326-power-of-three/NOTES.md",
    "content": "​"
  },
  {
    "path": "326-power-of-three/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/power-of-three/\">326. Power of Three</a></h2><h3>Easy</h3><hr><div><p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p>\n\n<p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 27\n<strong>Output:</strong> true\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 0\n<strong>Output:</strong> false\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 9\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you solve it without loops/recursion?</div>"
  },
  {
    "path": "329-longest-increasing-path-in-a-matrix/329-longest-increasing-path-in-a-matrix.java",
    "content": "class Solution {\n    int[][] matrix, helper;\n    int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n    public int longestIncreasingPath(int[][] matrix) {\n        helper = new int[matrix.length][matrix[0].length];\n        this.matrix= matrix;\n        int path = 0;\n        for(int i=0;i<matrix.length;i++) {\n            for(int j=0;j<matrix[0].length;j++) \n                path = Math.max(path, dfs(i, j));\n        }\n        \n        return path;\n    }\n     \n    private int dfs(int x, int y) {\n        if (helper[x][y] != 0) return helper[x][y];\n        for(int d=0;d<dirs.length;d++) {\n            int i = dirs[d][0] + x, j = dirs[d][1] + y;\n            if(i >= 0 && i < matrix.length && j >= 0 && j < matrix[0].length && matrix[x][y] < matrix[i][j]) {\n                helper[x][y] = Math.max(helper[x][y], dfs(i, j));\n            }\n        }\n        return ++helper[x][y];\n    }\n}"
  },
  {
    "path": "329-longest-increasing-path-in-a-matrix/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-increasing-path-in-a-matrix/\">329. Longest Increasing Path in a Matrix</a></h2><h3>Hard</h3><hr><div><p>Given an <code>m x n</code> integers <code>matrix</code>, return <em>the length of the longest increasing path in </em><code>matrix</code>.</p>\n\n<p>From each cell, you can either move in four directions: left, right, up, or down. You <strong>may not</strong> move <strong>diagonally</strong> or move <strong>outside the boundary</strong> (i.e., wrap-around is not allowed).</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg\" style=\"width: 242px; height: 242px;\">\n<pre><strong>Input:</strong> matrix = [[9,9,4],[6,6,8],[2,1,1]]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The longest increasing path is <code>[1, 2, 6, 9]</code>.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg\" style=\"width: 253px; height: 253px;\">\n<pre><strong>Input:</strong> matrix = [[3,4,5],[3,2,6],[2,2,1]]\n<strong>Output:</strong> 4\n<strong>Explanation: </strong>The longest increasing path is <code>[3, 4, 5, 6]</code>. Moving diagonally is not allowed.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> matrix = [[1]]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n</div>"
  },
  {
    "path": "33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.java",
    "content": "class Solution {\n    public int search(int[] nums, int target) {\n        int l=0,h=nums.length-1;\n        while(l<=h){\n            int mid=(l+h)/2;\n            if(nums[mid]==target){\n                return mid;\n            }\n            else if(nums[mid]>=nums[l]){\n                if(target>=nums[l] && target<nums[mid]){\n                    h=mid-1;\n                }else{\n                    l=mid+1;\n                }\n            }\n            else if(nums[mid]<=nums[h]){\n                if(target>nums[mid] && target<=nums[h]){\n                    l=mid+1;\n                }else{\n                    h=mid-1;\n                }\n            }\n        }\n        return -1;\n    }\n}"
  },
  {
    "path": "33-search-in-rotated-sorted-array/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/search-in-rotated-sorted-array/\">33. Search in Rotated Sorted Array</a></h2><h3>Medium</h3><hr><div><p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p>\n\n<p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p>\n\n<p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p>\n\n<p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0\n<strong>Output:</strong> 4\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3\n<strong>Output:</strong> -1\n</pre><p><strong>Example 3:</strong></p>\n<pre><strong>Input:</strong> nums = [1], target = 0\n<strong>Output:</strong> -1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li>All values of <code>nums</code> are <strong>unique</strong>.</li>\n\t<li><code>nums</code> is an ascending array that is possibly rotated.</li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "336-palindrome-pairs/336-palindrome-pairs.java",
    "content": "class Solution {\n    public List<List<Integer>> palindromePairs(String[] words) {\n        List<List<Integer>> ans=new ArrayList<>();\n        Map<String,Integer> map= new HashMap<>();\n        int idx=0;\n        for(String word:words){\n            StringBuilder sb=new StringBuilder(word);\n            map.put(sb.reverse().toString(),idx++);\n        }\n        for(int i=0;i<words.length;i++){\n            String word=words[i];\n            for(int j=0;j<=word.length();j++){\n                String s1=word.substring(0,j);\n                String s2=word.substring(j);\n                if(map.containsKey(s1) && map.get(s1)!=i && isPal(s2)){\n                    List<Integer> curr=new ArrayList<>();\n                    curr.add(i);\n                    curr.add(map.get(s1));\n                    ans.add(curr);\n                }\n                if(!s1.isEmpty() && map.containsKey(s2) && map.get(s2)!=i && isPal(s1)){\n                    List<Integer> curr=new ArrayList<>();\n                    curr.add(map.get(s2));\n                    curr.add(i);\n                    ans.add(curr);\n                }\n                \n            }\n        }\n        return ans;\n    }\n    boolean isPal(String s){\n        int i=0;\n        int j=s.length()-1;\n        while(i<j){\n            if(s.charAt(i)!=s.charAt(j))return false;\n            i++;\n            j--;\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "336-palindrome-pairs/NOTES.md",
    "content": "​"
  },
  {
    "path": "336-palindrome-pairs/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/palindrome-pairs/\">336. Palindrome Pairs</a></h2><h3>Hard</h3><hr><div><p>Given a list of <b>unique</b> words, return all the pairs of the&nbsp;<b><i>distinct</i></b> indices <code>(i, j)</code> in the given list, so that the concatenation of the two words&nbsp;<code>words[i] + words[j]</code> is a palindrome.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"abcd\",\"dcba\",\"lls\",\"s\",\"sssll\"]\n<strong>Output:</strong> [[0,1],[1,0],[3,2],[2,4]]\n<strong>Explanation:</strong> The palindromes are [\"dcbaabcd\",\"abcddcba\",\"slls\",\"llssssll\"]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"bat\",\"tab\",\"cat\"]\n<strong>Output:</strong> [[0,1],[1,0]]\n<strong>Explanation:</strong> The palindromes are [\"battab\",\"tabbat\"]\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"a\",\"\"]\n<strong>Output:</strong> [[0,1],[1,0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 5000</code></li>\n\t<li><code>0 &lt;= words[i].length &lt;= 300</code></li>\n\t<li><code>words[i]</code> consists of lower-case English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "34-find-first-and-last-position-of-element-in-sorted-array/34-find-first-and-last-position-of-element-in-sorted-array.java",
    "content": "class Solution {\n    public int[] searchRange(int[] nums, int target) {\n        int[] ans=new int[2];\n        ans[0]=Integer.MAX_VALUE;\n        ans[1]=Integer.MIN_VALUE;\n        dfs(nums,target,ans,0,nums.length-1);\n        if(ans[0]==Integer.MAX_VALUE){\n            ans[0]=-1;\n            ans[1]=-1;\n        }\n        return ans;\n    }\n    void dfs(int[]nums,int target,int[]ans,int l,int h){\n        if(l<=h){\n            int mid=l+(h-l)/2;\n            if(nums[mid]==target){\n                ans[0]=Math.min(ans[0],mid);\n                ans[1]=Math.max(ans[1],mid);\n                dfs(nums,target,ans,l,mid-1);\n                dfs(nums,target,ans,mid+1,h);\n            }else if(nums[mid]>target){\n                dfs(nums,target,ans,l,mid-1);\n            }else{\n                dfs(nums,target,ans,mid+1,h);\n            }\n        }\n    }\n}"
  },
  {
    "path": "34-find-first-and-last-position-of-element-in-sorted-array/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/\">34. Find First and Last Position of Element in Sorted Array</a></h2><h3>Medium</h3><hr><div><p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p>\n\n<p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p>\n\n<p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8\n<strong>Output:</strong> [3,4]\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6\n<strong>Output:</strong> [-1,-1]\n</pre><p><strong>Example 3:</strong></p>\n<pre><strong>Input:</strong> nums = [], target = 0\n<strong>Output:</strong> [-1,-1]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li>\n\t<li><code>nums</code> is a non-decreasing array.</li>\n\t<li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "341-flatten-nested-list-iterator/341-flatten-nested-list-iterator.java",
    "content": "public class NestedIterator implements Iterator<Integer> {\n    \n    List<Integer> list;\n    int index = 0;\n    \n    public NestedIterator(List<NestedInteger> nestedList) {\n        list = new ArrayList<Integer>();\n        worker(nestedList);\n    }\n\n    void worker(List<NestedInteger> node) {\n        if(node==null) {\n            return;\n        }\n        for(NestedInteger next:node) {\n            if(next.isInteger()) {\n                list.add(next.getInteger());\n            } else {\n                worker(next.getList());\n            }\n        }\n    }\n    \n    @Override\n    public Integer next() {\n        int val = list.get(index);\n        index++;\n        return val;\n    }\n\n    @Override\n    public boolean hasNext() {\n        return index<list.size();\n    }\n}"
  },
  {
    "path": "341-flatten-nested-list-iterator/NOTES.md",
    "content": "​"
  },
  {
    "path": "341-flatten-nested-list-iterator/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/flatten-nested-list-iterator/\">341. Flatten Nested List Iterator</a></h2><h3>Medium</h3><hr><div><p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.</p>\n\n<p>Implement the <code>NestedIterator</code> class:</p>\n\n<ul>\n\t<li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Initializes the iterator with the nested list <code>nestedList</code>.</li>\n\t<li><code>int next()</code> Returns the next integer in the nested list.</li>\n\t<li><code>boolean hasNext()</code> Returns <code>true</code> if there are still some integers in the nested list and <code>false</code> otherwise.</li>\n</ul>\n\n<p>Your code will be tested with the following pseudocode:</p>\n\n<pre>initialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n    append iterator.next() to the end of res\nreturn res\n</pre>\n\n<p>If <code>res</code> matches the expected flattened list, then your code will be judged as correct.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nestedList = [[1,1],2,[1,1]]\n<strong>Output:</strong> [1,1,2,1,1]\n<strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nestedList = [1,[4,[6]]]\n<strong>Output:</strong> [1,4,6]\n<strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nestedList.length &lt;= 500</code></li>\n\t<li>The values of the integers in the nested list is in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "342-power-of-four/342-power-of-four.java",
    "content": "class Solution {\n    public boolean isPowerOfFour(int n) {\n        if(n==0)return false;\n        int x=(int)(Math.log(n)/Math.log(4));\n        if(Math.pow(4,x)==n)return true;\n        return false;\n    }\n}"
  },
  {
    "path": "342-power-of-four/NOTES.md",
    "content": "​"
  },
  {
    "path": "342-power-of-four/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/power-of-four/\">342. Power of Four</a></h2><h3>Easy</h3><hr><div><p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p>\n\n<p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> n = 16\n<strong>Output:</strong> true\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> n = 5\n<strong>Output:</strong> false\n</pre><p><strong>Example 3:</strong></p>\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> true\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you solve it without loops/recursion?</div>"
  },
  {
    "path": "342-power-of-four/power of four.cpp",
    "content": "bool isPowerOfFour(int n) {\n        long int ans=0;\n        int i=0;\n        \n        while(ans<=n)\n        {\n            ans=pow(4,i);\n            i++;\n            if(ans==n)\n                return true;\n        }\n        return false;\n    }\n"
  },
  {
    "path": "344-reverse-string/344-reverse-string.java",
    "content": "class Solution {\n    public void reverseString(char[] s) {\n        int n=s.length;\n        for(int i=0;i<n/2;i++){\n            char a=s[i];\n            char b=s[n-1-i];\n            s[i]=b;\n            s[n-1-i]=a;\n        }\n    }\n}"
  },
  {
    "path": "344-reverse-string/NOTES.md",
    "content": "​"
  },
  {
    "path": "344-reverse-string/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/reverse-string/\">344. Reverse String</a></h2><h3>Easy</h3><hr><div><p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p>\n\n<p>You must do this by modifying the input array <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in-place</a> with <code>O(1)</code> extra memory.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> s = [\"h\",\"e\",\"l\",\"l\",\"o\"]\n<strong>Output:</strong> [\"o\",\"l\",\"l\",\"e\",\"h\"]\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\n<strong>Output:</strong> [\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> is a <a href=\"https://en.wikipedia.org/wiki/ASCII#Printable_characters\" target=\"_blank\">printable ascii character</a>.</li>\n</ul>\n</div>"
  },
  {
    "path": "347-top-k-frequent-elements/347-top-k-frequent-elements.cpp",
    "content": "class Solution {\npublic:\n    vector<int> topKFrequent(vector<int>& nums, int k) {\n        \n        // 1.\n        // unordered_map<int, int> mp;\n        // for(int i=0;i<nums.size();i++){\n        //     mp[nums[i]]++;\n        // }\n        // vector<int> ans;\n        // while(ans.size() < k){\n        //     int f = INT_MIN;\n        //     int t;\n        //     for(auto it : mp){            \n        //         if(f < it.second){\n        //             f = it.second;\n        //             t = it.first;\n        //         }\n        //     }\n        //     if(ans.size() < k)\n        //         ans.push_back(t);\n        //     mp.erase(t);\n        // }\n        // return ans;\n        \n        \n      // by default the priority queue will sort the first value of pairs in descending order\n        // 2. \n        unordered_map<int, int> mp;\n        for(int i=0;i<nums.size();i++){\n            mp[nums[i]]++;\n        }\n        vector<int> ans(k, 0);\n        priority_queue<pair<int, int>> pq;\n        for(auto it : mp){\n            pair<int, int> p;\n            p.first = it.second;\n            p.second = it.first;\n            pq.push(p);\n        }\n        int i=0;\n        while(i<k){\n            ans[i] = pq.top().second;\n            pq.pop();\n            i++;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "347-top-k-frequent-elements/347-top-k-frequent-elements.java",
    "content": "class Solution {\n    public int[] topKFrequent(int[] nums, int k) {\n        int []ans=new int[k];\n        Map<Integer,Integer>map=new HashMap<>();\n        for(int i:nums){\n            map.put(i,map.getOrDefault(i,0)+1);\n        }\n        PriorityQueue<int[]> pq=new PriorityQueue<>((a,b)->b[1]-a[1]);\n        for(Map.Entry<Integer,Integer> entry:map.entrySet()){\n            int[]a=new int[]{entry.getKey(),entry.getValue()};\n            pq.add(a);\n        }\n        int i=0;\n        while(i<k){\n            ans[i]=pq.remove()[0];\n            i++;\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "347-top-k-frequent-elements/NOTES.md",
    "content": "​"
  },
  {
    "path": "347-top-k-frequent-elements/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/top-k-frequent-elements/\">347. Top K Frequent Elements</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k</code> <em>most frequent elements</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,1,1,2,2,3], k = 2\n<strong>Output:</strong> [1,2]\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [1], k = 1\n<strong>Output:</strong> [1]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>k</code> is in the range <code>[1, the number of unique elements in the array]</code>.</li>\n\t<li>It is <strong>guaranteed</strong> that the answer is <strong>unique</strong>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Your algorithm's time complexity must be better than <code>O(n log n)</code>, where n is the array's size.</p>\n</div>"
  },
  {
    "path": "354-russian-doll-envelopes/354-russian-doll-envelopes.java",
    "content": "public class Solution {\n    public int maxEnvelopes(int[][] envelopes) {\n        if(envelopes.length < 2) return envelopes.length;\n        \n        Arrays.sort(envelopes, new EnvelopeComparator());\n        int[] dp = new int[envelopes.length];\n        int size = 0;\n        \n        for(int[] envelope: envelopes) {\n            // binary search\n            int left = 0, right = size, middle = 0;     // right = size\n            while(left < right) {\n                middle = left + (right - left) / 2;\n                if(dp[middle] < envelope[1]) left = middle + 1;\n                else right = middle;\n            }\n            \n            // left is the right position to 'replace' in dp array\n            dp[left] = envelope[1];\n            if(left == size) size++;\n        }\n        return size;\n    }\n    \n    class EnvelopeComparator implements Comparator<int[]> {\n        public int compare(int[] e1, int[] e2) {\n            return e1[0] == e2[0] ? e2[1] - e1[1] : e1[0] - e2[0];\n        }\n    }\n}"
  },
  {
    "path": "354-russian-doll-envelopes/NOTES.md",
    "content": "​"
  },
  {
    "path": "354-russian-doll-envelopes/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/russian-doll-envelopes/\">354. Russian Doll Envelopes</a></h2><h3>Hard</h3><hr><div><p>You are given a 2D array of integers <code>envelopes</code> where <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> represents the width and the height of an envelope.</p>\n\n<p>One 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.</p>\n\n<p>Return <em>the maximum number of envelopes you can Russian doll (i.e., put one inside the other)</em>.</p>\n\n<p><strong>Note:</strong> You cannot rotate an envelope.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> envelopes = [[5,4],[6,4],[6,7],[2,3]]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The maximum number of envelopes you can Russian doll is <code>3</code> ([2,3] =&gt; [5,4] =&gt; [6,7]).\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> envelopes = [[1,1],[1,1],[1,1]]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= envelopes.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>envelopes[i].length == 2</code></li>\n\t<li><code>1 &lt;= w<sub>i</sub>, h<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "363-max-sum-of-rectangle-no-larger-than-k/363-max-sum-of-rectangle-no-larger-than-k.cpp",
    "content": "// problem is a combination of 2 problems first is max sum of rectangle and second is sum of subarray not greater than k\nclass Solution {\npublic:\n    int maxSumSubmatrix(vector<vector<int>>& mat, int k) {\n        int row = mat.size();\n        int col = mat[0].size();\n        int maxLen=INT_MIN;\n        for(int left = 0; left < col; left++){\n            vector<int> v(row, 0);     \n            for(int right = left; right < col; right++){\n                for(int i = 0; i < row; i++){\n                    v[i] += mat[i][right];                    \n                }\n                set<int> s = {0};\n                int run_sum=0;\n                for(int sum : v){\n                    run_sum += sum;\n                    auto it = s.lower_bound(run_sum - k);\n                    if(it != s.end())\n                        maxLen = max(maxLen, run_sum - *it);                    \n                    s.insert(run_sum);\n                }\n            }\n        }\n        return maxLen;\n    }\n};\n"
  },
  {
    "path": "363-max-sum-of-rectangle-no-larger-than-k/363-max-sum-of-rectangle-no-larger-than-k.java",
    "content": "class Solution {\n    public int maxSumSubmatrix(int[][] mat, int k) {\n        int n=mat.length;\n        int m=mat[0].length;\n        \n        //create prefix sum array\n        int[][]pre=new int[n][m];\n        pre[0][0]=mat[0][0];\n        for(int i=1;i<n;i++){\n            pre[i][0]=mat[i][0]+pre[i-1][0];\n        }\n        for(int i=1;i<m;i++){\n            pre[0][i]=mat[0][i]+pre[0][i-1];\n        }\n        for(int i=1;i<n;i++){\n            for(int j=1;j<m;j++){\n                pre[i][j]=mat[i][j]+pre[i][j-1]+pre[i-1][j]-pre[i-1][j-1];\n            }\n        }\n        \n        //find all rect from one point and store the max sum <=k\n        int ans=Integer.MIN_VALUE;\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(i==0 && j==0){\n                    for(int x=i;x<n;x++){\n                        for(int y=j;y<m;y++){\n                            if(pre[x][y]<=k){\n                                ans=Math.max(ans,pre[x][y]);\n                            }\n                        }\n                    }\n                }else if(i==0){\n                    for(int x=i;x<n;x++){\n                        for(int y=j;y<m;y++){\n                            int sum=pre[x][y]-pre[x][j-1];\n                            if(sum<=k){\n                                ans=Math.max(ans,sum);\n                            }\n                        }\n                    }\n                }else if(j==0){\n                    for(int x=i;x<n;x++){\n                        for(int y=j;y<m;y++){\n                            int sum=pre[x][y]-pre[i-1][y];\n                            if(sum<=k){\n                                ans=Math.max(ans,sum);\n                            }\n                        }\n                    }\n                }else{\n                    for(int x=i;x<n;x++){\n                        for(int y=j;y<m;y++){\n                            int sum=pre[x][y]-pre[i-1][y]-pre[x][j-1]+pre[i-1][j-1];\n                            if(sum<=k){\n                                ans=Math.max(ans,sum);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "363-max-sum-of-rectangle-no-larger-than-k/NOTES.md",
    "content": "​"
  },
  {
    "path": "363-max-sum-of-rectangle-no-larger-than-k/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/\">363. Max Sum of Rectangle No Larger Than K</a></h2><h3>Hard</h3><hr><div><p>Given an <code>m x n</code> matrix <code>matrix</code> and an integer <code>k</code>, return <em>the max sum of a rectangle in the matrix such that its sum is no larger than</em> <code>k</code>.</p>\n\n<p>It is <strong>guaranteed</strong> that there will be a rectangle with a sum no larger than <code>k</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg\" style=\"width: 255px; height: 176px;\">\n<pre><strong>Input:</strong> matrix = [[1,0,1],[0,-2,3]], k = 2\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> matrix = [[2,2,-1]], k = 3\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> What if the number of rows is much larger than the number of columns?</p>\n</div>"
  },
  {
    "path": "37-Sudoku-solver/37-Sudoku-solver.js",
    "content": "var solveSudoku = function(board) {\n\n    function isValid(grid, row, col, k) {\n     for (let i = 0; i < 9; i++) {\n         const m = 3 * Math.floor(row / 3) + Math.floor(i / 3);\n         const n = 3 * Math.floor(col / 3) + i % 3;\n         if (grid[row][i] == k || grid[i][col] == k || grid[m][n] == k) {\n           return false;\n         }\n     }\n     return true;\n }\n\n\n function solve(grid) {\n\n   for (let i = 0; i < 9; i++) {\n     for (let j = 0; j < 9; j++) {\n\n       if (grid[i][j] == '.') {\n\n         for (let k = 1; k <= 9; k++) {\n\n           if (isValid(grid, i, j, k)) {\n              grid[i][j] = `${k}`;\n           if (solve(grid)) {\n            return true;\n           } else {\n            grid[i][j] = '.';\n           }\n          }\n        }\n\n        return false;\n      }\n    }\n  }\n\n      return true;\n  }\n     solve(board)\n     return board ;\n };"
  },
  {
    "path": "37-Sudoku-solver/README.md",
    "content": "\n<h2><a href=\"https://leetcode.com/problems/sudoku-solver/\">37. Sudoku Solver</a></h2><h3>Hard</h3><hr>\n<div><p>Write a program to solve a Sudoku puzzle by filling the empty cells.\nA sudoku solution must satisfy\n<strong>all of the following rules:</strong></p>\n\n<ol>\n\t<li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li>\n\t<li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li>\n\t<li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li>\n</ol>\n\n<p>The <code>'.'</code> character indicates empty cells.</p>\n<br>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png\" style=\"height:250px; width:250px\">\n<pre><strong>Input:</strong> 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\"]]\n<strong>Output:</strong> [[\"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\"]]\n<strong>Explanation:</strong>&nbsp;The input board is shown above and the only valid solution is shown below:\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png\" style=\"height:250px; width:250px\">\n</pre>\n\n\n<p><strong>Constraints:</strong></p>\n<br>\n<ul>\n\t<li><code>board.length == 9</code></li>\n\t<li><code>board[i].length == 9</code></li>\n\t<li><code>board[i][j]</code> is a digit or <code>'.'</code>.</li>\n\t<li>It is <strong>guaranteed</strong> that the input board has only one solution.</li>\n</ul>\n\n<p>Alice wants the rope to be <strong>colorful</strong>. She does not want <strong>two consecutive balloons</strong> to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it <strong>colorful</strong>. You are given a <strong>0-indexed</strong> integer array <code>neededTime</code> where <code>neededTime[i]</code> is the time (in seconds) that Bob needs to remove the <code>i<sup>th</sup></code> balloon from the rope.</p>\n\n<p>Return <em>the <strong>minimum time</strong> Bob needs to make the rope <strong>colorful</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/12/13/ballon1.jpg\" style=\"width: 404px; height: 243px;\">\n<pre><strong>Input:</strong> colors = \"abaac\", neededTime = [1,2,3,4,5]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3.</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/12/13/balloon2.jpg\" style=\"width: 244px; height: 243px;\">\n<pre><strong>Input:</strong> colors = \"abc\", neededTime = [1,2,3]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The rope is already colorful. Bob does not need to remove any balloons from the rope.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/12/13/balloon3.jpg\" style=\"width: 404px; height: 243px;\">\n<pre><strong>Input:</strong> colors = \"aabaa\", neededTime = [1,2,3,4,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == colors.length == neededTime.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= neededTime[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>colors</code> contains only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "371-sum-of-two-integers/371-sum-of-two-integers.java",
    "content": "class Solution {\n    public int getSum(int a, int b) {\n        while(b!=0){\n            int ans=(a^b);\n            int carry=(a&b)<<1;\n            a=ans;\n            b=carry;\n        }\n        return a;\n    }\n}"
  },
  {
    "path": "371-sum-of-two-integers/NOTES.md",
    "content": "​"
  },
  {
    "path": "371-sum-of-two-integers/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/sum-of-two-integers/\">371. Sum of Two Integers</a></h2><h3>Medium</h3><hr><div><p>Given two integers <code>a</code> and <code>b</code>, return <em>the sum of the two integers without using the operators</em> <code>+</code> <em>and</em> <code>-</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> a = 1, b = 2\n<strong>Output:</strong> 3\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> a = 2, b = 3\n<strong>Output:</strong> 5\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-1000 &lt;= a, b &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "376-wiggle-subsequence/376-wiggle-subsequence.java",
    "content": "public class Solution {\n    public int wiggleMaxLength(int[] nums) {\n        if (nums.length < 2)return nums.length;\n        int prevdiff = nums[1] - nums[0];\n        int count = prevdiff != 0 ? 2 : 1;\n        for (int i = 2; i < nums.length; i++) {\n            int diff = nums[i] - nums[i - 1];\n            if ((diff > 0 && prevdiff <= 0) || (diff < 0 && prevdiff >= 0)) {\n                count++;\n                prevdiff = diff;\n            }\n        }\n        return count;\n    }\n}"
  },
  {
    "path": "376-wiggle-subsequence/NOTES.md",
    "content": "​"
  },
  {
    "path": "376-wiggle-subsequence/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/wiggle-subsequence/\">376. Wiggle Subsequence</a></h2><h3>Medium</h3><hr><div><p>A <strong>wiggle sequence</strong> 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.</p>\n\n<ul>\n\t<li>For example, <code>[1, 7, 4, 9, 2, 5]</code> is a <strong>wiggle sequence</strong> because the differences <code>(6, -3, 5, -7, 3)</code> alternate between positive and negative.</li>\n\t<li>In contrast, <code>[1, 4, 7, 2, 5]</code> and <code>[1, 7, 4, 5, 5]</code> 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.</li>\n</ul>\n\n<p>A <strong>subsequence</strong> is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.</p>\n\n<p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>wiggle subsequence</strong> of </em><code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,7,4,9,2,5]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,17,5,10,13,15,10,5,16,8]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,4,5,6,7,8,9]\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you solve this in <code>O(n)</code> time?</p>\n</div>"
  },
  {
    "path": "377-combination-sum-iv/377-combination-sum-iv.java",
    "content": "class Solution {\n    private int[] dp;\n\n    public int combinationSum4(int[] nums, int target) {\n        dp = new int[target + 1];\n        Arrays.fill(dp, -1);\n        dp[0] = 1;\n        return helper(nums, target);\n    }\n\n    private int helper(int[] nums, int target) {\n        if (dp[target] != -1) \n            return dp[target];\n\n        int res = 0;\n        for (int num: nums) {\n            if (target >= num) {\n                res += helper(nums, target - num);\n            }\n        }\n        return dp[target] = res;\n        // res;\n    }\n}"
  },
  {
    "path": "377-combination-sum-iv/NOTES.md",
    "content": "​"
  },
  {
    "path": "377-combination-sum-iv/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/combination-sum-iv/\">377. Combination Sum IV</a></h2><h3>Medium</h3><hr><div><p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p>\n\n<p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3], target = 4\n<strong>Output:</strong> 7\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [9], target = 3\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 200</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>All the elements of <code>nums</code> are <strong>unique</strong>.</li>\n\t<li><code>1 &lt;= target &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> 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?</p>\n</div>"
  },
  {
    "path": "378-kth-smallest-element-in-a-sorted-matrix/378-kth-smallest-element-in-a-sorted-matrix.java",
    "content": "class Solution {\n    public int kthSmallest(int[][] mat, int k) {\n        int[]arr=new int[mat.length*mat[0].length];\n        int idx=0;\n        for(int i=0;i<mat.length;i++){\n            for(int j=0;j<mat[i].length;j++){\n                arr[idx++]=mat[i][j];\n            }\n        }\n        Arrays.sort(arr);\n        return arr[k-1];\n    }\n}"
  },
  {
    "path": "378-kth-smallest-element-in-a-sorted-matrix/NOTES.md",
    "content": "​"
  },
  {
    "path": "383-ransom-note/383-ransom-note.java",
    "content": "class Solution {\n    public boolean canConstruct(String ransomNote, String magazine) {\n        int[] a=new int[26];\n        for(char c:magazine.toCharArray()){\n            a[c-'a']++;\n        }\n        for(char c:ransomNote.toCharArray()){\n            a[c-'a']--;\n            if(a[c-'a']<0)return false;\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "383-ransom-note/NOTES.md",
    "content": "​"
  },
  {
    "path": "383-ransom-note/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/ransom-note/\">383. Ransom Note</a></h2><h3>Easy</h3><hr><div><p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p>\n\n<p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> ransomNote = \"a\", magazine = \"b\"\n<strong>Output:</strong> false\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> ransomNote = \"aa\", magazine = \"ab\"\n<strong>Output:</strong> false\n</pre><p><strong>Example 3:</strong></p>\n<pre><strong>Input:</strong> ransomNote = \"aa\", magazine = \"aab\"\n<strong>Output:</strong> true\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "383-ransom-note/ransom-note.cpp",
    "content": "class Solution {\npublic:\n    bool canConstruct(string ransomNote, string magazine) {\n        ios_base::sync_with_stdio(false);\n        cin.tie(NULL);\n        \n        vector<int> magazineHash(26,0); // 26 char, start from 0 , \n//         traverse magazing and keep count of each letter in magazineHash\n        for(int i =0; magazine[i]!='\\0'; ++i){\n            magazineHash[magazine[i]-'a'] +=1;\n            \n        }\n//         now traverse ransomNote and keep decrementing count in magazineHash\n        for(int i =0;  ransomNote[i]!='\\0'; ++i){\n            if(magazineHash[ransomNote[i]-'a'] == 0) return false;\n            magazineHash[ransomNote[i]-'a'] -=1; // using up char to lead decrement it by value 1 \n            \n        }\n        return true;\n//         TC:O(N+M) -> where n is the length of the magazing and M is length of randomString\n        \n    }\n};"
  },
  {
    "path": "383-ransom-note/ransome-note-two-approaches.cpp",
    "content": "class Solution {\npublic:\n    bool canConstruct(string rn, string mag) {\n        if(mag.size() < rn.size()) return false;\n        \n         // 1.\n//         unordered_map<char, int> m1, m2;\n//         for(int i=0;i<rn.size();i++){\n//             m1[rn[i]]++;\n//         }\n//         for(int i=0;i<mag.size();i++){\n//             m2[mag[i]]++;\n//         }\n        \n//         for(int i=0;i<rn.size();i++){\n//             if(m1[rn[i]] > m2[rn[i]]){\n//                 return false;\n//             }\n//         }\n        \n        \n        // 2.\n        vector<int> arr(26, 0);\n        for(int i=0;i<mag.size();i++){\n            arr[mag[i] - 'a']++;\n        }\n        for(int i=0;i<rn.size();i++){\n            if(arr[rn[i] - 'a'] == 0) return false;\n            else arr[rn[i] - 'a']--;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "387-first-unique-character-in-a-string/387-first-unique-character-in-a-string.java",
    "content": "class Solution {\n    public int firstUniqChar(String s) {\n        int ans = s.length();\n        for(char c = 'a'; c <= 'z'; c++){\n            int idx = s.indexOf(c);\n            if(idx != -1 && idx == s.lastIndexOf(c)){\n                ans = Math.min(ans, idx);\n            }\n        }\n        return ans == s.length() ? -1 : ans;\n    }\n}"
  },
  {
    "path": "387-first-unique-character-in-a-string/NOTES.md",
    "content": "​"
  },
  {
    "path": "387-first-unique-character-in-a-string/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/first-unique-character-in-a-string/\">387. First Unique Character in a String</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code>, <em>find the first non-repeating character in it and return its index</em>. If it does not exist, return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"leetcode\"\n<strong>Output:</strong> 0\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"loveleetcode\"\n<strong>Output:</strong> 2\n</pre><p><strong>Example 3:</strong></p>\n<pre><strong>Input:</strong> s = \"aabb\"\n<strong>Output:</strong> -1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "387-first-unique-character-in-a-string/first-unique-character-in-a-string.CPP",
    "content": " int firstUniqChar(string s) {\n        unordered_map<char,int>mp;\n        \n        for(int i=0;i<s.length();i++)\n        {\n            mp[s[i]]++;\n        }\n        \n        for(int i=0;i<s.length();i++)\n        {\n            if(mp[s[i]]==1)\n                return i;\n        }\n        return -1;\n    }\n"
  },
  {
    "path": "393-utf-8-validation/393-utf-8-validation.java",
    "content": "class Solution {\n    public boolean validUtf8(int[] data) \n    {\n\tif(data==null || data.length==0) return false;\n\tboolean isValid = true;\n\tfor(int i=0;i<data.length;i++) {\n\t\tif(data[i]>255) return false; // 1 after 8th digit, 100000000\n\t\tint numberOfBytes = 0;\n\t\tif((data[i] & 128) == 0) { // 0xxxxxxx, 1 byte, 128(10000000)\n\t\t\tnumberOfBytes = 1;\n\t\t} else if((data[i] & 224) == 192) { // 110xxxxx, 2 bytes, 224(11100000), 192(11000000)\n\t\t\tnumberOfBytes = 2;\n\t\t} else if((data[i] & 240) == 224) { // 1110xxxx, 3 bytes, 240(11110000), 224(11100000)\n\t\t\tnumberOfBytes = 3;\n\t\t} else if((data[i] & 248) == 240) { // 11110xxx, 4 bytes, 248(11111000), 240(11110000)\n\t\t\tnumberOfBytes = 4;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t\tfor(int j=1;j<numberOfBytes;j++) { // check that the next n bytes start with 10xxxxxx\n\t\t\tif(i+j>=data.length) return false;\n\t\t\tif((data[i+j] & 192) != 128) return false; // 192(11000000), 128(10000000)\n\t\t}\n\t\ti=i+numberOfBytes-1;\n\t}\n\treturn isValid;\n    }\n}\n\n\n//Approach 2\n\n\nclass Solution {\n    public boolean validUtf8(int[] data) {\n        int f[]=new int[256];\n        for(int i=0;i<256;i++) {   // storing All sequences in in array having data[i] as index. As 0<=data[i]<=255, stored in f array\n            int count=0;\n            for(int j=7;j>=0;j--) {\n                if((i&(1<<j))>0) {\n                    count+=1;\n                }\n                else {\n                    break;\n                }\n            }\n           \n            if(count<=4) f[i]=count; // if starting 1's count <=4 storing in f array\n            else f[i]=-1;  //if starting 1's count>=5, it is not part of any utf-8 sequence making as -1\n        }\n        \n        int bytes=-1;\n        int sequence=-1;\n        for(int i=0;i<data.length;i++) {\n            int setBits=f[data[i]];\n            if(setBits==-1) return false;  //if particular value at index equals -1, then returning false as it might not be part of any utf-8 sequence\n            \n            if(bytes==-1 || sequence==0 || sequence == -1 ) {   //if one sequence completed i.e , 2 having 11000000 10000000 10000000 then sequence becomes 0 or if 1->00000000 then sequence becomes -1\n                bytes=f[data[i]];\n                if(bytes==1 && (data[i]&(1<<7))>0) {\n                    return false;\n                }\n                sequence=bytes-1;\n                continue;\n            }          \n            \n            if(setBits==1) { // After having starting , remaining sequence should contain only 1's\n                sequence-=1;\n            }\n            else { // otherwise returning false\n                return false;\n            }\n        }\n      \n        if(sequence==0 || sequence == -1) {   //At end sequence should be either 0 or -1 which means sequence completed for 0/1/2/3. for 0->sequence becomes -1, for 1,2,3->sequence becomes 0\n             return true;\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "393-utf-8-validation/NOTES.md",
    "content": "​"
  },
  {
    "path": "393-utf-8-validation/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/utf-8-validation/\">393. UTF-8 Validation</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>data</code> representing the data, return whether it is a valid <strong>UTF-8</strong> encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).</p>\n\n<p>A character in <strong>UTF8</strong> can be from <strong>1 to 4 bytes</strong> long, subjected to the following rules:</p>\n\n<ol>\n\t<li>For a <strong>1-byte</strong> character, the first bit is a <code>0</code>, followed by its Unicode code.</li>\n\t<li>For an <strong>n-bytes</strong> character, the first <code>n</code> bits are all one's, the <code>n + 1</code> bit is <code>0</code>, followed by <code>n - 1</code> bytes with the most significant <code>2</code> bits being <code>10</code>.</li>\n</ol>\n\n<p>This is how the UTF-8 encoding would work:</p>\n\n<pre>     Number of Bytes   |        UTF-8 Octet Sequence\n                       |              (binary)\n   --------------------+-----------------------------------------\n            1          |   0xxxxxxx\n            2          |   110xxxxx 10xxxxxx\n            3          |   1110xxxx 10xxxxxx 10xxxxxx\n            4          |   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n</pre>\n\n<p><code>x</code> denotes a bit in the binary form of a byte that may be either <code>0</code> or <code>1</code>.</p>\n\n<p><strong>Note: </strong>The input is an array of integers. Only the <strong>least significant 8 bits</strong> of each integer is used to store the data. This means each integer represents only 1 byte of data.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> data = [197,130,1]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> data represents the octet sequence: 11000101 10000010 00000001.\nIt is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> data = [235,140,4]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> data represented the octet sequence: 11101011 10001100 00000100.\nThe first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\nThe next byte is a continuation byte which starts with 10 and that's correct.\nBut the second continuation byte does not start with 10, so it is invalid.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= data.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= data[i] &lt;= 255</code></li>\n</ul>\n</div>"
  },
  {
    "path": "399-evaluate-division/399-evaluate-division.java",
    "content": "class Solution {\n    class Node{\n        String key;\n        double val;\n        Node(String k,double v){\n            key=k;\n            val=v;\n        }\n    }\n    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {\n        Map<String,List<Node>>g=buildGraph(equations,values);\n        double[]res=new double[queries.size()];\n        for(int i=0;i<queries.size();i++){\n            res[i]=dfs(queries.get(i).get(0),queries.get(i).get(1),new HashSet<>(),g);\n        }\n        return res;\n    }\n    private double dfs(String s,String d,Set<String> vis,Map<String,List<Node>> g){\n        if(!(g.containsKey(s) && g.containsKey(d)))return -1.0;\n        if(s.equals(d))return 1.0;\n        vis.add(s);\n        for(Node n:g.get(s)){\n            if(!vis.contains(n.key)){\n                double ans=dfs(n.key,d,vis,g);\n                if(ans!=-1.0)return ans*n.val;\n            }\n        }\n        return -1.0;\n    }\n    private Map<String,List<Node>> buildGraph(List<List<String>> eq,double[] vals){\n        Map<String,List<Node>> g=new HashMap<>();\n        for(int i=0;i<vals.length;i++){\n            String src=eq.get(i).get(0);\n            String des=eq.get(i).get(1);\n            g.putIfAbsent(src,new ArrayList<>());\n            g.putIfAbsent(des,new ArrayList<>());\n            g.get(src).add(new Node(des,vals[i]));\n            g.get(des).add(new Node(src,1/vals[i]));\n        }\n        return g;\n    }\n}"
  },
  {
    "path": "399-evaluate-division/NOTES.md",
    "content": "​"
  },
  {
    "path": "399-evaluate-division/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/evaluate-division/\">399. Evaluate Division</a></h2><h3>Medium</h3><hr><div><p>You are given an array of variable pairs <code>equations</code> and an array of real numbers <code>values</code>, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and <code>values[i]</code> represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.</p>\n\n<p>You are also given some <code>queries</code>, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p>\n\n<p>Return <em>the answers to all queries</em>. If a single answer cannot be determined, return <code>-1.0</code>.</p>\n\n<p><strong>Note:</strong> 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.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]\n<strong>Output:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000]\n<strong>Explanation:</strong> \nGiven: <em>a / b = 2.0</em>, <em>b / c = 3.0</em>\nqueries are: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ?</em>\nreturn: [6.0, 0.5, -1.0, 1.0, -1.0 ]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]\n<strong>Output:</strong> [3.75000,0.40000,5.00000,0.20000]\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]\n<strong>Output:</strong> [0.50000,2.00000,-1.00000,-1.00000]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= equations.length &lt;= 20</code></li>\n\t<li><code>equations[i].length == 2</code></li>\n\t<li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li>\n\t<li><code>values.length == equations.length</code></li>\n\t<li><code>0.0 &lt; values[i] &lt;= 20.0</code></li>\n\t<li><code>1 &lt;= queries.length &lt;= 20</code></li>\n\t<li><code>queries[i].length == 2</code></li>\n\t<li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li>\n\t<li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li>\n</ul>\n</div>"
  },
  {
    "path": "4-median-of-two-sorted-arrays/4-median-of-two-sorted-arrays.java",
    "content": "class Solution {\n    public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n        int[] nums = new int[nums1.length + nums2.length];\n        System.arraycopy(nums1, 0, nums, 0, nums1.length);\n        System.arraycopy(nums2, 0, nums, nums1.length, nums2.length); \n        Arrays.sort(nums);\n        return (nums[nums.length >> 1] + nums[(nums.length - 1) >> 1]) / 2.0;\n    }\n}"
  },
  {
    "path": "4-median-of-two-sorted-arrays/NOTES.md",
    "content": "​"
  },
  {
    "path": "406-queue-reconstruction-by-height/406-queue-reconstruction-by-height.java",
    "content": "class Solution {\n    public int[][] reconstructQueue(int[][] people) {\n        Arrays.sort(people, (o1, o2) -> o1[0] != o2[0] ? o2[0] - o1[0] : o1[1] - o2[1]);\n        List<int[]> tempRes = new LinkedList<>();\n        for (int[] person : people) {\n            tempRes.add(person[1], person);\n        }\n        return tempRes.toArray(new int[people.length][]);\n    }\n}"
  },
  {
    "path": "406-queue-reconstruction-by-height/NOTES.md",
    "content": "​"
  },
  {
    "path": "406-queue-reconstruction-by-height/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/queue-reconstruction-by-height/\">406. Queue Reconstruction by Height</a></h2><h3>Medium</h3><hr><div><p>You are given an array of people, <code>people</code>, which are the attributes of some people in a queue (not necessarily in order). Each <code>people[i] = [h<sub>i</sub>, k<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> person of height <code>h<sub>i</sub></code> with <strong>exactly</strong> <code>k<sub>i</sub></code> other people in front who have a height greater than or equal to <code>h<sub>i</sub></code>.</p>\n\n<p>Reconstruct and return <em>the queue that is represented by the input array </em><code>people</code>. The returned queue should be formatted as an array <code>queue</code>, where <code>queue[j] = [h<sub>j</sub>, k<sub>j</sub>]</code> is the attributes of the <code>j<sup>th</sup></code> person in the queue (<code>queue[0]</code> is the person at the front of the queue).</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\n<strong>Output:</strong> [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\n<strong>Output:</strong> [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= people.length &lt;= 2000</code></li>\n\t<li><code>0 &lt;= h<sub>i</sub> &lt;= 10<sup>6</sup></code></li>\n\t<li><code>0 &lt;= k<sub>i</sub> &lt; people.length</code></li>\n\t<li>It is guaranteed that the queue can be reconstructed.</li>\n</ul>\n</div>"
  },
  {
    "path": "410-split-array-largest-sum/410-split-array-largest-sum.java",
    "content": "class Solution {\n    public int splitArray(int[] nums, int m) {\n        int max = Integer.MIN_VALUE;\n        int sum = 0;\n        // search range [max, sum];\n        for (int i = 0; i < nums.length; i++) {\n            max = Math.max(max, nums[i]);\n            sum += nums[i];\n        }\n        int left = max;\n        int right = sum;\n        while (left < right) {\n            int mid = left + (right - left) / 2;\n            if (canSplit(nums, m, mid)) {\n                right = mid;\n            } else {\n                left = mid + 1;\n            }\n        }\n       // if (canSplit(nums, m, right)) return right;\n        return left;\n    }\n    private boolean canSplit(int[] nums, int m, int largest) {\n        int count = 1;\n        int sum = 0;\n        for (int i = 0; i < nums.length; i++) {\n            sum += nums[i];\n            if (sum > largest) {\n                count++;\n                sum = nums[i];\n            }\n        }\n        return count <= m;\n    }\n}"
  },
  {
    "path": "410-split-array-largest-sum/NOTES.md",
    "content": "​"
  },
  {
    "path": "410-split-array-largest-sum/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/split-array-largest-sum/\">410. Split Array Largest Sum</a></h2><h3>Hard</h3><hr><div><p>Given an array <code>nums</code> which consists of non-negative integers and an integer <code>m</code>, you can split the array into <code>m</code> non-empty continuous subarrays.</p>\n\n<p>Write an algorithm to minimize the largest sum among these <code>m</code> subarrays.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [7,2,5,10,8], m = 2\n<strong>Output:</strong> 18\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,4,5], m = 2\n<strong>Output:</strong> 9\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,4,4], m = 3\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n\t<li><code>1 &lt;= m &lt;= min(50, nums.length)</code></li>\n</ul>\n</div>"
  },
  {
    "path": "417-pacific-atlantic-water-flow/417-pacific-atlantic-water-flow.java",
    "content": "class Solution {\n    public List<List<Integer>> pacificAtlantic(int[][] heights) {\n        int rows = heights.length, cols = heights[0].length;\n        boolean[][] pac = new boolean[rows][cols];\n        boolean[][] atl = new boolean[rows][cols];\n        \n        for (int col = 0; col< cols; col++){\n            dfs(0, col, rows, cols, pac, heights[0][col], heights);\n            dfs(rows-1, col,rows, cols, atl, heights[rows-1][col], heights);\n        }\n        for (int row = 0; row<rows; row++){\n            dfs(row, 0,rows, cols, pac, heights[row][0], heights);\n            dfs(row, cols-1,rows, cols, atl, heights[row][cols-1], heights);\n        }\n        List<List<Integer>> result = new ArrayList<List<Integer>>();\n        for (int i = 0; i < rows; i++)\n            for (int j = 0; j < cols; j++){\n                if (pac[i][j] && atl[i][j])\n                    result.add(Arrays.asList(i,j));\n            }\n        return result;\n    }\n    private void dfs(int row, int col, int rows, int cols, boolean[][] visited, int prevHeight, int[][] heights){\n        if (row < 0 || row >= rows || col < 0 || col >= cols || visited[row][col] || prevHeight > heights[row][col])\n            return;\n        visited[row][col]= true;\n        dfs(row+1, col, rows, cols, visited, heights[row][col], heights);\n        dfs(row-1, col, rows, cols, visited, heights[row][col], heights);\n        dfs(row, col+1, rows, cols, visited, heights[row][col], heights);\n        dfs(row, col-1, rows, cols, visited, heights[row][col], heights);\n        \n    }\n}"
  },
  {
    "path": "417-pacific-atlantic-water-flow/NOTES.md",
    "content": "​"
  },
  {
    "path": "417-pacific-atlantic-water-flow/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/pacific-atlantic-water-flow/\">417. Pacific Atlantic Water Flow</a></h2><h3>Medium</h3><hr><div><p>There is an <code>m x n</code> rectangular island that borders both the <strong>Pacific Ocean</strong> and <strong>Atlantic Ocean</strong>. The <strong>Pacific Ocean</strong> touches the island's left and top edges, and the <strong>Atlantic Ocean</strong> touches the island's right and bottom edges.</p>\n\n<p>The island is partitioned into a grid of square cells. You are given an <code>m x n</code> integer matrix <code>heights</code> where <code>heights[r][c]</code> represents the <strong>height above sea level</strong> of the cell at coordinate <code>(r, c)</code>.</p>\n\n<p>The 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 <strong>less than or equal to</strong> the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.</p>\n\n<p>Return <em>a <strong>2D list</strong> of grid coordinates </em><code>result</code><em> where </em><code>result[i] = [r<sub>i</sub>, c<sub>i</sub>]</code><em> denotes that rain water can flow from cell </em><code>(r<sub>i</sub>, c<sub>i</sub>)</code><em> to <strong>both</strong> the Pacific and Atlantic oceans</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/08/waterflow-grid.jpg\" style=\"width: 400px; height: 400px;\">\n<pre><strong>Input:</strong> 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]]\n<strong>Output:</strong> [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]\n<strong>Explanation:</strong> The following cells can flow to the Pacific and Atlantic oceans, as shown below:\n[0,4]: [0,4] -&gt; Pacific Ocean \n&nbsp;      [0,4] -&gt; Atlantic Ocean\n[1,3]: [1,3] -&gt; [0,3] -&gt; Pacific Ocean \n&nbsp;      [1,3] -&gt; [1,4] -&gt; Atlantic Ocean\n[1,4]: [1,4] -&gt; [1,3] -&gt; [0,3] -&gt; Pacific Ocean \n&nbsp;      [1,4] -&gt; Atlantic Ocean\n[2,2]: [2,2] -&gt; [1,2] -&gt; [0,2] -&gt; Pacific Ocean \n&nbsp;      [2,2] -&gt; [2,3] -&gt; [2,4] -&gt; Atlantic Ocean\n[3,0]: [3,0] -&gt; Pacific Ocean \n&nbsp;      [3,0] -&gt; [4,0] -&gt; Atlantic Ocean\n[3,1]: [3,1] -&gt; [3,0] -&gt; Pacific Ocean \n&nbsp;      [3,1] -&gt; [4,1] -&gt; Atlantic Ocean\n[4,0]: [4,0] -&gt; Pacific Ocean \n       [4,0] -&gt; Atlantic Ocean\nNote that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre><strong>Input:</strong> heights = [[1]]\n<strong>Output:</strong> [[0,0]]\n<strong>Explanation:</strong> The water can flow from the only cell to the Pacific and Atlantic oceans.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == heights.length</code></li>\n\t<li><code>n == heights[r].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= heights[r][c] &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "417_Pacific Atlantic Water Flow.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nclass Solution{\n    public:\n\n    // using dfs \n        int m, n;\n    // this denotes cells reachable starting from atlantic and pacific edged cells resp\n    vector<vector<bool> > atlantic, pacific;\n\tvector<vector<int> > res;    \n    vector<vector<int> > pacificAtlantic(vector<vector<int>>& heights) {\n        if(!size(heights)) return res; // check for null condition\n        m = size(heights), n = size(heights[0]); // initializing row and col\n\n    // taking bolean matrices(vector), to see whether a cell that can reach the  atalantic of pacific\n        atlantic = pacific = vector<vector<bool> >(m, vector<bool>(n, false));\n\t\t// perform dfs from all edge cells (ocean-connected cells)\n        for(int i = 0; i < m; i++) dfs(heights, pacific, i, 0), dfs(heights, atlantic, i, n - 1);\n        for(int i = 0; i < n; i++) dfs(heights, pacific, 0, i), dfs(heights, atlantic, m - 1, i);             \n        return res;\n    }\n    // define dfs\n    void dfs(vector<vector<int> >& mat, vector<vector<bool> >& visited, int i, int j){        \n        if(visited[i][j]) return;\n        visited[i][j] = true;\n\t\t// if cell reachable from both the oceans, insert into final result vector\n        if(atlantic[i][j] && pacific[i][j]) res.push_back(vector<int>{i, j});    \n\t\t// dfs from current cell only if height of next cell is greater\n/*down dir*/  if(i + 1 <  m && mat[i + 1][j] >= mat[i][j]) dfs(mat, visited, i + 1, j); \n/*Up dir*/  if(i - 1 >= 0 && mat[i - 1][j] >= mat[i][j]) dfs(mat, visited, i - 1, j);\n/*right dir*/  if(j + 1 <  n && mat[i][j + 1] >= mat[i][j]) dfs(mat, visited, i, j + 1); \n/*left dir*/  if(j - 1 >= 0 && mat[i][j - 1] >= mat[i][j]) dfs(mat, visited, i, j - 1);\n    }\n};\nint main(){\n\n}"
  },
  {
    "path": "42 Trapping Rain Water hd s18.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    int trap(vector<int>& height) {\n//         using 2 pointers tech\n        int i =0, j = height.size()-1, res =0, maxi =0, mini =0;\n        \n//         pointer i from left and j from right\n        while(i <=j){\n//             take mini ht\n            mini = min(height[i], height[j]);\n//             find max, min ht\n            maxi = max(maxi, mini);\n            \n//             unit of water being tapped is diff betn max_ht & min_ht\n            res += maxi - mini;\n//             move pointer i if ht[i] is smaller\n            if(height[i] < height[j]) i++;\n//             else move ptr j\n            else j--;\n        }\n        return res;\n//         TC: O(N), SC:O(1)\n    }\n};"
  },
  {
    "path": "42-trapping-rain-water/42-trapping-rain-water.java",
    "content": "class Solution {\n    public int trap(int[] h) {\n        int n=h.length;\n        int[] left=new int[n];\n        int[]right=new int[n];\n        \n        left[0]=h[0];\n        for(int i=1;i<n;i++){\n            left[i]=Math.max(left[i-1],h[i]);\n        }\n        right[n-1]=h[n-1];\n        for(int i=n-2;i>=0;i--){\n            right[i]=Math.max(right[i+1],h[i]);\n        }\n        \n        int ans=0;\n        for(int i=0;i<n;i++){\n            ans+=Math.min(right[i],left[i])-h[i];\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "42-trapping-rain-water/NOTES.md",
    "content": "​"
  },
  {
    "path": "42-trapping-rain-water/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/trapping-rain-water/\">42. Trapping Rain Water</a></h2><h3>Hard</h3><hr><div><p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png\" style=\"width: 412px; height: 161px;\">\n<pre><strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> height = [4,2,0,3,2,5]\n<strong>Output:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == height.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "429-n-ary-tree-level-order-traversal/429-n-ary-tree-level-order-traversal.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> levelOrder(Node* root) {\n        if(!root) return {};\n        vector<vector<int>> ans;\n        queue<Node*> q;\n        q.push(root);\n        while(!q.empty()){\n            int n = q.size();\n            vector<int> v;\n            for(int i=0;i<n;i++){\n                Node* node = q.front();q.pop();\n                v.push_back(node->val);\n                for(Node* child : node->children) q.push(child);\n            }\n            ans.push_back(v);\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "429-n-ary-tree-level-order-traversal/429-n-ary-tree-level-order-traversal.java",
    "content": "/*\n// Definition for a Node.\nclass Node {\n    public int val;\n    public List<Node> children;\n\n    public Node() {}\n\n    public Node(int _val) {\n        val = _val;\n    }\n\n    public Node(int _val, List<Node> _children) {\n        val = _val;\n        children = _children;\n    }\n};\n*/\n\nclass Solution {\n    public List<List<Integer>> levelOrder(Node root) {\n        List<List<Integer>> list=new ArrayList<>();\n        if(root==null)return list;\n        Queue<Node> q=new LinkedList<>();\n        q.add(root);\n        while(!q.isEmpty()){\n            int size=q.size();\n            List<Integer> l=new ArrayList<>();\n            for(int i=0;i<size;i++){\n                Node temp=q.poll();\n                l.add(temp.val);\n                for(Node node: temp.children){\n                    q.add(node);\n                }\n            }\n            list.add(l);\n            \n        }\n        return list;\n    }\n}\n\nApproach 2 by @Jay-Thesia:\n\n\nclass Solution {\n    public List<List<Integer>> levelOrder(Node root) {\n\n        List<List<Integer>> outter=new ArrayList<>();\n\n        if(root==null)\n            return outter;\n\n        Deque<Node> q=new LinkedList<>();\n\n        q.add(root);\n        List<Integer> inner=new ArrayList<>();\n        inner.add(root.val);\n        outter.add(inner);\n\n        while(q.size()>0){\n            //R P A\n            int len=q.size();\n            inner=new ArrayList<>();\n\n            for(int i=0;i<len;i++){\n                Node curr=q.remove();\n\n                List<Node> child=curr.children;\n\n                if(child.size()==0)\n                    continue;\n\n                int run=child.size();\n\n                for(int j=0;j<run;j++){\n                    q.add(child.get(j));\n                    inner.add(child.get(j).val);\n                }\n\n            }\n\n            if(inner.size()>0)\n             outter.add(inner);\n        }\n\n        return outter;\n    }\n}\n"
  },
  {
    "path": "429-n-ary-tree-level-order-traversal/NOTES.md",
    "content": "​"
  },
  {
    "path": "429-n-ary-tree-level-order-traversal/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/n-ary-tree-level-order-traversal/\">429. N-ary Tree Level Order Traversal</a></h2><h3>Medium</h3><hr><div><p>Given an n-ary tree, return the <em>level order</em> traversal of its nodes' values.</p>\n\n<p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<p><img src=\"https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png\" style=\"width: 100%; max-width: 300px;\"></p>\n\n<pre><strong>Input:</strong> root = [1,null,3,2,4,null,5,6]\n<strong>Output:</strong> [[1],[3,2,4],[5,6]]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png\" style=\"width: 296px; height: 241px;\"></p>\n\n<pre><strong>Input:</strong> 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]\n<strong>Output:</strong> [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The height of the n-ary tree is less than or equal to <code>1000</code></li>\n\t<li>The total number of nodes is between <code>[0, 10<sup>4</sup>]</code></li>\n</ul>\n</div>"
  },
  {
    "path": "456-132-pattern/456-132-pattern.java",
    "content": "class Solution {\n      public boolean find132pattern(int[] nums) {\n        int len = nums.length;\n        if (len < 3)return false;\n        Deque<Integer> stk = new ArrayDeque<>();\n        int k = -1;\n        for (int i = len - 1; i >= 0; i--) {\n            if (k > -1 && nums[k] > nums[i]) {\n                return true;\n            }\n\n            while (!stk.isEmpty() && nums[i] > nums[stk.peek()]) {\n                k = stk.pop();\n            }\n\n            stk.push(i);\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "456-132-pattern/NOTES.md",
    "content": "​"
  },
  {
    "path": "456-132-pattern/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/132-pattern/\">456. 132 Pattern</a></h2><h3>Medium</h3><hr><div><p>Given an array&nbsp;of <code>n</code> integers <code>nums</code>, a <strong>132 pattern</strong> is a subsequence of three integers <code>nums[i]</code>, <code>nums[j]</code> and <code>nums[k]</code> such that <code>i &lt; j &lt; k</code> and <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p>\n\n<p>Return <em><code>true</code> if there is a <strong>132 pattern</strong> in <code>nums</code>, otherwise, return <code>false</code>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,4]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There is no 132 pattern in the sequence.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [3,1,4,2]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> There is a 132 pattern in the sequence: [1, 4, 2].\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [-1,3,2,0]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "458-poor-pigs/458-poor-pigs.java",
    "content": "class Solution {\n    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {\n        int rounds=(minutesToTest/minutesToDie)+1;\n        return (int)Math.ceil(Math.log(buckets)/Math.log(rounds));\n    }\n}"
  },
  {
    "path": "458-poor-pigs/NOTES.md",
    "content": "​"
  },
  {
    "path": "458-poor-pigs/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/poor-pigs/\">458. Poor Pigs</a></h2><h3>Hard</h3><hr><div><p>There are <code>buckets</code> buckets of liquid, where <strong>exactly one</strong> of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have <code>minutesToTest</code> minutes to determine which bucket is poisonous.</p>\n\n<p>You can feed the pigs according to these steps:</p>\n\n<ol>\n\t<li>Choose some live pigs to feed.</li>\n\t<li>For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.</li>\n\t<li>Wait for <code>minutesToDie</code> minutes. You may <strong>not</strong> feed any other pigs during this time.</li>\n\t<li>After <code>minutesToDie</code> minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.</li>\n\t<li>Repeat this process until you run out of time.</li>\n</ol>\n\n<p>Given <code>buckets</code>, <code>minutesToDie</code>, and <code>minutesToTest</code>, return <em>the <strong>minimum</strong> number of pigs needed to figure out which bucket is poisonous within the allotted time</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> buckets = 1000, minutesToDie = 15, minutesToTest = 60\n<strong>Output:</strong> 5\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 15\n<strong>Output:</strong> 2\n</pre><p><strong>Example 3:</strong></p>\n<pre><strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 30\n<strong>Output:</strong> 2\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= buckets &lt;= 1000</code></li>\n\t<li><code>1 &lt;=&nbsp;minutesToDie &lt;=&nbsp;minutesToTest &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "462-minimum-moves-to-equal-array-elements-ii/462-minimum-moves-to-equal-array-elements-ii.java",
    "content": "class Solution {\n    public int minMoves2(int[] nums) {\n        Arrays.sort(nums);\n        int i=0;\n        int j=nums.length-1;\n        int staps=0;\n        while(i<j){\n            staps+=(nums[j]-nums[i]);\n            i++;\n            j--;\n        }\n        return staps;\n    }\n}"
  },
  {
    "path": "462-minimum-moves-to-equal-array-elements-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "462-minimum-moves-to-equal-array-elements-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/\">462. Minimum Moves to Equal Array Elements II</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> of size <code>n</code>, return <em>the minimum number of moves required to make all array elements equal</em>.</p>\n\n<p>In one move, you can increment or decrement an element of the array by <code>1</code>.</p>\n\n<p>Test cases are designed so that the answer will fit in a <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong>\nOnly two moves are needed (remember each move increments or decrements one element):\n[<u>1</u>,2,3]  =&gt;  [2,2,<u>3</u>]  =&gt;  [2,2,2]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,10,2,9]\n<strong>Output:</strong> 16\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "47-permutations-ii/47-permutations-ii.java",
    "content": "class Solution {\n    \n    List<List<Integer>> lists;\n    boolean[] added;\n    \n    public List<List<Integer>> permuteUnique(int[] nums) {\n        lists = new ArrayList<>();\n        Arrays.sort(nums);\n        added = new boolean[nums.length];\n        permuteUnique(nums, new ArrayList<>());\n        return lists;\n    }\n    \n    private void permuteUnique(int[] nums, List<Integer> list) {\n        if(list.size() == nums.length) {\n            lists.add(new ArrayList(list));\n            return;\n        }\n        for(int i = 0; i < nums.length; i++) {\n            if(added[i])\n                continue;\n            // avoid permute duplicates\n            if(i > 0 && nums[i] == nums[i - 1] && !added[i - 1])\n                continue;\n            list.add(nums[i]);\n            added[i] = true;\n            permuteUnique(nums, list);\n            list.remove(list.size() - 1);\n            added[i] = false;\n        }\n    }\n}"
  },
  {
    "path": "47-permutations-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "47-permutations-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/permutations-ii/\">47. Permutations II</a></h2><h3>Medium</h3><hr><div><p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,1,2]\n<strong>Output:</strong>\n[[1,1,2],\n [1,2,1],\n [2,1,1]]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 8</code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n</ul>\n</div>"
  },
  {
    "path": "473-matchsticks-to-square/473-matchsticks-to-square.java",
    "content": "import java.util.HashMap;\n\nclass Solution {\n\n    // The memoization cache to be used during recursion.\n    public HashMap<Pair<Integer, Integer>, Boolean> memo;\n\n    // Array containing our matchsticks.\n    public int[] nums;\n\n    // Possible side of our square depending on the total sum of all the matchsticks. \n    public int possibleSquareSide;\n\n    // Default constructor to initialise our memo cache.\n    public Solution() {\n        this.memo = new HashMap<Pair<Integer, Integer>, Boolean>();\n    }\n\n    // Main DP function.\n    public boolean recurse(Integer mask, Integer sidesDone) {\n        int total = 0;\n        int L = this.nums.length;\n\n        // The memo key for this recursion\n        Pair<Integer, Integer> memoKey = new Pair(mask, sidesDone);\n\n        // Find out the sum of matchsticks used till now.\n        for(int i = L - 1; i >= 0; i--) {\n            if ((mask&(1 << i)) == 0) {\n                total += this.nums[L - 1 - i];\n            }\n        }\n\n        // If the sum if divisible by our square's side, then we increment our number of complete sides formed variable.\n        if (total > 0 && total % this.possibleSquareSide == 0) {\n            sidesDone++;\n        }\n\n        // Base case.\n        if (sidesDone == 3) {\n            return true;\n        }\n\n\n        // Return precomputed results\n        if (this.memo.containsKey(memoKey)) {\n            return this.memo.get(memoKey);\n        }\n\n        boolean ans = false;\n        int c = total / this.possibleSquareSide;\n\n        // Remaining vlength in the current partially formed side.\n        int rem = this.possibleSquareSide * (c + 1) - total;\n\n        // Try out all remaining options (that are valid)\n        for(int i = L - 1; i >= 0; i--) {\n            if (this.nums[L - 1 - i] <= rem && (mask&(1 << i)) > 0) {\n                if (this.recurse(mask ^ (1 << i), sidesDone)) {\n                    ans = true;\n                    break;\n                }\n            }\n        }\n\n        // Cache the computed results.\n        this.memo.put(memoKey, ans);\n        return ans;\n    }\n\n    public boolean makesquare(int[] nums) {\n\n        // Empty matchsticks.\n        if (nums == null || nums.length == 0) {\n            return false;\n        }\n\n        // Find the perimeter of the square (if at all possible)\n        int L = nums.length;\n        int perimeter = 0;\n        for(int i = 0; i < L; i++) {\n            perimeter += nums[i];\n        }\n\n        int possibleSquareSide =  perimeter / 4;\n        if (possibleSquareSide * 4 != perimeter) {\n            return false;\n        }\n\n        this.nums = nums;\n        this.possibleSquareSide = possibleSquareSide;\n        return this.recurse((1 << L) - 1, 0);\n    }\n}"
  },
  {
    "path": "473-matchsticks-to-square/NOTES.md",
    "content": "​"
  },
  {
    "path": "473-matchsticks-to-square/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/matchsticks-to-square/\">473. Matchsticks to Square</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>matchsticks</code> where <code>matchsticks[i]</code> is the length of the <code>i<sup>th</sup></code> matchstick. You want to use <strong>all the matchsticks</strong> to make one square. You <strong>should not break</strong> any stick, but you can link them up, and each matchstick must be used <strong>exactly one time</strong>.</p>\n\n<p>Return <code>true</code> if you can make this square and <code>false</code> otherwise.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg\" style=\"width: 253px; height: 253px;\">\n<pre><strong>Input:</strong> matchsticks = [1,1,2,2,2]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> You can form a square with length 2, one side of the square came two sticks with length 1.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> matchsticks = [3,3,3,3,4]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> You cannot find a way to form a square with all the matchsticks.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= matchsticks.length &lt;= 15</code></li>\n\t<li><code>1 &lt;= matchsticks[i] &lt;= 10<sup>8</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "474-ones-and-zeroes/474-ones-and-zeroes.java",
    "content": "class Solution {\n    public static int findMaxForm(String[] strs, int m, int n) {\n        int[][] dp = new int[m + 1][n + 1];\n        for(String str : strs){\n            int one = 0;\n            int zero = 0;\n            for(char c : str.toCharArray()){\n                if(c == '1')\n                    one++;\n                else\n                    zero++;\n            }\n            for(int i = m; i >= zero; i--){\n                for(int j = n; j >= one; j--){\n                    if(one <= j && zero <= i)\n                        dp[i][j] = Math.max(dp[i][j],dp[i - zero][j - one] + 1);\n                }\n            }\n        }\n        return dp[m][n];\n    }\n}"
  },
  {
    "path": "474-ones-and-zeroes/NOTES.md",
    "content": "​"
  },
  {
    "path": "474-ones-and-zeroes/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/ones-and-zeroes/\">474. Ones and Zeroes</a></h2><h3>Medium</h3><hr><div><p>You are given an array of binary strings <code>strs</code> and two integers <code>m</code> and <code>n</code>.</p>\n\n<p>Return <em>the size of the largest subset of <code>strs</code> such that there are <strong>at most</strong> </em><code>m</code><em> </em><code>0</code><em>'s and </em><code>n</code><em> </em><code>1</code><em>'s in the subset</em>.</p>\n\n<p>A set <code>x</code> is a <strong>subset</strong> of a set <code>y</code> if all elements of <code>x</code> are also elements of <code>y</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> strs = [\"10\",\"0001\",\"111001\",\"1\",\"0\"], m = 5, n = 3\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The largest subset with at most 5 0's and 3 1's is {\"10\", \"0001\", \"1\", \"0\"}, so the answer is 4.\nOther valid but smaller subsets include {\"0001\", \"1\"} and {\"10\", \"1\", \"0\"}.\n{\"111001\"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> strs = [\"10\",\"0\",\"1\"], m = 1, n = 1\n<strong>Output:</strong> 2\n<b>Explanation:</b> The largest subset is {\"0\", \"1\"}, so the answer is 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= strs.length &lt;= 600</code></li>\n\t<li><code>1 &lt;= strs[i].length &lt;= 100</code></li>\n\t<li><code>strs[i]</code> consists only of digits <code>'0'</code> and <code>'1'</code>.</li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "48-rotate-image/48-Rotate-Image.cpp",
    "content": "class Solution {\npublic:\n    void rotate(vector<vector<int>>& mat) {\n        int n = mat.size();\n        int m = mat[0].size();\n        for(int i=0;i<n;i++){\n            for(int j=i;j<m;j++){\n                int t = mat[i][j];                \n                mat[i][j] = mat[j][i];\n                mat[j][i] = t;\n            }\n        }\n        for(int i=0;i<n;i++){\n            reverse(mat[i].begin(), mat[i].end());\n        }        \n    }\n};\n"
  },
  {
    "path": "48-rotate-image/48-rotate-image.java",
    "content": "class Solution {\n    public void rotate(int[][] matrix) {\n        int n=matrix.length;\n        //swap rows\n        for(int i=0;i<n/2;i++){\n            int[] row=matrix[i];\n            matrix[i]=matrix[n-1-i];\n            matrix[n-1-i]=row;\n        }\n        \n        //tranpose\n        for(int i=0;i<n;i++){\n            for(int j=i;j<n;j++){\n                int ele=matrix[j][i];\n                matrix[j][i]=matrix[i][j];\n                matrix[i][j]=ele;\n            }\n        }\n    }\n}"
  },
  {
    "path": "48-rotate-image/NOTES.md",
    "content": "​"
  },
  {
    "path": "48-rotate-image/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/rotate-image/\">48. Rotate Image</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p>\n\n<p>You have to rotate the image <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg\" style=\"width: 500px; height: 188px;\">\n<pre><strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]]\n<strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg\" style=\"width: 500px; height: 201px;\">\n<pre><strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\n<strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == matrix.length == matrix[i].length</code></li>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n\t<li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "5-longest-palindromic-substring/5-longest-palindromic-substring.java",
    "content": "class Solution {\n    public String longestPalindrome(String s) {\n        int n = s.length();\n        boolean dp[][] = new boolean[n][n];\n        int start = 0,end = 0;\n        \n        for(int gap = 0;gap < n;gap++){\n            for(int i = 0,j = gap;i< n && j < n;i++,j++){\n                if(gap == 0){\n                    dp[i][j] = true;\n                }else if(gap == 1){\n                    if(s.charAt(i) == s.charAt(j)){\n                        dp[i][j] = true;\n                    }else{\n                        dp[i][j] = false;\n                    }\n                }else{\n                    if(s.charAt(i) == s.charAt(j) && dp[i+1][j-1] == true){\n                        dp[i][j] = true;\n                    }else{\n                        dp[i][j] = false;\n                    }\n                }\n                if(dp[i][j] == true){\n                    if(j-i > end - start){\n                        start = i;\n                        end = j;\n                    }\n                }\n            }\n        }\n\t\t\n        return s.substring(start,end + 1);\n    }\n}"
  },
  {
    "path": "5-longest-palindromic-substring/NOTES.md",
    "content": "​"
  },
  {
    "path": "5-longest-palindromic-substring/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/longest-palindromic-substring/\">5. Longest Palindromic Substring</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, return <em>the longest palindromic substring</em> in <code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"babad\"\n<strong>Output:</strong> \"bab\"\n<strong>Explanation:</strong> \"aba\" is also a valid answer.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"cbbd\"\n<strong>Output:</strong> \"bb\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consist of only digits and English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "50-powx-n/50-powx-n.java",
    "content": "class Solution {\n    public double myPow(double x, int n) {\n        if(n == 0) return (double)1;\n        if(n < 0){\n            return 1 / x * myPow(1 / x , -(n + 1));\n        }\n        return (n % 2 == 0 ? myPow(x * x , n / 2) : x * myPow(x * x , n / 2));\n    }\n}"
  },
  {
    "path": "50-powx-n/NOTES.md",
    "content": "​"
  },
  {
    "path": "50-powx-n/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/powx-n/\">50. Pow(x, n)</a></h2><h3>Medium</h3><hr><div><p>Implement <a href=\"http://www.cplusplus.com/reference/valarray/pow/\" target=\"_blank\">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> x = 2.00000, n = 10\n<strong>Output:</strong> 1024.00000\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> x = 2.10000, n = 3\n<strong>Output:</strong> 9.26100\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> x = 2.00000, n = -2\n<strong>Output:</strong> 0.25000\n<strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-100.0 &lt; x &lt; 100.0</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "509-fibonacci-number/509-fibonacci-number.java",
    "content": "class Solution{\n    static long mod = 1000000007;\n    long[][] multiply(long [][]m1, long[][]m2){\n        long ans[][] =new long[2][2];\n        for(int i=0;i<2;i++)\n            for(int j=0;j<2;j++)\n                for(int k=0;k<2;k++)\n                    ans[i][j] += (m1[i][k]*m2[k][j])%mod;\n        return ans;\n    }\n    \n    long[][] matPow(long [][]mat,long n){\n        if(n == 1)return mat;\n        long[][] ans = matPow(mat,n/2);\n        ans = multiply(ans,ans);\n        if((n&1) == 1)ans = multiply(ans,mat);\n        return ans;\n    }\n    \n    public int fib(int N){\n       long n = N;\n       if(n==1 || n==0)return N;\n       long mat[][] = {{1,1},{1,0}};\n       mat = matPow(mat,n-1);\n       return (int) (mat[0][0]%mod);\n    }\n}"
  },
  {
    "path": "509-fibonacci-number/NOTES.md",
    "content": "​"
  },
  {
    "path": "509-fibonacci-number/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/fibonacci-number/\">509. Fibonacci Number</a></h2><h3>Easy</h3><hr><div><p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p>\n\n<pre>F(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n &gt; 1.\n</pre>\n\n<p>Given <code>n</code>, calculate <code>F(n)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 2\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 3\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> n = 4\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 30</code></li>\n</ul>\n</div>"
  },
  {
    "path": "51-n-queens/51-n-queens.java",
    "content": "class Solution {\n    public List<List<String>> solveNQueens(int n) {\n        char[][] board=new char[n][n];\n        for(int i=0;i<n;i++)\n            for(int j=0;j<n;j++)\n                board[i][j]='.';\n        int leftRow[]=new int[n];\n        int upperDiagonal[]=new int[2*n-1];\n        int lowerDiagonal[]=new int[2*n -1];\n        List<List<String>> res=new ArrayList<>();\n        solve(res, 0,board, leftRow, upperDiagonal, lowerDiagonal);\n        return res;\n    }\n    public static void solve(List<List<String>> res, int col, char[][] board, int[] leftRow, int[] upperDiagonal, int[] lowerDiagonal)\n    {\n        int n=board.length;\n        if(col==n){\n            res.add(construct(board));\n            return;\n        }\n        for(int row=0;row<board.length;row++)\n            if(leftRow[row]==0 && upperDiagonal[n-1+col-row]==0 && lowerDiagonal[row+col]==0){\n                board[row][col]='Q';\n                leftRow[row]=1;\n                upperDiagonal[n-1+col-row]=1;\n                lowerDiagonal[row+col]=1;\n                solve(res, col+1,board, leftRow, upperDiagonal, lowerDiagonal);\n                board[row][col]='.';\n                leftRow[row]=0;\n                upperDiagonal[n-1+col-row]=0;\n                lowerDiagonal[row+col]=0;\n            }\n        \n    }\n    \n    public static List<String> construct(char[][] board){\n        List<String> fans=new ArrayList<>();\n        for(int i=0;i<board.length;i++)\n        {\n            String s=new String(board[i]);\n            // fans.add(new String(board[i]));\n            fans.add(s);\n        }\n        return fans;\n    }\n}"
  },
  {
    "path": "51-n-queens/NOTES.md",
    "content": "​"
  },
  {
    "path": "51-n-queens/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/n-queens/\">51. N-Queens</a></h2><h3>Hard</h3><hr><div><p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p>\n\n<p>Given an integer <code>n</code>, return <em>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>Each solution contains a distinct board configuration of the n-queens' placement, where <code>'Q'</code> and <code>'.'</code> both indicate a queen and an empty space, respectively.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/queens.jpg\" style=\"width: 600px; height: 268px;\">\n<pre><strong>Input:</strong> n = 4\n<strong>Output:</strong> [[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]\n<strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> [[\"Q\"]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 9</code></li>\n</ul>\n</div>"
  },
  {
    "path": "52-n-queens-ii/52-n-queens-ii.java",
    "content": "class Solution {\n    int count;\n    public int totalNQueens(int n) {\n        boolean[][]board=new boolean[n][n];\n        dfs(board,0);\n        return count;    \n    }\n    public void dfs(boolean[][]board,int row){\n        if(row==board.length){\n            count++;\n            return;\n        }\n        for(int col=0;col<board.length;col++){\n            if(isSafe(board,row,col)){\n                board[row][col]=true;\n                dfs(board,row+1);\n                board[row][col]=false;\n            }\n        }\n    }\n    boolean isSafe(boolean[][] board,int row,int col){\n        //checking vertically\n        for(int i=0;i<row;i++){\n            if(board[i][col]){\n                return false;\n            }\n        }\n        \n        //checking upper left\n        int leftMin=Math.min(row,col);\n        for(int i=1;i<=leftMin;i++){\n            if(board[row-i][col-i]){\n                return false;\n            }\n        }\n        \n        //checking upper right\n        int rightMin=Math.min(row,board.length-1-col);\n        for(int i=1;i<=rightMin;i++){\n            if(board[row-i][col+i]){\n                return false;\n            }\n        }\n        //else true\n        return true;\n    }\n}"
  },
  {
    "path": "52-n-queens-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "52-n-queens-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/n-queens-ii/\">52. N-Queens II</a></h2><h3>Hard</h3><hr><div><p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p>\n\n<p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/queens.jpg\" style=\"width: 600px; height: 268px;\">\n<pre><strong>Input:</strong> n = 4\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 9</code></li>\n</ul>\n</div>"
  },
  {
    "path": "53-maximum-subarray/53-maximum-subarray.java",
    "content": "class Solution {\n    public int maxSubArray(int[] nums) {\n        int max=Integer.MIN_VALUE;\n        int temp=0;\n        for(int i=0;i<nums.length;i++){\n            temp+=nums[i];\n            if(temp>max)max=temp;\n            if(temp<0)temp=0;\n        }\n        return max;\n    }\n}"
  },
  {
    "path": "53-maximum-subarray/Maximum Subarray.py",
    "content": "class Solution:\n    def maxSubArray(self, nums: List[int]) -> int:\n        \n        \n        current = 0\n        maxsum = nums[0]\n        \n        for i in range(len(nums)):\n            current += nums[i]\n            \n            if current>maxsum:\n                maxsum = current\n            if current < 0:\n                current = 0\n            \n        return maxsum\n            \n"
  },
  {
    "path": "53-maximum-subarray/NOTES.md",
    "content": "​"
  },
  {
    "path": "53-maximum-subarray/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-subarray/\">53. Maximum Subarray</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, find the contiguous subarray (containing at least one number) which has the largest sum and return <em>its sum</em>.</p>\n\n<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> [4,-1,2,1] has the largest sum = 6.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [5,4,-1,7,8]\n<strong>Output:</strong> 23\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>\n</div>"
  },
  {
    "path": "535-encode-and-decode-tinyurl/535-encode-and-decode-tinyurl.java",
    "content": "public class Codec {\n\n    // Encodes a URL to a shortened URL.\n    public String encode(String s) {\n        return s;\n    }\n\n    // Decodes a shortened URL to its original URL.\n    public String decode(String s) {\n        return s;\n    }\n}\n\n// Your Codec object will be instantiated and called as such:\n// Codec codec = new Codec();\n// codec.decode(codec.encode(url));"
  },
  {
    "path": "535-encode-and-decode-tinyurl/NOTES.md",
    "content": "​"
  },
  {
    "path": "535-encode-and-decode-tinyurl/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/encode-and-decode-tinyurl/\">535. Encode and Decode TinyURL</a></h2><h3>Medium</h3><hr><div><blockquote>Note: This is a companion problem to the <a href=\"https://leetcode.com/discuss/interview-question/system-design/\" target=\"_blank\">System Design</a> problem: <a href=\"https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/\" target=\"_blank\">Design TinyURL</a>.</blockquote>\n\n<p>TinyURL is a URL shortening service where you enter a URL such as <code>https://leetcode.com/problems/design-tinyurl</code> and it returns a short URL such as <code>http://tinyurl.com/4e9iAk</code>. Design a class to encode a URL and decode a tiny URL.</p>\n\n<p>There 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.</p>\n\n<p>Implement the <code>Solution</code> class:</p>\n\n<ul>\n\t<li><code>Solution()</code> Initializes the object of the system.</li>\n\t<li><code>String encode(String longUrl)</code> Returns a tiny URL for the given <code>longUrl</code>.</li>\n\t<li><code>String decode(String shortUrl)</code> Returns the original long URL for the given <code>shortUrl</code>. It is guaranteed that the given <code>shortUrl</code> was encoded by the same object.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> url = \"https://leetcode.com/problems/design-tinyurl\"\n<strong>Output:</strong> \"https://leetcode.com/problems/design-tinyurl\"\n\n<strong>Explanation:</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= url.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>url</code> is guranteed to be a valid URL.</li>\n</ul>\n</div>"
  },
  {
    "path": "538-convert-bst-to-greater-tree/538-convert-bst-to-greater-tree.java",
    "content": "class Solution {\n    int sum=0;\n    public TreeNode convertBST(TreeNode root) {\n        if(root==null) return null;\n        convertBST(root.right);\n        sum+=root.val;\n        root.val=sum;\n        convertBST(root.left);\n        return root;\n    }\n}"
  },
  {
    "path": "538-convert-bst-to-greater-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "538-convert-bst-to-greater-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/convert-bst-to-greater-tree/\">538. Convert BST to Greater Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> 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.</p>\n\n<p>As a reminder, a <em>binary search tree</em> is a tree that satisfies these constraints:</p>\n\n<ul>\n\t<li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node's key.</li>\n\t<li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node's key.</li>\n\t<li>Both the left and right subtrees must also be binary search trees.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/05/02/tree.png\" style=\"width: 500px; height: 341px;\">\n<pre><strong>Input:</strong> root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\n<strong>Output:</strong> [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = [0,null,1]\n<strong>Output:</strong> [1,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>All the values in the tree are <strong>unique</strong>.</li>\n\t<li><code>root</code> is guaranteed to be a valid binary search tree.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as 1038: <a href=\"https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/\" target=\"_blank\">https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/</a></p>\n</div>"
  },
  {
    "path": "541-reverse-string-ii/541-reverse-string-ii.java",
    "content": "class Solution {\n    public String reverseStr(String s, int k) {\n        StringBuilder sb=new StringBuilder();\n        int i=0;\n        if(k>s.length())\n            return sb.append(s).reverse().toString();\n        boolean flag=true;\n        for(i=0;i<s.length();)\n        {\n            if(i+k<=s.length())\n            {\n                StringBuilder str=new StringBuilder(s.substring(i,i+k));\n                str.reverse();\n                sb.append(str);\n                flag=false;\n                i+=k;\n            }\n            if(i+k<=s.length())\n            {\n                sb.append(s.substring(i,i+k));\n                flag=true;\n            }\n            i+=k;\n        }\n        \n        if(sb.length()<s.length()&&flag==false)\n            sb.append(s.substring(sb.length(),s.length()));\n        else if(sb.length()<s.length()&&flag==true)\n        {\n            StringBuilder str=new StringBuilder(s.substring(sb.length(),s.length()));\n                str.reverse();\n                sb.append(str);\n        }\n        return sb.toString();\n    }\n}"
  },
  {
    "path": "541-reverse-string-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "541-reverse-string-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/reverse-string-ii/\">541. Reverse String II</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code> and an integer <code>k</code>, reverse the first <code>k</code> characters for every <code>2k</code> characters counting from the start of the string.</p>\n\n<p>If there are fewer than <code>k</code> characters left, reverse all of them. If there are less than <code>2k</code> but greater than or equal to <code>k</code> characters, then reverse the first <code>k</code> characters and leave the other as original.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"abcdefg\", k = 2\n<strong>Output:</strong> \"bacdfeg\"\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"abcd\", k = 2\n<strong>Output:</strong> \"bacd\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of only lowercase English letters.</li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "557 Reverse Words in a String III easy lc s22.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n//     2 -pointer tech TC: O(N) -outer loops iterate over N chars to find start & end idx of every word, reverse word also iterates N times to perform N/2 swaps. thus , TC is O(N+N) = O(N)\n//     SC: O(1) using const extra space to track last space idx\n    string reverseWords(string s) {\n        int lastSpaceIndex = -1;\n        int len = (int)s.size();\n        for(int i = 0; i <= len; i++){\n            if(i== len || s[i] == ' '){\n                int start_i = lastSpaceIndex +1;\n                int end_i = i-1;\n                while(start_i < end_i){\n                    char temp = s[start_i];\n                    s[start_i] = s[end_i];\n                    s[end_i] = temp;\n                    start_i++;\n                    end_i--;\n                }\n                lastSpaceIndex = i;\n            }\n        }\n        return s;\n        \n    }\n};"
  },
  {
    "path": "557-reverse-words-in-a-string-iii/557-reverse-words-in-a-string-iii.java",
    "content": "class Solution {\n    public String reverseWords(String sy) {\n        String[] arr=sy.split(\" \");\n        for(int i=0;i<arr.length;i++){\n            StringBuilder sb=new StringBuilder(arr[i]);\n            sb.reverse();\n            arr[i]=sb.toString();\n        }\n        StringBuilder ans=new StringBuilder();\n        for(String s:arr){\n            ans.append(s);\n            ans.append(\" \");\n        }\n        ans.deleteCharAt(ans.length()-1);\n        return ans.toString();\n    }\n}"
  },
  {
    "path": "557-reverse-words-in-a-string-iii/NOTES.md",
    "content": "​"
  },
  {
    "path": "560. Subarray Sum Equals K/560. Subarray Sum Equals K.cpp",
    "content": "class Solution {\npublic:\n    int subarraySum(vector<int>& nums, int k) {                \n        unordered_map<int, int> mp;\n        int sum=0, ans=0;\n        mp[sum] = 1; // we always have one subarray with sum 0\n        for(auto it : nums){\n            sum += it; // prefix sum \n            if(mp.find(sum - k) != mp.end()) ans += mp[sum - k];\n            mp[sum]++;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "576-out-of-boundary-paths/576-out-of-boundary-paths.java",
    "content": "class Solution {\n    int[][][] cache;\n    int MOD = 1000_000_007;\n    public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n        cache = new int[m][n][maxMove + 1];\n        for(int[][] cc : cache) {\n            for(int[] c : cc) {\n                Arrays.fill(c, -1);\n            }\n        }\n        return f(m, n, maxMove, startRow, startColumn);\n    }\n    int f(int m, int n, int max, int r, int c) {\n        if(r < 0 || c < 0 || r == m || c == n) {\n            return 1;\n        }\n        if(max == 0) {\n            return 0;\n        }\n        if(cache[r][c][max] > -1) {\n            return cache[r][c][max];\n        }\n        long l = f(m, n, max - 1, r - 1, c) % MOD;\n        l += f(m, n, max - 1, r + 1, c) % MOD;\n        l += f(m, n, max - 1, r, c + 1) % MOD;\n        l += f(m, n, max - 1, r, c - 1) % MOD;\n        cache[r][c][max] = (int)(l % MOD);\n        return cache[r][c][max];\n    }\n}"
  },
  {
    "path": "576-out-of-boundary-paths/NOTES.md",
    "content": "​"
  },
  {
    "path": "576-out-of-boundary-paths/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/out-of-boundary-paths/\">576. Out of Boundary Paths</a></h2><h3>Medium</h3><hr><div><p>There is an <code>m x n</code> grid with a ball. The ball is initially at the position <code>[startRow, startColumn]</code>. 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 <strong>at most</strong> <code>maxMove</code> moves to the ball.</p>\n\n<p>Given the five integers <code>m</code>, <code>n</code>, <code>maxMove</code>, <code>startRow</code>, <code>startColumn</code>, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png\" style=\"width: 500px; height: 296px;\">\n<pre><strong>Input:</strong> m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0\n<strong>Output:</strong> 6\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png\" style=\"width: 500px; height: 293px;\">\n<pre><strong>Input:</strong> m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1\n<strong>Output:</strong> 12\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>0 &lt;= maxMove &lt;= 50</code></li>\n\t<li><code>0 &lt;= startRow &lt; m</code></li>\n\t<li><code>0 &lt;= startColumn &lt; n</code></li>\n</ul>\n</div>"
  },
  {
    "path": "581-shortest-unsorted-continuous-subarray/581-shortest-unsorted-continuous-subarray.java",
    "content": "public class Solution {\n    public int findUnsortedSubarray(int[] nums) {\n        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;\n        boolean flag = false;\n        for (int i = 1; i < nums.length; i++) {\n            if (nums[i] < nums[i - 1])\n                flag = true;\n            if (flag)\n                min = Math.min(min, nums[i]);\n        }\n        flag = false;\n        for (int i = nums.length - 2; i >= 0; i--) {\n            if (nums[i] > nums[i + 1])\n                flag = true;\n            if (flag)\n                max = Math.max(max, nums[i]);\n        }\n        int l, r;\n        for (l = 0; l < nums.length; l++) {\n            if (min < nums[l])\n                break;\n        }\n        for (r = nums.length - 1; r >= 0; r--) {\n            if (max > nums[r])\n                break;\n        }\n        return r - l < 0 ? 0 : r - l + 1;\n    }\n}"
  },
  {
    "path": "581-shortest-unsorted-continuous-subarray/NOTES.md",
    "content": "​"
  },
  {
    "path": "581-shortest-unsorted-continuous-subarray/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/shortest-unsorted-continuous-subarray/\">581. Shortest Unsorted Continuous Subarray</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.</p>\n\n<p>Return <em>the shortest such subarray and output its length</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,6,4,8,10,9,15]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,4]\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?</div>"
  },
  {
    "path": "583-delete-operation-for-two-strings/583-delete-operation-for-two-strings.java",
    "content": "class Solution {\n    public int minDistance(String word1, String word2) {\n        \n        char[] s1= word1.toCharArray();\n        char[] s2 = word2.toCharArray();\n        \n        int[][] DP = new int[s1.length+1][s2.length+1];\n        \n        for (int i=s1.length-1;i>=0;--i){\n            for (int j=s2.length-1;j>=0;--j){\n                if(s1[i] == s2[j]){\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 word1.length()+word2.length()-(2*DP[0][0]);\n    }\n    \n    \n}"
  },
  {
    "path": "583-delete-operation-for-two-strings/NOTES.md",
    "content": "​"
  },
  {
    "path": "583-delete-operation-for-two-strings/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/delete-operation-for-two-strings/\">583. Delete Operation for Two Strings</a></h2><h3>Medium</h3><hr><div><p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p>\n\n<p>In one <strong>step</strong>, you can delete exactly one character in either string.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> word1 = \"sea\", word2 = \"eat\"\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> You need one step to make \"sea\" to \"ea\" and another step to make \"eat\" to \"ea\".\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> word1 = \"leetcode\", word2 = \"etco\"\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li>\n\t<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "59-spiral-matrix-ii/59-spiral-matrix-ii.java",
    "content": "class Solution {\n    public int[][] generateMatrix(int n) {\n        \n        int ans[][] = new int[n][n];\n        fillMatrix(ans, 0 , 0, 1,'r');\n        return ans;\n    }\n    \n    public void fillMatrix(int [][]ans, int i, int j, int cur, char dir){\n        if(i < 0 || j < 0 || i >=ans.length ||  j >= ans.length) return;\n        \n        if(ans[i][j] != 0) return;\n        \n        ans[i][j] = cur;\n        \n        if(dir == 'u'){\n            fillMatrix(ans, i-1,j,cur+1, 'u');    \n        }\n        \n        fillMatrix(ans, i,j+1,cur+1, 'r');\n        fillMatrix(ans, i+1,j,cur+1, 'd');\n        fillMatrix(ans, i,j-1,cur+1, 'l');\n        fillMatrix(ans, i-1,j,cur+1, 'u');\n       \n    }\n}"
  },
  {
    "path": "59-spiral-matrix-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "59-spiral-matrix-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/spiral-matrix-ii/\">59. Spiral Matrix II</a></h2><h3>Medium</h3><hr><div><p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg\" style=\"width: 242px; height: 242px;\">\n<pre><strong>Input:</strong> n = 3\n<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> [[1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n</ul>\n</div>"
  },
  {
    "path": "6-zigzag-conversion/6-zigzag-conversion.java",
    "content": "class Solution {\n    public String convert(String s, int numRows) {\n        int strlen = s.length();\n    int n = numRows;\n    StringBuilder sub = new StringBuilder();\n    if(n==1 || n > strlen) {\n      return s;\n    }\n    for (int i = 0; i < n; i++) {\n      int k = i;\n      if(i==0 || i == n-1) {\n        while(k<strlen) {\n          sub.append(s.charAt(k));\n          k+= (n-1)*2;\n        }\n      } else {\n        sub.append(s.charAt(k));\n        while(k<strlen) {\n          int j = k+ ((n-1)*2 - 2*i);\n          if(j<strlen) {\n            sub.append(s.charAt(j));\n          }\n          k+= (n-1)*2;\n          if(k<strlen) {\n            sub.append(s.charAt(k));\n          }\n        }\n      }\n    }\n        return sub.toString();\n    }\n}"
  },
  {
    "path": "6-zigzag-conversion/NOTES.md",
    "content": "​"
  },
  {
    "path": "6-zigzag-conversion/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/zigzag-conversion/\">6. Zigzag Conversion</a></h2><h3>Medium</h3><hr><div><p>The string <code>\"PAYPALISHIRING\"</code> 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)</p>\n\n<pre>P   A   H   N\nA P L S I I G\nY   I   R\n</pre>\n\n<p>And then read line by line: <code>\"PAHNAPLSIIGYIR\"</code></p>\n\n<p>Write the code that will take a string and make this conversion given a number of rows:</p>\n\n<pre>string convert(string s, int numRows);\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"PAYPALISHIRING\", numRows = 3\n<strong>Output:</strong> \"PAHNAPLSIIGYIR\"\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"PAYPALISHIRING\", numRows = 4\n<strong>Output:</strong> \"PINALSIGYAHRPI\"\n<strong>Explanation:</strong>\nP     I    N\nA   L S  I G\nY A   H R\nP     I\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"A\", numRows = 1\n<strong>Output:</strong> \"A\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consists of English letters (lower-case and upper-case), <code>','</code> and <code>'.'</code>.</li>\n\t<li><code>1 &lt;= numRows &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "606-construct-string-from-binary-tree/606-construct-string-from-binary-tree.java",
    "content": "/**\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    StringBuilder sb;\n    public String tree2str(TreeNode root) {\n        sb=new StringBuilder();\n        dfs(root);\n        return sb.toString();\n    }\n    public void dfs(TreeNode root){\n        if(root==null)return;\n        sb.append(root.val);\n        if(root.left==null && root.right==null)return;\n        sb.append(\"(\");\n        dfs(root.left);\n        sb.append(\")\");  \n        if(root.right!=null){\n            sb.append(\"(\");\n            dfs(root.right);\n            sb.append(\")\");\n        }\n    }\n}"
  },
  {
    "path": "606-construct-string-from-binary-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "606-construct-string-from-binary-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/construct-string-from-binary-tree/\">606. Construct String from Binary Tree</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.</p>\n\n<p>Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/cons1-tree.jpg\" style=\"width: 292px; height: 301px;\">\n<pre><strong>Input:</strong> root = [1,2,3,4]\n<strong>Output:</strong> \"1(2(4))(3)\"\n<strong>Explanation:</strong> Originally, it needs to be \"1(2(4)())(3()())\", but you need to omit all the unnecessary empty parenthesis pairs. And it will be \"1(2(4))(3)\"\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/cons2-tree.jpg\" style=\"width: 207px; height: 293px;\">\n<pre><strong>Input:</strong> root = [1,2,3,null,4]\n<strong>Output:</strong> \"1(2()(4))(3)\"\n<strong>Explanation:</strong> Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "609 Find Duplicate File in System lc med s19.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    vector<string> split(string str, char delim) {\n        string line;\n        vector<string> res;\n        stringstream ss(str);\n        while (getline(ss, line, delim)) res.push_back(line);\n        return res;\n    }\n\n    vector<vector<string>> findDuplicate(vector<string>& paths) {\n        vector<vector<string>> ans;\n        unordered_map<string, vector<string>> m;\n        for (auto p : paths) {\n            vector<string> path = split(p, ' ');\n            string directoryPath;\n            for (int i = 0; i < path.size(); i++) {\n                if (i == 0) {\n                    directoryPath = path[i];\n                } else {\n                    string fileName = path[i].substr(0, path[i].find('('));\n                    string fileContent =  path[i].substr(path[i].find('(') + 1, path[i].find(')') - path[i].find('(') - 1);\n                    m[fileContent].push_back(directoryPath + \"/\" + fileName);\n                }\n            }\n        }\n        for (auto x : m) {\n            if (x.second.size() > 1) {\n                ans.push_back(x.second);    \n            }\n        }\n        return ans;\n    }\n};"
  },
  {
    "path": "609-find-duplicate-file-in-system/609-find-duplicate-file-in-system.java",
    "content": "class Solution {\n    public List<List<String>> findDuplicate(String[] paths) {\n        Map<String, List<String>> map = new HashMap<>();\n        List<List<String>> res = new ArrayList<>();\n        for(int i = 0; i < paths.length; i++){\n            String s = paths[i];\n            String[] str = s.split(\" \");\n            String prefix = str[0] + \"/\";\n            for(int j = 1; j < str.length; j++){\n                String nc = str[j];\n                int t = nc.length() - 1;\n                while(t >= 0 && nc.charAt(t) != '(') t--;\n                String name = nc.substring(0, t);\n                String content = nc.substring(t + 1, nc.length() - 1);\n                map.computeIfAbsent(content, a -> new ArrayList<>());\n                map.get(content).add(prefix + name);\n            }\n        }\n        \n        for(String key: map.keySet()){\n            if(map.get(key).size() > 1){\n                res.add(map.get(key));\n            }\n        }\n        \n        return(res);\n        \n    }\n}"
  },
  {
    "path": "609-find-duplicate-file-in-system/NOTES.md",
    "content": "​"
  },
  {
    "path": "609-find-duplicate-file-in-system/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-duplicate-file-in-system/\">609. Find Duplicate File in System</a></h2><h3>Medium</h3><hr><div><p>Given a list <code>paths</code> of directory info, including the directory path, and all the files with contents in this directory, return <em>all the duplicate files in the file system in terms of their paths</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>A group of duplicate files consists of at least two files that have the same content.</p>\n\n<p>A single directory info string in the input list has the following format:</p>\n\n<ul>\n\t<li><code>\"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)\"</code></li>\n</ul>\n\n<p>It means there are <code>n</code> files <code>(f1.txt, f2.txt ... fn.txt)</code> with content <code>(f1_content, f2_content ... fn_content)</code> respectively in the directory \"<code>root/d1/d2/.../dm\"</code>. Note that <code>n &gt;= 1</code> and <code>m &gt;= 0</code>. If <code>m = 0</code>, it means the directory is just the root directory.</p>\n\n<p>The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:</p>\n\n<ul>\n\t<li><code>\"directory_path/file_name.txt\"</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]\n<strong>Output:</strong> [[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\"]\n<strong>Output:</strong> [[\"root/a/2.txt\",\"root/c/d/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= paths.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= paths[i].length &lt;= 3000</code></li>\n\t<li><code>1 &lt;= sum(paths[i].length) &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>paths[i]</code> consist of English letters, digits, <code>'/'</code>, <code>'.'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>\n\t<li>You may assume no files or directories share the same name in the same directory.</li>\n\t<li>You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>Imagine you are given a real file system, how will you search files? DFS or BFS?</li>\n\t<li>If the file content is very large (GB level), how will you modify your solution?</li>\n\t<li>If you can only read the file by 1kb each time, how will you modify your solution?</li>\n\t<li>What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?</li>\n\t<li>How to make sure the duplicated files you find are not false positive?</li>\n</ul>\n</div>"
  },
  {
    "path": "62-unique-paths/62-unique-paths.java",
    "content": "class Solution {\n    public int uniquePaths(int m, int n) {\n        int[][] dp = new int[m+1][n+1];\n        return helper(m, n, dp);\n    }\n    private int helper(int m, int n, int[][] dp) {\n        if(m<1 || n<1) return 0;\n        if(m == 1 || n == 1) return 1;\n        if(dp[m][n] != 0) return dp[m][n];\n        dp[m][n] = helper(m, n-1, dp) + helper(m-1, n, dp);\n        return dp[m][n];\n    }\n}"
  },
  {
    "path": "62-unique-paths/NOTES.md",
    "content": "​"
  },
  {
    "path": "62-unique-paths/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/unique-paths/\">62. Unique Paths</a></h2><h3>Medium</h3><hr><div><p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>\n\n<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>\n\n<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png\" style=\"width: 400px; height: 183px;\">\n<pre><strong>Input:</strong> m = 3, n = 7\n<strong>Output:</strong> 28\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> m = 3, n = 2\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "622-design-circular-queue/622-design-circular-queue.java",
    "content": "class MyCircularQueue {\n\n    int[] queue;\n    int size;\n    int used;\n    int front;\n    int rear;\n    \n    public MyCircularQueue(int k) {\n        queue = new int[k];\n        size = k;\n    }\n    \n    public boolean enQueue(int value) {\n        if(isFull())\n            return false;\n        queue[rear] = value;\n        rear = (rear+1)%size;\n        used++;\n        return true;\n    }\n    \n    public boolean deQueue()\n    {\n        if(isEmpty())\n            return false;\n        front = (front+1)%size;\n        used -- ;\n        return true;\n        \n    }\n    \n    public int Front() {\n        if(isEmpty())\n            return -1;\n        return queue[front];\n    }\n    \n    public int Rear() {\n        if(isEmpty())\n            return -1;\n        return queue[(rear-1+size)%size];\n    }\n    \n    public boolean isEmpty() {\n        return used ==0;\n    }\n    \n    public boolean isFull() {\n        return used == size;\n    }\n}"
  },
  {
    "path": "622-design-circular-queue/NOTES.md",
    "content": "​"
  },
  {
    "path": "622-design-circular-queue/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/design-circular-queue/\">622. Design Circular Queue</a></h2><h3>Medium</h3><hr><div><p>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\".</p>\n\n<p>One 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.</p>\n\n<p>Implementation the <code>MyCircularQueue</code> class:</p>\n\n<ul>\n\t<li><code>MyCircularQueue(k)</code> Initializes the object with the size of the queue to be <code>k</code>.</li>\n\t<li><code>int Front()</code> Gets the front item from the queue. If the queue is empty, return <code>-1</code>.</li>\n\t<li><code>int Rear()</code> Gets the last item from the queue. If the queue is empty, return <code>-1</code>.</li>\n\t<li><code>boolean enQueue(int value)</code> Inserts an element into the circular queue. Return <code>true</code> if the operation is successful.</li>\n\t<li><code>boolean deQueue()</code> Deletes an element from the circular queue. Return <code>true</code> if the operation is successful.</li>\n\t<li><code>boolean isEmpty()</code> Checks whether the circular queue is empty or not.</li>\n\t<li><code>boolean isFull()</code> Checks whether the circular queue is full or not.</li>\n</ul>\n\n<p>You must solve the problem without using the built-in queue data structure in your programming language.&nbsp;</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\n<strong>Output</strong>\n[null, true, true, true, false, 3, true, true, true, 4]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= 1000</code></li>\n\t<li><code>0 &lt;= value &lt;= 1000</code></li>\n\t<li>At most <code>3000</code> calls will be made to&nbsp;<code>enQueue</code>, <code>deQueue</code>,&nbsp;<code>Front</code>,&nbsp;<code>Rear</code>,&nbsp;<code>isEmpty</code>, and&nbsp;<code>isFull</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "623-add-one-row-to-tree/623-add-one-row-to-tree.java",
    "content": "/**\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        if(depth==1){\n            TreeNode head=new TreeNode(val);\n            head.left=root;\n            return head;\n        }\n        dfs(root,val,depth-1);\n        return root;\n    }\n    public void dfs(TreeNode root,int val,int depth){\n        if(depth==1){\n            TreeNode lefty=root.left;\n            TreeNode righty=root.right;\n            TreeNode newLeft=new TreeNode(val);\n            TreeNode newRight=new TreeNode(val);\n            newLeft.left=lefty;\n            root.left=newLeft;\n            newRight.right=righty;\n            root.right=newRight;\n            return;\n        }\n        if(root.left!=null)dfs(root.left,val,depth-1);\n        if(root.right!=null)dfs(root.right,val,depth-1);\n    }\n}"
  },
  {
    "path": "623-add-one-row-to-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "623-add-one-row-to-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/add-one-row-to-tree/\">623. Add One Row to Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree and two integers <code>val</code> and <code>depth</code>, add a row of nodes with value <code>val</code> at the given depth <code>depth</code>.</p>\n\n<p>Note that the <code>root</code> node is at depth <code>1</code>.</p>\n\n<p>The adding rule is:</p>\n\n<ul>\n\t<li>Given the integer <code>depth</code>, for each not null tree node <code>cur</code> at the depth <code>depth - 1</code>, create two tree nodes with value <code>val</code> as <code>cur</code>'s left subtree root and right subtree root.</li>\n\t<li><code>cur</code>'s original left subtree should be the left subtree of the new left subtree root.</li>\n\t<li><code>cur</code>'s original right subtree should be the right subtree of the new right subtree root.</li>\n\t<li>If <code>depth == 1</code> that means there is no depth <code>depth - 1</code> at all, then create a tree node with value <code>val</code> as the new root of the whole original tree, and the original tree is the new root's left subtree.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg\" style=\"width: 500px; height: 231px;\">\n<pre><strong>Input:</strong> root = [4,2,6,3,1,5], val = 1, depth = 2\n<strong>Output:</strong> [4,1,1,2,null,null,6,3,1,5]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/11/add2-tree.jpg\" style=\"width: 500px; height: 277px;\">\n<pre><strong>Input:</strong> root = [4,2,null,3,1], val = 1, depth = 3\n<strong>Output:</strong> [4,2,null,1,1,3,null,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li>The depth of the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= depth &lt;= the depth of tree + 1</code></li>\n</ul>\n</div>"
  },
  {
    "path": "629-k-inverse-pairs-array/629-k-inverse-pairs-array.java",
    "content": "public class Solution {\n    public int kInversePairs(int n, int k) {\n        int[][] dp = new int[n + 1][k + 1];\n        int M = 1000000007;\n        for (int i = 1; i <= n; i++) {\n            for (int j = 0; j <= k; j++) {\n                if (j == 0)\n                    dp[i][j] = 1;\n                else {\n                    int val = (dp[i - 1][j] + M - ((j - i) >= 0 ? dp[i - 1][j - i] : 0)) % M;\n                    dp[i][j] = (dp[i][j - 1] + val) % M;\n                }\n            }\n        }\n        return ((dp[n][k] + M - (k > 0 ? dp[n][k - 1] : 0)) % M);\n    }\n}"
  },
  {
    "path": "629-k-inverse-pairs-array/NOTES.md",
    "content": "​"
  },
  {
    "path": "629-k-inverse-pairs-array/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/k-inverse-pairs-array/\">629. K Inverse Pairs Array</a></h2><h3>Hard</h3><hr><div><p>For an integer array <code>nums</code>, an <strong>inverse pair</strong> is a pair of integers <code>[i, j]</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>nums[i] &gt; nums[j]</code>.</p>\n\n<p>Given two integers n and k, return the number of different arrays consist of numbers from <code>1</code> to <code>n</code> such that there are exactly <code>k</code> <strong>inverse pairs</strong>. Since the answer can be huge, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 3, k = 0\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 3, k = 1\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n\t<li><code>0 &lt;= k &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "63-unique-paths-ii/63-unique-paths-ii.java",
    "content": "class Solution {\n    public int uniquePathsWithObstacles(int[][] a) {\n        int result = 0;\n        int m = a.length;\n        int n = a[0].length;\n        int[] row = new int[n];\n        int prevCol;\n        row[0] = 1 - a[0][0];\n        for (int i = 1; i < n; ++i) {\n            if (a[0][i] == 1 || a[0][i-1] == 1) {\n                row[i] = 0;\n                continue;\n            }\n            row[i] = row[i-1];\n        }\n        \n        for (int i = 1; i < m; ++i) {\n            if (a[i-1][0] == 1 || a[i][0] == 1) {\n                row[0] = 0;\n            }\n            for (int j = 1; j < n; ++j) {\n                if (a[i][j] == 1) {\n                    row[j] = 0;\n                    continue;\n                }\n                int tmp = 0;\n                if (a[i-1][j] != 1) {\n                    tmp += row[j];\n                }\n                if (a[i][j-1] != 1) {\n                    tmp += row[j-1];\n                }\n                row[j] = tmp;\n            }\n        }\n        return row[n-1];\n    }\n}"
  },
  {
    "path": "63-unique-paths-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "63-unique-paths-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/unique-paths-ii/\">63. Unique Paths II</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m-1][n-1]</code>). The robot can only move either down or right at any point in time.</p>\n\n<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>\n\n<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>\n\n<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg\" style=\"width: 242px; height: 242px;\">\n<pre><strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg\" style=\"width: 162px; height: 162px;\">\n<pre><strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == obstacleGrid.length</code></li>\n\t<li><code>n == obstacleGrid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "630-course-schedule-iii/630-course-schedule-iii.java",
    "content": "public class Solution {\n    public int scheduleCourse(int[][] courses) {\n        Arrays.sort(courses, (a, b) -> a[1] - b[1]);\n        PriorityQueue < Integer > queue = new PriorityQueue < > ((a, b) -> b - a);\n        int time = 0;\n        for (int[] c: courses) {\n            if (time + c[0] <= c[1]) {\n                queue.offer(c[0]);\n                time += c[0];\n            } else if (!queue.isEmpty() && queue.peek() > c[0]) {\n                time += c[0] - queue.poll();\n                queue.offer(c[0]);\n            }\n        }\n        return queue.size();\n    }\n}"
  },
  {
    "path": "630-course-schedule-iii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/course-schedule-iii/\">630. Course Schedule III</a></h2><h3>Hard</h3><hr><div><p>There are <code>n</code> different online courses numbered from <code>1</code> to <code>n</code>. You are given an array <code>courses</code> where <code>courses[i] = [duration<sub>i</sub>, lastDay<sub>i</sub>]</code> indicate that the <code>i<sup>th</sup></code> course should be taken <b>continuously</b> for <code>duration<sub>i</sub></code> days and must be finished before or on <code>lastDay<sub>i</sub></code>.</p>\n\n<p>You will start on the <code>1<sup>st</sup></code> day and you cannot take two or more courses simultaneously.</p>\n\n<p>Return <em>the maximum number of courses that you can take</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\n<strong>Output:</strong> 3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1<sup>st</sup> course, it costs 100 days so you will finish it on the 100<sup>th</sup> day, and ready to take the next course on the 101<sup>st</sup> day.\nSecond, take the 3<sup>rd</sup> course, it costs 1000 days so you will finish it on the 1100<sup>th</sup> day, and ready to take the next course on the 1101<sup>st</sup> day. \nThird, take the 2<sup>nd</sup> course, it costs 200 days so you will finish it on the 1300<sup>th</sup> day. \nThe 4<sup>th</sup> course cannot be taken now, since you will finish it on the 3300<sup>th</sup> day, which exceeds the closed date.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> courses = [[1,2]]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> courses = [[3,2],[4,3]]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= courses.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= duration<sub>i</sub>, lastDay<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "637-average-of-levels-in-binary-tree/637-average-of-levels-in-binary-tree.cpp",
    "content": "class Solution {\npublic:\n    vector<double> averageOfLevels(TreeNode* root) {\n        queue<TreeNode*> q;\n        q.push(root);\n        vector<double> v;\n        while(!q.empty()){\n            int n = q.size();\n            double d=0;                        \n            for(int i=0;i<n;i++){\n                TreeNode* node = q.front();\n                if(node->left) q.push(node->left);\n                if(node->right) q.push(node->right);\n                q.pop();\n                d += node->val;\n            }\n            v.push_back(d/n);\n        }\n        return v;\n    }\n};\n\n\n// Same approach:\n// class Solution {\n// public:\n//     vector<double> ans;\n//     void getAverage(TreeNode *root){\n//         queue<TreeNode*> q;\n//         q.push(root);\n//         while(!q.empty()){\n//             double size = q.size();\n//             double sum = 0;\n//             for(int i = 0; i < size; i++){\n//                 auto node = q.front();\n//                 q.pop();\n//                 sum += node->val;\n//                 if(node->left)\n//                     q.push(node->left);\n//                 if(node->right)\n//                     q.push(node->right);\n//             }\n//             ans.push_back(sum / size);\n//         }\n//     }\n    \n//     vector<double> averageOfLevels(TreeNode* root) {\n//         getAverage(root);\n//         return ans;\n//     }\n// };\n"
  },
  {
    "path": "637-average-of-levels-in-binary-tree/637-average-of-levels-in-binary-tree.java",
    "content": "/**\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<Double> averageOfLevels(TreeNode root) {\n        List<Double> ans=new ArrayList<>();\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(root);\n        while(q.size()>0){\n            int sz=q.size();\n            int siz=sz;\n            Double avg=0.00;\n            while(siz-->0){\n                TreeNode curr=q.remove();\n                if(curr.left!=null)q.add(curr.left);\n                if(curr.right!=null)q.add(curr.right);\n                avg+=curr.val;\n            }\n            avg/=sz;\n            ans.add(avg);\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "637-average-of-levels-in-binary-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/average-of-levels-in-binary-tree/\">637. Average of Levels in Binary Tree</a></h2><h3>Easy</h3><hr><div>Given the <code>root</code> of a binary tree, return <em>the average value of the nodes on each level in the form of an array</em>. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg\" style=\"width: 277px; height: 302px;\">\n<pre><strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> [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</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg\" style=\"width: 292px; height: 302px;\">\n<pre><strong>Input:</strong> root = [3,9,20,15,7]\n<strong>Output:</strong> [3.00000,14.50000,11.00000]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n</div>"
  },
  {
    "path": "637-average-of-levels-in-binary-tree.py",
    "content": "class Solution:\n    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:\n       \n        quene = []  \n        res = []\n        quene.append(root)\n        \n        while(quene):   \n            qlen = len(quene)   \n            tmp = 0\n            for i in range(qlen):   \n                node = quene.pop(0)\n                tmp += node.val\n                if node.left:   \n                    quene.append(node.left)\n                if node.right:\n                    quene.append(node.right)\n            res.append(tmp/qlen)    \n        \n        return res\n"
  },
  {
    "path": "647-palindromic-substrings/647-palindromic-substrings.java",
    "content": "class Solution {\n    public int countSubstrings(String s) {\n        char[] cs = s.toCharArray();\n        int res = 0;\n        for(int i = 0;i<s.length(); i++){\n            //odd cases\n            for(int a = i, b = i; a >= 0 && b < s.length(); a --, b ++){\n                if(cs[a] != cs[b])\n                    break;\n                res++;\n            }\n            //even cases\n            for(int a = i, b = i + 1; a >= 0 && b < s.length(); a --, b ++){\n                if(cs[a] != cs[b])\n                    break;\n                res ++;\n            }\n        }\n        return res;\n    }\n}"
  },
  {
    "path": "647-palindromic-substrings/NOTES.md",
    "content": "​"
  },
  {
    "path": "653-two-sum-iv-input-is-a-bst/653-two-sum-iv-input-is-a-bst.java",
    "content": "public class Solution {\n    public boolean findTarget(TreeNode root, int k) {\n        return dfs(root, root, k);\n    }\n    private boolean dfs(TreeNode root, TreeNode cur, int target) {\n        if(cur == null) return false;\n        return search(root, cur, target - cur.val) ||\n               dfs(root, cur.left, target) ||\n               dfs(root, cur.right, target);\n    }\n    private boolean search(TreeNode root, TreeNode cur, int target) {\n        if(root == null) return false;\n        return (root.val == target && cur != root)||\n               (target > root.val && search(root.right, cur, target)) || \n               (target < root.val && search(root.left, cur, target));\n    }\n}"
  },
  {
    "path": "653-two-sum-iv-input-is-a-bst/NOTES.md",
    "content": "​"
  },
  {
    "path": "653-two-sum-iv-input-is-a-bst/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/two-sum-iv-input-is-a-bst/\">653. Two Sum IV - Input is a BST</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a Binary Search Tree and a target number <code>k</code>, return <em><code>true</code> if there exist two elements in the BST such that their sum is equal to the given target</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/21/sum_tree_1.jpg\" style=\"width: 400px; height: 229px;\">\n<pre><strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9\n<strong>Output:</strong> true\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/21/sum_tree_2.jpg\" style=\"width: 400px; height: 229px;\">\n<pre><strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>4</sup>&nbsp;&lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li>\n\t<li><code>-10<sup>5</sup>&nbsp;&lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "658-find-k-closest-elements/658-find-k-closest-elements.java",
    "content": "class Solution {\n    public List<Integer> findClosestElements(int[] arr, int k, int x) {\n        List<Integer> ans=new ArrayList<>();\n        int idx=binSea(arr,x);\n        int l=idx;\n        int h=idx;\n        while(k>0){\n            if(l==h){\n                ans.add(arr[l]);\n                k--;\n                l--;\n                h++;\n            }else{\n                int lefty=l<0?Integer.MAX_VALUE:Math.abs(x-arr[l]);\n                int righty=h<arr.length?Math.abs(x-arr[h]):Integer.MAX_VALUE;\n                if(lefty>righty){\n                    ans.add(arr[h]);\n                    h++;\n                    k--;\n                }else{\n                    ans.add(arr[l]);\n                    l--;\n                    k--;\n                }\n            }\n        }\n        Collections.sort(ans);\n        return ans;\n    }\n    public int binSea(int[]arr,int x){\n        int diff=Integer.MAX_VALUE;\n        int idx=-1;\n        for(int i=0;i<arr.length;i++){\n            if(Math.abs(x-arr[i])<diff){\n                diff=Math.abs(x-arr[i]);\n                idx=i;\n            }\n        }\n        return idx;\n    }\n}"
  },
  {
    "path": "658-find-k-closest-elements/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-k-closest-elements/\">658. Find K Closest Elements</a></h2><h3>Medium</h3><hr><div><p>Given a <strong>sorted</strong> integer array <code>arr</code>, two integers <code>k</code> and <code>x</code>, return the <code>k</code> closest integers to <code>x</code> in the array. The result should also be sorted in ascending order.</p>\n\n<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>\n\n<ul>\n\t<li><code>|a - x| &lt; |b - x|</code>, or</li>\n\t<li><code>|a - x| == |b - x|</code> and <code>a &lt; b</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> arr = [1,2,3,4,5], k = 4, x = 3\n<strong>Output:</strong> [1,2,3,4]\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> arr = [1,2,3,4,5], k = 4, x = -1\n<strong>Output:</strong> [1,2,3,4]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= arr.length</code></li>\n\t<li><code>1 &lt;= arr.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>\n\t<li><code>-10<sup>4</sup> &lt;= arr[i], x &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "659-split-array-into-consecutive-subsequences/659-split-array-into-consecutive-subsequences.cpp",
    "content": "class Solution {\npublic:\n    bool isPossible(vector<int>& nums) {\n\n        unordered_map<int,int> available, required;\n\n        for(int it : nums)\n            available[it]++;\n\n        for(int it : nums)\n        {\n            if(available[it] <= 0)\n                continue;\n\n            else if(required[it] > 0)\n            {\n                available[it]--;\n                required[it]--;\n                required[it+1]++;\n            }\n\n            else if(available[it] > 0 and available[it+1] > 0 and available[it+2] > 0)\n            {\n                available[it]--;\n                available[it+1]--;\n                available[it+2]--;\n                required[it+3]++;\n            }\n\n            else\n                return false;\n        }\n\n        return true;\n    }\n};\n"
  },
  {
    "path": "659-split-array-into-consecutive-subsequences/659-split-array-into-consecutive-subsequences.java",
    "content": "class Solution {\n    public boolean isPossible(int[] nums) {\n        Map<Integer,Integer>count=new HashMap<>();\n        for(int i:nums){\n            count.put(i,count.getOrDefault(i,0)+1);\n        }\n        Map<Integer,Integer> end=new HashMap<>();\n        for(int i:nums){\n            if(count.get(i)>0){\n                count.put(i,count.get(i)-1);\n                if(end.containsKey(i-1) && end.get(i-1)>0){\n                    end.put(i,end.getOrDefault(i,0)+1);\n                    end.put(i-1,end.get(i-1)-1);\n                }else if(count.containsKey(i+1) && count.containsKey(i+2) && count.get(i+1)>0 && count.get(i+2)>0){\n                    count.put(i+1,count.get(i+1)-1);\n                    count.put(i+2,count.get(i+2)-1);\n                    end.put(i+2,end.getOrDefault(i+2,0)+1);\n                }else{\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "659-split-array-into-consecutive-subsequences/NOTES.md",
    "content": "​"
  },
  {
    "path": "659-split-array-into-consecutive-subsequences/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/split-array-into-consecutive-subsequences/\">659. Split Array into Consecutive Subsequences</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>nums</code> that is <strong>sorted in non-decreasing order</strong>.</p>\n\n<p>Determine if it is possible to split <code>nums</code> into <strong>one or more subsequences</strong> such that <strong>both</strong> of the following conditions are true:</p>\n\n<ul>\n\t<li>Each subsequence is a <strong>consecutive increasing sequence</strong> (i.e. each integer is <strong>exactly one</strong> more than the previous integer).</li>\n\t<li>All subsequences have a length of <code>3</code><strong> or more</strong>.</li>\n</ul>\n\n<p>Return <code>true</code><em> if you can split </em><code>nums</code><em> according to the above conditions, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>A <strong>subsequence</strong> 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., <code>[1,3,5]</code> is a subsequence of <code>[<u>1</u>,2,<u>3</u>,4,<u>5</u>]</code> while <code>[1,3,2]</code> is not).</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,3,4,5]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> nums can be split into the following subsequences:\n[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,4,5] --&gt; 1, 2, 3\n[1,2,3,<strong><u>3</u></strong>,<strong><u>4</u></strong>,<strong><u>5</u></strong>] --&gt; 3, 4, 5\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,3,4,4,5,5]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> nums can be split into the following subsequences:\n[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,<strong><u>4</u></strong>,4,<strong><u>5</u></strong>,5] --&gt; 1, 2, 3, 4, 5\n[1,2,3,<strong><u>3</u></strong>,4,<strong><u>4</u></strong>,5,<strong><u>5</u></strong>] --&gt; 3, 4, 5\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,4,4,5]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> It is impossible to split nums into consecutive increasing subsequences of length 3 or more.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>\n</ul>\n</div>"
  },
  {
    "path": "665-non-decreasing-array/665-non-decreasing-array.java",
    "content": "class Solution {\n\tpublic boolean checkPossibility(int[] arr) {\n\t\tint index = helper(arr);\n\t\tif (index == -1) {\n\t\t\treturn true;\n\t\t}\n\t\tint temp = arr[index];\n\t\tarr[index] = arr[index + 1];\n\t\tif (helper(arr) == -1) {\n\t\t\treturn true;\n\t\t}\n\n\t\tarr[index] = temp;\n\t\tarr[index + 1] = temp;\n\t\tif (helper(arr) == -1) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic int helper(int[] arr) {\n\t\tfor (int i = 0; i < arr.length - 1; i++) {\n\t\t\tif (arr[i] > arr[i + 1]) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n}"
  },
  {
    "path": "665-non-decreasing-array/NOTES.md",
    "content": "​"
  },
  {
    "path": "665-non-decreasing-array/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/non-decreasing-array/\">665. Non-decreasing Array</a></h2><h3>Medium</h3><hr><div><p>Given an array <code>nums</code> with <code>n</code> integers, your task is to check if it could become non-decreasing by modifying <strong>at most one element</strong>.</p>\n\n<p>We define an array is non-decreasing if <code>nums[i] &lt;= nums[i + 1]</code> holds for every <code>i</code> (<strong>0-based</strong>) such that (<code>0 &lt;= i &lt;= n - 2</code>).</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [4,2,3]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> You could modify the first <code>4</code> to <code>1</code> to get a non-decreasing array.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [4,2,1]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> You can't get a non-decreasing array by modify at most one element.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "669-trim-a-binary-search-tree/669-trim-a-binary-search-tree.java",
    "content": "/**\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 trimBST(TreeNode root, int low, int high) {\n        if(root==null)return null;\n        if(root.val<low){\n            return trimBST(root.right,low,high);\n        }\n        if(root.val>high){\n            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    }\n}"
  },
  {
    "path": "669-trim-a-binary-search-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "669-trim-a-binary-search-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/trim-a-binary-search-tree/\">669. Trim a Binary Search Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> 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 <strong>unique answer</strong>.</p>\n\n<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg\" style=\"width: 450px; height: 126px;\">\n<pre><strong>Input:</strong> root = [1,0,2], low = 1, high = 2\n<strong>Output:</strong> [1,null,2]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg\" style=\"width: 450px; height: 277px;\">\n<pre><strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3\n<strong>Output:</strong> [3,2,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>The value of each node in the tree is <strong>unique</strong>.</li>\n\t<li><code>root</code> is guaranteed to be a valid binary search tree.</li>\n\t<li><code>0 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "680-valid-palindrome-ii/680-valid-palindrome-ii.java",
    "content": "class Solution {\n    public boolean validPalindrome(String s) {\n        \n        int len = s.length();\n        \n        if(len <= 2) \n            return true;\n        \n        byte[] chars = s.getBytes();\n        \n        for(int i=0,j=len-1; i<j; i++, j--) {\n            if(chars[i] != chars[j]) {\n                return (valid(chars,i,j-1)) || (valid(chars,i+1,j));\n            }\n        }\n        return true;\n\n    }\n    boolean valid(byte[] chars, int i, int j) {\n        for(;i<j; i++, j--) {\n            if(chars[i] != chars[j])\n                return false;\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "680-valid-palindrome-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "680-valid-palindrome-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/valid-palindrome-ii/\">680. Valid Palindrome II</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code>, return <code>true</code> <em>if the </em><code>s</code><em> can be palindrome after deleting <strong>at most one</strong> character from it</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"aba\"\n<strong>Output:</strong> true\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"abca\"\n<strong>Output:</strong> true\n<strong>Explanation:</strong> You could delete the character 'c'.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"abc\"\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "682-baseball-game/682-baseball-game.java",
    "content": "class Solution {\n    public int calPoints(String[] ops) {\n        Deque<Integer> st=new ArrayDeque<>();\n        for(int i=0;i<ops.length;i++){\n            String s=ops[i];\n            if(!s.equals(\"C\") && !s.equals(\"D\") && !s.equals(\"+\")){\n                st.push(Integer.parseInt(s));\n            }else{\n                if(s.equals(\"C\")){\n                    st.pop();\n                }else if(s.equals(\"D\")){\n                    int ele=2*st.peek();\n                    st.push(ele);\n                }else{\n                    int sec=st.pop();\n                    int fis=st.pop();\n                    int thir=fis+sec;\n                    st.push(fis);\n                    st.push(sec);\n                    st.push(thir);\n                }\n            }\n        }\n        int ans=0;\n        while(!st.isEmpty()){\n            ans+=st.pop();\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "682-baseball-game/NOTES.md",
    "content": "​"
  },
  {
    "path": "682-baseball-game/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/baseball-game/\">682. Baseball Game</a></h2><h3>Easy</h3><hr><div><p>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.</p>\n\n<p>At the beginning of the game, you start with an empty record. You are given a list of strings <code>ops</code>, where <code>ops[i]</code> is the <code>i<sup>th</sup></code> operation you must apply to the record and is one of the following:</p>\n\n<ol>\n\t<li>An integer <code>x</code> - Record a new score of <code>x</code>.</li>\n\t<li><code>\"+\"</code> - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.</li>\n\t<li><code>\"D\"</code> - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.</li>\n\t<li><code>\"C\"</code> - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.</li>\n</ol>\n\n<p>Return <em>the sum of all the scores on the record</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]\n<strong>Output:</strong> 30\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\n<strong>Output:</strong> 27\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> ops = [\"1\"]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= ops.length &lt;= 1000</code></li>\n\t<li><code>ops[i]</code> is <code>\"C\"</code>, <code>\"D\"</code>, <code>\"+\"</code>, or a string representing an integer in the range <code>[-3 * 10<sup>4</sup>, 3 * 10<sup>4</sup>]</code>.</li>\n\t<li>For operation <code>\"+\"</code>, there will always be at least two previous scores on the record.</li>\n\t<li>For operations <code>\"C\"</code> and <code>\"D\"</code>, there will always be at least one previous score on the record.</li>\n</ul>\n</div>"
  },
  {
    "path": "695-max-area-of-island/695-max-area-of-island.java",
    "content": "class Solution {\n    public int maxAreaOfIsland(int[][] grid) {\n\n        int max=0;\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                    int area=iarea(grid,i,j);\n                    if(area >max)\n                        max=area;\n                }\n            }\n        }\n        return max;\n    }\n    public static int iarea(int [][]grid,int i,int j){\n        if(i<grid.length && j<grid[0].length && i>=0 &&  j>=0 && grid[i][j]==1){\n            grid[i] [j]   =0;\n            int up=iarea(grid,i-1,j);\n            int down=iarea(grid, i+1,j);\n            int left=iarea(grid, i,j-1);\n            int right=iarea(grid,i,j+1);\n            return 1+left+right+up+down;\n        }\n     return 0;       \n    }\n}"
  },
  {
    "path": "695-max-area-of-island/NOTES.md",
    "content": "​"
  },
  {
    "path": "695-max-area-of-island/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/max-area-of-island/\">695. Max Area of Island</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>m x n</code> binary matrix <code>grid</code>. An island is a group of <code>1</code>'s (representing land) connected <strong>4-directionally</strong> (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.</p>\n\n<p>The <strong>area</strong> of an island is the number of cells with a value <code>1</code> in the island.</p>\n\n<p>Return <em>the maximum <strong>area</strong> of an island in </em><code>grid</code>. If there is no island, return <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg\" style=\"width: 500px; height: 310px;\">\n<pre><strong>Input:</strong> 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]]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The answer is not 11, because the island must be connected 4-directionally.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> grid = [[0,0,0,0,0,0,0,0]]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "695-max-area-of-island/SolutionCode.cpp",
    "content": "/*\n  Approach: Since we have to find the maximum Island Area, so for if have any square Island we would consider it's adjacent(Top, Bottom, Left, Right), if they have \n   value 1(which will mean it's land), similarily we would check thier adjacent square positions, so on...., now we could observe here that once a land position is\n   picked then we have to continue searching for land positon in all 4 directions of square, after that only total Island area could be found, then we move to another\n   position which is land and also not part of any previous calculated(Traversed) Islands,\n   \n By Observing above it is quite clear that we need to apply, DFS algorithm.\n\n*/\n\n\n// Code Below : \n\nclass Solution {\npublic:\nint travelMap(int r, int c, vector<vector<int>> &grid){\n    if(r<0 || c<0 || r>=grid.size() || c>=grid[0].size() || grid[r][c]==0){\n        return 0;\n    }\n    \n  // So as to make it marked as visited position.\n    grid[r][c] = 0;\n    \n    // int Down = travelMap(r+1, c, grid);\n    // int Right = travelMap(r, c+1, grid);\n    // int Up = travelMap(r-1, c, grid);\n    // int Left = travelMap(r, c-1, grid);\n  \n  \n  // 1 extra area added for the Area of Current position  \n    return 1 + travelMap(r+1, c, grid) + travelMap(r, c+1, grid) + \n        travelMap(r-1, c, grid) + travelMap(r, c-1, grid);\n}    \n    int maxAreaOfIsland(vector<vector<int>>& grid) {\n        int mxArea = 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]==1){\n                    mxArea = max(mxArea, travelMap(i,j, grid));\n                }\n            }\n        }\n        \n        return mxArea;\n    }\n};\n\n/*\n  Time Complexity : O(mn)\n  Space Complexity : O(1)\n*/\n"
  },
  {
    "path": "698-partition-to-k-equal-sum-subsets/698-partition-to-k-equal-sum-subsets.java",
    "content": "class Solution {\n    public boolean canPartitionKSubsets(int[] arr, int k) {\n        int n = arr.length;\n        int sum=0;\n        for(int i:arr) sum+=i;\n        if(sum%k!=0) return false;\n        Arrays.sort(arr);\n        \n        return (dfs(n-1,arr,new int[k],k,sum/k));\n    }\n    public boolean dfs(int ind,int[] arr,int[] sum, int k,int target){\n        if(ind == -1)return true;\n        for(int i=0;i<k;i++){\n            if((sum[i] + arr[ind]>target) || (i>0 && sum[i] == sum[i-1]))continue;\n            \n            sum[i]+=arr[ind];\n            \n            if(dfs(ind-1,arr,sum,k,target))return true;\n            sum[i]-= arr[ind];\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "698-partition-to-k-equal-sum-subsets/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/partition-to-k-equal-sum-subsets/\">698. Partition to K Equal Sum Subsets</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> if it is possible to divide this array into <code>k</code> non-empty subsets whose sums are all equal.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [4,3,2,3,5,2,1], k = 4\n<strong>Output:</strong> true\n<strong>Explanation:</strong> It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,4], k = 3\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= nums.length &lt;= 16</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li>The frequency of each element is in the range <code>[1, 4]</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "7 Segment Display.java",
    "content": "class Solution {\n    static String sevenSegments(String S, int N) {\n        int sum=0;\n        int nums[]={6,2,5,5,4,5,6,3,7,5};\n        for(int i=0;i<N;i++){\n            char ch=S.charAt(i);\n            int y=Integer.parseInt(ch+\"\");\n            sum+=nums[y];\n        }\n        int j=1;\n        StringBuilder s1=new StringBuilder();\n        while(j<N && (sum-6)>=2*(N-j)){\n            s1.append(\"0\");\n            sum-=6;\n            j++;\n        }\n        while(j<=N && sum>0){\n            sum-=2;\n            if(j==N && sum!=0){\n                sum+=2;\n                if(sum==5)\n                    s1.append(\"2\");\n                else if(sum==4)\n                    s1.append(\"4\");\n                else if(sum==3)\n                    s1.append(\"7\");\n                else if(sum==7)\n                    s1.append(\"8\");\n                break;\n            }\n            else{\n                s1.append(\"1\");\n            }\n            j++;\n        }\n        return s1+\"\";\n    }\n};\n"
  },
  {
    "path": "70-climbing-stairs/70-climbing-stairs.java",
    "content": "class Solution {\n    public int climbStairs(int n) {\n        \n        int dp[] = new int[n+1];\n        dp[n] = 1;\n        for(int i = n; i>=0; i--){\n            if(i+1<=n){\n                dp[i] = dp[i+1];\n            }\n            if(i+2<=n){\n                dp[i] = dp[i+1] + dp[i+2];\n            }\n        }\n        \n        return dp[0];\n    }\n}"
  },
  {
    "path": "70-climbing-stairs/NOTES.md",
    "content": ""
  },
  {
    "path": "70-climbing-stairs/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/climbing-stairs/\">70. Climbing Stairs</a></h2><h3>Easy</h3><hr><div><p>You are climbing a staircase. It takes <code>n</code> steps to reach the top.</p>\n\n<p>Each time you can either climb <code>1</code> or <code>2</code> steps. In how many distinct ways can you climb to the top?</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 2\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 3\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 45</code></li>\n</ul>\n</div>"
  },
  {
    "path": "700-search-in-a-binary-search-tree/700-search-in-a-binary-search-tree.java",
    "content": "/**\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 searchBST(TreeNode root, int val) {\n        if(root==null)return null;\n        if(root.val>val){\n            return searchBST(root.left,val);\n        }else if(root.val<val){\n            return searchBST(root.right,val);\n        }else{\n            return root;\n        }\n    }\n}"
  },
  {
    "path": "700-search-in-a-binary-search-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "700-search-in-a-binary-search-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/search-in-a-binary-search-tree/\">700. Search in a Binary Search Tree</a></h2><h3>Easy</h3><hr><div><p>You are given the <code>root</code> of a binary search tree (BST) and an integer <code>val</code>.</p>\n\n<p>Find the node in the BST that the node's value equals <code>val</code> and return the subtree rooted with that node. If such a node does not exist, return <code>null</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg\" style=\"width: 422px; height: 302px;\">\n<pre><strong>Input:</strong> root = [4,2,7,1,3], val = 2\n<strong>Output:</strong> [2,1,3]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg\" style=\"width: 422px; height: 302px;\">\n<pre><strong>Input:</strong> root = [4,2,7,1,3], val = 5\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 5000]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>7</sup></code></li>\n\t<li><code>root</code> is a binary search tree.</li>\n\t<li><code>1 &lt;= val &lt;= 10<sup>7</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "703-kth-largest-element-in-a-stream/703-kth-largest-element-in-a-stream.py",
    "content": "class KthLargest:\n\n    def __init__(self, k: int, nums: List[int]):\n        self.k=k\n        self.nums=nums\n        \n\n    def add(self, val: int) -> int:\n        self.nums.append(val)\n        self.nums.sort()\n        return self.nums[len(self.nums)-self.k]\n\n\n# Your KthLargest object will be instantiated and called as such:\n# obj = KthLargest(k, nums)\n# param_1 = obj.add(val)"
  },
  {
    "path": "703-kth-largest-element-in-a-stream/NOTES.md",
    "content": "​"
  },
  {
    "path": "704-binary-search/704-binary-search.java",
    "content": "class Solution {\n    public int search(int[] nums, int target) {\n        int start=0;\n        int end=nums.length-1;\n        while(start<=end){\n            int mid=(start+end)/2;\n            if(nums[mid]==target){\n                return mid;   \n            }else if(nums[mid]>target){\n                end=mid-1;\n            }else{\n                start=mid+1;\n            }\n        }\n        return -1;\n    }\n}"
  },
  {
    "path": "704-binary-search/NOTES.md",
    "content": "​"
  },
  {
    "path": "704-binary-search/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-search/\">704. Binary Search</a></h2><h3>Easy</h3><hr><div><p>Given an array of integers <code>nums</code> which is sorted in ascending order, and an integer <code>target</code>, write a function to search <code>target</code> in <code>nums</code>. If <code>target</code> exists, then return its index. Otherwise, return <code>-1</code>.</p>\n\n<p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [-1,0,3,5,9,12], target = 9\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> 9 exists in nums and its index is 4\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [-1,0,3,5,9,12], target = 2\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> 2 does not exist in nums so return -1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt; nums[i], target &lt; 10<sup>4</sup></code></li>\n\t<li>All the integers in <code>nums</code> are <strong>unique</strong>.</li>\n\t<li><code>nums</code> is sorted in ascending order.</li>\n</ul>\n</div>"
  },
  {
    "path": "705-design-hashset/705-design-hashset.java",
    "content": "class MyHashSet {\n    boolean[] arr;\n    public MyHashSet() {\n        arr=new boolean[1000001];\n    }\n    \n    public void add(int key) {\n        arr[key]=true;\n    }\n    \n    public void remove(int key) {\n        arr[key]=false;\n    }\n    \n    public boolean contains(int key) {\n        return arr[key];\n    }\n}\n\n/**\n * Your MyHashSet object will be instantiated and called as such:\n * MyHashSet obj = new MyHashSet();\n * obj.add(key);\n * obj.remove(key);\n * boolean param_3 = obj.contains(key);\n */"
  },
  {
    "path": "705-design-hashset/NOTES.md",
    "content": "​"
  },
  {
    "path": "705-design-hashset/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/design-hashset/\">705. Design HashSet</a></h2><h3>Easy</h3><hr><div><p>Design a HashSet without using any built-in hash table libraries.</p>\n\n<p>Implement <code>MyHashSet</code> class:</p>\n\n<ul>\n\t<li><code>void add(key)</code> Inserts the value <code>key</code> into the HashSet.</li>\n\t<li><code>bool contains(key)</code> Returns whether the value <code>key</code> exists in the HashSet or not.</li>\n\t<li><code>void remove(key)</code> Removes the value <code>key</code> in the HashSet. If <code>key</code> does not exist in the HashSet, do nothing.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]\n<strong>Output</strong>\n[null, null, null, true, false, null, true, null, false]\n\n<strong>Explanation</strong>\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)</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= key &lt;= 10<sup>6</sup></code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code>, <code>remove</code>, and <code>contains</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "706-design-hashmap/706-design-hashmap.java",
    "content": "class MyHashMap {\n    int[]map;\n    public MyHashMap() {\n        map=new int[1000001];\n        Arrays.fill(map,-1);\n    }\n    \n    public void put(int key, int value) {\n        map[key]=value;\n    }\n    \n    public int get(int key) {\n        if(map[key]==-1)return -1;\n        return map[key];\n    }\n    \n    public void remove(int key) {\n        map[key]=-1;\n    }\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 */"
  },
  {
    "path": "706-design-hashmap/NOTES.md",
    "content": "​"
  },
  {
    "path": "706-design-hashmap/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/design-hashmap/\">706. Design HashMap</a></h2><h3>Easy</h3><hr><div><p>Design a HashMap without using any built-in hash table libraries.</p>\n\n<p>Implement the <code>MyHashMap</code> class:</p>\n\n<ul>\n\t<li><code>MyHashMap()</code> initializes the object with an empty map.</li>\n\t<li><code>void put(int key, int value)</code> inserts a <code>(key, value)</code> pair into the HashMap. If the <code>key</code> already exists in the map, update the corresponding <code>value</code>.</li>\n\t<li><code>int get(int key)</code> returns the <code>value</code> to which the specified <code>key</code> is mapped, or <code>-1</code> if this map contains no mapping for the <code>key</code>.</li>\n\t<li><code>void remove(key)</code> removes the <code>key</code> and its corresponding <code>value</code> if the map contains the mapping for the <code>key</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"MyHashMap\", \"put\", \"put\", \"get\", \"get\", \"put\", \"get\", \"remove\", \"get\"]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]\n<strong>Output</strong>\n[null, null, null, 1, -1, null, 1, null, -1]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= key, value &lt;= 10<sup>6</sup></code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>put</code>, <code>get</code>, and <code>remove</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "713_Subarray_Product_Less_Than_K.cpp",
    "content": "class Solution {\npublic:\n    int numSubarrayProductLessThanK(vector<int>& n, int k) {\n        if(k<=1){\n            return 0;\n        }\n        int product=1,j=0,sub=0;\n        for(int i =0;i<n.size();i++){\n            product *=n[i];\n            while(product>=k){\n                product=product/n[j++];\n            }\n            sub+=i-j+1;\n        }\n        return sub;\n    }\n};\n"
  },
  {
    "path": "718-Maximum-Length-of-Repeated-Subarray.cpp",
    "content": "int findLength(vector<int>& nums1, vector<int>& nums2) \n    {\n        int n=nums1.size();\n        int m=nums2.size();\n        //INITIALIZATION\n        vector<vector<int>>dp(n+1,vector<int>(m+1));\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]=0;\n        ////////////\n        //MAIN LOGIC\n        for(int i=1;i<=n;++i)\n            for(int j=1;j<=m;++j)\n            {\n                if(nums1[i-1]==nums2[j-1])//IF CONTINIOUS, add 1 to previous\n                    dp[i][j]=dp[i-1][j-1]+1;\n                else //IF DISCONTINIOUS,then 0\n                    dp[i][j]=0;\n            }\n        //FINDING THE MAXIMUM LENGTH FROM DP MATRIX\n        int maxi=INT_MIN;\n        for(int i=0;i<=n;++i)\n            for(int j=0;j<=m;++j)\n                maxi=max(maxi,dp[i][j]);\n        return maxi;\n    }\n"
  },
  {
    "path": "718-maximum-length-of-repeated-subarray/718-maximum-length-of-repeated-subarray.java",
    "content": "import java.math.BigInteger;\n\nclass Solution {\n    int P = 113;\n    int MOD = 1_000_000_007;\n    int Pinv = BigInteger.valueOf(P).modInverse(BigInteger.valueOf(MOD)).intValue();\n\n    private int[] rolling(int[] source, int length) {\n        int[] ans = new int[source.length - length + 1];\n        long h = 0, power = 1;\n        if (length == 0) return ans;\n        for (int i = 0; i < source.length; ++i) {\n            h = (h + source[i] * power) % MOD;\n            if (i < length - 1) {\n                power = (power * P) % MOD;\n            } else {\n                ans[i - (length - 1)] = (int) h;\n                h = (h - source[i - (length - 1)]) * Pinv % MOD;\n                if (h < 0) h += MOD;\n            }\n        }\n        return ans;\n    }\n\n    private boolean check(int guess, int[] A, int[] B) {\n        Map<Integer, List<Integer>> hashes = new HashMap();\n        int k = 0;\n        for (int x: rolling(A, guess)) {\n            hashes.computeIfAbsent(x, z -> new ArrayList()).add(k++);\n        }\n        int j = 0;\n        for (int x: rolling(B, guess)) {\n            for (int i: hashes.getOrDefault(x, new ArrayList<Integer>()))\n                if (Arrays.equals(Arrays.copyOfRange(A, i, i+guess),\n                                  Arrays.copyOfRange(B, j, j+guess))) {\n                    return true;\n                }\n            j++;\n        }\n        return false;\n    }\n\n    public int findLength(int[] A, int[] B) {\n        int lo = 0, hi = Math.min(A.length, B.length) + 1;\n        while (lo < hi) {\n            int mi = (lo + hi) / 2;\n            if (check(mi, A, B)) lo = mi + 1;\n            else hi = mi;\n        }\n        return lo - 1;\n    }\n}"
  },
  {
    "path": "718-maximum-length-of-repeated-subarray/NOTES.md",
    "content": "​"
  },
  {
    "path": "718-maximum-length-of-repeated-subarray/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-length-of-repeated-subarray/\">718. Maximum Length of Repeated Subarray</a></h2><h3>Medium</h3><hr><div><p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>the maximum length of a subarray that appears in <strong>both</strong> arrays</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The repeated subarray with maximum length is [3,2,1].\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]\n<strong>Output:</strong> 5\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "718-maximum-length-of-repeated-subarray/Solved Using DP.java",
    "content": "class Solution {\n    public int findLength(int[] nums1, int[] nums2) {\n        int n = nums1.length;\n        int m = nums2.length;\n        \n        int[][] dp = new int[n+1][m+1];\n        \n        int ans = 0;\n        \n        for(int i = 1; i <= n; i++) {\n            for(int j = 1; j <= m; j++) {\n                if(nums1[i-1]==nums2[j-1]){\n                  dp[i][j] = dp[i-1][j-1] + 1;\n                  ans = Math.max(ans, dp[i][j]);  \n                }\n                else dp[i][j] = 0;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "718. Maximum Length of Repeated Subarray/718. Maximum Length of Repeated Subarray.cpp",
    "content": "class Solution {\npublic:\n    int findLength(vector<int>& nums1, vector<int>& nums2) {\n        // same as longest common substring\n        int n = nums1.size(), m = nums2.size();\n        int dp[n+1][m+1];\n        \n        for(int i=0;i<=n;i++){\n            for(int j=0;j<=m;j++){\n                if(i==0 || j==0) dp[i][j] = 0;\n            }\n        }\n        \n        int res = 0;\n        \n        for(int i=1;i<=n;i++){\n            for(int j=1;j<=m;j++){\n                if(nums1[i-1] == nums2[j-1]){\n                    dp[i][j] = 1 + dp[i-1][j-1];\n                    res = max(res, dp[i][j]);\n                }else{\n                    dp[i][j] = 0;\n                }\n            }\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "718. Maximum Length of Repeated Subarray lc med s20.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    int findLength(vector<int>& nums1, vector<int>& nums2) {\n        //         dp space optmized\n        int n = nums1.size(), m = nums2.size(), res = 0;\n//         swap to ensure n >m\n        if(n<m){\n            swap(nums1, nums2);\n            swap(n,m);\n        }\n//         dp records curr dp states\n//         dp2 records the prev dp states\n        vector<int> dp(n+1), dp2(n+1);\n        for(int i = 1; i<=n; i++){\n            for(int j =1; j<=m; j++){\n                if(nums1[i-1] == nums2[j-1]){\n//                     extend from the prev dp state\n                    dp[j] = dp2[j-1]+1;\n                    \n                }else\n//                     reset to 0\n                    dp[j] =0;\n//             record the max len\n            res = max(res, dp[j]);\n            }\n//             the curr state now becomes the prev state for nxt round\n            dp2 = dp;\n            \n        }\n        return res;\n    }\n};"
  },
  {
    "path": "724-find-pivot-index/724-find-pivot-index.java",
    "content": "class Solution {\n    public int pivotIndex(int[] nums) {\n        int sum=0;\n        for(int n:nums){\n            sum+=n;\n        }\n        int left=0;\n        for(int i=0;i<nums.length;i++){\n            sum -=nums[i];\n            if(left==sum){\n                return i;\n            }\n            left +=nums[i];\n        }\n        return -1;\n    }\n}"
  },
  {
    "path": "724-find-pivot-index/NOTES.md",
    "content": "​"
  },
  {
    "path": "724-find-pivot-index/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-pivot-index/\">724. Find Pivot Index</a></h2><h3>Easy</h3><hr><div><p>Given an array of integers <code>nums</code>, calculate the <strong>pivot index</strong> of this array.</p>\n\n<p>The <strong>pivot index</strong> is the index where the sum of all the numbers <strong>strictly</strong> to the left of the index is equal to the sum of all the numbers <strong>strictly</strong> to the index's right.</p>\n\n<p>If the index is on the left edge of the array, then the left sum is <code>0</code> because there are no elements to the left. This also applies to the right edge of the array.</p>\n\n<p>Return <em>the <strong>leftmost pivot index</strong></em>. If no such index exists, return -1.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,7,3,6,5,6]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong>\nThere is no index that satisfies the conditions in the problem statement.</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums = [2,1,-1]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as&nbsp;1991:&nbsp;<a href=\"https://leetcode.com/problems/find-the-middle-index-in-array/\" target=\"_blank\">https://leetcode.com/problems/find-the-middle-index-in-array/</a></p>\n</div>"
  },
  {
    "path": "729-my-calendar-i/729-my-calendar-i.java",
    "content": "class MyCalendar {\n\n    class TreeNode{\n        TreeNode left;\n        TreeNode right;\n        int start;\n        int end;\n        TreeNode(int start,int end){\n            this.start = start;\n            this.end = end;\n        }\n    }\n    TreeNode root;\n    public MyCalendar() {\n       \n    }\n    \n    public boolean book(int start, int end) {\n       if(root == null){\n           root = new TreeNode(start,end);\n           return true;\n       }\n       return insert(root,start,end);\n    }\n    \n    private boolean insert(TreeNode root, int start, int end){\n        if(end <= root.start){\n            if(root.left == null){\n                root.left = new TreeNode(start,end);\n                return true;\n            }\n            return insert(root.left,start,end);\n        }\n        if(start >= root.end){\n            if(root.right == null){\n                root.right = new TreeNode(start,end);\n                return true;\n            }\n            return insert(root.right,start,end);\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "729-my-calendar-i/NOTES.md",
    "content": "25-31\n33-40\n47-49\n​"
  },
  {
    "path": "729-my-calendar-i/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/my-calendar-i/\">729. My Calendar I</a></h2><h3>Medium</h3><hr><div><p>You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a <strong>double booking</strong>.</p>\n\n<p>A <strong>double booking</strong> happens when two events have some non-empty intersection (i.e., some moment is common to both events.).</p>\n\n<p>The event can be represented as a pair of integers <code>start</code> and <code>end</code> that represents a booking on the half-open interval <code>[start, end)</code>, the range of real numbers <code>x</code> such that <code>start &lt;= x &lt; end</code>.</p>\n\n<p>Implement the <code>MyCalendar</code> class:</p>\n\n<ul>\n\t<li><code>MyCalendar()</code> Initializes the calendar object.</li>\n\t<li><code>boolean book(int start, int end)</code> Returns <code>true</code> if the event can be added to the calendar successfully without causing a <strong>double booking</strong>. Otherwise, return <code>false</code> and do not add the event to the calendar.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"MyCalendar\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [15, 25], [20, 30]]\n<strong>Output</strong>\n[null, true, false, true]\n\n<strong>Explanation</strong>\nMyCalendar myCalendar = new MyCalendar();\nmyCalendar.book(10, 20); // return True\nmyCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.\nmyCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= start &lt; end &lt;= 10<sup>9</sup></code></li>\n\t<li>At most <code>1000</code> calls will be made to <code>book</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "732-my-calendar-iii/732-my-calendar-iii.java",
    "content": "class MyCalendarThree {\n    private Map<Integer, Integer> diff;\n\n    public MyCalendarThree() {\n        diff = new TreeMap<>();\n    }\n\n    public int book(int start, int end) {\n        diff.put(start, diff.getOrDefault(start, 0) + 1);\n        diff.put(end, diff.getOrDefault(end, 0) - 1);\n        int res = 0, cur = 0;\n        for (int delta : diff.values()) {\n            cur += delta;\n            res = Math.max(res, cur);\n        }\n        return res;\n    }\n}"
  },
  {
    "path": "732-my-calendar-iii/NOTES.md",
    "content": "​"
  },
  {
    "path": "732-my-calendar-iii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/my-calendar-iii/\">732. My Calendar III</a></h2><h3>Hard</h3><hr><div><p>A <code>k</code>-booking happens when <code>k</code> events have some non-empty intersection (i.e., there is some time that is common to all <code>k</code> events.)</p>\n\n<p>You are given some events <code>[start, end)</code>, after each given event, return an integer <code>k</code> representing the maximum <code>k</code>-booking between all the previous events.</p>\n\n<p>Implement the <code>MyCalendarThree</code> class:</p>\n\n<ul>\n\t<li><code>MyCalendarThree()</code> Initializes the object.</li>\n\t<li><code>int book(int start, int end)</code> Returns an integer <code>k</code> representing the largest integer such that there exists a <code>k</code>-booking in the calendar.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\n<strong>Output</strong>\n[null, 1, 1, 2, 3, 3, 3]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= start &lt; end &lt;= 10<sup>9</sup></code></li>\n\t<li>At most <code>400</code> calls will be made to <code>book</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "74-search-a-2d-matrix/74-search-a-2d-matrix.java",
    "content": "class Solution {\n    int x;\n    public boolean searchMatrix(int[][] matrix, int target) {\n        x=target;\n        int i=0;\n        int n=matrix.length;\n        int m=matrix[0].length;\n        while(i<n){\n            if(matrix[i][0]<=x && matrix[i][m-1]>=x){\n                return binarySearch(matrix,i);\n            }else{\n                i++;\n            }\n        }\n        return false;\n    }\n    public boolean binarySearch(int[][]matrix,int i){\n        int[]a=matrix[i];\n        int l=0;\n        int h=a.length;\n        while(l<=h){\n            int mid=(l+h)/2;\n            if(a[mid]==x){\n                return true;\n            }else if(a[mid]<x){\n                l=mid+1;\n            }else{\n                h=mid-1;\n            }\n        }\n        return false;\n    }\n}"
  },
  {
    "path": "74-search-a-2d-matrix/NOTES.md",
    "content": "​"
  },
  {
    "path": "74-search-a-2d-matrix/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/search-a-2d-matrix/\">74. Search a 2D Matrix</a></h2><h3>Medium</h3><hr><div><p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p>\n\n<ul>\n\t<li>Integers in each row are sorted from left to right.</li>\n\t<li>The first integer of each row is greater than the last integer of the previous row.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/mat.jpg\" style=\"width: 322px; height: 242px;\">\n<pre><strong>Input:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\n<strong>Output:</strong> true\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg\" style=\"width: 322px; height: 242px;\">\n<pre><strong>Input:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= matrix[i][j], target &lt;= 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "743-network-delay-time/743-network-delay-time.java",
    "content": "class Solution {\n    public int networkDelayTime(int[][] times, int n, int k) {\n        final int INF = Integer.MAX_VALUE/2;\n        \n        int[][] graph = new int[n][n];\n        for(int i = 0; i < n; i++){\n            Arrays.fill(graph[i], INF);\n        }\n        for(int t[] : times){\n            int x = t[0] - 1, y = t[1] - 1;\n            graph[x][y] = t[2];\n        }\n        int[] dist = new int[n];\n        Arrays.fill(dist, INF);\n        boolean[] visted = new boolean[n];\n        dist[k-1] = 0;\n        \n        for(int i = 0; i < n; i++){\n            int x = -1;\n            for(int y = 0; y < n; y++){\n                if(!visted[y] && (x == -1 || dist[y] < dist[x]))\n                    x = y;\n            }\n            visted[x] = true;\n            for(int y = 0; y < n; y++){\n                dist[y] = Math.min(dist[y], dist[x]+graph[x][y]);\n            }\n        }\n        \n        int ans = 0;\n        for (int i = 0; i < n; i++) {\n            ans = Math.max(ans, dist[i]);\n        }\n        \n        return ans == INF ? -1 : ans;\n\n    }\n}"
  },
  {
    "path": "743-network-delay-time/NOTES.md",
    "content": "​"
  },
  {
    "path": "743-network-delay-time/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/network-delay-time/\">743. Network Delay Time</a></h2><h3>Medium</h3><hr><div><p>You are given a network of <code>n</code> nodes, labeled from <code>1</code> to <code>n</code>. You are also given <code>times</code>, a list of travel times as directed edges <code>times[i] = (u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>)</code>, where <code>u<sub>i</sub></code> is the source node, <code>v<sub>i</sub></code> is the target node, and <code>w<sub>i</sub></code> is the time it takes for a signal to travel from source to target.</p>\n\n<p>We will send a signal from a given node <code>k</code>. Return the time it takes for all the <code>n</code> nodes to receive the signal. If it is impossible for all the <code>n</code> nodes to receive the signal, return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/05/23/931_example_1.png\" style=\"width: 217px; height: 239px;\">\n<pre><strong>Input:</strong> times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> times = [[1,2,1]], n = 2, k = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> times = [[1,2,1]], n = 2, k = 2\n<strong>Output:</strong> -1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 100</code></li>\n\t<li><code>1 &lt;= times.length &lt;= 6000</code></li>\n\t<li><code>times[i].length == 3</code></li>\n\t<li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n</code></li>\n\t<li><code>u<sub>i</sub> != v<sub>i</sub></code></li>\n\t<li><code>0 &lt;= w<sub>i</sub> &lt;= 100</code></li>\n\t<li>All the pairs <code>(u<sub>i</sub>, v<sub>i</sub>)</code> are <strong>unique</strong>. (i.e., no multiple edges.)</li>\n</ul>\n</div>"
  },
  {
    "path": "745-prefix-and-suffix-search/745-prefix-and-suffix-search.java",
    "content": "class WordFilter {\n    TrieNode trie;\n    public WordFilter(String[] words) {\n        trie = new TrieNode();\n        for (int weight = 0; weight < words.length; ++weight) {\n            String word = words[weight] + \"{\";\n            for (int i = 0; i < word.length(); ++i) {\n                TrieNode cur = trie;\n                cur.weight = weight;\n                for (int j = i; j < 2 * word.length() - 1; ++j) {\n                    int k = word.charAt(j % word.length()) - 'a';\n                    if (cur.children[k] == null)\n                        cur.children[k] = new TrieNode();\n                    cur = cur.children[k];\n                    cur.weight = weight;\n                }\n            }\n        }\n    }\n    public int f(String prefix, String suffix) {\n        TrieNode cur = trie;\n        for (char letter: (suffix + '{' + prefix).toCharArray()) {\n            if (cur.children[letter - 'a'] == null) return -1;\n            cur = cur.children[letter - 'a'];\n        }\n        return cur.weight;\n    }\n}\n\nclass TrieNode {\n    TrieNode[] children;\n    int weight;\n    public TrieNode() {\n        children = new TrieNode[27];\n        weight = 0;\n    }\n}"
  },
  {
    "path": "745-prefix-and-suffix-search/NOTES.md",
    "content": "​"
  },
  {
    "path": "745-prefix-and-suffix-search/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/prefix-and-suffix-search/\">745. Prefix and Suffix Search</a></h2><h3>Hard</h3><hr><div><p>Design a special dictionary with some words that searchs the words in it by a prefix and a suffix.</p>\n\n<p>Implement the <code>WordFilter</code> class:</p>\n\n<ul>\n\t<li><code>WordFilter(string[] words)</code> Initializes the object with the <code>words</code> in the dictionary.</li>\n\t<li><code>f(string prefix, string suffix)</code> Returns <em>the index of the word in the dictionary,</em> which has the prefix <code>prefix</code> and the suffix <code>suffix</code>. If there is more than one valid index, return <strong>the largest</strong> of them. If there is no such word in the dictionary, return <code>-1</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"WordFilter\", \"f\"]\n[[[\"apple\"]], [\"a\", \"e\"]]\n<strong>Output</strong>\n[null, 0]\n\n<strong>Explanation</strong>\nWordFilter wordFilter = new WordFilter([\"apple\"]);\nwordFilter.f(\"a\", \"e\"); // return 0, because the word at index 0 has prefix = \"a\" and suffix = 'e\".\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 15000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 10</code></li>\n\t<li><code>1 &lt;= prefix.length, suffix.length &lt;= 10</code></li>\n\t<li><code>words[i]</code>, <code>prefix</code> and <code>suffix</code> consist of lower-case English letters only.</li>\n\t<li>At most <code>15000</code> calls will be made to the function <code>f</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "746-min-cost-climbing-stairs/746-min-cost-climbing-stairs.java",
    "content": "class Solution {\n    public int minCostClimbingStairs(int[] cost) {\n        int[] mem = new int[cost.length];\n        mem[0]=cost[0];\n        mem[1]=cost[1];\n        for(int i=2;i<cost.length;i++) {\n            mem[i]=cost[i]+Math.min(mem[i-1],mem[i-2]);\n        }\n        return Math.min(mem[cost.length-1],mem[cost.length-2]);\n    }\n}"
  },
  {
    "path": "746-min-cost-climbing-stairs/NOTES.md",
    "content": "​"
  },
  {
    "path": "746-min-cost-climbing-stairs/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/min-cost-climbing-stairs/\">746. Min Cost Climbing Stairs</a></h2><h3>Easy</h3><hr><div><p>You are given an integer array <code>cost</code> where <code>cost[i]</code> is the cost of <code>i<sup>th</sup></code> step on a staircase. Once you pay the cost, you can either climb one or two steps.</p>\n\n<p>You can either start from the step with index <code>0</code>, or the step with index <code>1</code>.</p>\n\n<p>Return <em>the minimum cost to reach the top of the floor</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> cost = [10,<u>15</u>,20]\n<strong>Output:</strong> 15\n<strong>Explanation:</strong> You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> cost = [<u>1</u>,100,<u>1</u>,1,<u>1</u>,100,<u>1</u>,<u>1</u>,100,<u>1</u>]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= cost.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= cost[i] &lt;= 999</code></li>\n</ul>\n</div>"
  },
  {
    "path": "76-minimum-window-substring/76-minimum-window-substring.java",
    "content": "class Solution {\n    public String minWindow(String s, String t) {\n        int[] cs = new int[256];\n        for (char ch : t.toCharArray()) {\n            cs[ch]++;\n        }\n        int l = 0, r = 0, cnt = t.length();\n        int start = -1, end = s.length(); // substring [start, end)\n        while (r < s.length()) {\n            if (cs[s.charAt(r++)]-- > 0) {\n                cnt--;\n            }\n            while (cnt == 0) {\n                if (cs[s.charAt(l++)]++ == 0) {\n                    cnt++;\n                }\n                if (r - l + 1 < end - start) {\n                    start = l - 1;\n                    end = r;\n                }\n            }\n        }\n        return end - start > s.length() ? \"\" : s.substring(start, end);\n    }\n}"
  },
  {
    "path": "76-minimum-window-substring/NOTES.md",
    "content": "​"
  },
  {
    "path": "76-minimum-window-substring/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-window-substring/\">76. Minimum Window Substring</a></h2><h3>Hard</h3><hr><div><p>Given two strings <code>s</code> and <code>t</code> of lengths <code>m</code> and <code>n</code> respectively, return <em>the <strong>minimum window substring</strong> of </em><code>s</code><em> such that every character in </em><code>t</code><em> (<strong>including duplicates</strong>) is included in the window. If there is no such substring</em><em>, return the empty string </em><code>\"\"</code><em>.</em></p>\n\n<p>The testcases will be generated such that the answer is <strong>unique</strong>.</p>\n\n<p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"ADOBECODEBANC\", t = \"ABC\"\n<strong>Output:</strong> \"BANC\"\n<strong>Explanation:</strong> The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"a\", t = \"a\"\n<strong>Output:</strong> \"a\"\n<strong>Explanation:</strong> The entire string s is the minimum window.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"a\", t = \"aa\"\n<strong>Output:</strong> \"\"\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == s.length</code></li>\n\t<li><code>n == t.length</code></li>\n\t<li><code>1 &lt;= m, n&nbsp;&lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> and <code>t</code> consist of uppercase and lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you find an algorithm that runs in <code>O(m + n)</code> time?</div>"
  },
  {
    "path": "763-partition-labels/763-partition-labels.java",
    "content": "class Solution {\n    public List<Integer> partitionLabels(String s) {\n        List<Integer> ans = new ArrayList<>();\n        int[] lastIndex = new int[26];\n        for (int i = 0; i < 26; i++) {\n            lastIndex[i] = s.lastIndexOf('a' + i);\n        }\n        int left = 0;\n        int right;\n        while (left < s.length()) {\n            right = lastIndex[s.charAt(left) - 'a'];\n            for (int i = left; i < right; i++) {\n                right = Math.max(right, lastIndex[s.charAt(i) - 'a']);\n            }\n            ans.add(right - left + 1);  // size: right -left + 1\n            left = right + 1;\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "763-partition-labels/NOTES.md",
    "content": "​"
  },
  {
    "path": "763-partition-labels/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/partition-labels/\">763. Partition Labels</a></h2><h3>Medium</h3><hr><div><p>You are given a string <code>s</code>. We want to partition the string into as many parts as possible so that each letter appears in at most one part.</p>\n\n<p>Note that the partition is done so that after concatenating all the parts in order, the resultant string should be <code>s</code>.</p>\n\n<p>Return <em>a list of integers representing the size of these parts</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"ababcbacadefegdehijhklij\"\n<strong>Output:</strong> [9,7,8]\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"eccbbbbdec\"\n<strong>Output:</strong> [10]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 500</code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "785-is-graph-bipartite/785-is-graph-bipartite.java",
    "content": "class Solution {\n    public boolean isBipartite(int[][] graph) {\n        boolean[]vis=new boolean[100];\n        boolean[]color=new boolean[100];\n        Queue<Integer> q=new LinkedList<>();\n        for(int i=0;i<graph.length;i++){\n            if(graph[i].length==0 || vis[i]){\n                continue;\n            }\n            q.add(i);\n            vis[i]=true;\n            color[i]=true;\n            while(!q.isEmpty()){\n                int node=q.remove();\n                for(int neb:graph[node]){\n                    if(!vis[neb]){\n                        q.add(neb);\n                        vis[neb]=true;\n                        color[neb]=!color[node];\n                    }else if(color[neb]==color[node]){\n                        return false;\n                    }\n                }\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "785-is-graph-bipartite/NOTES.md",
    "content": "​"
  },
  {
    "path": "785-is-graph-bipartite/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/is-graph-bipartite/\">785. Is Graph Bipartite?</a></h2><h3>Medium</h3><hr><div><p>There is an <strong>undirected</strong> graph with <code>n</code> nodes, where each node is numbered between <code>0</code> and <code>n - 1</code>. You are given a 2D array <code>graph</code>, where <code>graph[u]</code> is an array of nodes that node <code>u</code> is adjacent to. More formally, for each <code>v</code> in <code>graph[u]</code>, there is an undirected edge between node <code>u</code> and node <code>v</code>. The graph has the following properties:</p>\n\n<ul>\n\t<li>There are no self-edges (<code>graph[u]</code> does not contain <code>u</code>).</li>\n\t<li>There are no parallel edges (<code>graph[u]</code> does not contain duplicate values).</li>\n\t<li>If <code>v</code> is in <code>graph[u]</code>, then <code>u</code> is in <code>graph[v]</code> (the graph is undirected).</li>\n\t<li>The graph may not be connected, meaning there may be two nodes <code>u</code> and <code>v</code> such that there is no path between them.</li>\n</ul>\n\n<p>A graph is <strong>bipartite</strong> if the nodes can be partitioned into two independent sets <code>A</code> and <code>B</code> such that <strong>every</strong> edge in the graph connects a node in set <code>A</code> and a node in set <code>B</code>.</p>\n\n<p>Return <code>true</code><em> if and only if it is <strong>bipartite</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/21/bi2.jpg\" style=\"width: 222px; height: 222px;\">\n<pre><strong>Input:</strong> graph = [[1,2,3],[0,2],[0,1,3],[0,2]]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/21/bi1.jpg\" style=\"width: 222px; height: 222px;\">\n<pre><strong>Input:</strong> graph = [[1,3],[0,2],[1,3],[0,2]]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> We can partition the nodes into two sets: {0, 2} and {1, 3}.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>graph.length == n</code></li>\n\t<li><code>1 &lt;= n &lt;= 100</code></li>\n\t<li><code>0 &lt;= graph[u].length &lt; n</code></li>\n\t<li><code>0 &lt;= graph[u][i] &lt;= n - 1</code></li>\n\t<li><code>graph[u]</code>&nbsp;does not contain&nbsp;<code>u</code>.</li>\n\t<li>All the values of <code>graph[u]</code> are <strong>unique</strong>.</li>\n\t<li>If <code>graph[u]</code> contains <code>v</code>, then <code>graph[v]</code> contains <code>u</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "791-Custom-Sort-String-Leetcode.cpp",
    "content": "class Solution {\npublic:\n    string customSortString(string order, string s) \n    {\n        unordered_map<char,int>mp;\n        for(auto it:s)\n            mp[it]++;\n        \n        string ans=\"\";\n        for(int i=0;i<order.size();++i)\n        {\n            auto x=find(s.begin(),s.end(),order[i]);\n            if(x!=s.end())\n            {\n                while(mp[order[i]]--)\n                    ans+=order[i];\n            }  \n        }\n        \n        for(int i=0;i<s.size();++i)\n        {\n            auto x=find(order.begin(),order.end(),s[i]);\n            if(x==order.end())\n                ans+=s[i];\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "792-number-of-matching-subsequences/792-number-of-matching-subsequences.java",
    "content": "class Solution {\n    public int numMatchingSubseq(String s, String[] words) {\n        \n        Map<String,Integer> map = new HashMap<>();\n        for(String str:words){\n            map.put(str,map.getOrDefault(str,0)+1);\n        }\n        \n        int ans = 0;\n        char ch[] = s.toCharArray();\n        \n        for(String str:map.keySet()){\n            \n            char temp[] = str.toCharArray();\n            int i = 0;\n            int j = 0;\n            \n            while(i<ch.length && j<temp.length){\n                if(ch[i]==temp[j]){\n                    i++;\n                    j++;\n                }else{\n                    i++;\n                }\n            }\n            \n            if(j==temp.length){\n                ans+=map.get(str);\n            }\n            \n        }\n        \n      return ans;  \n    }\n}"
  },
  {
    "path": "792-number-of-matching-subsequences/NOTES.md",
    "content": "​"
  },
  {
    "path": "792-number-of-matching-subsequences/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/number-of-matching-subsequences/\">792. Number of Matching Subsequences</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code> and an array of strings <code>words</code>, return <em>the number of</em> <code>words[i]</code> <em>that is a subsequence of</em> <code>s</code>.</p>\n\n<p>A <strong>subsequence</strong> 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.</p>\n\n<ul>\n\t<li>For example, <code>\"ace\"</code> is a subsequence of <code>\"abcde\"</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"abcde\", words = [\"a\",\"bb\",\"acd\",\"ace\"]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> There are three strings in words that are a subsequence of s: \"a\", \"acd\", \"ace\".\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"dsahjpjauf\", words = [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words.length &lt;= 5000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 50</code></li>\n\t<li><code>s</code> and <code>words[i]</code> consist of only lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "802. Find Eventual Safe States.java",
    "content": "class Solution {\n    public List<Integer> eventualSafeNodes(int[][] graph) {\n        int n=graph.length;\n        List<List<Integer>> adj=new ArrayList<>();\n        \n        for(int i=0;i<n;i++){\n            List<Integer> list=new ArrayList<>();\n            adj.add(list);\n        }\n        \n        for(int i=0;i<n;i++){\n            for(int j=0;j<graph[i].length;j++){\n                adj.get(i).add(graph[i][j]);\n            }\n        }\n        \n        int[] vis=new int[n];\n        int[] dfsVis=new int[n];\n        int[] check=new int[n];\n        List<Integer> ans=new ArrayList<>();\n        \n        for(int i=0;i<n;i++){\n            if(vis[i]==0){\n                dfs(adj,i,vis,dfsVis,check);\n            }\n        }\n        \n        for(int i=0;i<n;i++){\n            if(check[i]==1) ans.add(i);\n        }\n        \n        return ans;\n    }\n    \n    public boolean dfs(List<List<Integer>> adj,int node,int[] vis,int[] dfsVis,int[] check){\n        vis[node]=1;\n        dfsVis[node]=1;\n        \n        for(int e:adj.get(node)){\n            if(vis[e]==0){\n                if(dfs(adj,e,vis,dfsVis,check)){\n                    check[node]=0;\n                    return true;\n                }\n            }\n            if(dfsVis[e]==1){\n                check[node]=0;\n                return true;\n            }\n        }\n        dfsVis[node]=0;\n        check[node]=1;\n        return false;\n    }\n}\n"
  },
  {
    "path": "804-unique-morse-code-words/804-unique-morse-code-words.java",
    "content": "class Solution {\n    //gou\n    public int uniqueMorseRepresentations(String[] words) {\n\n        String[] MORSE = new String[]{\n            \".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\n            \"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\n            \"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\n            \"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n        \n        Set<String> uniqueSet = new HashSet<>();\n        for (String word : words) {\n            uniqueSet.add(convertToMorseStr(MORSE, word));\n        }\n        \n        return uniqueSet.size();\n    }\n    \n    private String convertToMorseStr(String[] MORSE, String word) {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < word.length(); i++) {\n            sb.append(MORSE[word.charAt(i)-'a']);\n        }\n        return sb.toString();\n    }\n    \n    \n}"
  },
  {
    "path": "804-unique-morse-code-words/NOTES.md",
    "content": "​"
  },
  {
    "path": "804-unique-morse-code-words/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/unique-morse-code-words/\">804. Unique Morse Code Words</a></h2><h3>Easy</h3><hr><div><p>International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:</p>\n\n<ul>\n\t<li><code>'a'</code> maps to <code>\".-\"</code>,</li>\n\t<li><code>'b'</code> maps to <code>\"-...\"</code>,</li>\n\t<li><code>'c'</code> maps to <code>\"-.-.\"</code>, and so on.</li>\n</ul>\n\n<p>For convenience, the full table for the <code>26</code> letters of the English alphabet is given below:</p>\n\n<pre>[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]</pre>\n\n<p>Given an array of strings <code>words</code> where each word can be written as a concatenation of the Morse code of each letter.</p>\n\n<ul>\n\t<li>For example, <code>\"cab\"</code> can be written as <code>\"-.-..--...\"</code>, which is the concatenation of <code>\"-.-.\"</code>, <code>\".-\"</code>, and <code>\"-...\"</code>. We will call such a concatenation the <strong>transformation</strong> of a word.</li>\n</ul>\n\n<p>Return <em>the number of different <strong>transformations</strong> among all words we have</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"gin\",\"zen\",\"gig\",\"msg\"]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"a\"]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 100</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 12</code></li>\n\t<li><code>words[i]</code> consists of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "804-unique-morse-code-words/unique-morse-code.cpp",
    "content": "class Solution {\npublic:\n    int uniqueMorseRepresentations(vector<string>& words) {\n        \n        vector<string> morse = {\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\n        \"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\n        \"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n        \n        unordered_set<string> s;\n        \n        for(int i = 0; i < words.size(); i++){\n            string str = words[i];\n            string morseCode = \"\";\n            for(int j = 0; j < str.length(); j++){\n                morseCode += morse[str[j] - 'a'];\n            }\n            s.insert(morseCode);\n        }\n        return s.size();\n    }\n};\n"
  },
  {
    "path": "81-search-in-rotated-sorted-array-ii/81-search-in-rotated-sorted-array-ii.java",
    "content": "class Solution {\n    public boolean search(int[] nums, int target) {\n         int left=0;\n        int right=nums.length-1;\n        while(left<=right){\n            int mid=(left+right)/2;\n            if(nums[mid]==target){\n                return true;\n            }\n            //case: when all left right and mid are same\n            else if(nums[left]==nums[mid] && nums[right]==nums[mid]){\n                left++;\n                right--;\n            }\n            //case: when mid is on higher level\n            else if(nums[left]<=nums[mid]){\n                //when left to mid is increasing\n                if(nums[left]<=target && nums[mid]>target){\n                    right=mid-1;\n                }else{\n                    left=mid+1;\n                }\n            }\n            //case: when mid is smaller than left\n            else{\n                //when mid to right is increasing\n                if(nums[mid]<target && nums[right]>=target){\n                    left=mid+1;\n                }else{\n                    right=mid-1;\n                }\n            }\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "81-search-in-rotated-sorted-array-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "81-search-in-rotated-sorted-array-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/search-in-rotated-sorted-array-ii/\">81. Search in Rotated Sorted Array II</a></h2><h3>Medium</h3><hr><div><p>There is an integer array <code>nums</code> sorted in non-decreasing order (not necessarily with <strong>distinct</strong> values).</p>\n\n<p>Before being passed to your function, <code>nums</code> is <strong>rotated</strong> at an unknown pivot index <code>k</code> (<code>0 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,4,4,5,6,6,7]</code> might be rotated at pivot index <code>5</code> and become <code>[4,5,6,6,7,0,1,2,4,4]</code>.</p>\n\n<p>Given the array <code>nums</code> <strong>after</strong> the rotation and an integer <code>target</code>, return <code>true</code><em> if </em><code>target</code><em> is in </em><code>nums</code><em>, or </em><code>false</code><em> if it is not in </em><code>nums</code><em>.</em></p>\n\n<p>You must decrease the overall operation steps as much as possible.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [2,5,6,0,0,1,2], target = 0\n<strong>Output:</strong> true\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [2,5,6,0,0,1,2], target = 3\n<strong>Output:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> is guaranteed to be rotated at some pivot.</li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> This problem is similar to&nbsp;<a href=\"/problems/search-in-rotated-sorted-array/description/\" target=\"_blank\">Search in Rotated Sorted Array</a>, but&nbsp;<code>nums</code> may contain <strong>duplicates</strong>. Would this affect the runtime complexity? How and why?</p>\n</div>"
  },
  {
    "path": "814-binary-tree-pruning/814-binary-tree-pruning.java",
    "content": "/**\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    Map<TreeNode,Integer>map;\n    boolean del;\n    public TreeNode pruneTree(TreeNode root) {\n        map=new HashMap<>();\n        int sum=root.val+sum(root.right)+sum(root.left);\n        if(sum==0){\n            return null;\n        }\n        dfs(root);\n        return root;\n    }\n    void dfs(TreeNode root){\n        if(root==null)return;\n        if(sum(root.left)==0){\n            root.left=null;\n        }\n        if(sum(root.right)==0){\n            root.right=null;\n        }\n        dfs(root.left);\n        dfs(root.right);\n    }\n    int sum(TreeNode root){\n        if(root==null)return 0;\n        if(map.containsKey(root))return map.get(root);\n        int sum=root.val+sum(root.left)+sum(root.right);\n        map.putIfAbsent(root,sum);\n        return sum;\n    }\n    \n}\n\n\nApproach-2 BY @Jay-Thesia\n\nclass Solution {\n    public TreeNode pruneTree(TreeNode root) {\n        \n        return helper(root)?null:root;\n    }\n    \n    public boolean helper(TreeNode root){\n        \n        if(root==null)\n            return true;\n        \n        boolean left=helper(root.left);\n        boolean right=helper(root.right);\n        \n        if(left)\n            root.left=null;\n        if(right)\n            root.right=null;\n        \n        return root.val==0 && left && right;\n    }\n}\n"
  },
  {
    "path": "814-binary-tree-pruning/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-tree-pruning/\">814. Binary Tree Pruning</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the same tree where every subtree (of the given tree) not containing a </em><code>1</code><em> has been removed</em>.</p>\n\n<p>A subtree of a node <code>node</code> is <code>node</code> plus every node that is a descendant of <code>node</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_2.png\" style=\"width: 500px; height: 140px;\">\n<pre><strong>Input:</strong> root = [1,null,0,0,1]\n<strong>Output:</strong> [1,null,0,null,1]\n<strong>Explanation:</strong> \nOnly the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_1.png\" style=\"width: 500px; height: 115px;\">\n<pre><strong>Input:</strong> root = [1,0,1,0,0,0,1]\n<strong>Output:</strong> [1,null,1,null,1]\n</pre>\n\n<p><strong>Example 3:</strong></p>\n<img alt=\"\" src=\"https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/05/1028.png\" style=\"width: 500px; height: 134px;\">\n<pre><strong>Input:</strong> root = [1,1,0,1,1,0,1,0]\n<strong>Output:</strong> [1,1,0,1,1,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 200]</code>.</li>\n\t<li><code>Node.val</code> is either <code>0</code> or <code>1</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "82-remove-duplicates-from-sorted-list-ii/82-remove-duplicates-from-sorted-list-ii.java",
    "content": "/**\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 */\npublic class Solution {\n    public ListNode deleteDuplicates(ListNode A) {\n        ListNode head=null;\n        ListNode curr=null;\n        ListNode temp=A;\n        while(temp!=null){\n            if(temp.next!=null){\n                int value=temp.val;\n                if(temp.next.val==value){\n                    while(temp!=null && temp.val==value){\n                        temp=temp.next;\n                    }\n                }else{\n                    if(head==null){\n                        head=temp;\n                        curr=temp;\n                    }else{\n                        curr.next=temp;\n                        curr=curr.next;\n                    }\n                    temp=temp.next;\n                    curr.next=null;\n                }\n            }else{\n                if(head==null){\n                    head=temp;\n                    curr=temp;\n                }else{\n                    curr.next=temp;\n                    curr=curr.next;\n                }\n                temp=temp.next;\n                curr.next=null;\n            }\n        }\n        return head;\n    }\n}\n"
  },
  {
    "path": "82-remove-duplicates-from-sorted-list-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "82-remove-duplicates-from-sorted-list-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/\">82. Remove Duplicates from Sorted List II</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a sorted linked list, <em>delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list</em>. Return <em>the linked list <strong>sorted</strong> as well</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg\" style=\"width: 500px; height: 142px;\">\n<pre><strong>Input:</strong> head = [1,2,3,3,4,4,5]\n<strong>Output:</strong> [1,2,5]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg\" style=\"width: 500px; height: 205px;\">\n<pre><strong>Input:</strong> head = [1,1,1,2,3]\n<strong>Output:</strong> [2,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[0, 300]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li>The list is guaranteed to be <strong>sorted</strong> in ascending order.</li>\n</ul>\n</div>"
  },
  {
    "path": "820-short-encoding-of-words/820-short-encoding-of-words.java",
    "content": "class Solution {\n    public int minimumLengthEncoding(String[] words) {\n        Trie trie = new Trie();\n        int sum = 0;\n        Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());\n        for (String word : words) {\n            boolean isNew = trie.insert(word);\n            if (isNew) {\n                sum += word.length() + 1;\n            }\n        }\n        return sum;\n    }\n}\n\n// 定义tire\nclass Trie {\n    \n    TrieNode root;\n    \n    public Trie() {\n        root = new TrieNode();\n    }\n\n    public boolean insert(String word) {\n        boolean isNew = false;\n        TrieNode node = root;\n        for (int i = word.length() - 1; i >= 0; --i) {\n            int index = word.charAt(i) - 'a';\n            if (node.children[index] == null) {\n                isNew = true;\n                node.children[index] = new TrieNode();\n            }\n            node = node.children[index];\n        }\n        return isNew;\n    }\n}\n\nclass TrieNode {\n    TrieNode[] children = new TrieNode[26];\n\n    public TrieNode() {}\n}"
  },
  {
    "path": "820-short-encoding-of-words/NOTES.md",
    "content": "​"
  },
  {
    "path": "820-short-encoding-of-words/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/short-encoding-of-words/\">820. Short Encoding of Words</a></h2><h3>Medium</h3><hr><div><p>A <strong>valid encoding</strong> of an array of <code>words</code> is any reference string <code>s</code> and array of indices <code>indices</code> such that:</p>\n\n<ul>\n\t<li><code>words.length == indices.length</code></li>\n\t<li>The reference string <code>s</code> ends with the <code>'#'</code> character.</li>\n\t<li>For each index <code>indices[i]</code>, the <strong>substring</strong> of <code>s</code> starting from <code>indices[i]</code> and up to (but not including) the next <code>'#'</code> character is equal to <code>words[i]</code>.</li>\n</ul>\n\n<p>Given an array of <code>words</code>, return <em>the <strong>length of the shortest reference string</strong> </em><code>s</code><em> possible of any <strong>valid encoding</strong> of </em><code>words</code><em>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"time\", \"me\", \"bell\"]\n<strong>Output:</strong> 10\n<strong>Explanation:</strong> A valid encoding would be s = <code>\"time#bell#\" and indices = [0, 2, 5</code>].\nwords[0] = \"time\", the substring of s starting from indices[0] = 0 to the next '#' is underlined in \"<u>time</u>#bell#\"\nwords[1] = \"me\", the substring of s starting from indices[1] = 2 to the next '#' is underlined in \"ti<u>me</u>#bell#\"\nwords[2] = \"bell\", the substring of s starting from indices[2] = 5 to the next '#' is underlined in \"time#<u>bell</u>#\"\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"t\"]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> A valid encoding would be s = \"t#\" and indices = [0].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 2000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 7</code></li>\n\t<li><code>words[i]</code> consists of only lowercase letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "823-binary-trees-with-factors/823-binary-trees-with-factors.java",
    "content": "class Solution {\n    public int numFactoredBinaryTrees(int[] arr) {\n        Arrays.sort(arr);\n        int n = arr.length, mod = 1_000_000_007;\n        long[] dp = new long[n];\n        long res = 0;\n        Map<Integer, Integer> idxs = new HashMap();\n        for (int i = 0; i < n; i++) {\n            dp[i] = 1;\n            for (int j = 0; j < i; j++) {\n                if (arr[j]*arr[j] > arr[i]) break;\n                if (arr[i] % arr[j] == 0 && idxs.containsKey(arr[i]/arr[j])) {\n                    if (arr[j]*arr[j] == arr[i]) {\n                        dp[i] += dp[j]*dp[j];\n                        dp[i] %= mod;\n                    }\n                    else {\n                        dp[i] += 2*dp[j]*dp[idxs.get(arr[i]/arr[j])];\n                        dp[i] %= mod;\n                    }\n                }\n            }\n            idxs.put(arr[i], i);\n            res += dp[i];\n            res %= mod;\n        }\n        return (int) res;\n    }\n}"
  },
  {
    "path": "823-binary-trees-with-factors/NOTES.md",
    "content": "​"
  },
  {
    "path": "823-binary-trees-with-factors/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-trees-with-factors/\">823. Binary Trees With Factors</a></h2><h3>Medium</h3><hr><div><p>Given an array of unique integers, <code>arr</code>, where each integer <code>arr[i]</code> is strictly greater than <code>1</code>.</p>\n\n<p>We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.</p>\n\n<p>Return <em>the number of binary trees we can make</em>. The answer may be too large so return the answer <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> arr = [2,4]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> We can make these trees: <code>[2], [4], [4, 2, 2]</code></pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> arr = [2,4,5,10]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> We can make these trees: <code>[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]</code>.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= arr.length &lt;= 1000</code></li>\n\t<li><code>2 &lt;= arr[i] &lt;= 10<sup>9</sup></code></li>\n\t<li>All the values of <code>arr</code> are <strong>unique</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "838-push-dominoes/838-push-dominoes.java",
    "content": "class Solution {\n    public String pushDominoes(String dominoes) {\n        int n = dominoes.length();\n        char[] dArray = dominoes.toCharArray();\n        char start = '.';\n        char last = '.';\n        int stidx = 0;\n        int i = 0;\n        while(i<n){\n            stidx = i;\n            while(i<n && dArray[i]=='.'){\n                i++;\n            }\n            if(i<n){\n                last = dArray[i];\n            }\n            if(i-stidx>0){\n                if(start=='R' && last=='L'){\n                    int l = stidx;\n                    int r = i-1;\n                    while(l<r){\n                        dArray[l]='R';\n                        dArray[r]='L';\n                        l++;\n                        r--;\n                        \n                    }\n                   \n                }\n                else if(last=='L'){\n                    int l = i-1;\n                    while(l>=stidx){\n                        dArray[l]='L';\n                        l--;\n                    }\n                }\n                else if(start=='R'){\n                    int r = stidx;\n                    while(r<i){\n                        dArray[r]='R';\n                        r++;\n                    }   \n                }\n            }\n            \n            start = last;\n            i++;\n            last = '.';\n        }\n        return new String(dArray);\n    }\n}"
  },
  {
    "path": "838-push-dominoes/NOTES.md",
    "content": "​"
  },
  {
    "path": "838-push-dominoes/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/push-dominoes/\">838. Push Dominoes</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> 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.</p>\n\n<p>After 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.</p>\n\n<p>When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.</p>\n\n<p>For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.</p>\n\n<p>You are given a string <code>dominoes</code> representing the initial state where:</p>\n\n<ul>\n\t<li><code>dominoes[i] = 'L'</code>, if the <code>i<sup>th</sup></code> domino has been pushed to the left,</li>\n\t<li><code>dominoes[i] = 'R'</code>, if the <code>i<sup>th</sup></code> domino has been pushed to the right, and</li>\n\t<li><code>dominoes[i] = '.'</code>, if the <code>i<sup>th</sup></code> domino has not been pushed.</li>\n</ul>\n\n<p>Return <em>a string representing the final state</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> dominoes = \"RR.L\"\n<strong>Output:</strong> \"RR.L\"\n<strong>Explanation:</strong> The first domino expends no additional force on the second domino.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://s3-lc-upload.s3.amazonaws.com/uploads/2018/05/18/domino.png\" style=\"height: 196px; width: 512px;\">\n<pre><strong>Input:</strong> dominoes = \".L.R...LR..L..\"\n<strong>Output:</strong> \"LL.RR.LLRRLL..\"\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == dominoes.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>dominoes[i]</code> is either <code>'L'</code>, <code>'R'</code>, or <code>'.'</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "844-backspace-string-compare/844-backspace-string-compare.java",
    "content": "class Solution {\n    public boolean backspaceCompare(String s, String t) {\n        int sPointer = s.length() - 1;\n        int tPointer = t.length() - 1;\n        \n        while (sPointer >= 0 || tPointer >= 0) {\n            sPointer = getNextCharacterPosition(s, sPointer); // can be negative, empty string;\n            tPointer = getNextCharacterPosition(t, tPointer); // can be negative, empty string;\n            \n            if ((sPointer < 0 && tPointer >= 0) ||\n                (tPointer < 0 && sPointer >= 0) ||\n                (sPointer >= 0 && tPointer >= 0) && (s.charAt(sPointer) != t.charAt(tPointer))\n               ) {\n                return false;\n            }\n            \n            sPointer--;\n            tPointer--;\n        }\n        \n        return true;\n    }\n\n    public int getNextCharacterPosition(String s, int start) {\n        if (start < 0) {\n            return start;\n        }\n        \n        char c = s.charAt(start);\n        int count = c == '#' ? 2 : 0;\n        \n        while (count > 0) {\n            start--;\n            \n            if (start < 0) {\n                start -= count;\n                break;\n            }\n            \n            c = s.charAt(start);\n            \n            if (c == '#') {\n                count++;\n            } else {\n                count--;\n            }\n        }\n               \n        return start;\n    }\n}"
  },
  {
    "path": "844-backspace-string-compare/NOTES.md",
    "content": "​"
  },
  {
    "path": "844-backspace-string-compare/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/backspace-string-compare/\">844. Backspace String Compare</a></h2><h3>Easy</h3><hr><div><p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> <em>if they are equal when both are typed into empty text editors</em>. <code>'#'</code> means a backspace character.</p>\n\n<p>Note that after backspacing an empty text, the text will continue empty.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"ab#c\", t = \"ad#c\"\n<strong>Output:</strong> true\n<strong>Explanation:</strong> Both s and t become \"ac\".\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"ab##\", t = \"c#d#\"\n<strong>Output:</strong> true\n<strong>Explanation:</strong> Both s and t become \"\".\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"a#c\", t = \"b\"\n<strong>Output:</strong> false\n<strong>Explanation:</strong> s becomes \"c\" while t becomes \"b\".\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code><span>1 &lt;= s.length, t.length &lt;= 200</span></code></li>\n\t<li><span><code>s</code> and <code>t</code> only contain lowercase letters and <code>'#'</code> characters.</span></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time and <code>O(1)</code> space?</p>\n</div>"
  },
  {
    "path": "845_Longest_Mountain_in_Array.cpp",
    "content": "class Solution {\npublic:\n    int longestMountain(vector<int>& arr) {\n        int ans = 0;\n        for(int i =1;i<arr.size()-1;i++){\n            if(arr[i]>arr[i+1]&&arr[i]>arr[i-1]){\n                int x =i,y=i;\n                while(x>0&&arr[x]>arr[x-1]){\n                    x--;\n                }\n                while(y<arr.size()-1&&arr[y]>arr[y+1]){\n                    y++;\n                }\n                ans = max(ans,y-x+1);\n                i=y;\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "856-score-of-parentheses/856-score-of-parentheses.java",
    "content": "class Solution {\n    public int scoreOfParentheses(String S) {\n        int ans = 0, bal = 0;\n        for (int i = 0; i < S.length(); ++i) {\n            if (S.charAt(i) == '(') {\n                bal++;\n            } else {\n                bal--;\n                if (S.charAt(i-1) == '(')\n                    ans += 1 << bal;\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "856-score-of-parentheses/NOTES.md",
    "content": "​"
  },
  {
    "path": "856-score-of-parentheses/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/score-of-parentheses/\">856. Score of Parentheses</a></h2><h3>Medium</h3><hr><div><p>Given a balanced parentheses string <code>s</code>, return <em>the <strong>score</strong> of the string</em>.</p>\n\n<p>The <strong>score</strong> of a balanced parentheses string is based on the following rule:</p>\n\n<ul>\n\t<li><code>\"()\"</code> has score <code>1</code>.</li>\n\t<li><code>AB</code> has score <code>A + B</code>, where <code>A</code> and <code>B</code> are balanced parentheses strings.</li>\n\t<li><code>(A)</code> has score <code>2 * A</code>, where <code>A</code> is a balanced parentheses string.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"()\"\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"(())\"\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"()()\"\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= s.length &lt;= 50</code></li>\n\t<li><code>s</code> consists of only <code>'('</code> and <code>')'</code>.</li>\n\t<li><code>s</code> is a balanced parentheses string.</li>\n</ul>\n</div>"
  },
  {
    "path": "86-partition-list/86-partition-list.java",
    "content": "/**\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 partition(ListNode head, int x) {\n        ListNode temp=head;\n        ListNode small=new ListNode(-1);\n        ListNode smallEnd=small;\n        ListNode large=new ListNode(-1);\n        ListNode currLarge=large;\n        while(temp!=null){\n            ListNode curr=temp;\n            temp=temp.next;\n            curr.next=null;\n            if(curr.val<x){\n                smallEnd.next=curr;\n                smallEnd=smallEnd.next;\n            }else{\n                currLarge.next=curr;\n                currLarge=currLarge.next;\n            }\n        }\n        smallEnd.next=large.next;\n        return small.next;\n    }\n}"
  },
  {
    "path": "86-partition-list/NOTES.md",
    "content": "​"
  },
  {
    "path": "86-partition-list/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/partition-list/\">86. Partition List</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p>\n\n<p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/partition.jpg\" style=\"width: 662px; height: 222px;\">\n<pre><strong>Input:</strong> head = [1,4,3,2,5,2], x = 3\n<strong>Output:</strong> [1,2,2,4,3,5]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> head = [2,1], x = 2\n<strong>Output:</strong> [1,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>-200 &lt;= x &lt;= 200</code></li>\n</ul>\n</div>"
  },
  {
    "path": "867-transpose-matrix/867-transpose-matrix.java",
    "content": "class Solution {\n    public int[][] transpose(int[][] A) {\n        int R = A.length, C = A[0].length;\n        int[][] ans = new int[C][R];\n        for (int r = 0; r < R; ++r)\n            for (int c = 0; c < C; ++c) \n                ans[c][r] = A[r][c];\n            \n        return ans;\n    }\n}"
  },
  {
    "path": "867-transpose-matrix/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/transpose-matrix/\">867. Transpose Matrix</a></h2><h3>Easy</h3><hr><div><p>Given a 2D integer array <code>matrix</code>, return <em>the <strong>transpose</strong> of</em> <code>matrix</code>.</p>\n\n<p>The <strong>transpose</strong> of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.</p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/10/hint_transpose.png\" style=\"width: 600px; height: 197px;\"></p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]]\n<strong>Output:</strong> [[1,4,7],[2,5,8],[3,6,9]]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> matrix = [[1,2,3],[4,5,6]]\n<strong>Output:</strong> [[1,4],[2,5],[3,6]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 1000</code></li>\n\t<li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "869-Reordered-Power-of-2/869-Reordered-Power-of-2.cpp",
    "content": "class Solution {\npublic:\n    bool reorderedPowerOf2(int n) {\n        string res = to_string(n);\n        sort(res.begin(), res.end());\n        for(int i =0; i<30; i++){\n            string res1 = to_string(1<<i);\n            sort(res1.begin(), res1.end());\n            if(res == res1) return true;\n        }\n        return false;\n    }\n};"
  },
  {
    "path": "871-minimum-number-of-refueling-stops/871-minimum-number-of-refueling-stops.java",
    "content": "class Solution {\n    public int minRefuelStops(int target, int startFuel, int[][] stations) {\n        int n = stations.length;\n        int maxPos = startFuel, ans = 0;\n        while (maxPos < target) {\n            int curMax = 0;\n            int curPos = -1;\n            for (int i = 0; i < n; i++) {\n                if (maxPos >= stations[i][0] && stations[i][1] > curMax) {\n                    curMax = stations[i][1];\n                    curPos = i;\n                }\n            }\n            if (curMax == 0) {\n                break;\n            }\n            ans++;\n            maxPos += curMax;\n            stations[curPos][0] = Integer.MAX_VALUE;\n        }\n        return maxPos >= target ? ans : -1;\n    }\n}"
  },
  {
    "path": "871-minimum-number-of-refueling-stops/Minimum-Number-of-Refueling-Stops.cpp",
    "content": "class Solution {\npublic:\n    int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {\n        priority_queue<int> pq;\n        stations.push_back({target, 0});\n        int pumps=0;\n        for(int i=0;i<stations.size();i++){\n            startFuel -= (stations[i][0] - (i==0?0:stations[i-1][0]));\n            while(startFuel < 0 and !pq.empty()){\n                startFuel += pq.top();\n                pq.pop();\n                pumps++;\n            }           \n            if(startFuel < 0) return -1;\n            pq.push(stations[i][1]);\n        }\n        return pumps;\n    }\n};\n"
  },
  {
    "path": "871-minimum-number-of-refueling-stops/NOTES.md",
    "content": "​"
  },
  {
    "path": "871-minimum-number-of-refueling-stops/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/minimum-number-of-refueling-stops/\">871. Minimum Number of Refueling Stops</a></h2><h3>Hard</h3><hr><div><p>A car travels from a starting position to a destination which is <code>target</code> miles east of the starting position.</p>\n\n<p>There are gas stations along the way. The gas stations are represented as an array <code>stations</code> where <code>stations[i] = [position<sub>i</sub>, fuel<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> gas station is <code>position<sub>i</sub></code> miles east of the starting position and has <code>fuel<sub>i</sub></code> liters of gas.</p>\n\n<p>The car starts with an infinite tank of gas, which initially has <code>startFuel</code> 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.</p>\n\n<p>Return <em>the minimum number of refueling stops the car must make in order to reach its destination</em>. If it cannot reach the destination, return <code>-1</code>.</p>\n\n<p>Note that if the car reaches a gas station with <code>0</code> fuel left, the car can still refuel there. If the car reaches the destination with <code>0</code> fuel left, it is still considered to have arrived.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> target = 1, startFuel = 1, stations = []\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> We can reach the target without refueling.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> target = 100, startFuel = 1, stations = [[10,100]]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> We can not reach the target (or even the first gas station).\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= target, startFuel &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= stations.length &lt;= 500</code></li>\n\t<li><code>0 &lt;= position<sub>i</sub> &lt;= position<sub>i+1</sub> &lt; target</code></li>\n\t<li><code>1 &lt;= fuel<sub>i</sub> &lt; 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "871. Minimum Number of Refueling Stops.cpp",
    "content": " int minRefuelStops(int target, int sf, vector<vector<int>>& s) {\n        priority_queue<int>pq;\n        int i=0,res;\n        \n        for(res=0;sf<target;res++)\n        {\n            while(i<s.size() && s[i][0]<=sf)\n            {\n                pq.push(s[i++][1]);\n            }\n                if(pq.empty())return -1;\n                \n                sf+=pq.top();\n                pq.pop();\n            \n        }\n        return res;\n    }\n"
  },
  {
    "path": "876-middle-of-the-linked-list/876-middle-of-the-linked-list.java",
    "content": "/**\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 middleNode(ListNode head) {\n        ListNode slow = head;\n        ListNode fast = head;\n        \n        \n        while(fast!=null && fast.next!=null){\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n        \n        return slow;\n\n    }\n}"
  },
  {
    "path": "876-middle-of-the-linked-list/NOTES.md",
    "content": ""
  },
  {
    "path": "876-middle-of-the-linked-list/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/middle-of-the-linked-list/\">876. Middle of the Linked List</a></h2><h3>Easy</h3><hr><div><p>Given the <code>head</code> of a singly linked list, return <em>the middle node of the linked list</em>.</p>\n\n<p>If there are two middle nodes, return <strong>the second middle</strong> node.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/23/lc-midlist1.jpg\" style=\"width: 544px; height: 65px;\">\n<pre><strong>Input:</strong> head = [1,2,3,4,5]\n<strong>Output:</strong> [3,4,5]\n<strong>Explanation:</strong> The middle node of the list is node 3.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/23/lc-midlist2.jpg\" style=\"width: 664px; height: 65px;\">\n<pre><strong>Input:</strong> head = [1,2,3,4,5,6]\n<strong>Output:</strong> [4,5,6]\n<strong>Explanation:</strong> Since the list has two middle nodes with values 3 and 4, we return the second one.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[1, 100]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n</div>"
  },
  {
    "path": "88-merge-sorted-array/88-merge-sorted-array.java",
    "content": "class Solution {\n    public void merge(int[] nums1, int m, int[] nums2, int n) {\n        int index = m + n - 1;\n        int index1 = m - 1;\n        int index2 = n - 1;\n        while (index1 >= 0 && index2 >= 0) {\n            if (nums1[index1] > nums2[index2]) {\n                nums1[index] = nums1[index1];\n                index1--;\n            } else {\n                nums1[index] = nums2[index2];\n                index2--;\n            }\n            index--;\n        }\n        while (index2 >= 0) {\n            nums1[index--] = nums2[index2--];\n        }\n    }\n}"
  },
  {
    "path": "88-merge-sorted-array/NOTES.md",
    "content": "​"
  },
  {
    "path": "88-merge-sorted-array/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/merge-sorted-array/\">88. Merge Sorted Array</a></h2><h3>Easy</h3><hr><div><p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p>\n\n<p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p>\n\n<p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\n<strong>Output:</strong> [1,2,2,3,5,6]\n<strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0\n<strong>Output:</strong> [1]\n<strong>Explanation:</strong> The arrays we are merging are [1] and [].\nThe result of the merge is [1].\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1\n<strong>Output:</strong> [1]\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>nums1.length == m + n</code></li>\n\t<li><code>nums2.length == n</code></li>\n\t<li><code>0 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>1 &lt;= m + n &lt;= 200</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>\n</div>"
  },
  {
    "path": "881-boats-to-save-people/881-boats-to-save-people.java",
    "content": "class Solution {\n    public int numRescueBoats(int[] people, int limit) {\n        Arrays.sort(people);\n        int i = 0, j = people.length - 1;\n        int ans = 0;\n\n        while (i <= j) {\n            ans++;\n            if (people[i] + people[j] <= limit)\n                i++;\n            j--;\n        }\n\n        return ans;\n    }\n}"
  },
  {
    "path": "881-boats-to-save-people/NOTES.md",
    "content": "​"
  },
  {
    "path": "881-boats-to-save-people/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/boats-to-save-people/\">881. Boats to Save People</a></h2><h3>Medium</h3><hr><div><p>You are given an array <code>people</code> where <code>people[i]</code> is the weight of the <code>i<sup>th</sup></code> person, and an <strong>infinite number of boats</strong> where each boat can carry a maximum weight of <code>limit</code>. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most <code>limit</code>.</p>\n\n<p>Return <em>the minimum number of boats to carry every given person</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> people = [1,2], limit = 3\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> 1 boat (1, 2)\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> people = [3,2,2,1], limit = 3\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 3 boats (1, 2), (2) and (3)\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> people = [3,5,3,4], limit = 5\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> 4 boats (3), (3), (4), (5)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= people.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= people[i] &lt;= limit &lt;= 3 * 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "890-find-and-replace-pattern/890-find-and-replace-pattern.java",
    "content": "class Solution {\n    public static List<String> findAndReplacePattern(String[] words, String pattern) {\n        List<String> list=new LinkedList<>();\n        for(int i=0;i<words.length;i++){\n            if(checkPattern(words[i],pattern)){\n                list.add(words[i]);\n            }\n        }\n        return list;\n    }\n    private static boolean checkPattern(String word, String pattern){\n        for(int i=0;i<word.length();i++){\n            if(word.indexOf(word.charAt(i))!=pattern.indexOf(pattern.charAt(i)))\n                 return false;\n        }\n        return  true;\n    }\n}"
  },
  {
    "path": "890-find-and-replace-pattern/NOTES.md",
    "content": "​"
  },
  {
    "path": "890-find-and-replace-pattern/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/find-and-replace-pattern/\">890. Find and Replace Pattern</a></h2><h3>Medium</h3><hr><div><p>Given a list of strings <code>words</code> and a string <code>pattern</code>, return <em>a list of</em> <code>words[i]</code> <em>that match</em> <code>pattern</code>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>A word matches the pattern if there exists a permutation of letters <code>p</code> so that after replacing every letter <code>x</code> in the pattern with <code>p(x)</code>, we get the desired word.</p>\n\n<p>Recall 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.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"], pattern = \"abb\"\n<strong>Output:</strong> [\"mee\",\"aqq\"]\n<strong>Explanation:</strong> \"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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> words = [\"a\",\"b\",\"c\"], pattern = \"a\"\n<strong>Output:</strong> [\"a\",\"b\",\"c\"]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= pattern.length &lt;= 20</code></li>\n\t<li><code>1 &lt;= words.length &lt;= 50</code></li>\n\t<li><code>words[i].length == pattern.length</code></li>\n\t<li><code>pattern</code> and <code>words[i]</code> are lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "895-maximum-frequency-stack/895-maximum-frequency-stack.java",
    "content": "class FreqStack {\n    Map<Integer,Integer> cnt;//frequency count for every digit\n    int max;//max frequency present for any num(we don't know which)\n    \n    //used to store frequency-wise stacks of inputs.eg.\n    //([2,1,2,5,5,5])(1 freq-[2,1,5],2 freq-[2,5],3 freq-[5])\n    Map<Integer,ArrayList<Integer>> stack;//stack assigned with num of frequencies\n    public FreqStack() {\n        //initialise our members\n        cnt=new HashMap<>();\n        stack=new HashMap<>();\n        max=0;\n    }\n    \n    public void push(int val) {\n        //increment val count\n        int valCnt=cnt.getOrDefault(val,0)+1;\n        cnt.put(val,valCnt);\n        //if current cal count is more than max\n        if(valCnt>max){\n            max=valCnt;\n            stack.put(max,new ArrayList<>());//add new stack for this new max count\n        }\n        stack.get(valCnt).add(val);//add this num to its stacks\n    }\n    \n    public int pop() {\n        //remove last element of max freq\n        int res=stack.get(max).remove(stack.get(max).size()-1);\n        cnt.put(res,cnt.get(res)-1);//reduce freq of number\n        if(stack.get(max).size()==0){//if now this freq have no num left\n            max--;//reduce the freq\n        }\n        return res;\n    }\n}\n\n/**\n * Your FreqStack object will be instantiated and called as such:\n * FreqStack obj = new FreqStack();\n * obj.push(val);\n * int param_2 = obj.pop();\n */"
  },
  {
    "path": "895-maximum-frequency-stack/NOTES.md",
    "content": "​"
  },
  {
    "path": "895-maximum-frequency-stack/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-frequency-stack/\">895. Maximum Frequency Stack</a></h2><h3>Hard</h3><hr><div><p>Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.</p>\n\n<p>Implement the <code>FreqStack</code> class:</p>\n\n<ul>\n\t<li><code>FreqStack()</code> constructs an empty frequency stack.</li>\n\t<li><code>void push(int val)</code> pushes an integer <code>val</code> onto the top of the stack.</li>\n\t<li><code>int pop()</code> removes and returns the most frequent element in the stack.\n\t<ul>\n\t\t<li>If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.</li>\n\t</ul>\n\t</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[], [5], [7], [5], [7], [4], [5], [], [], [], []]\n<strong>Output</strong>\n[null, null, null, null, null, null, null, 5, 7, 5, 4]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= val &lt;= 10<sup>9</sup></code></li>\n\t<li>At most <code>2 * 10<sup>4</sup></code> calls will be made to <code>push</code> and <code>pop</code>.</li>\n\t<li>It is guaranteed that there will be at least one element in the stack before calling <code>pop</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "897-increasing-order-search-tree/897-increasing-order-search-tree.java",
    "content": "class Solution {\n    public TreeNode increasingBST(TreeNode root){\n        List<TreeNode> list=new ArrayList<>();\n        inOrder(root,list);\n        TreeNode newHead=new TreeNode(-1);\n        TreeNode temp=newHead;\n        for(int i=0;i<list.size();i++){\n            temp.right=list.get(i);\n            temp=temp.right;\n        }\n        return newHead.right;\n    }\n    public void inOrder(TreeNode root,List<TreeNode> list){\n        if(root==null)return;\n        TreeNode lefty=root.left;\n        root.left=null;\n        TreeNode righty=root.right;\n        root.right=null;\n        inOrder(lefty,list);\n        list.add(root);\n        inOrder(righty,list);\n    }\n}"
  },
  {
    "path": "897-increasing-order-search-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "897-increasing-order-search-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/increasing-order-search-tree/\">897. Increasing Order Search Tree</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary search tree, rearrange the tree in <strong>in-order</strong> 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.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg\" style=\"width: 600px; height: 350px;\">\n<pre><strong>Input:</strong> root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\n<strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg\" style=\"width: 300px; height: 114px;\">\n<pre><strong>Input:</strong> root = [5,1,7]\n<strong>Output:</strong> [1,null,5,null,7]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the given tree will be in the range <code>[1, 100]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 1000</code></li>\n</ul></div>"
  },
  {
    "path": "905-sort-array-by-parity/905-sort-array-by-parity.java",
    "content": "class Solution {\n    public int[] sortArrayByParity(int[] nums) {\n        int left = 0, right = nums.length-1;\n        while (left < right) {\n            if (nums[left]%2 == 1) {\n                if (nums[right]%2 == 0) {\n                    int temp = nums[left];\n                    nums[left] = nums[right];\n                    nums[right] = temp;\n                    left++;\n                }\n                right--;\n            } else {\n                left++;\n            }\n        }\n        return nums;\n    }\n}"
  },
  {
    "path": "905-sort-array-by-parity/NOTES.md",
    "content": "​"
  },
  {
    "path": "905-sort-array-by-parity/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/sort-array-by-parity/\">905. Sort Array By Parity</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code>, move all the even integers at the beginning of the array followed by all the odd integers.</p>\n\n<p>Return <em><strong>any array</strong> that satisfies this condition</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [3,1,2,4]\n<strong>Output:</strong> [2,4,3,1]\n<strong>Explanation:</strong> The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [0]\n<strong>Output:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 5000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "91-decode-ways/91-decode-ways.java",
    "content": "class Solution {\n    public int numDecodings(String s) {\n        int[] dp=new int[s.length()];\n        if(s.charAt(0)=='0'){\n            return 0;\n        }\n        dp[0]=1;\n        for(int i=1;i<dp.length;i++){\n            if(s.charAt(i)!='0'){\n                dp[i]+=dp[i-1];\n            }\n            int two=Integer.parseInt(s.substring(i-1,i+1));\n            if(two>=10&&two<=26){\n                if(i==1){\n                    dp[i]++;\n                }\n                else{\n                    dp[i]+=dp[i-2];\n                }\n                \n            }\n        }\n        return dp[dp.length-1];\n    }\n}"
  },
  {
    "path": "91-decode-ways/NOTES.md",
    "content": "​"
  },
  {
    "path": "91-decode-ways/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/decode-ways/\">91. Decode Ways</a></h2><h3>Medium</h3><hr><div><p>A message containing letters from <code>A-Z</code> can be <strong>encoded</strong> into numbers using the following mapping:</p>\n\n<pre>'A' -&gt; \"1\"\n'B' -&gt; \"2\"\n...\n'Z' -&gt; \"26\"\n</pre>\n\n<p>To <strong>decode</strong> 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, <code>\"11106\"</code> can be mapped into:</p>\n\n<ul>\n\t<li><code>\"AAJF\"</code> with the grouping <code>(1 1 10 6)</code></li>\n\t<li><code>\"KJF\"</code> with the grouping <code>(11 10 6)</code></li>\n</ul>\n\n<p>Note that the grouping <code>(1 11 06)</code> is invalid because <code>\"06\"</code> cannot be mapped into <code>'F'</code> since <code>\"6\"</code> is different from <code>\"06\"</code>.</p>\n\n<p>Given a string <code>s</code> containing only digits, return <em>the <strong>number</strong> of ways to <strong>decode</strong> it</em>.</p>\n\n<p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> s = \"12\"\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> \"12\" could be decoded as \"AB\" (1 2) or \"L\" (12).\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s = \"226\"\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> \"226\" could be decoded as \"BZ\" (2 26), \"VF\" (22 6), or \"BBF\" (2 2 6).\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s = \"06\"\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> \"06\" cannot be mapped to \"F\" because of the leading zero (\"6\" is different from \"06\").\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s</code> contains only digits and may contain leading zero(s).</li>\n</ul>\n</div>"
  },
  {
    "path": "916-word-subsets/916-word-subsets.java",
    "content": "class Solution {\n    public List<String> wordSubsets(String[] A, String[] B) {\n        int[] bmax = count(\"\");\n        for (String b: B) {\n            int[] bCount = count(b);\n            for (int i = 0; i < 26; ++i)\n                bmax[i] = Math.max(bmax[i], bCount[i]);\n        }\n\n        List<String> ans = new ArrayList();\n        search: for (String a: A) {\n            int[] aCount = count(a);\n            for (int i = 0; i < 26; ++i)\n                if (aCount[i] < bmax[i])\n                    continue search;\n            ans.add(a);\n        }\n\n        return ans;\n    }\n\n    public int[] count(String S) {\n        int[] ans = new int[26];\n        for (char c: S.toCharArray())\n            ans[c - 'a']++;\n        return ans;\n    }\n}"
  },
  {
    "path": "916-word-subsets/NOTES.md",
    "content": "​"
  },
  {
    "path": "916-word-subsets/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/word-subsets/\">916. Word Subsets</a></h2><h3>Medium</h3><hr><div><p>You are given two string arrays <code>words1</code> and <code>words2</code>.</p>\n\n<p>A string <code>b</code> is a <strong>subset</strong> of string <code>a</code> if every letter in <code>b</code> occurs in <code>a</code> including multiplicity.</p>\n\n<ul>\n\t<li>For example, <code>\"wrr\"</code> is a subset of <code>\"warrior\"</code> but is not a subset of <code>\"world\"</code>.</li>\n</ul>\n\n<p>A string <code>a</code> from <code>words1</code> is <strong>universal</strong> if for every string <code>b</code> in <code>words2</code>, <code>b</code> is a subset of <code>a</code>.</p>\n\n<p>Return an array of all the <strong>universal</strong> strings in <code>words1</code>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"e\",\"o\"]\n<strong>Output:</strong> [\"facebook\",\"google\",\"leetcode\"]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"l\",\"e\"]\n<strong>Output:</strong> [\"apple\",\"google\",\"leetcode\"]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words1.length, words2.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words1[i].length, words2[i].length &lt;= 10</code></li>\n\t<li><code>words1[i]</code> and <code>words2[i]</code> consist only of lowercase English letters.</li>\n\t<li>All the strings of <code>words1</code> are <strong>unique</strong>.</li>\n</ul>\n</div>"
  },
  {
    "path": "92-reverse-linked-list-ii/92-reverse-linked-list-ii.java",
    "content": "class Solution {\n    public ListNode reverseBetween(ListNode head, int left, int right) {\n        if (left == right || head == null) return head;\n\n        ListNode dummy = new ListNode(0);\n        dummy.next = head;\n        ListNode pre = dummy, post = dummy; \n        \n        for (int i = 1; i <= right+1; i++) {\n            if (i < left) pre = pre.next;     //Find the pre node (i.e. node before Start node)\n            post = post.next;                 //Find the post node (i.e. node after End node)\n        }\n        ListNode start = pre.next;\n        ListNode temp = post;                 //temp is reverse part which is followed by post node\n\t\t\n        while (start != post) {\n            ListNode next = start.next;\n            start.next = temp;\n            temp = start;\n            start = next;\n        }\n\t\t\n        pre.next = temp;   // pre node is followed by reversed part \n        return dummy.next;\n    }\n}"
  },
  {
    "path": "92-reverse-linked-list-ii/NOTES.md",
    "content": "​"
  },
  {
    "path": "92-reverse-linked-list-ii/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/reverse-linked-list-ii/\">92. Reverse Linked List II</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg\" style=\"width: 542px; height: 222px;\">\n<pre><strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4\n<strong>Output:</strong> [1,4,3,2,5]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> head = [5], left = 1, right = 1\n<strong>Output:</strong> [5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is <code>n</code>.</li>\n\t<li><code>1 &lt;= n &lt;= 500</code></li>\n\t<li><code>-500 &lt;= Node.val &lt;= 500</code></li>\n\t<li><code>1 &lt;= left &lt;= right &lt;= n</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you do it in one pass?</div>"
  },
  {
    "path": "923-3sum-with-multiplicity/923-3sum-with-multiplicity.java",
    "content": "class Solution {\n    public int threeSumMulti(int[] A, int target) {\n        int MOD = 1_000_000_007;\n\n        // Initializing as long saves us the trouble of\n        // managing count[x] * count[y] * count[z] overflowing later.\n        long[] count = new long[101];\n        int uniq = 0;\n        for (int x: A) {\n            count[x]++;\n            if (count[x] == 1)\n                uniq++;\n        }\n\n        int[] keys = new int[uniq];\n        int t = 0;\n        for (int i = 0; i <= 100; ++i)\n            if (count[i] > 0)\n                keys[t++] = i;\n\n        long ans = 0;\n        // Now, let's do a 3sum on \"keys\", for i <= j <= k.\n        // We will use count to add the correct contribution to ans.\n\n        for (int i = 0; i < keys.length; i++) {\n            int x = keys[i];\n            int T = target - x;\n            int j = i, k = keys.length - 1;\n            while (j <= k) {\n                int y = keys[j], z = keys[k];\n                if (y + z < T) {\n                    j++;\n                } else if (y + z > T) {\n                    k--;\n                } else {  // # x+y+z == T, now calc the size of the contribution\n                    if (i < j && j < k) {\n                        ans += count[x] * count[y] * count[z];\n                    } else if (i == j && j < k) {\n                        ans += count[x] * (count[x] - 1) / 2 * count[z];\n                    } else if (i < j && j == k) {\n                        ans += count[x] * count[y] * (count[y] - 1) / 2;\n                    } else {  // i == j == k\n                        ans += count[x] * (count[x] - 1) * (count[x] - 2) / 6;\n                    }\n\n                    ans %= MOD;\n                    j++;\n                    k--;\n                }\n            }\n        }\n\n        return (int) ans;\n    }\n}"
  },
  {
    "path": "923-3sum-with-multiplicity/NOTES.md",
    "content": "​"
  },
  {
    "path": "923-3sum-with-multiplicity/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/3sum-with-multiplicity/\">923. 3Sum With Multiplicity</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>arr</code>, and an integer <code>target</code>, return the number of tuples <code>i, j, k</code> such that <code>i &lt; j &lt; k</code> and <code>arr[i] + arr[j] + arr[k] == target</code>.</p>\n\n<p>As the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> arr = [1,1,2,2,3,3,4,4,5,5], target = 8\n<strong>Output:</strong> 20\n<strong>Explanation: </strong>\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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> arr = [1,1,2,2,2,2], target = 5\n<strong>Output:</strong> 12\n<strong>Explanation: </strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= arr.length &lt;= 3000</code></li>\n\t<li><code>0 &lt;= arr[i] &lt;= 100</code></li>\n\t<li><code>0 &lt;= target &lt;= 300</code></li>\n</ul>\n</div>"
  },
  {
    "path": "936-stamping-the-sequence/936-stamping-the-sequence.java",
    "content": "class Solution {\n    public int[] movesToStamp(String stamp, String target) {\n        char[] s = stamp.toCharArray();\n        char[] t = target.toCharArray();\n        int m = s.length, n = t.length, count = 0; // count chars replaced successfully\n\n        boolean[] visited = new boolean[n];\n        int[] res = new int[n];\n        int top = res.length;\n        while (count < n) {\n            boolean stamped = false;\n            for (int i = 0; i <= n - m; i++)\n                if (!visited[i] && canStamp(i, s, t)) {\n                    visited[i] = true;\n                    // System.out.printf(\"%s%d\\n%s\\n%s%s\\n\\n\", \" \".repeat(i), i, new String(t), \" \".repeat(i), new String(s));\n                    count = stamp(i, s, t, count);\n                    stamped = true; // successfully stamped this round\n                    res[--top] = i; // add result\n                    if (count == n) break; // all stamped\n                }\n            \n            if (!stamped) return new int[0]; // nothing found, return an empty array\n        }\n        \n        return Arrays.copyOfRange(res, top, res.length);\n    }\n    \n    private int stamp(int start, char[] s, char[] t, int count) {\n        for (int i = 0; i < s.length; i++)\n            if (t[start + i] != '*') {\n                t[start + i] = '*';\n                count++;\n            }\n        \n        return count;\n    }\n    \n    private boolean canStamp(int start, char[] s, char[] t) {\n        int count = 0;\n        for (int i = 0; i < s.length; i++) {\n            if (t[start + i] == '*') count++;\n            else if (t[start + i] != '*' && s[i] != t[start + i])\n                return false;\n        }\n\n        return count != s.length;\n    }\n}\n\n/*\nCase 0:\n\"abc\"\n\"abababcbcbababcbc\"\n\n    4\nabababcbcbababcbc\n    abc\n\n      6\nabab***bcbababcbc\n      abc\n\n            12\nabab*****bababcbc\n            abc\n\n              14\nabab*****bab***bc\n              abc\n\n  2\nabab*****bab*****\n  abc\n\n          10\nab*******bab*****\n          abc\n\n0\nab*******b*******\nabc\n\n        8\n*********b*******\n        abc\n\n\n\nCase 1:\n\"abc\"\n\"ababc\"\n\n  2\nababc\n  abc\n  \n0\nab***\nabc\n\n\"abca\"\n\"aabcaca\"\n\n 1\naabcaca\n abca\n \n   3\na****ca\n   abca\n   \n0\na******\nabca\n\n*/"
  },
  {
    "path": "936-stamping-the-sequence/NOTES.md",
    "content": "​"
  },
  {
    "path": "936-stamping-the-sequence/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/stamping-the-sequence/\">936. Stamping The Sequence</a></h2><h3>Hard</h3><hr><div><p>You are given two strings <code>stamp</code> and <code>target</code>. Initially, there is a string <code>s</code> of length <code>target.length</code> with all <code>s[i] == '?'</code>.</p>\n\n<p>In one turn, you can place <code>stamp</code> over <code>s</code> and replace every letter in the <code>s</code> with the corresponding letter from <code>stamp</code>.</p>\n\n<ul>\n\t<li>For example, if <code>stamp = \"abc\"</code> and <code>target = \"abcba\"</code>, then <code>s</code> is <code>\"?????\"</code> initially. In one turn you can:\n\n\t<ul>\n\t\t<li>place <code>stamp</code> at index <code>0</code> of <code>s</code> to obtain <code>\"abc??\"</code>,</li>\n\t\t<li>place <code>stamp</code> at index <code>1</code> of <code>s</code> to obtain <code>\"?abc?\"</code>, or</li>\n\t\t<li>place <code>stamp</code> at index <code>2</code> of <code>s</code> to obtain <code>\"??abc\"</code>.</li>\n\t</ul>\n\tNote that <code>stamp</code> must be fully contained in the boundaries of <code>s</code> in order to stamp (i.e., you cannot place <code>stamp</code> at index <code>3</code> of <code>s</code>).</li>\n</ul>\n\n<p>We want to convert <code>s</code> to <code>target</code> using <strong>at most</strong> <code>10 * target.length</code> turns.</p>\n\n<p>Return <em>an array of the index of the left-most letter being stamped at each turn</em>. If we cannot obtain <code>target</code> from <code>s</code> within <code>10 * target.length</code> turns, return an empty array.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> stamp = \"abc\", target = \"ababc\"\n<strong>Output:</strong> [0,2]\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> stamp = \"abca\", target = \"aabcaca\"\n<strong>Output:</strong> [3,0,1]\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= stamp.length &lt;= target.length &lt;= 1000</code></li>\n\t<li><code>stamp</code> and <code>target</code> consist of lowercase English letters.</li>\n</ul>\n</div>"
  },
  {
    "path": "936-stamping-the-sequence/Stamping The Sequence.cpp",
    "content": "class Solution {\npublic:\n    // Function to check whether the substring can be replaced with stamp\n    bool canReplace(string &stamp, string &target, int i, int n)\n    {        \n        for(int p=0; p<n; p++)\n            if(target[i+p] != '?' and target[i+p] != stamp[p])\n                return false;\n        \n        return true;\n    }\n    \n    // Function to replace all non '?' to '?' and return no. of changed value\n    void replace(string &stamp, string &target, int i, int n, int &cnt)\n    {        \n        for(int p=0; p<n; p++)\n            if(target[i+p] != '?')\n                cnt++, target[i+p] = '?';\n    }\n    \n    vector<int> movesToStamp(string stamp, string target) {\n        \n        int n = stamp.length(), m = target.length(), cnt = 0;\n        \n        vector<int> ans;\n        vector<bool> visited(m,false);\n        \n        while(cnt < m)\n        {\n            bool f = false;\n            \n            for(int i=0; i<=m-n; i++)\n                if(!visited[i] and canReplace(stamp, target, i, n))\n                {\n                    replace(stamp, target, i, n, cnt);\n                    ans.push_back(i);\n                    visited[i] = f = true;\n                }\n            \n            if(!f)\n                break;\n        }\n        \n        if(cnt < m)\n            return {};\n        \n        reverse(ans.begin(), ans.end());\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "936-stamping-the-sequence/stamping-the-sequence.cpp",
    "content": "// What I basiclly did here is trying to reverse the whole operations.\n// The operation token later will be more apperant than the operation token before. The letters which stamped later will cover the letters stamped before and we really don't care about the letters which are covered.\n\n//  *  *  *  *  *  *  *\n//  *  *  * |a  b  c  a|\n// |a  b  c  a| b  c  a\n//  a |a  b  c  a| c  a\n// We just try to match the stamp with the target. Since we do not care about the letters which are coverd by others, so we can apply a * match any letters. For example:\n\n// \"aabcaca\" -> \"a****ca\" -> \"*****ca\"->\"*******\"\n\n\nclass Solution {\npublic:\n    vector<int> movesToStamp(string stamp, string target) {\n        vector<int> ans;\n        vector<int> output;\n        string str = target;\n        string aim(target.length(),'*');\n        while(str != aim){\n            int tmp = remove(str,stamp); // index of first match case when stamp is found in str or target.\n            if(tmp == str.length()) return output;\n            ans.push_back(tmp);\n        }\n        for(int iter=ans.size()-1;iter>=0;--iter) output.push_back(ans[iter]);\n        return output;\n    }\n    int remove(string& str, string stamp){\n        for(int iter=0;iter<str.length();++iter){\n            int jter=0,tmp=iter;\n            bool flag=false;\n            while(jter<stamp.length() && tmp<str.length() && (str[tmp]=='*' || str[tmp]==stamp[jter])){\n                if(str[tmp]==stamp[jter]) flag=true;\n                tmp++;\n                jter++;\n            }\n            if(jter==stamp.length() && flag){\n                for(int kter=0;kter<stamp.length();++kter)\n                    str[iter+kter]='*';\n                return iter;\n            }\n        }\n        return str.length();\n    }\n};\n"
  },
  {
    "path": "94-binary-tree-inorder-traversal/94-binary-tree-inorder-traversal.java",
    "content": "/**\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<Integer> inorderTraversal(TreeNode root) {\n        List<Integer> list=new ArrayList<>();\n        inOrder(root,list);\n        return list;\n    }\n    void inOrder(TreeNode root,List<Integer> list){\n        if(root==null)return;\n        inOrder(root.left,list);\n        list.add(root.val);\n        inOrder(root.right,list);\n    }\n}"
  },
  {
    "path": "94-binary-tree-inorder-traversal/Binary Tree InOrder Traversal lc.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n/**\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<int> res;\n    void inorder(TreeNode* node){\n        if(!node) return;\n//         traverse the left node\n        inorder(node->left);\n//         do something with node value here\n        res.push_back(node->val);\n//         traverse right\n        inorder(node->right);\n    }\n    vector<int> inorderTraversal(TreeNode* root) {\n        inorder(root);\n        return res;\n    }\n};"
  },
  {
    "path": "94-binary-tree-inorder-traversal/NOTES.md",
    "content": "​"
  },
  {
    "path": "94-binary-tree-inorder-traversal/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-tree-inorder-traversal/\">94. Binary Tree Inorder Traversal</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes' values</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg\" style=\"width: 125px; height: 200px;\">\n<pre><strong>Input:</strong> root = [1,null,2,3]\n<strong>Output:</strong> [1,3,2]\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> root = [1]\n<strong>Output:</strong> [1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</div>"
  },
  {
    "path": "94. Binary Tree Inorder Traversal.cpp",
    "content": "class Solution {\npublic:\n    void solve(TreeNode *root,vector<int> &result)\n    {\n        if(root == NULL){\n            return ;\n        }\n        solve(root->left,result);\n        result.push_back(root->val);\n        solve(root->right,result);\n    }\n    vector<int> inorderTraversal(TreeNode* root) {\n        vector<int> result;\n        solve(root,result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "948 Bag of Tokens lc med.cpp",
    "content": "class Solution {\npublic:\n    int bagOfTokensScore(vector<int>& tokens, int power) {\n//         approach 2 pointer tech\n        // sort, then define 2 pointer , start =0, and end\n//         check\n        sort(tokens.begin(), tokens.end());\n        int left_start =0, right_end = tokens.size()-1;\n        int score =0; // initializing score 0\n        while(left_start<=right_end){\n            if(power>=tokens[left_start]){\n                \n                power-=tokens[left_start++];\n                score++;\n            }else{\n                if(power+tokens[right_end]>= tokens[left_start] && score!=0 && right_end !=left_start){\n                    power+= tokens[right_end--];\n                    score--;\n                }else break;\n            }\n        }\n        return score;\n    }\n};"
  },
  {
    "path": "948-bag-of-tokens/948-bag-of-tokens.java",
    "content": "class Solution {\n    public int bagOfTokensScore(int[] tokens, int power) {\n        Arrays.sort(tokens);\n        int i=0;\n        int j=tokens.length-1;\n        int ans=0;\n        int curr=0;\n        while(i<=j){\n            if(power>=tokens[i]){\n                power-=tokens[i];\n                curr++;\n                ans=Math.max(ans,curr);\n                i++;\n            }else{\n                if(curr==0)break;\n                power+=tokens[j];\n                curr--;\n                j--;\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "948-bag-of-tokens/NOTES.md",
    "content": "​"
  },
  {
    "path": "948-bag-of-tokens/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/bag-of-tokens/\">948. Bag of Tokens</a></h2><h3>Medium</h3><hr><div><p>You have an initial <strong>power</strong> of <code>power</code>, an initial <strong>score</strong> of <code>0</code>, and a bag of <code>tokens</code> where <code>tokens[i]</code> is the value of the <code>i<sup>th</sup></code> token (0-indexed).</p>\n\n<p>Your goal is to maximize your total <strong>score</strong> by potentially playing each token in one of two ways:</p>\n\n<ul>\n\t<li>If your current <strong>power</strong> is at least <code>tokens[i]</code>, you may play the <code>i<sup>th</sup></code> token face up, losing <code>tokens[i]</code> <strong>power</strong> and gaining <code>1</code> <strong>score</strong>.</li>\n\t<li>If your current <strong>score</strong> is at least <code>1</code>, you may play the <code>i<sup>th</sup></code> token face down, gaining <code>tokens[i]</code> <strong>power</strong> and losing <code>1</code> <strong>score</strong>.</li>\n</ul>\n\n<p>Each token may be played <strong>at most</strong> once and <strong>in any order</strong>. You do <strong>not</strong> have to play all the tokens.</p>\n\n<p>Return <em>the largest possible <strong>score</strong> you can achieve after playing any number of tokens</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> tokens = [100], power = 50\n<strong>Output:</strong> 0\n<strong>Explanation</strong><strong>:</strong> Playing the only token in the bag is impossible because you either have too little power or too little score.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> tokens = [100,200], power = 150\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> Play the 0<sup>th</sup> token (100) face up, your power becomes 50 and score becomes 1.\nThere is no need to play the 1<sup>st</sup> token since you cannot play it face up to add to your score.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> tokens = [100,200,300,400], power = 200\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Play the tokens in this order to get a score of 2:\n1. Play the 0<sup>th</sup> token (100) face up, your power becomes 100 and score becomes 1.\n2. Play the 3<sup>rd</sup> token (400) face down, your power becomes 500 and score becomes 0.\n3. Play the 1<sup>st</sup> token (200) face up, your power becomes 300 and score becomes 1.\n4. Play the 2<sup>nd </sup>token (300) face up, your power becomes 0 and score becomes 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= tokens.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= tokens[i],&nbsp;power &lt; 10<sup>4</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "96-Unique Binary Search Trees.java",
    "content": "// Using Memoization\n\npublic static int helper(int n, int[] dp) {\n        if(n<=1) return dp[n] = 1;\n        \n        if(dp[n] != -1) {\n            return dp[n];\n        }\n        int ans = 0;\n        for(int i = 0; i < n; i++) {\n            ans += helper(i, dp) * helper(n-i-1, dp);\n        }\n        return dp[n] = ans;\n    }\n    public int numTrees(int n) {\n        int[] dp = new int[n+1];\n        Arrays.fill(dp, -1);\n        return helper(n, dp);  \n    }\n\n// Using Tabulation\n\npublic int numTrees(int n) {\n        int[] dp = new int[n+1];\n        dp[0] = 1;\n        dp[1] = 1;\n        \n        for(int i = 2; i <= n; i++) {\n            for(int j =0; j < i; j++) {\n                dp[i] += (dp[j] * dp[i-j-1]);\n            }\n        }\n        return dp[n];  \n    }\n"
  },
  {
    "path": "967-numbers-with-same-consecutive-differences/967-numbers-with-same-consecutive-differences.java",
    "content": "class Solution {\n    List<Integer> ans;\n    public int[] numsSameConsecDiff(int n, int k) {\n        ans=new ArrayList<>();\n        for(int i=1;i<10;i++){\n            dfs(i,n,k);\n        }\n        int[] arr=new int[ans.size()];\n        int i=0;\n        for(int ele:ans){\n            arr[i++]=ele;\n        }\n        return arr;\n    }\n    void dfs(int num,int n,int k){\n        if((int)Math.floor(Math.log10(num) + 1)==n){\n            ans.add(num);\n            return;\n        }\n        int last=num%10;\n        if(k==0){\n            dfs(num*10+(last+k),n,k);\n            return;\n        }\n        if(last+k<10){\n            dfs(num*10+(last+k),n,k);\n        }\n        if(last-k>-1){\n            dfs(num*10+(last-k),n,k);\n        }\n    }\n}"
  },
  {
    "path": "967-numbers-with-same-consecutive-differences/NOTES.md",
    "content": "​"
  },
  {
    "path": "967-numbers-with-same-consecutive-differences/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/numbers-with-same-consecutive-differences/\">967. Numbers With Same Consecutive Differences</a></h2><h3>Medium</h3><hr><div><p>Return all <strong>non-negative</strong> integers of length <code>n</code> such that the absolute difference between every two consecutive digits is <code>k</code>.</p>\n\n<p>Note that <strong>every</strong> number in the answer <strong>must not</strong> have leading zeros. For example, <code>01</code> has one leading zero and is invalid.</p>\n\n<p>You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> n = 3, k = 7\n<strong>Output:</strong> [181,292,707,818,929]\n<strong>Explanation:</strong> Note that 070 is not a valid number, because it has leading zeroes.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> n = 2, k = 1\n<strong>Output:</strong> [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= n &lt;= 9</code></li>\n\t<li><code>0 &lt;= k &lt;= 9</code></li>\n</ul>\n</div>"
  },
  {
    "path": "968-binary-tree-cameras/968-binary-tree-cameras.java",
    "content": "class Solution {\n    private int NOT_MONITORED = 0;\n    private int MONITORED_NOCAM = 1;\n    private int MONITORED_WITHCAM = 2;\n    private int cameras = 0;\n    \n    public int minCameraCover(TreeNode root) {\n        int top = dfs(root);\n        return top == NOT_MONITORED ? cameras+1 :cameras;\n    }\n    \n    private int dfs (TreeNode root){\n        if(root == null)return MONITORED_NOCAM;\n        int left = dfs(root.left);\n        int right = dfs(root.right);\n        \n        if (left == MONITORED_NOCAM && right == MONITORED_NOCAM) {\n            return NOT_MONITORED;\n        } else if (left == NOT_MONITORED || right == NOT_MONITORED) {\n            cameras++;\n            return MONITORED_WITHCAM;\n        } else {\n            return MONITORED_NOCAM;\n        }\n    }\n}"
  },
  {
    "path": "968-binary-tree-cameras/NOTES.md",
    "content": "​"
  },
  {
    "path": "968-binary-tree-cameras/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-tree-cameras/\">968. Binary Tree Cameras</a></h2><h3>Hard</h3><hr><div><p>You are given the <code>root</code> 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.</p>\n\n<p>Return <em>the minimum number of cameras needed to monitor all nodes of the tree</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_01.png\" style=\"width: 138px; height: 163px;\">\n<pre><strong>Input:</strong> root = [0,0,null,0,0]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> One camera is enough to monitor all nodes if placed as shown.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_02.png\" style=\"width: 139px; height: 312px;\">\n<pre><strong>Input:</strong> root = [0,0,null,0,null,0,null,null,0]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>\n\t<li><code>Node.val == 0</code></li>\n</ul>\n</div>"
  },
  {
    "path": "97-interleaving-string/97-interleaving-string.java",
    "content": "class Solution {\n    public boolean isInterleave(String s1, String s2, String s3) {\n        boolean[][] canReach = new boolean[s1.length()][s2.length()];\n        return isInterleaveHelper(s1, s2, s3, 0, 0, 0, canReach);\n    }\n    \n    private boolean isInterleaveHelper(String s1, String s2, String s3, int i1, int i2, int i3, boolean[][] canReach) {\n        if (i3 == s3.length()) {\n            if (i1 == s1.length() && i2 == s2.length()) return true;\n            return false;\n        }\n        if (i1 == s1.length()) {\n            return s2.substring(i2, s2.length()).equals(s3.substring(i3, s3.length()));\n        }\n        if (i2 == s2.length()) {\n            return s1.substring(i1, s1.length()).equals(s3.substring(i3, s3.length()));\n        }\n        if (canReach[i1][i2]) return false;\n        canReach[i1][i2] = true;\n        boolean s1Match = (s1.charAt(i1) == s3.charAt(i3));\n        boolean s2Match = (s2.charAt(i2) == s3.charAt(i3));\n        if (s1Match && s2Match) {\n            return isInterleaveHelper(s1, s2, s3, i1 + 1, i2, i3 + 1, canReach) || isInterleaveHelper(s1, s2, s3, i1, i2 + 1, i3 + 1, canReach);\n        }\n        else if (s1Match) {\n            return isInterleaveHelper(s1, s2, s3, i1 + 1, i2, i3 + 1, canReach);\n        }\n        else if (s2Match) {\n            return isInterleaveHelper(s1, s2, s3, i1, i2 + 1, i3 + 1, canReach);\n        }\n        else {\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "97-interleaving-string/NOTES.md",
    "content": "​"
  },
  {
    "path": "97-interleaving-string/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/interleaving-string/\">97. Interleaving String</a></h2><h3>Medium</h3><hr><div><p>Given strings <code>s1</code>, <code>s2</code>, and <code>s3</code>, find whether <code>s3</code> is formed by an <strong>interleaving</strong> of <code>s1</code> and <code>s2</code>.</p>\n\n<p>An <strong>interleaving</strong> of two strings <code>s</code> and <code>t</code> is a configuration where they are divided into <strong>non-empty</strong> substrings such that:</p>\n\n<ul>\n\t<li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li>\n\t<li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li>\n\t<li><code>|n - m| &lt;= 1</code></li>\n\t<li>The <strong>interleaving</strong> is <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> or <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li>\n</ul>\n\n<p><strong>Note:</strong> <code>a + b</code> is the concatenation of strings <code>a</code> and <code>b</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg\" style=\"width: 561px; height: 203px;\">\n<pre><strong>Input:</strong> s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbcbcac\"\n<strong>Output:</strong> true\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbbaccc\"\n<strong>Output:</strong> false\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> s1 = \"\", s2 = \"\", s3 = \"\"\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= s3.length &lt;= 200</code></li>\n\t<li><code>s1</code>, <code>s2</code>, and <code>s3</code> consist of lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you solve it using only <code>O(s2.length)</code> additional memory space?</p>\n</div>"
  },
  {
    "path": "98-validate-binary-search-tree/98-validate-binary-search-tree.java",
    "content": "/**\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 boolean isValidBST(TreeNode root) {\n        return dfs(root,Long.MIN_VALUE,Long.MAX_VALUE);\n    }\n    boolean dfs(TreeNode root,long lower,long upper){\n        if(root==null)return true;\n        if(root.val<=lower || root.val>=upper)return false;\n        return dfs(root.left,lower,root.val) && dfs(root.right,root.val,upper);\n    }\n}"
  },
  {
    "path": "98-validate-binary-search-tree/NOTES.md",
    "content": "​"
  },
  {
    "path": "98-validate-binary-search-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/validate-binary-search-tree/\">98. Validate Binary Search Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p>\n\n<p>A <strong>valid BST</strong> is defined as follows:</p>\n\n<ul>\n\t<li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node's key.</li>\n\t<li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node's key.</li>\n\t<li>Both the left and right subtrees must also be binary search trees.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg\" style=\"width: 302px; height: 182px;\">\n<pre><strong>Input:</strong> root = [2,1,3]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg\" style=\"width: 422px; height: 292px;\">\n<pre><strong>Input:</strong> root = [5,1,4,null,null,3,6]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The root node's value is 5 but its right child's value is 4.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n</div>"
  },
  {
    "path": "981-time-based-key-value-store/981-time-based-key-value-store.java",
    "content": "class TimeValue {\n    \n    public int time;\n    public String value;\n    \n    public TimeValue(int time, String value) {\n        \n        this.time = time;\n        this.value = value;\n    }\n    \n    public String toString() {\n        \n        return \"TimeValue with time \" + this.time \n            + \" and value \" + this.value;\n    }\n}\n\nclass TimeMap {\n    \n    private Map<String, List<TimeValue>> map = new HashMap<>();\n\n    public TimeMap() {\n        \n    }\n    \n    public void set(String key, String value, int timestamp) {\n        \n        // Add the given (key, timestamp) combination \n        \n        TimeValue newTimeValue = new TimeValue(timestamp, value);\n        \n        if (!this.map.containsKey(key)) {\n            \n            this.map.put(key, new ArrayList<>());\n        }\n        \n        this.map.get(key).add(newTimeValue);\n        \n        // System.out.println(this.map.get(key));\n    }\n    \n    public String get(String key, int timestamp) {\n        \n        List<TimeValue> list = this.map.get(key);\n        \n        if (list == null) {\n            \n            return \"\";\n        }\n        \n        // Binary search \n        int left = 0;\n        int right = list.size() - 1;\n        \n        TimeValue best = null;\n        \n        while (left <= right) {\n            \n            int mid = left + (right - left) / 2;\n            \n            if (list.get(mid).time <= timestamp) {\n                \n                // Valid time \n                best = list.get(mid);\n                left = mid + 1;\n            } else {\n                \n                right = mid - 1;\n            }\n        }\n        \n        return (best != null ? best.value : \"\");\n    }\n}"
  },
  {
    "path": "981-time-based-key-value-store/NOTES.md",
    "content": "​"
  },
  {
    "path": "981-time-based-key-value-store/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/time-based-key-value-store/\">981. Time Based Key-Value Store</a></h2><h3>Medium</h3><hr><div><p>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.</p>\n\n<p>Implement the <code>TimeMap</code> class:</p>\n\n<ul>\n\t<li><code>TimeMap()</code> Initializes the object of the data structure.</li>\n\t<li><code>void set(String key, String value, int timestamp)</code> Stores the key <code>key</code> with the value <code>value </code>at the given time <code>timestamp</code>.</li>\n\t<li><code>String get(String key, int timestamp)</code> Returns a value such that <code>set</code> was called previously, with <code>timestamp_prev &lt;= timestamp</code>. If there are multiple such values, it returns the value associated with the largest <code>timestamp_prev</code>. If there are no values, it returns <code>\"\"</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input</strong>\n[\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n[[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]\n<strong>Output</strong>\n[null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]\n\n<strong>Explanation</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= key.length, value.length &lt;= 100</code></li>\n\t<li><code>key</code> and <code>value</code> consist of lowercase English letters and digits.</li>\n\t<li><code>1 &lt;= timestamp &lt;= 10<sup>7</sup></code></li>\n\t<li>All the timestamps <code>timestamp</code> of <code>set</code> are strictly increasing.</li>\n\t<li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>set</code> and <code>get</code>.</li>\n</ul>\n</div>"
  },
  {
    "path": "985 Sum of Even Numbers After Queries lc med.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n        int S =0;\n        for(auto x : nums)\n            if(x%2==0) S+=x;\n        \n        vector<int>res;\n        \n        for(auto q : queries ){\n            int val = q[0], idx = q[1];\n//             if original nums[idx] is even, then we deduct it from evenSum\n            if(nums[idx] % 2==0) S-=nums[idx];\n//             in-place update nums\n            nums[idx]+=val;\n//             check if we need to update evenSum for the new value\n            if (nums[idx] % 2 == 0) S += nums[idx];\n//             then we have evenSum after this query, push it to ans \n            res.push_back(S);\n\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "985-sum-of-even-numbers-after-queries/985-sum-of-even-numbers-after-queries.java",
    "content": "class Solution {\n    public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {\n        int sum=0;\n        for(int i:nums){\n            if((i&1)==0)sum+=i;\n        }\n        int[]ans=new int[queries.length];\n        for(int i=0;i<queries.length;i++){\n            if((nums[queries[i][1]]&1)==0){\n                sum-=nums[queries[i][1]];\n            }\n            nums[queries[i][1]]+=queries[i][0];\n            if((nums[queries[i][1]]&1)==0){\n                sum+=nums[queries[i][1]];\n            }\n            ans[i]=sum;\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "985-sum-of-even-numbers-after-queries/NOTES.md",
    "content": "​"
  },
  {
    "path": "985-sum-of-even-numbers-after-queries/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/sum-of-even-numbers-after-queries/\">985. Sum of Even Numbers After Queries</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>nums</code> and an array <code>queries</code> where <code>queries[i] = [val<sub>i</sub>, index<sub>i</sub>]</code>.</p>\n\n<p>For each query <code>i</code>, first, apply <code>nums[index<sub>i</sub>] = nums[index<sub>i</sub>] + val<sub>i</sub></code>, then print the sum of the even values of <code>nums</code>.</p>\n\n<p>Return <em>an integer array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the answer to the </em><code>i<sup>th</sup></code><em> query</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]\n<strong>Output:</strong> [8,6,2,4]\n<strong>Explanation:</strong> At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> nums = [1], queries = [[4,0]]\n<strong>Output:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= queries.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= val<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= index<sub>i</sub> &lt; nums.length</code></li>\n</ul>\n</div>"
  },
  {
    "path": "987-vertical-order-traversal-of-a-binary-tree/987-vertical-order-traversal-of-a-binary-tree.java",
    "content": "/**\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    Map<Integer,PriorityQueue<int[]>> map;\n    int min;\n    public List<List<Integer>> verticalTraversal(TreeNode root) {\n        map=new HashMap<>();\n        min=Integer.MAX_VALUE;\n        dfs(root,0,0);\n        List<List<Integer>> ans=new ArrayList<>();\n        while(map.containsKey(min)){\n            PriorityQueue<int[]>pq=map.get(min);\n            List<Integer> ls=new ArrayList<>();\n            while(pq.size()>0){\n                ls.add(pq.remove()[0]);\n            }\n            ans.add(ls);\n            min++;\n        }\n        return ans;\n    }\n    void dfs(TreeNode root,int row,int col){\n        if(root==null)return;\n        min=Math.min(min,col);\n        PriorityQueue<int[]> pq;\n        if(map.containsKey(col)){\n            pq=map.get(col);\n        }else{\n            pq=new PriorityQueue<>((a,b)->{\n                if(a[1]==b[1]){\n                    return a[0]-b[0];\n                }\n                return a[1]-b[1];\n            });\n        }\n        pq.add(new int[]{root.val,row});\n        map.put(col,pq);\n        dfs(root.left,row+1,col-1);\n        dfs(root.right,row+1,col+1);\n    }\n}\n\n################  Approach-2 by @Jay-Thesia  ###########################3\n\nclass Solution {\n\n    class Pair{\n\n        TreeNode value;\n        int hdist;\n\n        Pair(TreeNode value,int hdist){\n            this.value=value;\n            this.hdist=hdist;\n        }\n\n    }\n    public List<List<Integer>> verticalTraversal(TreeNode root) {\n\n        List<List<Integer>> outter=new ArrayList<>();\n\n        TreeMap<Integer,ArrayList<Integer>>  tm=new TreeMap();\n\n        Deque<Pair> q=new LinkedList<>();\n        q.add(new Pair(root,0));\n\n        while(q.size()>0){\n\n            int len=q.size();\n            HashMap<Integer,ArrayList<Integer>> hm=new HashMap<>();\n\n            for(int i=0;i<len;i++){\n                //RPA\n                Pair curr=q.remove();\n                TreeNode cVal=curr.value;\n                int cHdist=curr.hdist;\n\n                List<Integer> inner=hm.getOrDefault(cHdist,new ArrayList<>());\n                inner.add(cVal.val);\n                Collections.sort(inner);\n\n                hm.put(cHdist,new ArrayList<>(inner));\n\n                if(cVal.left!=null) q.add(new Pair(cVal.left,cHdist-1));\n                if(cVal.right!=null) q.add(new Pair(cVal.right,cHdist+1));\n            }\n\n            for(Map.Entry<Integer,ArrayList<Integer>> item:hm.entrySet()){\n\n                ArrayList<Integer> list=tm.getOrDefault(item.getKey(),new ArrayList<>());\n                list.addAll(item.getValue());\n                tm.put(item.getKey(),list);\n\n            }\n        }\n\n        return new ArrayList<>(tm.values());\n\n\n    }\n}\n"
  },
  {
    "path": "987-vertical-order-traversal-of-a-binary-tree/NOTES.md",
    "content": "key=col\nval=pq -> sorting acc to row || val\n[0] -> val\n[1] -> row"
  },
  {
    "path": "987-vertical-order-traversal-of-a-binary-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/\">987. Vertical Order Traversal of a Binary Tree</a></h2><h3>Hard</h3><hr><div><p>Given the <code>root</code> of a binary tree, calculate the <strong>vertical order traversal</strong> of the binary tree.</p>\n\n<p>For each node at position <code>(row, col)</code>, its left and right children will be at positions <code>(row + 1, col - 1)</code> and <code>(row + 1, col + 1)</code> respectively. The root of the tree is at <code>(0, 0)</code>.</p>\n\n<p>The <strong>vertical order traversal</strong> 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.</p>\n\n<p>Return <em>the <strong>vertical order traversal</strong> of the binary tree</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/29/vtree1.jpg\" style=\"width: 431px; height: 304px;\">\n<pre><strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> [[9],[3,15],[20],[7]]\n<strong>Explanation:</strong>\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.</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/29/vtree2.jpg\" style=\"width: 512px; height: 304px;\">\n<pre><strong>Input:</strong> root = [1,2,3,4,5,6,7]\n<strong>Output:</strong> [[4],[2],[1,5,6],[3],[7]]\n<strong>Explanation:</strong>\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</pre>\n\n<p><strong>Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/29/vtree3.jpg\" style=\"width: 512px; height: 304px;\">\n<pre><strong>Input:</strong> root = [1,2,3,4,6,5,7]\n<strong>Output:</strong> [[4],[2],[1,5,6],[3],[7]]\n<strong>Explanation:</strong>\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</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n</div>"
  },
  {
    "path": "99-recover-binary-search-tree/99-recover-binary-search-tree.java",
    "content": "class Solution {\n    TreeNode prev = null;\n    TreeNode first = null;\n    TreeNode second = null;\n    public void recoverTree(TreeNode root) {\n        inorder(root);\n        swap(first,second);\n    }\n    public void swap(TreeNode a, TreeNode b) {\n        int temp = a.val;\n        a.val=b.val;\n        b.val=temp;\n    }\n    public void inorder(TreeNode root) {\n        if(root!=null) {\n            if(root.left!=null) {\n                inorder(root.left);\n            }\n            if(prev!=null && prev.val>root.val) {\n                if(first==null) {\n                    first=prev;\n                } \n                if(first!=null) {\n                    second=root;\n                }\n            }\n            prev=root;\n            if(root.right!=null) {\n                inorder(root.right);\n            }\n        }\n    }\n}"
  },
  {
    "path": "99-recover-binary-search-tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/recover-binary-search-tree/\">99. Recover Binary Search Tree</a></h2><h3>Medium</h3><hr><div><p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg\" style=\"width: 422px; height: 302px;\">\n<pre><strong>Input:</strong> root = [1,3,null,null,2]\n<strong>Output:</strong> [3,1,null,null,2]\n<strong>Explanation:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg\" style=\"width: 581px; height: 302px;\">\n<pre><strong>Input:</strong> root = [3,1,4,null,null,2]\n<strong>Output:</strong> [2,1,4,null,null,3]\n<strong>Explanation:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution?</div>"
  },
  {
    "path": "990-satisfiability-of-equality-equations/990-satisfiability-of-equality-equations.java",
    "content": "class Solution {\n    int[] parent = new int[26];\n    public int find(int x) {\n        // with path compression\n        if (parent[x] == x) return x;\n        return parent[x] = find(parent[x]);\n        // without path compression\n        // return parent[x] == x ? x : find(parent[x]);\n    }\n    // the idea is to put all characters in the same group if they are equal\n    // in order to do that, we can use Disjoint Set Union (dsu) aka Union Find\n    // for dsu tutorial, please check out https://wingkwong.github.io/leetcode-the-hard-way/tutorials/graph-theory/disjoint-set-union\n    public boolean equationsPossible(String[] equations) {\n        int n = equations.length;\n        // at the beginning, put each character index in its own group\n        // so we will have 26 groups with one character each\n        // i.e. 'a' in group 0, 'b' in group 1, ..., 'z' in group 25\n        for (int i = 0; i < 26; i++) parent[i] = i;\n        for (String e : equations) {\n            // if two character is equal, \n            if (e.charAt(1) == '=') {\n                // e.g. a = b\n                // then we group them together\n                // how? we use `find` function to find out the parent group of the target character index\n                // then update parent. a & b would be in group 1 (i.e. a merged into the group where b belongs to)\n                // or you can also do `parent[find(e.charAt(3)- 'a')] = find(e.charAt(0) - 'a');` (i.e. b merged into the group where a belongs to)\n                parent[find(e.charAt(0)- 'a')] = find(e.charAt(3) - 'a');\n            }\n        }\n        // handle != case\n        for (String e : equations) {\n            // if two characters are not equal\n            // then which means their parent must not be equal\n            if (e.charAt(1) == '!' && find(e.charAt(0) - 'a') == find(e.charAt(3) - 'a')) {\n                return false;\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "990-satisfiability-of-equality-equations/NOTES.md",
    "content": "​"
  },
  {
    "path": "990-satisfiability-of-equality-equations/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/satisfiability-of-equality-equations/\">990. Satisfiability of Equality Equations</a></h2><h3>Medium</h3><hr><div><p>You are given an array of strings <code>equations</code> that represent relationships between variables where each string <code>equations[i]</code> is of length <code>4</code> and takes one of two different forms: <code>\"x<sub>i</sub>==y<sub>i</sub>\"</code> or <code>\"x<sub>i</sub>!=y<sub>i</sub>\"</code>.Here, <code>x<sub>i</sub></code> and <code>y<sub>i</sub></code> are lowercase letters (not necessarily different) that represent one-letter variable names.</p>\n\n<p>Return <code>true</code><em> if it is possible to assign integers to variable names so as to satisfy all the given equations, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> equations = [\"a==b\",\"b!=a\"]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> 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</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> equations = [\"b==a\",\"a==b\"]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> We could assign a = 1 and b = 1 to satisfy both equations.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= equations.length &lt;= 500</code></li>\n\t<li><code>equations[i].length == 4</code></li>\n\t<li><code>equations[i][0]</code> is a lowercase letter.</li>\n\t<li><code>equations[i][1]</code> is either <code>'='</code> or <code>'!'</code>.</li>\n\t<li><code>equations[i][2]</code> is <code>'='</code>.</li>\n\t<li><code>equations[i][3]</code> is a lowercase letter.</li>\n</ul>\n</div>"
  },
  {
    "path": "991-broken-calculator/991-broken-calculator.java",
    "content": "class Solution {\n    public int brokenCalc(int startValue, int target) {\n        int ans = 0;\n        while (target > startValue) {\n            ans++;\n            if (target % 2 == 1)\n                target++;\n            else\n                target /= 2;\n        }\n\n        return ans + startValue - target;\n    }\n}"
  },
  {
    "path": "991-broken-calculator/NOTES.md",
    "content": "​"
  },
  {
    "path": "991-broken-calculator/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/broken-calculator/\">991. Broken Calculator</a></h2><h3>Medium</h3><hr><div><p>There is a broken calculator that has the integer <code>startValue</code> on its display initially. In one operation, you can:</p>\n\n<ul>\n\t<li>multiply the number on display by <code>2</code>, or</li>\n\t<li>subtract <code>1</code> from the number on display.</li>\n</ul>\n\n<p>Given two integers <code>startValue</code> and <code>target</code>, return <em>the minimum number of operations needed to display </em><code>target</code><em> on the calculator</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> startValue = 2, target = 3\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Use double operation and then decrement operation {2 -&gt; 4 -&gt; 3}.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> startValue = 5, target = 8\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Use decrement and then double {5 -&gt; 4 -&gt; 8}.\n</pre>\n\n<p><strong>Example 3:</strong></p>\n\n<pre><strong>Input:</strong> startValue = 3, target = 10\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Use double, decrement and double {3 -&gt; 6 -&gt; 5 -&gt; 10}.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= x, y &lt;= 10<sup>9</sup></code></li>\n</ul>\n</div>"
  },
  {
    "path": "Add 1 to linked list.java",
    "content": "class Solution\n{\n    public static Node addOne(Node head) \n    { \n        //code here.\n        Node newHead=reverse(head);\n        Node list=newHead;\n        while(list!=null){\n            if(list.data<9){\n                list.data++;\n                break;\n            }else{\n                if(list.next==null){\n                    list.next=new Node(0);\n                }\n                list.data=0;\n                list=list.next;\n            }\n        }\n        return reverse(newHead);\n        \n    }\n    public static Node reverse(Node head){\n        Node cur=head;\n        Node prev=null;\n        while(cur!=null){\n            Node temp=cur.next;\n            cur.next=prev;\n            prev=cur;\n            cur=temp;\n        }\n        return prev;\n    }\n}\n"
  },
  {
    "path": "Add Binary Strings.java",
    "content": "import java.math.BigInteger;\npublic class Solution {\n    public String addBinary(String A, String B) {\n        BigInteger a = new BigInteger(A, 2);\n        BigInteger b = new BigInteger(B, 2);\n        BigInteger c=a.add(b);\n        return c.toString(2);\n    }\n}\n\n==========================================================\n    public class Solution {\n    public String addBinary(String A, String B) {\n        StringBuilder sb = new StringBuilder();\n        int i = A.length() - 1;\n        int j = B.length() - 1;\n        int carry = 0;\n        while(i>=0||j>=0){\n            int sum = carry;\n            if(i>=0) sum =sum+A.charAt(i)-'0';\n            if(j>=0) sum += B.charAt(j)-'0';\n            sb.append(sum%2);\n            carry = sum/2;\n            i--;j--;\n        }\n        if(carry!=0) sb.append(carry);\n        return sb.reverse().toString();\n    }\n}\n"
  },
  {
    "path": "Add Digits.java",
    "content": "class Solution {\n    public int addDigits(int num) {\n        if(num % 9 == 0 && num != 0) return 9;\n        return num % 9;\n    }\n}\n"
  },
  {
    "path": "Add One To Array.java",
    "content": "public class Solution {\n    public int[] plusOne(int[] a) {\n        //if all elements are 9 than increase size\n        if(allNines(a)){\n            int[]ans=new int[a.length+1];\n            ans[0]=1;\n            return ans;\n        }else{\n            // add 1 to specified position\n            for(int i=a.length-1;i>=0;i--){\n                if(a[i]+1<10){\n                    a[i]=a[i]+1;\n                    break;\n                }else{\n                    a[i]=0;\n                }\n            }\n            //check if there are preceding zeroes if yes then store index of first nonzero digit index\n            int start=0;\n            for(int i=0;i<a.length;i++){\n                if(a[i]!=0){\n                    start=i;\n                    break;\n                }\n            }\n            // new array of size= size-no. of preceding zeroes\n            int[]ans=new int[a.length-start];\n            for(int i=0;i<ans.length;i++){\n                ans[i]=a[start+i];\n            }\n            return ans;\n        }\n    }\n    //helper fxn to check if there are all zeroes\n    public boolean allNines(int[]a){\n        for(int i=0;i<a.length;i++){\n            if(a[i]!=9){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "Add Two Numbers.java",
    "content": "class Solution {\n    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n        int carry = 0;\n        \n        ListNode dummyHead = new ListNode(-1);\n        ListNode curr = dummyHead;\n        \n        while (l1 != null || l2 != null) {\n            int v1 = l1 == null ? 0 : l1.val;\n            int v2 = l2 == null ? 0 : l2.val;\n            \n            int sum = v1 + v2 + carry;\n            carry = sum / 10;\n            sum = sum % 10;\n            \n            curr.next = new ListNode(sum);\n            curr = curr.next;\n            \n            l1 = l1 == null ? l1 : l1.next;\n            l2 = l2 == null ? l2 : l2.next;\n        }\n        \n        if (carry == 1) {\n            curr.next = new ListNode(1);\n        }\n        \n        return dummyHead.next;\n    }\n}\n"
  },
  {
    "path": "Add all greater values to every node in a BST.java",
    "content": "class Solution{\n    \n    // modify the BST and return its root\n    public Node modify(Node root){\n        //Write your code here\n        mod(root,0);\n        return root;\n    }\n    public void mod(Node node,int increment){\n        if(node!=null){\n            node.data=node.data+sum(node.right)+increment;\n            mod(node.right,increment);\n            mod(node.left,node.data);\n        }        \n    }\n    public int sum(Node node){\n        if(node==null)return 0;\n        return node.data+sum(node.left)+sum(node.right);\n    }\n    \n}\n"
  },
  {
    "path": "Add binary.java",
    "content": "class Solution {\n    public String addBinary(String a, String b) {\n        int i=a.length()-1;\n        int j=b.length()-1;\n        StringBuilder sb=new StringBuilder();\n        int carry=0;\n        while(i>=0 || j>=0){\n            int sum=carry;\n            if(i>=0)sum+=a.charAt(i)-'0';\n            if(j>=0)sum+=b.charAt(j)-'0';\n            carry=sum>1? 1:0;\n            sb.append(sum%2);\n            i--;\n            j--;\n        }\n        if(carry != 0) sb.append(carry);\n        return sb.reverse().toString();\n    }\n}\n"
  },
  {
    "path": "Adding Array Elements.java",
    "content": "class Solution {\n    int minOperations(int[] arr, int n, int k) {\n        // code here\n        if(n==1)return 0;\n        PriorityQueue<Integer> pq=new PriorityQueue<>();\n        for(int i:arr)pq.add(i);\n        int count=0;\n        while(pq.size()>1){\n            if(pq.peek()>=k)break;\n            int f=pq.remove();\n            int s=pq.remove();\n            int sum=f+s;\n            count++;\n            pq.add(sum);\n        }\n        if(pq.peek()<k)return -1;\n        return count;\n    }\n}\n"
  },
  {
    "path": "Adventure in a Maze - GFG/README.md",
    "content": "# Adventure in a Maze\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">You have got&nbsp;a maze, which is a n*n&nbsp;Grid. Every cell of the maze contains these numbers 1, 2 or 3.&nbsp;<br>\nIf it contains&nbsp;</span><span style=\"font-size:18px\">1 :</span><span style=\"font-size:18px\"> means we can go Right from that cell only.<br>\nIf it contains&nbsp;</span><span style=\"font-size:18px\">2 :</span><span style=\"font-size:18px\"> means we can go Down from that cell only.<br>\nIf it contains&nbsp;</span><span style=\"font-size:18px\">3 :</span><span style=\"font-size:18px\"> means we can go Right and Down to both paths from that cell.</span><br>\n<span style=\"font-size:18px\">We cant go out of the maze at any time.<br>\nInitially, You are on the Top Left Corner of The maze(Entry). And, You need to go to the Bottom Right Corner of the Maze(Exit).<br>\nYou need to find the total number of paths from Entry to Exit Point.<br>\nThere may be many paths but you need to select that path which contains the maximum number of Adventure.<br>\nThe Adventure on a path is calculated by taking the sum of all the cell values thatlies</span><span style=\"font-size:18px\"> in the path.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>matrix = {{1,1,3,2,1},{3,2,2,1,2},\n{1,3,3,1,3},{1,2,3,1,2},{1,1,1,3,1}}\n<strong>Output: </strong>{4,18}\n<strong>Explanation: </strong>There are total 4 Paths Available \nout of which The Max Adventure is 18. Total \npossible Adventures are 18,17,17,16. Of these \n18 is the maximum.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>FindWays()&nbsp;</strong>which takes matrix as input parameter and returns a list containg total number of ways to reach at (n, n) modulo 10<sup>9</sup>&nbsp;+ 7 and maximum number of Adventure.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(n<sup>2</sup>)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(n<sup>2</sup>)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n &lt;= 100&nbsp;</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Adventure in a Maze - GFG/adventure-in-a-maze.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            int n = Integer.parseInt(br.readLine().trim());\n            int[][] matrix = new int[n][n];\n            for(int i = 0; i < n; i++){\n                String[] s = br.readLine().trim().split(\" \");\n                for(int j = 0; j < n; j++)\n                    matrix[i][j] = Integer.parseInt(s[j]);\n            }\n            Solution obj = new Solution();\n            int[] ans = obj.FindWays(matrix);\n            for(int i = 0; i < ans.length; i++){\n                System.out.print(ans[i] + \" \");\n            }\n            System.out.println();\n\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static int MOD = 1000000007;\n    public int[] FindWays(int[][] matrix){\n        int n = matrix.length;\n        \n        int max_dp[][] = new int[n][n];\n        int count_dp[][] = new int[n][n];\n        \n        for(int i=n-1; i>=0; i--){\n            for(int j=n-1; j>=0; j--){\n                if(i==n-1 && j==n-1){\n                    count_dp[i][j] = 1;\n                    max_dp[i][j] = matrix[i][j];\n                }else{\n                    int val = matrix[i][j];\n                    if(val==1){\n                        if(j+1<n && max_dp[i][j+1]!=0){\n                            count_dp[i][j] = count_dp[i][j+1];\n                            max_dp[i][j] += val + max_dp[i][j+1];\n                        }\n                    }else if(val==2){\n                        if(i+1<n && max_dp[i+1][j]!=0){\n                            count_dp[i][j] = count_dp[i+1][j];\n                            max_dp[i][j] += val+max_dp[i+1][j];\n                        }\n                    }else{\n                        if(j+1<n && max_dp[i][j+1]!=0){\n                            count_dp[i][j] += count_dp[i][j+1];\n                            max_dp[i][j] += val+max_dp[i][j+1];\n                        }\n                        count_dp[i][j] = count_dp[i][j] % MOD;\n                        max_dp[i][j] = max_dp[i][j] % MOD;\n                        if(i+1<n && max_dp[i+1][j]!=0){\n                            count_dp[i][j] += count_dp[i+1][j];\n                            max_dp[i][j] = Math.max(max_dp[i][j], val+max_dp[i+1][j]);\n                        }\n                    }\n                    count_dp[i][j] = count_dp[i][j] % MOD;\n                    max_dp[i][j] = max_dp[i][j] % MOD;\n                }\n            }\n        }\n        return new int[]{count_dp[0][0], max_dp[0][0]};\n    }\n}"
  },
  {
    "path": "Alien Dictionary - GFG/Alien Dictionary.cpp",
    "content": "// { Driver Code Starts\r\n// Initial Template for C++\r\n\r\n#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\n // } Driver Code Ends\r\n// User function Template for C++\r\n\r\nclass Solution{\r\nvoid solve(int i,vector<vector<int>> v,vector<int> &vis,string &res){\r\n        vis[i] = 1;\r\n        \r\n        for(auto a:v[i]){\r\n            if(!vis[a])\r\n                solve(a,v,vis,res);\r\n        }\r\n        \r\n        char ch = i+'a';\r\n        res =ch+res;\r\n    }\r\n    \r\n    public:\r\n    string findOrder(string dict[], int n, int k) {\r\n        vector<vector<int>> v(k);\r\n        int i,j;\r\n        \r\n        for(i=0;i<n-1;i++){\r\n            string s1 = dict[i];\r\n            string s2 = dict[i+1];\r\n            \r\n            for(j=0;j<min(s1.size(),s2.size());j++){\r\n                if(s1[j]!=s2[j]){\r\n                    v[s1[j]-'a'].push_back(s2[j]-'a');\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n        \r\n        \r\n        vector<int> vis(k,0);\r\n        string res = \"\";\r\n        \r\n        \r\n        for(i=0;i<k;i++){\r\n            if(!vis[i])\r\n                solve(i,v,vis,res);\r\n        }\r\n        return res;\r\n    }\r\n};\r\n\r\n// { Driver Code Starts.\r\nstring order;\r\nbool f(string a, string b) {\r\n    int p1 = 0;\r\n    int p2 = 0;\r\n    for (int i = 0; i < min(a.size(), b.size()) and p1 == p2; i++) {\r\n        p1 = order.find(a[i]);\r\n        p2 = order.find(b[i]);\r\n    }\r\n\r\n    if (p1 == p2 and a.size() != b.size()) return a.size() < b.size();\r\n\r\n    return p1 < p2;\r\n}\r\n\r\n// Driver program to test above functions\r\nint main() {\r\n    int t;\r\n    cin >> t;\r\n    while (t--) {\r\n        int N, K;\r\n        cin >> N >> K;\r\n        string dict[N];\r\n        for (int i = 0; i < N; i++) cin >> dict[i];\r\n        \r\n        Solution obj;\r\n        string ans = obj.findOrder(dict, N, K);\r\n        order = \"\";\r\n        for (int i = 0; i < ans.size(); i++) order += ans[i];\r\n\r\n        string temp[N];\r\n        std::copy(dict, dict + N, temp);\r\n        sort(temp, temp + N, f);\r\n\r\n        bool f = true;\r\n        for (int i = 0; i < N; i++)\r\n            if (dict[i] != temp[i]) f = false;\r\n\r\n        if(f)cout << 1;\r\n        else cout << 0;\r\n        cout << endl;\r\n    }\r\n    return 0;\r\n}\r\n  // } Driver Code Ends\r\n"
  },
  {
    "path": "All Elements in Two Binary Search Trees.java",
    "content": "class Solution {\n    public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {\n        LinkedList<Integer> ret = new LinkedList<>();\n        List<Integer> ret2 = new ArrayList<>();\n        \n        dfs(root1, ret);\n        dfs2(root2, ret2, ret);\n        \n        if (ret.size()>0) ret2.addAll(ret);\n        return ret2;\n    }\n    \n    private void dfs(TreeNode node, LinkedList<Integer> ret) {\n        if (node==null) return;\n        if (node.left!=null) dfs(node.left, ret);\n        ret.add(node.val);\n        if (node.right!=null) dfs(node.right, ret);\n    }\n    \n    private void dfs2(TreeNode node, List<Integer> ret, LinkedList<Integer> ex) {\n        if (node==null) return;\n        if (node.left!=null) dfs2(node.left, ret, ex);\n        while(!ex.isEmpty() && ex.peekFirst()<node.val) ret.add(ex.pollFirst());\n        ret.add(node.val);\n        if (node.right!=null) dfs2(node.right, ret, ex);\n    }\n    \n    \n   \n}\n"
  },
  {
    "path": "All Factors.py",
    "content": "class Solution:\n\t# @param A : integer\n\t# @return a list of integers\n\tdef allFactors(self, A):\n        ans=[]\n        i=1\n        while i<= math.sqrt(A):\n            if A%i==0:\n                if A//i==i:\n                    ans.append(i)\n                else:\n                    ans.append(i)\n                    ans.append(A//i)\n            i+=1\n        ans.sort()\n        return ans\n"
  },
  {
    "path": "All Possible Combinations.java",
    "content": "public class Solution {\n    public ArrayList<String> specialStrings(ArrayList<String> A) {\n        ArrayList<String> ans=new ArrayList<>();\n        dfs(ans,A,new StringBuilder());\n        return ans;\n    }\n    void dfs(ArrayList<String> ans,ArrayList<String> arr,StringBuilder sb){\n        if(sb.length()==arr.size()){\n            ans.add(sb.toString());\n            return;\n        }\n        String s=arr.get(sb.length());\n        for(int i=0;i<s.length();i++){\n            sb.append(s.charAt(i));\n            dfs(ans,arr,sb);\n            sb.deleteCharAt(sb.length()-1);\n        }\n    }\n}\n"
  },
  {
    "path": "All Unique Permutations.java",
    "content": "public class Solution {\n    ArrayList<ArrayList<Integer>> lists;\n    boolean[] added;\n\n    public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> nums) {\n        lists = new ArrayList<>();\n        Collections.sort(nums);\n        added = new boolean[nums.size()];\n        permuteUnique(nums, new ArrayList<>());\n        return lists;\n    }\n\n    private void permuteUnique(ArrayList<Integer> nums, List<Integer> list) {\n        if(list.size() == nums.size()) {\n            lists.add(new ArrayList(list));\n            return;\n        }\n        for(int i = 0; i < nums.size(); i++) {\n            if(added[i])\n                continue;\n            if(i > 0 && nums.get(i) == nums.get(i-1) && !added[i - 1])\n                continue;\n            list.add(nums.get(i));\n            added[i] = true;\n            permuteUnique(nums, list);\n            list.remove(list.size() - 1);\n            added[i] = false;\n        }\n    }\n}\n"
  },
  {
    "path": "Allocate minimum number of pages.cpp",
    "content": "\nclass Solution \n{\n    public:\n    //Function to find minimum number of pages.\n    bool allocationPoss(int p,int M,int A[],int n){\n        int stds = 0, pages = p;\n        for(int i=0;i<n;i++){\n            if(A[i]>p) return false;\n            if(A[i]+pages>p){\n                stds++;\n                pages = A[i];\n            }else pages+=A[i];\n            \n            if(stds>M) return false;\n        }\n        \n        return true;\n    }\n    int findPages(int A[], int N, int M) \n    {\n        if(M>N) return -1;\n        int start = A[0],end = A[0];\n        for(int i=1;i<N;i++){\n            end+=A[i];\n            start = max(start,A[i]);\n        }\n        int rs = -1;\n        while(start<=end){\n            int mid = (start + end)/2;\n            if(allocationPoss(mid,M,A,N)){\n                rs = mid;\n                end = mid-1;\n            }else{\n                start = mid+1;\n            }\n        }\n        \n        return rs;\n    }\n};\n"
  },
  {
    "path": "Alternate positive and negative numbers.cpp",
    "content": "class Solution{\npublic:\n\nvoid rearrange(int arr[], int n) {\n\t// code here\n\tstack<int> st,st1;\n       for(int i=n-1;i>=0;i--){\n           if(arr[i]>=0) st.push(arr[i]);\n           else st1.push(arr[i]);\n       }\n       for(int i=0;i<n;i++){\n           if(i%2==0 && !st.empty()){\n               arr[i]=st.top();\n               st.pop();\n           }\n           else if(i%2==1 && !st1.empty()){\n               arr[i]=st1.top();\n               st1.pop();\n           }else if(!st.empty()){\n               arr[i]=st.top();\n               st.pop();\n           }else{\n               arr[i]=st1.top();\n               st1.pop();\n           }\n       }\n   }\n};"
  },
  {
    "path": "Alternate positive and negative numbers.java",
    "content": "class Solution {\n    void rearrange(int arr[], int n) {\n        // code here\n        boolean needNeg=false;\n        for(int i=0;i<n;i++){\n            if(arr[i]>=0){\n                //need pos\n                if(needNeg==false){\n                    needNeg=true;\n                }else{\n                    //find neg\n                    int j=i+1;\n                    while(j<n && arr[j]>=0){\n                        j++;\n                    }\n                    if(j==n)return;\n                    int ele=arr[j];\n                    j--;\n                    while(j>=i){\n                        arr[j+1]=arr[j];\n                        j--;\n                    }\n                    arr[i]=ele;\n                    needNeg=false;\n                }\n            }else{\n                //needed neg\n                if(needNeg==true){\n                    needNeg=false;\n                }else{\n                    //find pos\n                    int j=i+1;\n                    while(j<n && arr[j]<0){\n                        j++;\n                    }\n                    if(j==n)return;\n                    int ele=arr[j];\n                    j--;\n                    while(j>=i){\n                        arr[j+1]=arr[j];\n                        j--;\n                    }\n                    arr[i]=ele;\n                    needNeg=true;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Anagram of String.java",
    "content": "class GfG\n{\n\tpublic int remAnagrams(String s,String s1){\n        //add code here.\n        int[]fq=new int[26];\n        for(char c:s.toCharArray()){\n            fq[c-'a']++;\n        }\n        for(char c:s1.toCharArray()){\n            fq[c-'a']--;\n        }\n        int ans=0;\n        for(int i:fq){\n            ans+=Math.abs(i);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Anagrams.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE LIST. IT IS READ ONLY\n    public ArrayList<ArrayList<Integer>> anagrams(final List<String> A) {\n        ArrayList<ArrayList<Integer>> ans=new ArrayList<>();\n        HashMap<HashMap<Character,Integer>,Integer> map=new HashMap<>();\n        int listIndex=0;\n        for(int i=0;i<A.size();i++){\n            String s=A.get(i);\n            HashMap<Character,Integer> curr=new HashMap<>();\n            for(char c:s.toCharArray())curr.put(c,curr.getOrDefault(c,0)+1);\n            if(!map.containsKey(curr)){\n                map.put(curr,listIndex);\n                ans.add(new ArrayList<>());\n                ans.get(listIndex).add(i+1);\n                listIndex++;\n            }else{\n                int idx=map.get(curr);\n                ans.get(idx).add(i+1);\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Anti Diagonals.py",
    "content": "class Solution:\n    def diagonal(self, A):\n        output=[]\n        outputIndex=0\n        # UPPER\n        for i in range(0, len(A)):\n            x = 0\n            y = i\n            output.append([])\n            for j in range(i+1):\n                output[outputIndex].append(A[x][y])\n                x += 1\n                y -= 1\n            outputIndex += 1\n        # LOWER\n        for i in range(1, len(A)):\n            x = i\n            y = len(A) - 1\n            output.append([])   \n            for j in range(len(A)-i):\n                output[outputIndex].append(A[x][y])\n                x += 1\n                y -= 1\n            outputIndex += 1\n        return output\n"
  },
  {
    "path": "Arithmetic Slices.java",
    "content": "class Solution {\n    public int numberOfArithmeticSlices(int[] nums) {\n        int n = nums.length;\n        if (n<3){\n            return 0;\n        }\n        int ans=0;\n        int[] dp = new int[n];\n        for(int i=2;i<n;i++){\n            if ((nums[i]-nums[i-1])==(nums[i-1]-nums[i-2])){\n                dp[i] = dp[i-1]+1;\n                ans+=dp[i];\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Array 3 Pointers.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE LIST. IT IS READ ONLY\n    public int minimize(final List<Integer> A, final List<Integer> B, final List<Integer> C) {\n        int diff = Integer.MAX_VALUE;\n        int res_i =0, res_j = 0, res_k = 0;\n        int i = 0, j = 0, k = 0;\n        while (i < A.size() && j < B.size() && k < C.size()){\n            int minimum = Math.min(A.get(i),\n                          Math.min(B.get(j), C.get(k)));\n            int maximum = Math.max(A.get(i),\n                          Math.max(B.get(j), C.get(k)));\n            // Update result if current diff is\n            // less than the min diff so far\n            if (maximum-minimum < diff){\n                res_i = i;\n                res_j = j;\n                res_k = k;\n                diff = maximum - minimum;\n            }\n            // We can't get less than 0\n            // as values are absolute\n            if (diff == 0) break;\n     \n            // Increment index of array\n            // with smallest value\n            if (A.get(i)== minimum) i++;\n            else if (B.get(j) == minimum) j++;\n            else k++;\n        }\n        \n            int minimum = Math.min(A.get(res_i),\n                          Math.min(B.get(res_j), C.get(res_k)));\n            int maximum = Math.max(A.get(res_i),\n                          Math.max(B.get(res_j), C.get(res_k)));\n                          return maximum-minimum;\n    }\n    \n    public int abs(int a){\n        if(a<0){\n            return -a;\n        }\n        return a;\n    }\n    \n    \n}\n\n"
  },
  {
    "path": "Array Partition - GFG/README.md",
    "content": "# Array Partition\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an&nbsp;array of <strong>N</strong> integers, you have to find if it is possible to partition the array with following rules:</span></p>\n\n<ul>\n\t<li><span style=\"font-size:18px\">Each element should belong to exactly one partition.</span></li>\n\t<li><span style=\"font-size:18px\">Each partition should have atleast <strong>K</strong> elements.</span></li>\n\t<li><span style=\"font-size:18px\">Absolute difference between any pair of elements in the same partition should not exceed <strong>M</strong>.</span></li>\n</ul>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 5\nK = 2\nM = 3\nA[] = {8, 3, 9, 1, 2}\n<strong>Output:</strong>\nYES\n<strong>Explanation</strong>:\nWe can partition the array into two \npartitions: {8, 9} and {3, 1, 2} such that\nall rules are satisfied.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>partitionArray()</strong>&nbsp;which takes the number of elements&nbsp;<strong>N,</strong>&nbsp;integer <strong>K,</strong>&nbsp;integer <strong>M&nbsp;</strong>and array&nbsp;<strong>A[ ]</strong>&nbsp;as input parameters&nbsp;and returns true if we can partition the array such that all rules are satisfied, else returns false.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N * Log(N))<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(N)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N&nbsp;≤ 2*10<sup>5</sup><br>\n1 ≤ K&nbsp;≤ N<br>\n1 ≤ M&nbsp;≤ 10<sup>9</sup><br>\n1 ≤ A[i]&nbsp;≤ 10<sup>9</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Array Partition - GFG/array-partition.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n    \tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n    \tint test = Integer.parseInt(br.readLine());\n    \twhile(test-- > 0) {\n    \t\tString [] str = br.readLine().trim().split(\" \");\n    \t\tint N = Integer.parseInt(str[0]);\n    \t\tint K = Integer.parseInt(str[1]);\n    \t\tint M = Integer.parseInt(str[2]);\n    \t\tint [] A = new int[N];\n    \t\tstr = br.readLine().trim().split(\" \");\n    \t\tfor(int i = 0; i < N; i++)\n    \t\t\tA[i] = Integer.parseInt(str[i]);\n    \t\tSolution obj = new Solution();\n    \t\tboolean ans = obj.partitionArray(N, K, M, A);\n    \t\tif(ans){\n                System.out.println(\"YES\");\n            }\n            else{\n            \tSystem.out.println(\"NO\");\n            }\n    \t}\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    boolean rec( int start , int[] A , int K , int M ){\n        int n = A.length ;\n        if(start >= n)\n            return true ;\n        for ( int i = start + K - 1 ; i < n ; i ++ ){\n            if( (A[i] - A[start]) > M)\n                return false ;\n            if(rec(i+1 , A , K , M ))\n                return true ;\n            \n        }\n        return false ;\n    }\n\tboolean partitionArray(int N, int K, int M, int [] A){\n        // code here\n        Arrays.sort(A);\n        return rec(0 , A , K , M ) ; \n    }\n}"
  },
  {
    "path": "Array Sum.java",
    "content": "public class Solution {\n    public int[] addArrays(int[] A, int[] B) {\n        int n1=A.length;\n        int n2=B.length;\n        int[] sum = new int[n1>n2?n1:n2];\n        int i=n1-1;\n        int j=n2-1;\n        int k=sum.length-1;\n\n        int c=0;\n\n        while(k>=0){\n            int d = c;\n\n            if(i>=0){\n                d+=A[i];\n            }\n\n            if(j>=0){\n                d+=B[j];\n            }\n\n            c=d/10;\n            d=d%10;\n\n            sum[k]=d;\n\n            i--;\n            j--;\n            k--;\n        }\n\n        if(c!=0){\n            int[] ans = new int[(n1>n2?n1:n2) + 1];\n            ans[0]=c;\n             for (i = 0; i < ans.length-1; i++)\n                ans[i+1] = sum[i];\n  \n            return ans;\n        }\n        return sum;\n    }\n}\n"
  },
  {
    "path": "Array to BST - GFG/README.md",
    "content": "# Array to BST\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a sorted array. Convert it into a Height balanced&nbsp;Binary Search Tree (BST). Find the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest.<br>\nHeight balanced BST means a binary tree in which the depth of the left subtree and the right subtree&nbsp;of every node never differ by more than 1.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> nums = {1, 2, 3, 4}\n<strong>Output:</strong> {2, 1, 3, 4}\n<strong>Explanation:</strong> \nThe preorder traversal of the following \nBST formed is {2, 1, 3, 4}:\n</span><span style=\"font-size:18px\">&nbsp;          2\n</span><span style=\"font-size:18px\">&nbsp;        /   \\\n</span>           <span style=\"font-size:18px\">1     3\n</span><span style=\"font-size:18px\">&nbsp;              \\\n&nbsp;               4</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>nums = {1,2,3,4,5,6,7}\n<strong>Ouput: </strong>{4,2,1,3,6,5,7}\n<strong>Explanation: \n</strong>The preorder traversal of the following\nBST formed is {4,2,1,3,6,5,7} :\n        4\n       / \\\n      2   6\n     / \\  / \\\n    1   3 5  7</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>sortedArrayToBST()&nbsp;</strong>which takes the sorted array <strong>nums</strong> as input paramater and returns the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity: </strong>O(n)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(n)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ |nums| ≤&nbsp;10<sup>4</sup><br>\n-10<sup>4</sup>&nbsp;≤&nbsp;nums[i] ≤&nbsp;10<sup>4</sup></span><br>\n&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Array to BST - GFG/array-to-bst.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            int n = Integer.parseInt(br.readLine().trim());\n            int[] nums = new int[n];\n            String[] S = br.readLine().trim().split(\" \");\n            for(int i = 0; i < n; i++){\n                nums[i] = Integer.parseInt(S[i]);\n            }\n            Solution obj = new Solution();\n            int[] ans = obj.sortedArrayToBST(nums);\n            for(int i = 0; i < ans.length; i++)\n                System.out.print(ans[i] + \" \");\n            System.out.println();\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n   public void fillArray(int[] res,int[] n, int s, int e, int[] i){\n        if(s>e)return;\n        int mid=s+(e-s)/2;\n        res[i[0]]=n[mid];\n        i[0]++; \n        fillArray(res,n,s,mid-1,i);\n        fillArray(res,n,mid+1,e,i);\n   }\n   public int[] sortedArrayToBST(int[] n){\n        int[] res=new int[n.length], i=new int[1];\n        int s=0,e=n.length-1;\n        fillArray(res,n,s,e,i);\n        return res;\n   }\n}"
  },
  {
    "path": "Assign Mice to Holes.java",
    "content": "public class Solution {\n    public int mice(int[] A, int[] B) {\n\t\tArrays.sort(A);\n\t\tArrays.sort(B);\n\t\tint ans=0;\n\t\tfor(int i=0;i<A.length;i++){\n\t\t\tans=Math.max(ans,Math.abs(A[i]-B[i]));\n\t\t}\n\t\treturn ans;\n    }\n}\n"
  },
  {
    "path": "Assignment Problem - GFG/README.md",
    "content": "# Assignment Problem\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">You are the head of a firm and you have to assign jobs to people. You have <strong>N</strong> persons working under you and you have N jobs that are to be done by these persons. Each person has to do exactly one job and each job has to be done by exactly one person. Each person has his own capability (in terms of time taken) to do any particular job. Your task is to assign the jobs to the persons in such a way that the total time taken is minimum. A job can be assigned to only one person and a person can do only one job.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>N = </strong>2</span>\n<span style=\"font-size:18px\"><strong>Arr[] = </strong>{3, 5, 10, 1}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">4</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">The first person takes times 3 and 5\nfor jobs 1 and 2 respectively. The second\nperson takes times 10 and 1 for jobs 1 and\n2 respectively. We can see that the optimal\nassignment will be to give job 1 to person 1\nand job 2 to person 2 for a total for 3+1 = 4.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>N = </strong>3</span>\n<span style=\"font-size:18px\"><strong>Arr[] = </strong>{</span><span style=\"font-size:18px\">2, 1, 2,&nbsp;9, 8, 1, 1, 1, 1}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">3 \n<strong>Explanation: </strong>\nThe optimal arrangement would be to assign \njob 1 to person 3,job 2 to person 1 and job \n3 to person 2.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>assignmentProblem()</strong> which takes an Integer N and an array Arr[] of size N<sup>2</sup> as input and returns the time taken for the best possible assignment.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N<sup>2</sup>)<br>\n<strong>Expected Auxiliary Space:</strong> O(N<sup>2</sup>)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 &lt;= N &lt;= 30<br>\n1 &lt;= Arr[i] &lt;= 100</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Assignment Problem - GFG/assignment-problem.cpp",
    "content": "// { Driver Code Starts\n#include <bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\nclass Solution {\n  public:\n  \n    int cost[31][31]; //cost matrix\n    int n, max_match; //n workers and n jobs\n    int lx[31], ly[31]; //labels of X and Y parts\n    int xy[31]; //xy[x] - vertex that is matched with x,\n    int yx[31]; //yx[y] - vertex that is matched with y\n    bool S[31], T[31]; //sets S and T in algorithm\n    int slack[31]; //as in the algorithm description\n    int slackx[31]; //slackx[y] such a vertex, that\n    int prev_ious[31]; //array for memorizing alternating p\n  \n    void init_labels()\n    {\n        memset(lx, 0, sizeof(lx));\n        memset(ly, 0, sizeof(ly));\n        for (int x = 0; x < n; x++)\n        for (int y = 0; y < n; y++)\n        lx[x] = max(lx[x], cost[x][y]);\n    }\n    \n     \n    void update_labels()\n    {\n        int x, y;\n        int delta = 99999999; //init delta as infinity\n        for (y = 0; y < n; y++) //calculate delta using slack\n            if (!T[y])\n                delta = min(delta, slack[y]);\n        for (x = 0; x < n; x++) //update X labels\n            if (S[x])\n                lx[x] -= delta;\n        for (y = 0; y < n; y++) //update Y labels\n            if (T[y])\n                ly[y] += delta;\n        for (y = 0; y < n; y++) //update slack array\n            if (!T[y])\n                slack[y] -= delta;\n    }\n    \n    \n    void add_to_tree(int x, int prev_iousx) \n    //x - current vertex,prev_iousx - vertex from X before x in the alternating path,\n    //so we add edges (prev_iousx, xy[x]), (xy[x], x)\n    {\n        S[x] = true; //add x to S\n        prev_ious[x] = prev_iousx; //we need this when augmenting\n        for (int y = 0; y < n; y++) //update slacks, because we add new vertex to S\n            if (lx[x] + ly[y] - cost[x][y] < slack[y])\n            {\n                slack[y] = lx[x] + ly[y] - cost[x][y];\n                slackx[y] = x;\n            }\n    }\n    \n    \n    \n    void augment() //main function of the algorithm\n    {\n        if (max_match == n) return; //check wether matching is already perfect\n        int x, y, root; //just counters and root vertex\n        int q[31], wr = 0, rd = 0; //q - queue for bfs, wr,rd - write and read\n        //pos in queue\n        memset(S, false, sizeof(S)); //init set S\n        memset(T, false, sizeof(T)); //init set T\n        memset(prev_ious, -1, sizeof(prev_ious)); //init set prev_ious - for the alternating tree\n        \n        for (x = 0; x < n; x++) //finding root of the tree\n        {\n            if (xy[x] == -1)\n            {\n                q[wr++] = root = x;\n                prev_ious[x] = -2;\n                S[x] = true;\n                break;\n            }\n        }\n        \n        for (y = 0; y < n; y++) //initializing slack array\n        {\n            slack[y] = lx[root] + ly[y] - cost[root][y];\n            slackx[y] = root;\n        }\n        \n        //second part of augment() function\n        while (true) //main cycle\n        {\n            while (rd < wr) //building tree with bfs cycle\n            {\n                x = q[rd++]; //current vertex from X part\n                for (y = 0; y < n; y++) //iterate through all edges in equality graph\n                    if (cost[x][y] == lx[x] + ly[y] && !T[y])\n                    {\n                        if (yx[y] == -1) break; //an exposed vertex in Y found, so\n                                                //augmenting path exists!\n                            T[y] = true; //else just add y to T,\n                        q[wr++] = yx[y]; //add vertex yx[y], which is matched\n                        //with y, to the queue\n                        add_to_tree(yx[y], x); //add edges (x,y) and (y,yx[y]) to the tree\n                    }\n                if (y < n)\n                    break; //augmenting path found!\n            }\n            if (y < n)\n                break; //augmenting path found!\n            \n            update_labels(); //augmenting path not found, so improve labeling\n            \n            wr = rd = 0; \n            for (y = 0; y < n; y++) \n            //in this cycle we add edges that were added to the equality graph as a\n            //result of improving the labeling, we add edge (slackx[y], y) to the tree if\n            //and only if !T[y] && slack[y] == 0, also with this edge we add another one\n            //(y, yx[y]) or augment the matching, if y was exposed\n            if (!T[y] && slack[y] == 0)\n            {\n                if (yx[y] == -1) //exposed vertex in Y found - augmenting path exists!\n                {\n                    x = slackx[y];\n                    break;\n                }\n                else\n                {\n                    T[y] = true; //else just add y to T,\n                    if (!S[yx[y]]) \n                    {\n                        q[wr++] = yx[y]; //add vertex yx[y], which is matched with\n                        //y, to the queue\n                        add_to_tree(yx[y], slackx[y]); //and add edges (x,y) and (y,\n                        //yx[y]) to the tree\n                    }\n                }\n            }\n            if (y < n) break; //augmenting path found!\n        }\n        \n        if (y < n) //we found augmenting path!\n        {\n            max_match++; //increment matching\n            //in this cycle we inverse edges along augmenting path\n            for (int cx = x, cy = y, ty; cx != -2; cx = prev_ious[cx], cy = ty)\n            {\n                ty = xy[cx];\n                yx[cy] = cx;\n                xy[cx] = cy;\n            }\n            augment(); //recall function, go to step 1 of the algorithm\n        }\n    }//end of augment() function\n     \n    int hungarian()\n    {\n        int ret = 0; //weight of the optimal matching\n        max_match = 0; //number of vertices in current matching\n        memset(xy, -1, sizeof(xy)); \n        memset(yx, -1, sizeof(yx));\n        init_labels(); //step 0\n        augment(); //steps 1-3\n        \n        for (int x = 0; x < n; x++) //forming answer there\n            ret += cost[x][xy[x]];\n    \n        return ret;\n    }\n    \n    int assignmentProblem(int Arr[], int N) {\n        \n        n = N;\n        for(int i=0; i<n; i++)\n            for(int j=0; j<n; j++)\n                cost[i][j] = -1*Arr[i*n+j];\n                \n        int ans = -1 * hungarian();\n        \n        return ans;\n    }\n};\n\n// { Driver Code Starts.\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin>>n;\n        \n        int Arr[n*n];\n        for(int i=0; i<n*n; i++)\n            cin>>Arr[i];\n\n        Solution ob;\n        cout << ob.assignmentProblem(Arr,n) << endl;\n    }\n    return 0;\n}  // } Driver Code Ends"
  },
  {
    "path": "Assignment Problem - GFG/assignment-problem.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int N = Integer.parseInt(read.readLine());\n            String S[] = read.readLine().split(\" \");\n            \n            int[] Arr = new int[N*N];\n            \n            for(int i=0; i<N*N; i++)\n                Arr[i] = Integer.parseInt(S[i]);\n\n            Solution ob = new Solution();\n            System.out.println(ob.assignmentProblem(Arr,N));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n//0  1  2\n\n//3  5  3  p0\n//10 1  5  p1\n//12 3  5  p2\n\n//2 0 1\n\n\nclass Solution {\n    static int assignmentProblem(int a[], int n) {\n        // code here\n        int[][]mat=new int[n][n];\n        int idx=0;\n        for(int i=0;i<n;i++)\n            for(int j=0;j<n;j++)\n                mat[i][j]=a[idx++];\n        \n        int[]ans=dfs(mat,n);\n        int sum=0;\n        for(int i=0;i<ans.length;i++){\n            sum+=mat[ans[i]][i];\n        }\n        return sum;\n    }\n    static int[] dfs(int[][]mat,int n){\n        int[]ind=new int[n];\n        Arrays.fill(ind,-1);\n        int[]u=new int[n];\n        int[]v=new int[n];\n        \n        for(int i=0;i<n;i++){\n            boolean[]vis=new boolean[n];\n            int[]mins=new int[n];\n            Arrays.fill(mins,1000);\n            int[]links=new int[n];\n            Arrays.fill(links,-1);\n            \n            int j=-1;\n            int mark_i=i;\n            int mark_j=-1;\n            while(mark_i!=-1){\n                j=-1;\n                for(int j1=0;j1<n;j1++){\n                    if(!vis[j1]){\n                        int current=mat[mark_i][j1]-u[mark_i]-v[j1];\n                        if(current<mins[j1]){\n                            mins[j1]=current;\n                            links[j1]=mark_j;\n                        }\n                        if(j==-1 || mins[j1]<mins[j]){\n                            j=j1;\n                        }    \n                    }\n                }\n                int delta=mins[j];\n                for(int j1=0;j1<n;j1++){\n                    if(vis[j1]){\n                        u[ind[j1]]+=delta;\n                        v[j1]-=delta;\n                    }else{\n                        mins[j1]-=delta;\n                    }\n                }\n                u[i]+=delta;\n                vis[j]=true;\n                mark_j=j;\n                mark_i=ind[j];\n            }\n            while(links[j]!=-1){\n                ind[j]=ind[links[j]];\n                j=links[j];\n            }\n            \n            ind[j]=i;\n        }\n        \n        return ind;\n    }\n};"
  },
  {
    "path": "Assignment Problem - GFG/assignment-problem.py",
    "content": "#User function Template for python3\n\nclass Solution:\n    def assignmentProblem(self, Arr, N):\n        n=N\n        l=Arr\n        m = []\n        m_beg = []\n        for i in range(n):\n            m.append(l[i*n:(i+1)*n])\n            m_beg.append(l[i*n:(i+1)*n])\n        def util():\n            u, v, ind = [0]*n, [0]*n, [-1]*n\n            for i in range(n):\n                links, mins, visited = [-1]*n, [1000]*n, [False]*n\n                marked_i, marked_j = i, -1\n                while marked_i != -1:\n                    j = -1\n                    for j1 in range(n):\n                        if not visited[j1]:\n                            current = m[marked_i][j1] - u[marked_i] - v[j1]\n                            if current < mins[j1]:\n                                mins[j1] = current\n                                links[j1] = marked_j\n                            if j == -1 or mins[j1] < mins[j]:\n                                j = j1\n                    delta = mins[j]\n                    for j1 in range(n):\n                        if visited[j1]:\n                            u[ind[j1]] += delta;  v[j1] -= delta\n                        else:\n                            mins[j1] -= delta\n                    u[i] += delta\n                    visited[j] = True\n                    marked_j, marked_i = j, ind[j]\n                while links[j] != -1:\n                    ind[j] = ind[links[j]]\n                    j = links[j]\n                ind[j] = i\n            return [(ind[j], j) for j in range(n)]\n        return (sum(m_beg[x][y] for x,y in util()))\n#{ \n#  Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__': \n    t = int (input ())\n    for _ in range (t):\n        N=int(input())\n        Arr=list(map(int,input().split()))\n        \n        ob = Solution()\n        print(ob.assignmentProblem(Arr,N))\n# } Driver Code Ends"
  },
  {
    "path": "Assignment Problem - GFG/hungarian_java(not_accepted).java",
    "content": "\nclass Solution {\n    static int MARK_ZERO = 2;\n    static int INTERSECTION = 3;\n    static int DELETED = 1;\n    static int UNDELETED = 0;\n\n    public static void main(String[] args) {\n        System.out.println(assignmentProblem(new int[]{2, 1, 2, 9, 8, 1, 1, 1, 1}, 3));\n    }\n\n    static int assignmentProblem(int Arr[], int N) {\n        int[][] mat = new int[N][N];\n        makeMat(Arr, mat, N);\n\n        int[][] temp = new int[N][N];\n        copy(mat, temp, N);\n        reduction(temp, N);\n\n        while (true) {\n            int[][] sign = new int[N][N];\n            optimisation(temp, sign, N);\n            int zeroes = 0;\n            //count the zeroes\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (sign[i][j] == MARK_ZERO) zeroes++;\n                }\n            }\n\n            if (zeroes == N) {\n                int ans = 0;\n                //get the final answer\n                for (int i = 0; i < N; i++) {\n                    for (int j = 0; j < N; j++) {\n                        if (sign[i][j] == MARK_ZERO) {\n                            ans += mat[i][j];\n                        }\n                    }\n                }\n                return ans;\n            } else {\n                int min = Integer.MAX_VALUE;\n                //get min value from undeleted elements\n                for (int i = 0; i < N; i++) {\n                    for (int j = 0; j < N; j++) {\n                        if (sign[i][j] == UNDELETED) {\n                            min = Math.min(min, temp[i][j]);\n                        }\n                    }\n                }\n\n                //add min value to intersaction points\n                for (int i = 0; i < N; i++) {\n                    for (int j = 0; j < N; j++) {\n                        if (sign[i][j] == INTERSECTION) {\n                            temp[i][j] += min;\n                        }\n                    }\n                }\n\n                //subtract min from all undeleted elements\n                for (int i = 0; i < N; i++) {\n                    for (int j = 0; j < N; j++) {\n                        if (sign[i][j] == UNDELETED) {\n                            temp[i][j] -= min;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    //n2\n    static void makeMat(int[] Arr, int[][] mat, int N) {\n        int idx = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                mat[i][j] = Arr[idx++];\n            }\n        }\n    }\n\n    //n2\n    static void copy(int[][] mat, int[][] temp, int N) {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                temp[i][j] = mat[i][j];\n            }\n        }\n    }\n\n    //n2\n    static void reduction(int[][] temp, int N) {\n        //row reduction\n        for (int i = 0; i < N; i++) {\n            int min = Integer.MAX_VALUE;\n            for (int j = 0; j < N; j++) {\n                min = Math.min(min, temp[i][j]);\n            }\n            for (int j = 0; j < N; j++) {\n                temp[i][j] -= min;\n            }\n        }\n        //col reduction\n        for (int j = 0; j < N; j++) {\n            int min = Integer.MAX_VALUE;\n            for (int i = 0; i < N; i++) {\n                min = Math.min(min, temp[i][j]);\n            }\n            for (int i = 0; i < N; i++) {\n                temp[i][j] -= min;\n            }\n        }\n\n    }\n\n    //n2\n    static void optimisation(int[][] temp, int[][] sign, int N) {\n        for(int row=0;row<N;row++){\n            int zeroes=countInRow(temp,sign,row,N);\n            if(zeroes==1){\n                int delCol=indexInRow(temp,sign,row,N);\n                deleteCol(sign,delCol,N);\n                sign[row][delCol]=MARK_ZERO;\n            }\n        }\n        int uncoveredZeroes=0;\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                if(temp[i][j]==0 && sign[i][j]==UNDELETED)uncoveredZeroes++;\n            }\n        }\n        if(uncoveredZeroes>0){\n            for(int col=0;col<N;col++){\n                int zeroes=countInCol(temp,sign,col,N);\n                if(zeroes==1){\n                    int rowDel=indexInCol(temp,sign,col,N);\n                    deleteRow(sign,rowDel,N);\n                    sign[rowDel][col]=MARK_ZERO;\n                }\n            }\n        }\n    }\n\n    //n\n\n    static void deleteRow(int[][] sign, int rowDel, int n) {\n        for(int col=0;col<n;col++){\n            if(sign[rowDel][col]==UNDELETED){\n                sign[rowDel][col]=DELETED;\n            }else if(sign[rowDel][col]==DELETED){\n                sign[rowDel][col]=INTERSECTION;\n            }\n        }\n    }\n\n    static int indexInCol(int[][] temp,int[][]sign, int col, int n) {\n        int i=0;\n        for(int row=0;row<n;row++){\n            if(sign[row][col]==UNDELETED)\n                if(temp[row][col]==0)return row;\n        }\n        return i;\n    }\n\n    static int countInCol(int[][] temp,int[][]sign, int col, int n) {\n        int ans=0;\n        for(int row=0;row<n;row++){\n            if(sign[row][col]==UNDELETED)\n                if(temp[row][col]==0)ans++;\n        }\n        return ans;\n    }\n\n    static void deleteCol(int[][] sign, int delCol,int N) {\n        for(int row=0;row<N;row++){\n            if(sign[row][delCol]==UNDELETED)\n                sign[row][delCol]=DELETED;\n            else if(sign[row][delCol]==DELETED)\n                sign[row][delCol]=INTERSECTION;\n        }\n    }\n\n    static int indexInRow(int[][] temp,int[][]sign, int row, int N) {\n        int i=0;\n        for(int col=0;col<N;col++){\n            if(sign[row][col]==UNDELETED)\n                if(temp[row][col]==0)return col;\n        }\n        return i;\n    }\n\n    static int countInRow(int[][] temp,int[][]sign, int row,int N) {\n        int ans=0;\n        for(int col=0;col<N;col++){\n            if(sign[row][col]==UNDELETED)\n                if(temp[row][col]==0)ans++;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Average of level in Binary tree.cpp",
    "content": "// Q) Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. \n//Answers within 10-5 of the actual answer will be accepted.\n\n\n\n/// We can directly do a Breadth-First search, which would be more intuitive and efficient than DFS, \n//since we are concerned with each levels of the binary Tree(exactly what BFS achieves).\n\n///As in any BFS, we use a simple queue, iterate nodes at each row & push their children to queue after popping the current node. \n//For each row, sum of all node's value at that level of the binary tree would be calculated and the average would be stored in ans array \n//which will be our final answer.\n\n\n\n\nclass Solution {\npublic:\n    vector<double> averageOfLevels(TreeNode* root) {\n        vector<double> ans;\n        queue<TreeNode*> q;\n        q.push(root);\n        \n        // while there are nodes remaining to be visited\n        while(!q.empty()){\n            double temp = q.size();\n            double sum = 0;\n            // iterating each level of binary tree\n            for(int i = 0; i < temp; i++){\n                auto tt = q.front();\n                q.pop();\n                sum += (tt->val);\n\t\t\t\t// check for not NULL and pushing into queue.\n                if(tt->left){\n                    q.push(tt->left);\n                }\n                if(tt->right){\n                    q.push(tt->right);\n                }\n            }\n            ans.push_back(sum/ temp);\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Average of levels in binary tree.java",
    "content": "class Solution {\n    public List<Double> averageOfLevels(TreeNode root) {\n        List<Double> result=new ArrayList<>();\n        Queue<TreeNode> que=new LinkedList<>();\n        que.add(root);\n        while(!que.isEmpty()){\n            int size=que.size();\n            double sum=0;\n            for(int i=0;i<size;i++){\n                TreeNode curr=que.poll();\n                sum+=curr.val;\n                if(curr.left!=null) que.add(curr.left);\n                if(curr.right!=null) que.add(curr.right);\n            }\n            result.add(sum/size);\n            \n        } \n        return result;\n        \n    }\n}\n"
  },
  {
    "path": "BST To Max Heap.cpp",
    "content": "class Solution{\n  public:\n  \n    void recur(Node *root,priority_queue<int>&pq)\n  {\n      if(!root)\n      return;\n      \n      pq.push(root->data);\n      recur(root->left,pq);\n      recur(root->right,pq);\n\n  }\n  void change(Node *root,priority_queue<int>&pq)\n  {\n      if(!root or pq.empty())\n      return;\n      \n      root->data=pq.top();\n      pq.pop();\n      change(root->right,pq);\n      change(root->left,pq);\n      \n  }\n    void convertToMaxHeapUtil(Node* root)\n    {\n        // Your code goes here\n        priority_queue<int>pq;\n        recur(root,pq);\n        \n        change(root,pq);\n    }    \n};\n"
  },
  {
    "path": "BST to greater sum tree - GFG/README.md",
    "content": "# BST to greater sum tree\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a BST, transform it into greater sum tree where each node contains sum of all nodes greater than that node.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\n           2\n         /    \\\n        1      6\n              /  \\\n             3    7\n<strong>Output:</strong> 18 16 13 7 0\n<strong>Explanation:</strong>\nEvery node is replaced with the \nsum of nodes greater than itself. \nThe resultant tree is:\n               16\n             /    \\\n           18       7\n                  /   \\\n                 13    0\n</span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong><strong>:</strong>\n</span><span style=\"font-size:18px\">          2\n         /\n        1</span>\n<span style=\"font-size:18px\"><strong>Output: </strong>2 0</span>\n<strong><span style=\"font-size:18px\">Explanation:</span></strong>\n<span style=\"font-size:18px\">The resultant tree is :</span>\n<span style=\"font-size:18px\">             0</span>\n<span style=\"font-size:18px\">            /</span>\n<span style=\"font-size:18px\">          2</span>\n</pre>\n\n<div><span style=\"font-size:18px\"><strong>Your task :</strong></span></div>\n\n<div><span style=\"font-size:18px\">You don't have to read input or print anything. Your task is to complete the function <strong>transformTree() </strong>which takes the root of the tree as input and transforms the BST to a greater sum tree.</span></div>\n\n<div><span style=\"font-size:18px\"><strong>Note :</strong> The driver code prints the inorder traversal of the transformed BST.</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Time Complexity: </strong>O(N), N = number of nodes</span></div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Auxiliary Space: </strong>O(N), N = number of nodes</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Constraints :</strong></span></div>\n\n<div><span style=\"font-size:18px\">1 ≤ N ≤ 10<sup>4</sup></span></div>\n <p></p>\n            </div>"
  },
  {
    "path": "BST to greater sum tree - GFG/bst-to-greater-sum-tree.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.LinkedList; \nimport java.util.Queue; \nimport java.io.*;\nimport java.util.*;\n\nclass Node{\n    int data;\n    Node left;\n    Node right;\n    Node(int data){\n        this.data = data;\n        left=null;\n        right=null;\n    }\n}\n\nclass Tree {\n    \n    static Node buildTree(String str){\n        \n        if(str.length()==0 || str.charAt(0)=='N'){\n            return null;\n        }\n        \n        String ip[] = str.split(\" \");\n        // Create the root of the tree\n        Node root = new Node(Integer.parseInt(ip[0]));\n        // Push the root to the queue\n        \n        Queue<Node> queue = new LinkedList<>(); \n        \n        queue.add(root);\n        // Starting from the second element\n        \n        int i = 1;\n        while(queue.size()>0 && i < ip.length) {\n            \n            // Get and remove the front of the queue\n            Node currNode = queue.peek();\n            queue.remove();\n                \n            // Get the current node's value from the string\n            String currVal = ip[i];\n                \n            // If the left child is not null\n            if(!currVal.equals(\"N\")) {\n                    \n                // Create the left child for the current node\n                currNode.left = new Node(Integer.parseInt(currVal));\n                // Push it to the queue\n                queue.add(currNode.left);\n            }\n                \n            // For the right child\n            i++;\n            if(i >= ip.length)\n                break;\n                \n            currVal = ip[i];\n                \n            // If the right child is not null\n            if(!currVal.equals(\"N\")) {\n                    \n                // Create the right child for the current node\n                currNode.right = new Node(Integer.parseInt(currVal));\n                    \n                // Push it to the queue\n                queue.add(currNode.right);\n            }\n            i++;\n        }\n        \n        return root;\n    }\n    static void inOrder(Node root)\n    {\n        if(root == null)\n            return;\n            \n        inOrder(root.left);\n        System.out.print(root.data+\" \");\n        inOrder(root.right);\n        \n    \n    }\n    \n\tpublic static void main (String[] args) throws IOException{\n\t        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t        \n\t        int t=Integer.parseInt(br.readLine());\n    \n\t        while(t > 0){\n\t            String s = br.readLine();\n    \t    \tNode root = buildTree(s);\n    \t    \t\n                Solution g = new Solution();\n                g.transformTree(root);\n                inOrder(root);\n                \n                System.out.println();\n                    \n                t--;\n            \n        }\n    }\n}\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n/*class Node{\n    int data;\n    Node left;\n    Node right;\n    Node(int data){\n        this.data = data;\n        left=null;\n        right=null;\n    }\n} */\nclass Solution\n{\n    static int sum;\n    public static void transformTree (Node root)\n    {\n        //code here\n        sum=0;\n        dfs(root);\n    }\n    static void dfs(Node root){\n        if(root==null)return;\n        dfs(root.right);\n        int temp=root.data;\n        root.data=sum;\n        sum+=temp;\n        dfs(root.left);\n    }\n}"
  },
  {
    "path": "BST to max heap GFG/BstToMaxHeap.cpp",
    "content": "\n  void helper1(Node *root,vector<int>&ans){\n      if(root==NULL){\n          return;\n      }\n      helper1(root->left,ans);\n      ans.push_back(root->data);\n      helper1(root->right,ans);\n  }\n  \n  void helper2(Node *root,vector<int>&ans,int &index){\n      if(root==NULL)return;\n      helper2(root->left,ans,index);\n      helper2(root->right,ans,index);\n      root->data=ans[index];\n      index++;\n  \n      \n  }\n    void convertToMaxHeapUtil(Node* root)\n    {\n        \n        vector<int>ans;\n        helper1(root,ans);\n        int index=0;\n        helper2(root,ans,index);\n        \n    }    \n"
  },
  {
    "path": "BST to max heap gfg med.cpp",
    "content": "//{ Driver Code Starts\n//Initial Template for C++\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n    int data;\n    Node *left, *right;\n};\n\n/* Helper function that allocates a new node\nwith the given data and NULL left and right\npointers. */\nNode* newNode(int val)\n{\n    Node* temp = new Node;\n    temp->data = val;\n    temp->left = NULL;\n    temp->right = NULL;\n\n    return temp;\n}\n\nNode* buildTree(string str)\n{\n    // Corner Case\n    if (str.length() == 0 || str[0] == 'N')\n        return NULL;\n\n    // Creating vector of strings from input\n    // string after spliting by space\n    vector<string> ip;\n\n    istringstream iss(str);\n    for (string str; iss >> str; )\n        ip.push_back(str);\n\n    // Create the root of the tree\n    Node* root = newNode(stoi(ip[0]));\n\n    // Push the root to the queue\n    queue<Node*> queue;\n    queue.push(root);\n\n    // Starting from the second element\n    int i = 1;\n    while (!queue.empty() && i < ip.size()) {\n\n        // Get and remove the front of the queue\n        Node* currNode = queue.front();\n        queue.pop();\n\n        // Get the current node's value from the string\n        string currVal = ip[i];\n\n        // If the left child is not null\n        if (currVal != \"N\") {\n\n            // Create the left child for the current node\n            currNode->left = newNode(stoi(currVal));\n\n            // Push it to the queue\n            queue.push(currNode->left);\n        }\n\n        // For the right child\n        i++;\n        if (i >= ip.size())\n            break;\n        currVal = ip[i];\n\n        // If the right child is not null\n        if (currVal != \"N\") {\n\n            // Create the right child for the current node\n            currNode->right = newNode(stoi(currVal));\n\n            // Push it to the queue\n            queue.push(currNode->right);\n        }\n        i++;\n    }\n\n    return root;\n}\nvoid postorderTraversal(Node* root)\n{\n    if (!root)\n        return;\n\n    // recur on left subtree\n    postorderTraversal(root->left);\n\n    // then recur on right subtree\n    postorderTraversal(root->right);\n\n    // print the root's data\n    cout << root->data << \" \";\n}\nclass Solution{\n  public:\n  vector<int> v;\n  int i =0;\n  void postorder(Node* root){\n      if(!root) return;\n      postorder(root->left);\n      postorder(root->right);\n      root->data = v[i++];\n  }\n  void inorder(Node *root){\n      if(!root) return;\n      inorder(root->left);\n      v.push_back(root->data);\n      inorder(root->right);\n  }\n    void convertToMaxHeapUtil(Node* root)\n    {\n        // Your code goes here\n        inorder(root);\n        postorder(root);\n    }    \n};\nint main()\n{\n    int t;\n    cin >> t;\n    getchar();\n    while (t--)\n    {\n        string inp, ch;\n        getline(cin, inp);\n        struct Node* root = buildTree(inp);\n        Solution ob;\n        ob.convertToMaxHeapUtil(root);\n        postorderTraversal(root);\n        cout << \"\\n\";\n    }\n    return 0;\n}"
  },
  {
    "path": "BST-to-max-Heap/BSTtoMaxHeap.java",
    "content": "class Solution\n{\n    static int i=0;\n    public static void convertToMaxHeapUtil(Node root)\n    {\n        //code here\n        ArrayList<Integer> nodes=new ArrayList<>();\n        i=0;\n        inOrder(root, nodes);\n    }\n    \n    public static void inOrder(Node root, ArrayList<Integer> nodes) {\n        if(root==null) return ;\n        \n        inOrder(root.left, nodes);\n        nodes.add(root.data);  //adding data to ArrayList stores in Ascending order\n        inOrder(root.right, nodes);\n         root.data=nodes.get(i++);  //Modifying root value in postOrder Traversal, so that All Left and Right Nodes store lesser value compared to root as ArrayList stores in Ascending Order\n    }\n   \n}\n"
  },
  {
    "path": "BST-to-max-Heap/Solution.cpp",
    "content": "class Solution{\n\n  public:\n\n  Node* helper(Node* root){\n\n       if(!root)return NULL;\n\n         Node* left=helper(root->left);\n\n         Node* right=helper(root->right);\n\n         if(!left&&!right)return root;\n\n         if(!left&&right){\n\n            if(right->data>root->data){swap(root->data,right->data);helper(root->right);}  \n\n         }\n\n         else if(left&&!right){\n\n             if(left->data>root->data){swap(root->data,left->data); helper( root->left);}\n\n         }\n\n         else{\n\n         if(left->data>root->data){swap(root->data,left->data); helper( root->left);}\n\n         if(right->data>root->data){swap(root->data,right->data);helper(root->right);}\n\n         }\n\n        return root;\n\n  }\n\n    void convertToMaxHeapUtil(Node* root)\n\n    {\n\n        helper(root);\n\n    }    \n\n};"
  },
  {
    "path": "BST-to-max-Heap/question.md",
    "content": "### BST to max heap\n\n**Medium**Accuracy: **70.68%**Submissions: **4473**Points: **4**\n\nGiven a Binary Search Tree. Convert a given BST into a Special Max Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied on all the nodes in the so converted Max Heap.\n\n**Example 1:**\n\n```\nInput :\n                 4\n               /   \\\n              2     6\n            /  \\   /  \\\n           1   3  5    7  \n\nOutput : 1 2 3 4 5 6 7 \nExaplanation :\n               7\n             /   \\\n            3     6\n          /   \\  /   \\\n         1    2 4     5\nThe given BST has been transformed into a\nMax Heap and it's postorder traversal is\n1 2 3 4 5 6 7.\n```\n\n**Your task :**\n\nYou don't need to read input or print anything. Your task is to complete the function convertToMaxHeapUtil() which takes the root of the tree as input and converts the BST to max heap.\n\nNote : The driver code prints the postorder traversal of the converted BST.\n\n**Expected Time Complexity : **O(n)\n\n**Expected Auxiliary Space : **O(n)\n\n**Constraints :**\n\n1 ≤ n ≤ 10^5^\n"
  },
  {
    "path": "Bag Of Tokens.java",
    "content": "class Solution {\n    public int bagOfTokensScore(int[] tokens, int power) {\n        int ans=0;\n        Arrays.sort(tokens); //sorted the tokens as in question they mentioned to take in any order\n        int i=0, j=tokens.length-1, steps=0;\n        while(i<=j) {\n            if(tokens[i]<=power) { //if current value is less than equal to power we reduce power and increase steps   \n                power-=tokens[i];  \n                steps+=1;\n                i+=1;\n            }\n            else {     //else we need to increase power to continue further\n                if(steps>0) {    //if steps > 0, we can increase power and reduces steps by 1\n                    power+=tokens[j];\n                    j-=1;\n                    steps-=1;\n                }\n                else { // if steps ==0 , we cannot increase power according to question and we cannot increase power. As array is sorted, we cannot increase steps as power is less than all other tokens hence break loop\n                    break;\n                }                \n            }     \n            ans=Math.max(ans, steps);  // At each step calculate max Ans as we no need to consider all the tokens\n        }\n        return ans;\n        \n    }\n}\n"
  },
  {
    "path": "Balance Array.java",
    "content": "class Solution:\n    # @param A : list of integers\n    # @return an integer\n    def solve(self, A):\n            arr=A\n            s1=0\n            s2=0\n            n=len(A)\n            s3=0\n            s4=0\n            for i in range(n):\n                if i%2:\n                    s2+=arr[i]\n                else:\n                    s1+=arr[i]\n            c=0\n            for i in range(n):\n                    if i%2:\n                        s2-=arr[i]\n                        if s2+s4==s1+s3:\n                            c+=1\n                        s3+=arr[i]\n                    else:\n                        s1-=arr[i]\n                        if s2+s4==s3+s1:\n                            c+=1\n                        s4+=arr[i]\n            return c\n"
  },
  {
    "path": "Balanced Binary Tree.java",
    "content": "public class Solution {\n    public int isBalanced(TreeNode A) {\n        if(A==null)\n            return 1;\n        Queue<TreeNode> queue=new LinkedList<>();\n        queue.add(A);\n        while(!queue.isEmpty()){\n            TreeNode current=queue.remove();\n            if(Math.abs(getHeight(current.left)-getHeight(current.right))>1)\n                return 0;\n\n            if(current.left!=null)\n                queue.add(current.left);\n            if(current.right!=null)\n                queue.add(current.right);\n        }\n    return 1;        \n}\n\n\n    int getHeight(TreeNode root){\n        if(root==null)\n            return -1;\n        else\n            return 1+Math.max(getHeight(root.left),getHeight(root.right));\n    }\n}\n"
  },
  {
    "path": "Balanced Parantheses!.java",
    "content": "public class Solution {\n    public int solve(String A) {\n        ArrayDeque<Character> st=new ArrayDeque<>();\n        for(int i=0;i<A.length();i++){\n            char ch=A.charAt(i);\n            if(ch=='('){\n                st.push(ch);\n            }else{\n                if(st.size()==0)\n                    return 0;\n                else\n                    st.pop();\n            }\n        }\n        if(st.size()>0)return 0;\n        return 1;\n    }\n}\n"
  },
  {
    "path": "Ball Coloring.cpp",
    "content": "class Solution {\n  public:\n    unsigned long long int noOfWays(unsigned long long int n){\n        // code here\n        if(n<3){\n            return n*2;\n        }\n        else{\n              return ((n*n)-(n-2));\n            }\n    }\n};\n"
  },
  {
    "path": "Ball coloring.cpp",
    "content": "class Solution {\n  public:\n    unsigned long long int noOfWays(unsigned long long int n){\n        // code here\n        if(n<3){\n            return n*2;\n        }\n        else{\n              return ((n*n)-(n-2));\n            }\n    }\n};\n"
  },
  {
    "path": "Ball coloring.java",
    "content": "class Solution {\n    static long noOfWays(long n){\n        // code here\n        return 2 + n * (n - 1);\n    }\n}\n"
  },
  {
    "path": "Ball coloring.py",
    "content": "class Solution:\n    def noOfWays (self, n):\n         return  (n*(n-1))+2;\n"
  },
  {
    "path": "Ball-Coloring/ball_coloring.java",
    "content": "class Solution{\n    static long noOfWays(long n){\n        // code here\n        return (n*(n-1)+2);\n    }\n}\n"
  },
  {
    "path": "Ball-Coloring/question.md",
    "content": "Given n balls . All of them are initially  uncolored . You have to color the balls with two colors RED and BLUE such that there can be atmost 2 positions where a RED ball is touching BLUE ball or vice versa. You have to color all the balls.Find the number of ways in which balls can be colored.\n\n**Example 1:**\n\n```\nInput: n = 1\nOutput: 2\nExplanation: Possible ways to color are {{R},{B}}. \nSo the answer is 2 .\n```\n\n**Example 2:**\n\n```\nInput: n = 2\nOutput: 4\nExplanation: Possible ways to color are \n{{RB},{BR},{RR},{BB}}.So the answer is 4.\n```\n\n**Your Task:  **\nYou dont need to read input or print anything. Complete the function **noOfWays() **which takes n as input parameter and returns  the number of ways in which balls can be colored.\n\n**Expected Time Complexity:** O(1)\n**Expected Auxiliary Space:** O(1)\n\n**Constraints:**\n1<= n <=10^5^\n"
  },
  {
    "path": "Best Time to Buy and Sell Stock IV.java",
    "content": "class Solution {\n    public int maxProfit(int k, int[] prices) {\n        int [][][]dp=new int[k+1][prices.length+1][2];\n        for(int i=0;i<dp.length;i++) {\n            for(int j=0;j<dp[0].length;j++) {\n                for(int m=0;m<dp[0][0].length;m++) dp[i][j][m]=-1;\n            }\n        }\n        return maximumProfit(prices, k, 0, 0, dp);\n    }\n    public int maximumProfit(int[] prices, int k, int ind, int buy, int [][][]dp) {\n        if(ind>=prices.length) return 0;\n        if(k==0) return 0;\n                \n        if(dp[k][ind][buy]!=-1) {\n            return dp[k][ind][buy];\n        }\n        int ans1=0, ans2=0, ans3=0, ans4=0;\n        if(buy==0) {\n            ans1=maximumProfit(prices, k, ind+1, buy, dp); //not buying in this index and continuing\n            ans2=-prices[ind]+maximumProfit(prices, k, ind+1, 1, dp); //buying at this index by passing 1 by subtracting the current amount and continuing\n        }\n        else {\n            ans3=maximumProfit(prices, k, ind+1, buy, dp);  //not selling at this index and continuing\n            ans4=(prices[ind])+maximumProfit(prices, k-1, ind+1, 0,  dp); //selling at this index by adding current index amount and reducing transactions by 1 and continuing\n        }\n        return  dp[k][ind][buy]=Math.max(ans1, Math.max(ans2, Math.max(ans3, ans4))); // taking maximum of all these combinations\n        \n    }\n}\n"
  },
  {
    "path": "Best Time to Buy and Sell Stock.java",
    "content": "class Solution {\n    public int maxProfit(int[] prices) {\n        int min=Integer.MAX_VALUE;\n        int max=0;\n        for(int i=0;i<prices.length;i++){\n            min=Math.min(min,prices[i]);\n            max=Math.max(max,prices[i]-min);            \n        }\n        return max;\n    }\n}\n"
  },
  {
    "path": "Biconnected Graph.java",
    "content": "class Solution {\n   static int biGraph(int[] arr, int n, int e) {\n       // code here\n        if(n<=2) return 1;\n        int p= 2* e;\n        int freq[]= new int[n];\n        for(int i=0;i<p;i+=2){\n             freq[arr[i]]++;\n             freq[arr[i+1]]++;\n        }\n        for(int num:freq)\n            if(num<=1)return 0;\n        return 1;\n   }\n};\n"
  },
  {
    "path": "Bike Racing - GFG/README.md",
    "content": "# Bike Racing\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Geek is organising a bike race with N bikers. The initial speed of the ith biker is denoted by H<sub>i</sub> Km/hr and the acceleration of ith biker as A<sub>i</sub> Km/Hr2. A biker whose speed is 'L' or more, is considered be a fast biker. The total speed on the track for every hour is calculated by adding the speed of each fast biker in that hour. When the total speed on the track is 'M' kilometers per hour or more, the safety alarm turns on.&nbsp;<br>\nFind the minimum number of hours after which the safety alarm will start.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>\nN = 3, M = 400, L = 120\nH = {20, 50, 20}\nA = {20, 70, 90}\n<strong>Output:</strong> 3\n<strong>Explaination: </strong>\nSpeeds of all the Bikers at ith hour\nBiker1= [20  40  60  80 100] \nBiker2= [50 120 190 260 330]\nBiker3= [20 110 200 290 380] </span>\n\n<span style=\"font-size:18px\">Initial Speed on track  = 0 \nbecause none of the biker's speed is fast enough.\nSpeed on track after 1st Hour= 120\nSpeed on track after 2nd Hour= 190+200=390\nSpeed on track after 3rd Hour= 260+290=550\nAlarm will start at 3rd Hour.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>\nN = 2, M = 60, L = 120\nH = {50, 30}\nA = {20, 40}\n<strong>Output:</strong> 3\n<strong>Explaination: </strong>\nSpeeds of all the Bikers at ith hour\nBiker1= [50 70  90 110 130] \nBiker2= [30 70 110 150 190]</span>\n\n<span style=\"font-size:18px\">Initial Speed on track = 0 because none of the \nbiker's speed is fast enough.\nSpeed on track at 1st Hour= 0\nSpeed on track at 2nd Hour= 0\nSpeed on track at 3rd Hour= 150\nAlarm will buzz at 3rd Hour.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>buzzTime() </strong>which takes N, M, L and array H and array A as input parameters and returns the time when alarm buzzes.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N*log(max(L,M)))<br>\n<strong>Expected Auxiliary Space: </strong>O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n1 ≤ L, M ≤ 10<sup>10</sup><br>\n1 ≤ H<sub>i</sub>, A<sub>i</sub> ≤ 10<sup>9</sup> &nbsp;</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Bike Racing - GFG/bike-racing.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException{\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            String a[] = in.readLine().trim().split(\"\\\\s+\");\n            int N = Integer.parseInt(a[0]);\n            long M = Long.parseLong(a[1]);\n            long L = Long.parseLong(a[2]);\n            long H[] = new long[N];\n            long A[] = new long[N];\n            for(int i = 0; i < N; i++){\n                String a1[] = in.readLine().trim().split(\"\\\\s+\");\n                H[i] = Long.parseLong(a1[0]);\n                A[i] = Long.parseLong(a1[1]);\n            }\n            \n            Solution ob = new Solution();\n            System.out.println(ob.buzzTime(N, M, L, H, A));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static boolean check(long T, long L, long S[], long A[], long N, long M){\n\n        long ans = 0;\n\n        for(int i=0;i<N; i++){\n\n            long x = S[i]+A[i]*T;\n\n            ans += (x>=L ? x : 0);\n\n        }\n        return ans >= M;\n\n    }\n\n    static long buzzTime(long N, long M, long L, long H[], long A[])\n\n    {\n\n        long low,high,mid;\n        low = 0;\n        high  = M;\n\n        \n\n        while(low<high){\n\n            mid = low +(high-low)/2;\n\n            if(check(mid, L, H,A, N,M))\n\n                high = mid;\n\n            else\n\n                low = mid+1;\n\n        }\n\n        return high;\n\n    }\n}\n"
  },
  {
    "path": "Binary Matrix with at most K 1s.java",
    "content": "class Solution {\n    static ArrayList<Integer> largestSquare(ArrayList<ArrayList<Integer>> M, int R, int C, int K, int Q, int[] q_i, int[] q_j) {\n        // code here\n        ArrayList<Integer> ans=new ArrayList<>();\n        int[][]dp=new int[R][C];\n        dp[0][0]=M.get(0).get(0);\n        \n        for(int i=1;i<R;i++){\n            dp[i][0]=dp[i-1][0]+M.get(i).get(0);\n        }\n        for(int j=1;j<C;j++){\n            dp[0][j]=dp[0][j-1]+M.get(0).get(j);\n        }\n        for(int i=1;i<R;i++){\n            for(int j=1;j<C;j++){\n                dp[i][j]=M.get(i).get(j)+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1];\n            }\n        }\n        \n        \n        for(int q=0;q<Q;q++){\n            int i=q_i[q];\n            int j=q_j[q];\n            int min_dist=Math.min(Math.min(i,j),Math.min(R-1-i,C-1-j));\n            int curr=0;\n            int l=0;\n            int h=min_dist;\n            while(l<=h){\n                int k=(l+h)/2;\n                int x1=i-k;\n                int y1=j-k;\n                int x2=i+k;\n                int y2=j+k;\n                int count=dp[x2][y2];\n                if(y1>0)count-=dp[x2][y1-1];\n                if(x1>0)count-=dp[x1-1][y2];\n                if(x1>0 && y1>0)count+=dp[x1-1][y1-1];\n                \n                if(count<=K){\n                    curr=2*k+1;\n                    l=k+1;\n                }else{\n                    h=k-1;\n                }\n            }\n            ans.add(curr);\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Binary Tree Pruning lc.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n//     TC: O(N) where N is the number of the nodes in the tree\n//     SC: O(H) where H is the height of the tree\n//     In worse case, H can be N when it is a left skewed binary tree / right skewed binary tree\n    TreeNode* pruneTree(TreeNode* root) {\n//         if root is nullptr, then return nullptr\n        if(!root) return nullptr;\n//         DFS on left sub tree\n        root->left = pruneTree(root->left);\n//         DFS on right sub tree\n        root->right = pruneTree(root->right);\n//         !root->left means left sub tree does not contain 1\n//         !root->right means right sub tree does not contain 1\n//         !root->val means curr_node val is 0\n//         for this case , return nullptr else keep node\n        return(!root->left && !root->right && !root->val) ? nullptr : root;\n    }\n};\n\n"
  },
  {
    "path": "Binary Tree Pruning.java",
    "content": "class Solution {\n    public TreeNode pruneTree(TreeNode root) {\n        make(root);    //In this function checked all childs of root, whether they contain root node 1 as sub tree, if does not exist removed the node\n        if(root.left==null && root.right==null && root.val==0) return null;   // This is the case when only single node present and it is 0 In that case we should return null\n        return root;\n    }\n    public boolean make(TreeNode root) {\n        if(root==null) return false;\n        \n        boolean left=make(root.left);\n        boolean right=make(root.right);\n        \n        if(left==false) {\n            if(root.left!=null) root.left=null;\n        }\n        \n        if(right==false) {\n            if(root.right!=null) root.right=null;\n        }\n        \n        if(left==true || right==true) return true;\n        \n        if(root.val==1) return true;\n        \n        return false;\n    }\n}\n"
  },
  {
    "path": "Bipartite Graph - GFG/README.md",
    "content": "# Bipartite Graph\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an adjacency list&nbsp;of a graph<strong> adj&nbsp; </strong>of V no. of vertices having 0 based index. Check whether the graph is bipartite or not.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: \n</strong><img alt=\"\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARQAAACbCAYAAACj4WTAAAAYJ0lEQVR4Ae2dC3BU1RnHb4uFKaStYws44yitbUdsYVCmwthRQTtKbW1t7bRMqShalNKx7ZSOxY6lSoGG8IogAcIbggQIEMKbBAyQGGJAQgiEvN8hIUASIMm++Xe+ay4TF0I23HvO3nP3uzuZze7ePY//d85vz3fuud/RwAcrAMANN+pQh3zk4yzOIg1p+BAfYjZmYwqm4Hf4Hd7BO1iABViJlTiKoyhGMYpQhBa0sIasgK6AxjpEtgIEkb3Yi3/gHxiN0fgavgatB4/7cT9+hV8hFrGoRCWa0BTZgkZ47RkoEdgAXHDpo5G5mIshGNIDfHSPmp/gJ1iO5ahHfQQqy1VmoERYGyCXZjImoxd6WQqSYNR8G9/GEixBLWojTOHIri4DJULsX4MaTMd0oRAJhgq9JpdoMzajFKURonRkV5OB4nD7X8EVHMZh0IjhVh1e1ntP4kl9Etfhckd89RgoDm4CjWhEDGLCCpLOwPo6vo6t2IpWtDpY9ciuGgPFofYnF2csxtoGJp3BEoc4vtTs0HbHQHGgYWl9yEt4yZYwMcCyDMvQgAYHqh/ZVWKgOMz+F3ABP8PPbA0TAyp02boNbQ6zQGRXh4HiIPs3oxl/wB+UgIkBFRqp+OF3kBUiuyoMFIfY3wcfVmGVUjAxoJKLXIdYgavBQHFIG8hAhpIwIah8B99BCUocYonIrgYDxQH2p3mTYRimLFAIKlMxFXRLAB9qK8BAUdt+CCCgL3E33AeVn+kuZz7UVoCBorb9UI5y9EM/pUcnBgSfwlP6TYuKmySii89AUdj8NDqZgRmOgIkBlUxkKmwRLjoDReE2QMGN7sbdjgLK83geV3FVYatEdtEZKArbPwEJjoKJMUrhkAfqNkoGiqK2o0hrz+AZRwJlIRYqahUuNgNF0TZwCqfEwyRZgzZSg6Zp0AZq0F7VoFUY4whxz4/gEdClcD7UU4CBop7N9BInIUksUKI7QPKQBi1Wgzap4zXB5Zg4mFDKX8KXONKbou2SgaKg4Tzw4GW8LA4o6R3wGBsEDhqd0EiF/lxBn1lcGgqczYd6CjBQ1LOZvlZD6MrYMR1AuZV7s6bjM3KHBD7+jr8raBkuMgNFwTZQgQp8C98S053rO4AxqgtcEGTI7SEXSOCDQjDwfj/qNU4Gino2QyEKxXVlmh8hYEztAhfk6tDn9CfwQdt7UNQ5PtRSgIGilr300tJqUmGdObEDFjQp29XDAAqNZgQ9BmAAylCmoHUiu8gMFAXtvx/7BXVjDZoBFHru6vFiB3QEAoUCWtNOhHyopQADRS176aXdhE1ddXXz79sEKLQRGd34yIdaCjBQ1LKXXlraiqLL0YPZT2wClK/gK6DJZz7UUoCBopa99NIewAGz2Oj6+wZQwjyHQi4PA0W9xslAUc9m+Bgfdw0Es5/Y5CoPTcry9qXqNU4Gino207f0FObyhLoOJXgVrVmQBX1/KIbyZWMF2yYDRUGj0WQl/YILg0ooK2VvdxXIgpK9gBdA+zLzoZYCDBS17KWXthrVeBSPWtBtu0DSvo7LwsGjEIn38vwFf1HQMlxkBoqCbcALL17H6+KAQikbdxsP6lg1K/FuY8Ic3xyoYMMEwEBR027Yju1igUKphykeSh/0AY3C+FBPAQaKejbTS0wBlihuSBdOi9Lvj8AI3khd0XbJQFHUcJdwCRTQ2YlAWYzFilqFi81AUbgNbMRGxwGFltyzu6Nuo2SgqGs70E57AzHQUVChOCh8uVjdRslAUdd28MGHWZjlKKDkIU9hi3DRGSiKt4EzOIN7cI8joPIcnuMobYq3RwaK4gb0w++YzdL53h3FGyOvQ1HfgFQDimz2OB5XepTyH/wHbridYZAIrgWPUBxi/CxkKQsUih/L4R6d0RAZKM6wI9rQhnjEKwkVholDGiG7PM4xJNWE7kIWugGYAFytwRpnGSHCa8MjFIc1APq1H4dxArq+9Wtyl2M52tHuMAtEdnUYKA60/0dZH2F8y3hbQyURiWhGswPVj+wqMVAcZv+dO3fixIkTqEIVJmGSLaGSghS44HKY8lwdUoCB4qB2cPz4cezatetGjS7jMtZirW2gMgiDwCthb5jHkf8wUBxi1rq6OsTHx99UGwrGlI98DMfwsIJlLMbiPM7fVD5+w1kKMFAcYM9AIIDp06fftibFKMYCLEA/9JMKlofxMA7jMN/wd1vrOOdDBooDbLl06VLU19d3WxNaq0IL4KZgCvqjv1CwDMMw0CVhXk7frVkcdQIDRXFzpqSk4OTJkz2qRQta9LmMOZiDURhlGVho9PMb/Eaft+HFaj0yiWNOZqAobMqcnBzs2bPHVA0KUIBUpGI+5uswoIlTCnIUyqqTKEThh/ghXsNroMvAlFYDGkyVh7+stgIMFEXtV1tbixUrVlhaegpsRNt/1qAGOcgBLTyLQxz+i//iDbyBGMRgJVaCIsVRcKc61DFALLWA+okxUBS0od/vx4wZMxQsORfZ6QowUBS08JIlS9DQwK6FgqZzfJEZKIqZODk5Gbm5uYqVmosbKQowUBSydHZ2Nvbu3atQibmokaYAA0URi1dVVWHVqlWKlJaLGakKMFAUsLzP5+NJWAXsxEXkmwOVaANxcXFobGxUoqxcyMhWgEcoNrf/9u3bkZfHe9XY3ExcvA4FGCg2bgrHjh3Dvn37bFxCLhor8EUFGChf1MM2ryorK7F69WrblIcLwgqEogADJRSVJJ/j8Xgwa9YsyblydqyAeQUYKOY1tDyFxYsX4+LFi5anywmyAqIVYKCIVriH6W/btg2nT5/u4bf4dFbAHgowUOxhB70UWVlZOHDggI1KxEVhBXqmAAOlZ3oJO7uiogJr164Vlj4nzArIUICBIkPlbvJwu92Ijo7u5iz+mBWwvwIMFBvYaNGiRbh06ZINSsJFYAXMKcBAMaef6W8nJSUhPz/fdDqcACtgBwUYKGG0QmZmJlJTU8NYAs6aFbBWAQaKtXqGnFpZWRnWrVsX8vl8IiugggIMlDBYqb29HbNnzw5DzpwlKyBWAQaKWH1vmfrChQvR1NR0y8/4TVZAZQUYKJKtt2XLFpw5c0ZyrpwdKyBHAQaKHJ31XDIyMpCWliYxR86KFZCrAANFkt6lpaVYv369pNw4G1YgPAowUCTo3tbWhpiYGAk5cRasQHgVYKBI0D82NhbNzc0ScuIsWIHwKsBAEaz/pk2bUFBQIDgXTp4VsIcCDBSBdjh69CgOHTokMAdO2gkKXMM1lKEMx3AMKUjRN6SPRjTmYR4SkIA0pCEXuTiP87avLgNFkIlKSkqwYcMGQalzsior0IpWJCEJb+JNPIgHofXw8TSeBgHnNOwXiIuBIqBltra2Yu7cuQJS5iRVViATmXgVr6If+vUQIV0jZwiG4EN8iGbYY46OgSKghS5YsAAtLS0CUuYkVVQgFal4Ck9ZBpFb4eUb+AamYRou43JYJWKgWCx/YmIizp07Z3GqnJyKClSjGuSe3AoAot6LQhTexbthG7E4CijXr18H/QUCAfj9ftCewPRH/9MfvU+fizoOHz6Mjz/+WFTynK4iCvjgw1zMtdS16SmA7sbdmImZ0sGiNFAIDgSKwkIPMjM9OHmyHXv2uLFkiQcxMV68/bYHb7zhxcyZXixb5sa2bW5kZ7cjO9uN06c9uHLFq0PGinZaVFSEjz76yIqkOA2FFShEIUZghNRRye1gQ3M27WiXpqiSQCGInDvnxqZNHrz9thdPP+1H//7XoWkI6S8q6joee8yPiRO9iI/3ID/fhZYW3x3D5erVq5g3b540o3FG9lTgIA6iL/raBiYGaEZipLSRilJAaWryIjfXhfff92Lw4EBI8AgFMvfeG8C4cT7s2OFGXZ2nx2CZP38+CCp8RK4CBJPe6G07mBhQGYqhuIALwg2kBFCKi31ITXVj3DivZRDpCjQ02klOdqO62hOS+Bs3bgS5O3xErgJHcAR90Me2MDGgMhiDhS+OszVQfL4Azpxx4c9/9gkHSTBgnn3Wj+PHXSgv93XZU9LT00ETsXxErgIncCKsk68GLEJ9JqiIvLRsW6AUFtJEqgcDBoQ+NxIMBSteT57sRV7ezaOVwsJC0OiEj8hVoAENGIABth+ZBMPmp/ipMKPZEihFRR5MmiTevQkVOD/+cQDp6W643Z9fcr5y5Qpo3oSPyFUggABGY7RyMDHgshRLhRjPdkApKnLj0Uetm3ANFRrdndenD5CV1Q6vN6Avq7927ZoQg3CiaijwHt5TFiYEFboaVYpSy8W2FVCysjz4/vfD6+J0B5b4+GzU1jZabghOUB0FaAUsrUg1fu1VfX4ST1ouum2AUlHhwve+Z7+Rya0Ac+iQC16vuBW3lluZE7RUgbEYqzxMDAiuwRpLtbEFUKqr3fpCs1t1Xru+t3+/G34/Q8XS1qhAYiUoQS/0cgxQ7sN9oFsFrDrCDhRarDZ5svzLwmZB9dBDAZw967bKDpyOIgrQUnbj190pz4lItEz9sAKFltCvW+eRvsbELEyM70+Y4ENj482XlC2zDidkKwWcNjoxgEhL8606wgqUysp29Otn70lYAx5dPaekuHq8VN8q43E6chVQ/cqOAZBbPZej3BIxwwaUa9e8ePNN9VydYLDQRHJ+Prs+lrRGGydyHddxP+53nLtjwGUqplqifliAQmEH6N6c4M6p6uu//tWHpibrJrYssSwnYqkCFCTa6HzCns9p0F7VoA3UoGkatEEatEkatHphOd6o0yAMskSvsADl4kUPXnhB/dGJAcCBA6/r9xxZYhFOxJYKxCL2RucT0r1jOyBCMCGI0Ouxnd47JiTXL9SpAhWmtZcOFBqdHDnicszoxIAKBXTy+fymDcIJ2FOBX+PXX+h8lnbv3A5wjNSgNQelTCCh0QqBxhX0mcUlWod1psWXDpS2Nh/+9CfnjE4MoAwZEkB5Oc+lmG6RNk3gITxkcfftBIfoDmjs6/Re59ymdvN553NN/G/FPIp0oBQUuEABjYyO6KTnjAyX0Ji1Nu1rji+WH358GV820VW7AIWR4t86RiBdzZUkdgCFngU+XsSLpm0pFSgUJFruuhMX/qUNwwktEc+FGB7SDOBeecWH1laenDXdKm2WAK0/EdmRu03bGMEkd3umqXLSKMzsIRUoHo9ParCkl7SxOKFp0oAybFgApaXs9phtlHb7Pm0RKrYr3yZ1mlMxrvpU3OY8C0o4EANNSy8VKDU1blCnMzMKCO27zXhLG9MBE3lAobIVFsqLMG7a+pxAtwrQau40T5oF3fUOYWBc6SG3SPCDNgsze0gFSl6eG3fdFVpk+tDAcXNaj2uJ2KkN7ICJ8SzH5aEyUxR9cu34kK8A6e52u/WA4RcvXkRdXR0qKyv1mL+nT5/GZ599hqysLD1sZ1paGnbv3o3t27dj8+bNWL9+PVauXIm4uDjExsYiJiYGM2bM0P9mb50tuCt3gQrD1aGrP4Kv8FAJKC6u2UMaUORcLk5Euu7iDMQnWiJe1YzX8oAybZpH31zMrGEi4fsejwcUqOrSpUuor69HVVUViouLcfbsWeTm5iI7OxtHjx7FwYMHsWfPHiQnJ2PLli1ISEjAqlWrsGzZMixcuFAPeDVr1ixMnz4d0dHRejS9xYsXY/ny5VizZo0eqnPr1q1ISUnB/v379c3YMjIykJOTg7y8PH2nx7KyMtTU1ODChQtobm5GW1vbDTumI10+UIwrO7e6lCyoNEqNUGjouHGj6NWxydivxeI9rRlR+iSsfKD89rc+fQMxpwGBdmCkTeCbmprQ0NCA6upqlJaWoqCgAKdOndI7Z2Zmpt5Z9+3bp3fepKQkbNiwQe/U8fHxWLRokd7ZqdO///77IAjQpvL0/tKlS7F69Wp9szSCxo4dO0DpEEwIKp9++qkOmTNnzqCkpETPnyBE5aFyEZxEHVLnUGgkQqtlae2JRJjQCEWpORQCCi3+ulNX5s6+Jx8oTzzhR22tV1TbDild0rq9vV3fsL2xsVH/5aVfYNpzmX6Rjx8/jk8++QQUtf/AgQPYtWsXtm3bBtqXee3atfovO/3C06bvs2fP1n/5Z86ciTlz5uCDDz7AkiVLdPeA3IRNmzbpI4e9e/eC3IgjR47oIwtyL/Lz8/URR0VFhe5+0EiE9i8it0Slg1aQduGUWPs+TcCO6oAJzZ1IcHM612sYhpk2izSXh37h/vlP5wNl5Eg/KipC/7U0/H4KfG34/dQBaa8f8vtPnDhxw+9PTU294fdTRzb8furgwX4/zQHQezQnsGLFCqxbt04HBoGDAEIgoS1AaE6B8qC8KJJ/eXk5amtr9bK0tLToYIr0OSHh61AISwQPGpHQyISW3ofhQZHozB5SgTJxouwVsvJHKEOH+rF//0n919rw+2nSz/D7aWjfnd9PowTaooP8/p07d97w+8mlCNXvN9sw+PtfVEDoSlmChwETmogN04PCM5g9pALltdecP0IZOjSA3btzQJN+ht9Pk4yG30/zD4bf7/WG1zUy23gi6fsTMEFcNzduDCQ3J4yPHdhh2qRSgUIbm9/ZXMjNl4dDS0f+CKWnLo9pC3ICUhSgYM5COju5OsbCNXJ3bvcneOl9M5pNaykVKHPmOB8oo0f79Q3XTVuGE7CVAsImZo07jW8HEuMzgUCxYkKWDCYNKHIuGwePZOSPUOiycUsLuzK2ooFFhaFOJ2SUYoNUrZg/kQoUOQvbwg8UXthmUe+1YTLRiLZB1xeDtDKUWaK4tBEKlTY/34VevYI7vcjX8kcoCQleXnpvSdO0XyK0Y6CY7hzeVJ/AE5aJLRUotbVu0GXV0CZUrQCNfKBQvBc+nKuAE/flSUayZQaTChSv1yd5Uy+5QOGobZa1S9smVIxiR41SHsEjoIj+Vh1SgUIrLuUGWLJilBN6GuPH++FycYAlqxqnXdN5Ha87BipWrD3pbCepQKGMT51yoX9/tTf36splS093cwjIzq3Lof83ohFRiFIeKmMwxnILSQcKBal2wgZfwVB5+GEOUm1567RxgvMwT3mgFKDAcoWlA4VqQL/kwR1S9ddTpvA2Gpa3ThsnGEAAz+AZZaFC+wyJOMIClIsXvRgzRubVntDnQe4EbPfccx1FRXx1R0QDtXOa9ajXY4iE96Jvz3P/JX4pTNawAIUWue3a5ZxRyjvveOF282SssFZq44RzkKPUfMpwDMc1XBOmaFiAQrVpavLg5ZdlhzOwfqRy330BHp0Ia55qJEwhIikea8/HCnK/MRiDcRmXhYoaNqBQrUpK2tG7t/Wd/E7cljv9zubNbl4ZK7SJqpF4BjLwTXzTtlB5HI/jEi4JFzOsQPF4/FiwwKPsBO3zz/tRU8M3AgpvpYpkQPfD0ChA7rij+9zGYZw0BcMKFKplaakXL76onuvzwAMBnD3LE7HSWqoiGV3BFfwcP7cFVHqjNxZjsVTlwg4Uqm1RkQff/a6MDcCsc6927+ZFbFJbqmKZ0WXZvugbNrA8iAeRhSzpqtkCKJ9DRZ1N1NPS3PB6rbv/QbrVOUMpClSiEs/iWalQuQt3YSqmwo3w7CxgG6CQhXNy3Lj3XnuPVHbs8DBMpHRH52RyCIcwCqOEgoXcm4mYiHKUh1U4WwGFlCgpceEHP7AnVHJyXAgEeGQS1harcOaZyASFP+iHfpbBZRAGYRqmgWK12OGwHVBIlJISD155xT4TtT/6UQAFBTxnYocG64QytKIVSUjCH/FHPIAHegyXkRiJf+PfOIqjtpPDlkAhlaqqvJgzx4O+fcN7Z/LkyV7U1YXHH7Vda+ECCVHABRfokjNteUrhBFZgBf6H/2E+5iMBCUhFKk7iJGpRKyR/KxO1LVCokj6fH0VF7ZgwQf5o5bHHAsjOduHqVV5Sb2WD47ScrYCtgWJIT1HkDx504xe/EH9D4fDhAaxc6UZVFbs4hv78zAqEqoASQKHK0A2Fzc1efPaZG1OnejFokHWuUFTUdX1x3Zo1HpSXe3gpfaith89jBYIUUAYoRrkJLLTxOoUL2LDBg7fe8mLECD+++tXQF61R5P3BgwP4/e+9iIvz6NH4L1zgaPWGxvzMCtypAsoBpXNFKUbt53BxIzub/tqxbZtbvz9o+vTPYTN+vA/vvuvV30tI8OD4cReqqtpx/jwtTvOCNiDjgxVgBaxRQGmgBEtAoxcCBEHG+DNe0zMBiM7hgxVgBcQo4CigiJGIU2UFWIFQFWCghKoUn8cKsALdKsBA6VYiPoEVYAVCVYCBEqpSfB4rwAp0q8D/AVXBgwgSrHAYAAAAAElFTkSuQmCC\" class=\"img-responsive\">\n<strong>Output: </strong>1\n<strong>Explanation: </strong>The given graph can be colored \nin two colors so, it is a bipartite graph.\n</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example&nbsp;2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong><img alt=\"\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAATkAAAClCAYAAAAnMop9AAAgAElEQVR4Ae2dCXQV1f3Hx2r1VNJNC/TUtlTbHqHFg1qV2lMFrdTa2trahaMVUUtFemx7Smtpj3+rVDDsKGULi4ABgrLvq0YgBAxLgLBkIwmQkLCFsCRvlvfy/Z/f8IaEl/de5r2ZO29m3u/m5Mx7s9y593t/+eR3dwkcWAFWgBXwsQKSj/PGWWMFWAFWAAw5NgJWgBXwtQIMOV8XL2eOFWAFGHJsA6wAK+BrBRhyvi5ezhwrwAow5NgGWAFWwNcKMOR8XbycOVaAFWDIsQ2wAqyArxVgyPm6eDlzrAArwJDzqQ3IkFGDGhShCAdxEBuxEf/D/zACIzAYg/E7/A7/wr8wDuMwAzOwBVtQilKUoAQNaPCpKpytdFSAIeezUiewrcEa/B1/R2/0xmfxWUgJ/HwNX8Mv8UuMx3hUoQr1qPeZQpyddFOAIeeDEg8goHttozEa3dE9AaS1j78f4UeYhmmoRa0PlOIspKMCDDmPlzpVRwdhEK7FtbbCLRJ/38A3MBmTUY1qjyvGyU83BRhyHi3x4ziOoRgqFGyRoKPvVJ19H++jHOUeVY6TnW4KMOQ8VuLncR4f42OQZxUNQk6dewAP6B0VHpOPk5uGCjDkPFTop3AKIzEypXBrDdHP4XNYhEW4hEseUpGTmm4KMOQ8UuJUPe2Lvq4BXGvYTcIkHnbiETtKx2Qy5DxQ6jR+7Uk86UrAGbCbiqmoQ50H1OQkppsCDDmXl/hJnMRP8VNXA84AHQ1haUSjyxXl5KWbAgw5F5f4OZzD7/F7TwDOAB15dEEEXawqJy3dFGDIubTENWiYiZmeApwBukIUulRVTlY6KsCQc2mpb8VWTwKOQHcrbkUZylyqLCcr3RRgyLmwxKkdrgd6eBZyBLohGAKabsaBFUi1Agy5VJdAxPtDCOnTp4yqn5ePtPoJB1Yg1Qow5FJdAhHvr0AFOqCDp704A8wP4kF94YCILPJXVsBRBRhyjsod/2Xkxb2JN30BOAN0eciLn2m+ygoIVoAhJ1jgRKKnBSu/gC/4CnKP4TFcwIVEZOB7WQFbFWDI2Sqntciyke0rwBneHC/PZM0u+GlrCjDkrOln29O0ou/DeNiXkHsH79imE0fECiSqAEMuUcUE3b8Xe8UDbqkEqacESZIgdZYg9ZcgVRr+lrjjnbgTNCyGg38UCAaD0DQNx5XjKJVLcUg+hNJAKUqbSrGvaR/KA+WoDFSiRq5Bo9Ko30vPNDc3Oy4CQ85xyaO/cCEWioVcZhhut0uQxkuQBoa/E/C2iwMcxXwNruEVhaMXu6fOEqTq1DqUN5VjubwcL6ovok+wD7qFuuHm5ptxI268YsM34AZ8Hp/Hbc234YHgAxgUHIT58nwcbjqMarlah55TwGPIucDMFCh4Bs9cMRDbkZMbBlrfiJjJiyOPjn4DEddsTg1trsPBewoQiMhbK24qxjh1HHqEeuBTzZ+yZB23Nt+KV9RXsDOwE6eV0wiFQkKFYcgJlddc5NQeJ3SGw6NhyEWrms4KX6OqrMCfv+Fv5sTgu1yhAMHthHoCGwMb8XBQXFvxnaE7sVReiiq5ShjsGHIuMKlKVOJL+JIYxNSGIdYrBsIIfFRlpeqrwB9aLor3c3WBsZlIwkXtIvYE9uBhTRzcIm3t9uDtWCGvQK1i/65wDDkThS76lmIUi8MLtbcRxIZEmlX4O1VT6Tr9CvyhrRJpdWMO7lWAvLdqpRqD1cECLSG+lfXR+iBPzrPVq2PIucDmaFZA/KK3cDUnDDDqeIj1Y0COvD5BP53QCUdwxAVqcxKiKUCdCgeaDoDay0TZQCLxzpHn4Jx6LlpSEz7HkEtYMvsfWId14gzLgBwdY/08EQahQMjRpjdVqLJfPI7RsgINWgMmKBNiWUfKzg/QBqBGqbGcP4acZQmtR7AAC8QZkksgR5tf0+IDHNylQEOoASNV9+wAF/mP+HHtcZSqpZZEY8hZks+eh2lbv8jCte27SyD3aXwa1MHCwT0KnNXO4m31bXG2Z1PMT2pP4oiSfFMHQ84FNrce620yhyhoNCCX4jY5qq4y5FxgbOEk1Gq1GK4MF2d3Nsf8WPAxHFGTAx1DzgV29xE+stkkWsHOJb2r1PFQjnIXqM1JoMG3K+WV4mxOUMwDtYEg7zPRwJBLVDEB99O+qq2wZO9ns+PkImdD2JsK3IE7eAiJANtJJkqaY3odrrO5hIVZ8FXpXCwvTnh4CUMuGSux+RlqkCdPR5iZmJnxEK/31YaUPY7HcR7nbVaOo0tUgRKlBN8Pft+GEhVmrXHTdj2ux4HAgYSyzZBLSC4xNx/DMdyFu+IWriWTWhseIhLprTk4d/XP+LMY8ThW0wrQWLgsJUucnTkU8zPaMwmNoWPImTYRcTeqUPECXhBrIsYqJF3Csx8cXIWEAM0T9MXZj9mY98n7kNGcIdbOHIp9mbzMdLWVIWfWQgTftwRLxJtHitaTo2V3yFvlkDoFLmgXMEQdIt7GHHoDLd9UJ9eZEpQhZ0om8TfRopm07pqlaqlLn74P96EO5gxSvNLp+QZqx7qp+SaXWkhyVr81sNWUN8eQc4nNn8EZ0KYvyRW3u5+aiIkuUTk9k0Er+I5U3DurIVnr/an2UzSoDe0WKkOuXYmcu2E+5vsOcjSdi6uqztlQtDfRopf3Bu/1nW1RT2tZU1m0LF91jiF3lRyp/UI7zndGZ18ZI60jx0NHUmtXW+QtvrKp1p7fFGUKqNc4XmDIxVPH4WsaNAyHd6batDa2WJ/3YZ/DKvLrWitAVdVhyjBHIffvIRJ2PSHhxw68lVYtPqOcaZ3lNp8Zcm0kSe2JAziAm+CPBuIf48e8GnBqzQknlZP4kfYjB3Bz+d/ckzkSdknOQa5jc0d9l7B4MjPk4qmTgmtBBDEZkx0zylgemB3nea5qCgwo4pVFcpFjvaovjw8DzkHIkZ2uU9bF3eqQIRdhFG74Sivo3o/7PQ26/+A/kCG7Qc60TQMtZ76naY9wO7q/UMKKXmHAdXbWkyPITVOmxR1KwpBz6Z9APvKFG6cd3lq0OGg/B17qPPWGRauN0E5Y0crItnO1EnLJc5MkbPurhP6Hw98dapOjfLysvgxVVWMKzpCLKU1qLzSiEVnw5jxDBlxqbcd4O/U6ZqqZwiG3rq+E1ysl6BPGDOg5CLmHgg/FncvKkDMswoVHWp1E6KbTAsx/Fma5UMn0TBL1rP5H/Y+AUo7jB6YAcjTFK95Whgw5l9s/eUVP42lnDTWJt10TugbTMA1NaHK5oumTPILcQHVgEqUZB2LtxZYCyN0TvAdH5aMxC5YhF1Ma91yYlz8P/Rr6tWdeKb0+PzQfC1cudI9onBI0ao34lfYrZ+0iBZDrGuyKYqU4Zokz5GJK444LK1aswK5du3AURzEQDv9XNvnnsRzLEUAAO3fuxLx589whHKcC5MkNUgeZLEUL3lvrN6QAcveG7gVNXYsVGHKxlHHBeYLGypUrr6TkLM5iNma3NqmUfu6CLoic0VBSUoKpU6deSTN/SJ0CBLlXlVedtZEUQO7B4IM4rZyOKTRDLqY0qb1QU1ODrKysNomgBTaLUIS7cbezxhvxtr7oixM40SZ9dKK2thYjRoyAoihRr/NJZxSg3tXX1dcjSs4mjy1WrCmA3MPawwiogZiiMuRiSpO6CzS+aejQoXETQJvfjMM4dECHWOYm5Hw3dMPH+LjdSfdNTU0YPnw4Tp+O/R82bgb5omUFyI5WBFYIsYOYqEwB5P6i/kWvmscSjCEXS5kUnp8yZYruDbWXBBpLR4OGB2MwOqKjUGPugR6g4SGJTtWaOHEijhxJbr/M9vLP19tXoChQJNQu2sAuBZCbKc+MuxIJQ659O3H0juXLl2PPnj0JvbMBDXrb2CiMQi/0ss2oyUv8NX6ttwNaGeD73nvvobCwMKE88c32KLBX2YvOIQeX70oB5D6SP+K5q/aYi/hYCgoKsHr1aksvOoRD2IANGIuxOqCoc4AWrmzzHzfKmQxk4Lv4Lp7H88hBDiguu5YtX7p0KT7++GNLeeOHE1egTq0DraBrpvxtucdhyN0SugVHAvFrCuzJJW43Qp6orq7G9OnTbY2bFqusRKW+qXMBCvTBupMwCf/Ff/FH/BEjMRIzMAO0IjEt2FmDGtugFi0jH330EWhIDAfnFKAe1rHKWN9C7mfaz3BRuRhXUIZcXHmcuUi9YG+++aYzL0vxW2jM39y5c1OcivR6fWGg0DnIOfymqfLUuCuQUEkz5Fxg75MnT0ZdXfrsZlVWVgbKMwdnFDimHAONJbOlOuqiWD7X/DmUNJW0KyJDrl2JxN5AbVXp2Ch/8uRJZGZmQpZ5zTmxFga953GMMsZFeLIHt7/RfoMmtf250gw50RYWJ/4dO3ZgzZo1ce7w96VAIKCD7tSpU/7OqAtyd1A+iC7NXXwFul2BXXF7VQ3ZGXKGEg4fjx49ipkzZzr8Vne+btKkSaAqLAdxCihBBaPV0b6B3GPaYzilmPvnyJATZ1cxY6Yer3TpaIgpQsSF7Oxs7N69O+Isf7VTgUK5EF8NfdUXoMuX89vtcDC0Y8gZSjh4JM+Fq2htBaeB0Lm5uW0v8BlbFKBpXjlyjuch9w/tH5A18225DDlbzMd8JEuWLMG+fbwXaSzFaMAwwY6DGAVK1VL00fp4FnSdmjuhXClPSByGXEJyWbt5+/btWLt2rbVI0uBpmtZGU8E4iFFgd2A3Ojc7ONXLRqTmBfJMdTa0Vo4h11oNgZ+rqqrw7rvvCnyDv6IuLy8HTe7nYL8Cweag+F28bASbMeBkpDIyoWqqoRxDzlBC4JHWVaNlhzgkpgAt0/TWW2+Blm3iYK8C9aF6TJOnCUCRgSR7j7TCcb1an5QIDLmkZEvsIfJIeF21xDQz7qZ/ELQAZzrNCDHyLvpYF6zDpIZJuEa7xtWw+7P6Z5SribXDtdaOIddaDQGfFy9ejP379wuIOb2ipGlgpaWl6ZVpwbmlITvZy7IxXZnuWsi9pL2ECq3CkhIMOUvyxX84Pz8f69evj38TXzWtAE3sp30vOFhXgJoAyEOmcCl4CfOUebgBN7gKdrRn7Fn1rOXMMuQsSxg9gsrKSsyePTv6RT6btAK0sQ8t2cTBmgKzZs0CdYYZobm5GYebDoN2vrK3NS3x2G5qvgmb5c36lopG+qwcGXJW1IvxLE06p8nnHMQosHnzZtDCBhySU4DmTMcaykT7lw5VhqbMq6MOhhKlJOFhIvGUYMjFUyfJaxMmTMCZM2eSfJofM6MArdwyZ84cM7fyPa0UOH/+PMaNG9fqTNuPVH2lvSF+Hfy1Y15db603cgO5aFAb2ibI4hmGnEUBIx9fuHAhioqKIk/zdwEK0AY59A+Fg3kFpk2bBtru0kyoUWuwp2kPnlKfQsdm+zdK+jQ+jUe0R3S4VSqVtnpvrfPHkGuthsXPeXl52LBhg8VY+PFEFCCPediwYWhsbEzksbS8d8uWLdi0aVNCeae2ulqtFjRLgsbVPRJ8BF9p/krSHt5nmz+L+4P3Y5QyCkVNRTilnjI90T6hhLe6mSHXSgwrH8mr4OqTFQWTf5ZWdRk5cqSpbRyTf4u3n6QFIazOIKFl+ovUInwS+ASrAqvwsvoy+mn9QFXNbsFuuK35Nh2ANGXsG6FvoFuoG3pqPfFb7bf4r/JfrJZX42DTQVQpVXG3ELRbaYacDYq27o63ITqOIkkFaL/a4uLiJJ/292N2D0gnD4/+uZzUTurQKpaLQQtz7g3sRYFcgP2B/aBzFXIFLqoX9XvpmVQEhpwNqr/zzjuor09uyokNr+coWimQk5MD2tqRQ4sCVEWlqmq6BoacxZL/4IMPcODAAYux8ON2KkB7127cuNHOKD0bF3UyZGVleTb9diScIWdBxa1bt/IfkwX9RD5KZUNr96V7oOEiDQ32D8vwkq4MuSRLi5YC4jXPkhTPocf27t0LGtmfroEG/NLA33QPDLkkLICGK1BvHgf3K0BTl6jNNN0CTytsKXGGXIsWpj+NHz8e586dM30/35haBahTiDYOunjxYmoT4uDb6Z8wr8N3WXCGXIKGt2DBAhw6dCjBp/j2VCtAY7xGjx5terR/qtNr5f20RwYtIc/hsgIMuQQsgbrhP/zwwwSe4FvdpgBNazp8+LDQZF3ERRzBEWzHdizHcszADGQiE2MwBtnIxkZsRCEKcQInbE9HSUkJ5s2bZ3u8Xo6QIWey9GjzY1rPjIP3FSBv3M4G+Uu4hIVYiBfxIm7DbQlPeXoID+kQ3A/ri6tStZy8Vg4tCjDkWrSI+enSpUt6VSfmDXzBcwqsWbPG8jzjPOShP/qjAzokDLZYq6x1R3f8D//DOSTe5suLQ0Q3Q4ZcdF2uOstjja6SwzdfaEGFRYsWJZyfDdiAB/GgbWCLBrzP4/N4Da/hLMytjEsr3xDkOLRVgCHXVpOrztA0IdFtOFe9kL84qgDBwexWkcdwDFS1jAYlUecykIFX8Wpcz46qp1RN5RBdAVdDjib00m8oFNLbGWhCMP1SodIvnRc56Zd2c+eltqMbjp/OHj16FDQsKFbQoGE0RttaLU0Uil/AFzAMw6LCjjoaqMOBQ3QFXAU5AhbBq7hYQV6egj17mrB6tYzJkxWMHKnilVcU/PGPKoYNUzF1qozFi2Xs2NGEHTtk7N+v4Px51ba1qbiXKrrB+PUsjXscOnQoLly4cFUWi1GM+3Cfo95bPABSG2ATWvahpaEiNGSEQ2wFXAE5AtvhwzIWLFDwyisqHnooiI4dmyFJMPWbkdGMe+8NYsAAFVlZCoqKAmho0JIGHhn6mDFjYqvGV3ypANUMxo4di+PHj+v524RNuBE3ugZwBvx6oqfu0dFgX555074pphRy9fUqCgsDeOMNFV27hkwBzQz4vvzlEJ5+WsOyZTJqapSEYUeGHvkfvX0p+Q6/KDB9+nSsaVyD63G96wBngO4O3IEZ82eAqtoc4iuQEsiVlmrYsEHG00+rtoEtFvzIK1y6VMaxY0p8JcJX58+fz+0bppTy702bsRlfPP1F1wLOAF1XdBUyoNhvJeso5DQthAMHAvjTnzThcIuEXp8+QezcGUBFhRazDHNzc0GdDRzSV4Fd2JXSDgYDYGaPBDqzw0zStVQdg1xxMXUWKOjUyXxbWySo7Pg+aJCKffvaenW0bDZ5cRzSV4E61KETOrneg4sE4E/wk/QtNBM5dwRyJSUKBg4UXzU1C8Ef/CCE3FwZsnx5zXnai5La4TikrwIhhNAbvT0HOAN4UzAlfQuvnZwLh1xJiYy77rKvU8EsyNq774YbgPz8JqhqSJ+ylU7L8LRjE2l5+XW87lnAEeioF7gc5WlZdu1lWijk8vMVfPvbqa2etge7rKwdqK4+1Z5OfN3HCtBMBppZYHhFXj0+gAd8XErJZ00Y5CorA/jWt9znwUWD3ocfBqCqqdkuLfmi4yftUqAv+noecAaYZyF9l3uPZQ9CIHfsmKwPzo0GFLeeW7dORjDIoItlKH49X4YyXItrfQO5W3ALaBoahxYFbIccDfAdNMj5ISJW4Xn77SEcPCi3KMOf0kIBmiZleEF+OeYgJy3KzmwmbYUcTc+aM0dxfAycVcAZzz/3nIZTp9oOLzErJt/nLQX85sUZkKZpXxxaFLAVclVVTejQwd0dDQbQYh2XLw8kPA2sRU7+5CUFvN6jakAt2rECFV4qCqFptQ1yFy+qePFF71VTI2FHnSVFRVxtFWp1Loi8Gc34Gr7mu6qqAbwhGOICld2RBFsgR0sk0VzUSGB49ftf/qKhvp4bb91homJSQRvJGEAQdjwsQeovQZLCv70kSEuFve2q/HRBFzHCeTBWWyB3+rSCxx/3vhdnQLlz52Z9jq0Hy5OTbFKB8Rh/FRRsR8/aMNg6S5D+KkEaL0G6PXyOwOfATyUqTarh79ssQ468uM2bA77x4gzQ0SKdmsa7HvnV/H+FX4nDzDkJEsGNfisjcEbAI88uJ+K8gNTMwRy/Fl9C+bIMucZGDS+95B8vzoBc9+4hVFRw21xC1uShm2/H7QKwEgbXrDDI6Bj5Q9AjyD3R5krknZa/c7vcZYO0DLlDhwKgRSoNOPjpuHVrQOgeEh5igq+SGkQQn8KnLEMkJqaoatpTglQY5Y7aMOTIyxP88wSe8FW5JZsZS5Cj5aJFj4vLkA5jjNQf26TO2CVJ2CV1wTZpIGZJtbjZ5PLoyYL32Wc1XLrEHRDJGpdbn6PxcaIBEzN+6nggT25IzDtsSxt5qxwAS5BTFE3oApjdpfHI1cFGgBuIRdJ4zJP6hmHXGduk7eguEHQ9eoRQXs5VVr/9oWzHdttAYhpVgXA7XKy2OgEp6ozOfiu6pPJjCXLHj8sgECTrKcV/rhCzdMD1xCLpHDJawSxD2o55YfgtksR2ehQXt+yMlJTC/JCrFKBZORuVjQKQEgd31P5mDCOhHtbIzghBqaENqjlY9OT27ZNx3XXmdtSKD7S2cWRImWGPbW1Ub62LNOTK9e+1AmCi72nvftr9i6rlHJxXgHSXZVnfVOj06dOoqalBVVWVvgfH/v37sXv3buTn5+tL1m/cuBGrVq3CkiVL8P777+O9997DjBkzMGnSJH1PVdrVijZgpt8Ri0YIwkoM0A0MDyHp26o9LjfGvTam7Abc4HyhufCNSXtyooeO9JL+qrfD5Uq1MTzFnHBVNgc/Fgi5115T9A2tXVh2rkuSoiigxUfPnDmD2tpafSep0tJSHDx4EIWFhdixYwe2bNmCTZs2YfXq1Vi6dCk++OADZGdnY+bMmZg6dSreeecdfRHT4cOH6/ugZmZm6qs2T5w4EdOmTcOsWbP0ZeoXLVqk7ze6bt06fQPwrVu3oqCgAPv27cPhw4dx5MgRfWvBkydPgvZUbWxsvFKOuci1ESUJwmp7K69OsEfHntzlP5GkIUdu//z5qZvl0OLpLUUvgZD77W81fdNq1xHFYoI0jTpVLqG+vh51dXU4duwYysvLcejQIezdu1cHRl5eng6QtWvX6kBZuHAh5s6dq4MmKysLEyZM0AFEIHrjjTdAYBo9erR+fsqUKXj33XdBu7sTyJYtWwaKhwBHoPvkk0908B04cABlZWX6+wmMlB5KFwFTVEhJm1xrrFLvK1Vf6Sjwh9vkLluQJcjRgNn2qntirp/D8HBva65UKTQNP/xhENXVqqi/N1Px0j8U2ki4oaEBp06d0j0U8lTIYyHPZefOndi2bRtot7H169dj5cqVWLx4MXJycjB79mzdAyJPaNy4cRgxYoTuIQ0bNgyjRo3C22+/jcmTJ+tVO6riLViwQPew1qxZA6oCbt68WffAqGpYVFQE8swqKyv1qiN5bLQ/LVUpvRRoJoBIuLQbN1VVCXKZ7d5pKZ090MNLxSIsrUlDjjyBf/4zNZB7/EoP61/xukAvjgDds2cQlZXmvQqjHYk2xzHakQgKJSUloHakXbt2XWlH2rBhw5V2JIKL0Y5E0Bk/fry+O7rRjkRtSnSO2pho8+M5c+boECOYEdQIbrSdIrVR0TvoXbQDWUVFBaqrq/W0ECQJlunexih8nBzNUaVeVJr5EO3HmPIlGHK04jEHCx0PBLkBA5yf6fA9KRPbwr2u8wT3rBLk7rgjiHXr9uhejdGORA3bRjsSVcvaa0cib4q2O6R2pBUrVsBoR6LqoNl2JDZWexUQOuOBOhrIU4s1Gd+Y2hXrejQwJnGOlpLiYBFyzz/vrCfXSxpyBXCRw0rEVIsJciGsWlUAatg22pGoId1oR6L2LKMdSVVTW61lgzavwHN4LglsRPXL2sZjdC7QrIdIb47mrBIA6RqNnRP4swzLzAvi4zstVVdfecUpyAXwlNQ/PGSkJ+ZFjJsTBbhkqqs+thVfZY02fBEJGMmYv0rVVmMVkkfDgOvizFi5czjnqzJLNjOWIDdqlBOQO4d/S73CgOuLLAeqqK2h2bt3EDU15tvkki0Ifs5ZBRzpfIhcT468tylC0XoF3Nzp0GJPSUPOmSEkAQyWeoYBNxDDBXcytIab8ZmGkDQ0cDW0xWT884lA4AxynH8Lt8e12GnSkBM9GJgg0/8K4DLx7xQAjtLAg4FbjMVvnzKR6VvIHcERvxVX0vlJGnL0xqKiAK69tu2ULMMLsnLMkMaHOxn6YkKKAEfpz85W037IRdLW5fIHj+GYLyH3Q/zQ5co7mzxLkKuulvUhFlZgFv3ZAP59ZWklWl4p3q/YaV20Xh4H/yrgx31Xl2KpfwssiZxZgpyqaoI2ki4MrzISD27GNXGQ49WBk7Aojz1SilJfeXN34k7QTmQcWhSwBDkaOS960czonp6YKnLku/r1CyIQ4EUzW8zFn59ewAu+AR2PjWtro5YgR9Ht3RtAx47e3lA6Em7G99xcmZc/b2szvjtzCqeQgQzPg+5RPOq7srEjQ5YhRxvZ+GFTaQNsxrFbN97Ixg4D80ocYzDG85A7hENekdvRdFqGHKWWPB4DDn45Dh7MWxI6aokpflkIITyMhz0LOtpHlkN0BWyB3OnTKh59NOgb0N10UzNKSrhXNbrJ+PdsLWpBa7A5P3TX2ht/gV/4t1BsyJktkKOBwStX+seb+9e/VMgydzjYYF+ei6IABZ5qn7sbd+MiLnpOZycTbAvkKMH19Qqeecb5pZfsrh7fckuIvTgnLdCF76Ll0Wl/BGv+lfinu6IrzuKsCxV0V5Jsgxxlq6ysCddf78zwDrvhZsT3/vsyz3Bwl42mJDVbsRU342bXgu5+3I8zOJMSbbz2UlshpyhBjBuneLZt7rHHgjh+nCfje82IRaWX5n+StyTeJ0vsDU/jaVFZ9mW8tkKOFCovV/HEE96rtn796yEcPMidDb60cguZOo/z+Bl+5grQXY/rMRETLeQmPR+1HXIkY0mJgm9+U9Sm02Kqw6tW8cDf9PwTMJdrGqJxI25MGexuw23IR765xPJdVykgBILKnlAAAAJPSURBVHL0BhqC8eUvewN0GzfKUFWe73eVZfCXNgpUoQp90MdR0F2H6zAEQyDDWzuitREvhSeEQY7yVFAgux50y5YpDLgUGqAXX/0hPkQv9BIKO6qaDsAAVKDCixK5Ks1CIUc5LSsL4DvfcadHV1AQQCjEHpyrLNJDiclDHmippg7oYBvwuqALXsNroLXuONijgHDIUTLLyhQ8+6x7OiPuuSeEQ4e4Dc4eE+JYLuESFmIh/oA/4Ov4esLA64me+D/8H7ZgC4spQAFHIEfpPnpUxahRCm68MbUrlgwapKKmhts3BNgSRxlWIIAAaPjJdmwHLX00HdPxFt7CWIxFNrKxARuwB3tQjWrWzAEFHIMc5UXTgigpacJzzznv1d17bwg7dgRw4QJP13LArvgVrIBrFHAUckauaferTZtk/Pzn4if13313CDNmyDh6lKunhv58ZAXSSYGUQI4Epkn9586p2L1bxpAhKrp0sa8am5HRrA9InjVLQUWFwtO00smiOa+sQIQCKYOckQ6CnaZp+ri6uXMVvPyyivvuC+IznzE/6Jd2DOvaNYSnnlIxaZKi7yJ28iTvsmVozEdWIJ0VSDnkWotPe0ZcBp6MHTvotwmLF8v6fNihQy8DsF8/Da++qurnsrMV7NwZwNGjTThxggb0qqBNrzmwAqwAK2Ao4CrIGYkyjuTlEbQIfMav8Z2OBEW6hwMrwAqwArEUcDXkYiWaz7MCrAArYFYBhpxZpfg+VoAV8KQCDDlPFhsnmhVgBcwqwJAzqxTfxwqwAp5U4P8BtVjhw9BOzqsAAAAASUVORK5CYII=\" class=\"img-responsive\">\n<strong>Output: </strong>0\n<strong>Explanation: </strong>The given graph cannot be colored \nin two colors such that color of adjacent \nvertices differs. \n</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>isBipartite()&nbsp;</strong>which takes V denoting no. of vertices and adj denoting adjacency list of the graph and returns a boolean value true if the graph is bipartite otherwise returns false.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(V + E)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(V)<br>\n<br>\n<strong>Constraints:</strong><br>\n1 ≤ V, E ≤ 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Bipartite Graph - GFG/bipartite-graph.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String[] S = br.readLine().trim().split(\" \");\n            int V = Integer.parseInt(S[0]);\n            int E = Integer.parseInt(S[1]);\n            ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n            for(int i = 0; i < V; i++){\n                adj.add(new ArrayList<Integer>());\n            }\n            for(int i = 0; i < E; i++){\n                String[] s = br.readLine().trim().split(\" \");\n                int u = Integer.parseInt(s[0]);\n                int v = Integer.parseInt(s[1]);\n                adj.get(u).add(v);\n                adj.get(v).add(u);\n            }\n            Solution obj = new Solution();\n            boolean ans = obj.isBipartite(V, adj);\n            if(ans)\n                System.out.println(\"1\");\n            else System.out.println(\"0\");\n       }\n    }\n}// } Driver Code Ends\n\n\nclass Solution\n{\n    public boolean isBipartite(int V, ArrayList<ArrayList<Integer>>adj)\n    {\n        boolean[] vis=new boolean[V+1];\n        boolean[] color=new boolean[V+1];\n        Queue<Integer> q=new LinkedList<>();\n        for(int i=0;i<adj.size();i++){\n            if(vis[i])continue;\n            q.add(i);\n            vis[i]=true;\n            color[i]=true;\n            while(!q.isEmpty()){\n                int node=q.remove();\n                for(int neb:adj.get(node)){\n                    if(!vis[neb]){\n                        q.add(neb);\n                        vis[neb]=true;\n                        color[neb]=!color[node];\n                    }else if(color[node]==color[neb]){\n                        return false;\n                    }\n                }\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "Bit Difference - GFG/Bit Difference.cpp",
    "content": "// { Driver Code Starts\r\n// Initial Template for C++\r\n\r\n#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\n // } Driver Code Ends\r\n// User function Template for C++\r\n\r\nclass Solution{\r\npublic:\r\n int countBits(int N, long long int A[])\r\n   {\r\n       int m=log2(*max_element(A,A+N));\r\n       int mod=1000000007;\r\n       int r=0;\r\n       for(int i=0;i<=m;i++)\r\n       {\r\n         long long c=0;\r\n           for(int j=0;j<N;j++)\r\n           {\r\n               if((A[j]&(1<<i))!=0)\r\n               c++;\r\n           }\r\n           r=(r+2*c*(N-c))%mod;\r\n       }\r\n       return r;\r\n   }\r\n};\r\n\r\n// { Driver Code Starts.\r\n\r\nint main(){\r\n    int t;\r\n    cin>>t;\r\n    while(t--){\r\n        int N;\r\n        cin>>N;\r\n        long long int A[N];\r\n        for(int i = 0;i < N; i++)\r\n            cin>>A[i];\r\n        \r\n        Solution ob;\r\n        cout<<ob.countBits(N, A)<<\"\\n\";\r\n    }\r\n    return 0;\r\n}  // } Driver Code Ends\r\n"
  },
  {
    "path": "Bitwise AND of the Array.java",
    "content": "class Solution {\n    int count(int N, int A[], int X){\n        int p=0;\n        int ans=N;\n        for(int i=31;i>=0;i--){\n            int bit=(X>>i)&1;\n            if(bit==1){\n                p=p|(1<<i);\n            }else{\n                int temp=p|(1<<i);\n                int cnt=0;\n                for(int ele:A){\n                    if((ele&temp)==temp){\n                        cnt++;\n                    }\n                }\n                ans=Math.min(ans,N-cnt);\n            }\n        }\n        return ans;\n    }\n} \n"
  },
  {
    "path": "Black Shapes.java",
    "content": "public class Solution {\n    int ans;\n    public int black(String[] A) {\n        ans=0;\n        char[][]arr=new char[A.length][A[0].length()];\n        for(int i=0;i<A.length;i++){\n            arr[i]=A[i].toCharArray();\n        }\n        for(int i=0;i<A.length;i++){\n            for(int j=0;j<A[i].length();j++){\n                if(arr[i][j]=='X'){\n                    dfs(arr,i,j);\n                    ans++;\n                }\n            }\n        }\n        return ans;\n    }\n    void dfs(char[][]arr,int i,int j){\n        if(i<0 || j<0 || i==arr.length || j==arr[i].length || arr[i][j]=='O')return;\n        arr[i][j]='O';\n        dfs(arr,i,j+1);\n        dfs(arr,i,j-1);\n        dfs(arr,i+1,j);\n        dfs(arr,i-1,j);\n    }\n}\n"
  },
  {
    "path": "Book_Allcoation_Problem.cpp",
    "content": "//Book Allocation Problem\n/*\nGiven an array �pages� of integer numbers, where �pages[i]'\nrepresents the number of pages in the �i-th� book.\nThere are �m� number of students, and the task is to allocate all the books to their students. \nAllocate books in a way such that:\n\n1. Each student gets at least one book.\n2. Each book should be allocated to a student.\n3. Book allocation should be in a contiguous manner.\n\nYou have to allocate the books to �m� students such that the maximum number \nof pages assigned to a student is minimum.\n\nExample: \nNumber of books = 4 and Number of students = 2\npages[] = { 10,20,30,40}\n\nAll possible way to allocate the �4� books in �2� number of students is -\n10 | 20, 30, 40 - sum of all the pages of books which allocated to \nstudent-1 is �10�, and student-2 is �20+ 30+ 40 = 90� so maximum is �max(10, 90)= 90�.\n\n10, 20 | 30, 40 - sum of all the pages of books which allocated to \nstudent-1 is �10+ 20 = 30�, and student-2 is �30+ 40 = 70� so maximum is �max(30, 70)= 70�.\n\n10, 20, 30 | 40 - sum of all the pages of books which allocated to \nstudent-1 is �10+ 20 +30 = 60�, and student-2 is �40� so maximum is �max(60, 40)= 60�.\n\nSo possible maximum number of pages which allocated to a single student is { 90, 70, 60 }.\nBut you have to return a minimum of this so return �min(90,70,60) =60�.\n*/\n#include<iostream>\nusing namespace std;\nbool isPossible(int arr[],int m,int n,int mid)\n{\n\tint StudentCount = 1;\n\tint pageSum = 0;\n\t\n\tfor(int i = 0; i<n ; i++)\t\n\t{\n\t\tif(pageSum + arr[i] <= mid)\n\t\t{\n\t\t\tpageSum += arr[i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tStudentCount += 1;\n\t\t\tif(StudentCount > m || arr[i] > mid)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tpageSum = arr[i];\n\t\t}\n\t}\n\treturn true;\n}\nint allocatedBooK(int arr[],int m,int n)\n{\n\tint start = 0;\n\tint sum = 0;\n\tfor(int i =0;i<n;i++)\n\t{\n\t\tsum = sum + arr[i];\n\t}\n\tint end = sum;\n\tint mid = start + (end - start)/2;\n\tint ans = -1;\n\n\twhile(start <= end)\n\t{\n\t\tif(isPossible(arr,m,n,mid))\n\t\t{\n\t\t\tans = mid;\n\t\t\tend = mid - 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstart = mid + 1;\n\t\t}\n\t\tmid = start + (end - start)/2;\n\t}\n\treturn ans;\n}\nint main()\n{\n\tint pages[] = {60,45,26,90};\n\tint student = 2;\n\tint books = sizeof(pages)/sizeof(int);\n\tcout<<\"Allocated Total Pages Book is : \"<<allocatedBooK(pages,student,books);\n\treturn 0;\n}\n"
  },
  {
    "path": "Brackets in Matrix Chain Multiplication - GFG/README.md",
    "content": "# Brackets in Matrix Chain Multiplication\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array&nbsp;<strong>p[]</strong>&nbsp;of length <strong>n </strong>used to denote the dimensions of a series of matrices such that&nbsp;dimension of <strong>i'th</strong> matrix is <strong>p[i] * p[i+1]</strong>. There are a total of&nbsp;<strong>n-1</strong> matrices.&nbsp;Find the most efficient way to multiply these matrices together.&nbsp;<br>\nThe problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications such that you need to perform minimum number of multiplications. There are&nbsp;many options to multiply a chain of matrices because matrix multiplication is associative i.e.&nbsp;no matter how one&nbsp;parenthesize the product, the result will be the same.</span></p>\n\n<p><br>\n<strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> \nn = 5\np[] = {1, 2, 3, 4, 5}\n<strong>Output:</strong> (((AB)C)D)\n<strong>Explaination:</strong> The total number of \nmultiplications are (1*2*3) + (1*3*4) \n+ (1*4*5) = 6 + 12 + 20 = 38.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> \nn = 3\np = {3, 3, 3}\n<strong>Output:</strong> (AB)\n<strong>Explaination:</strong> The total number of \nmultiplications are (3*3*3) = 27.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>matrixChainOrder()</strong> which takes n and p[] as input parameters and returns the string with the proper order of parenthesis for n-1 matrices. Use uppercase alphabets to denote each matrix.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(n<sup>3</sup>)<br>\n<strong>Expected Auxiliary Space:</strong> O(n<sup>2</sup>)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n2 ≤ n ≤ 26&nbsp;<br>\n1 ≤ p[i] ≤ 500&nbsp;</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Brackets in Matrix Chain Multiplication - GFG/brackets-in-matrix-chain-multiplication.cpp",
    "content": "// { Driver Code Starts\n// Initial Template for C++\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\n// User function Template for C++\n\nclass Solution {\n    \n    // Cache\n    map<string, pair<int, string>> dp;\n    \n  public:\n    string matrixChainOrder(int A[], int n) {\n        return matrixChainOrderUtil(A, 0, n - 1).second;\n    }\n    \n    pair<int, string> matrixChainOrderUtil(int p[], int l, int r) {\n    \t// Base case\n    \t/*\n\t\tFor [1, 2, 3], base case will hit when l = 0, r = 1 or l = 1, r = 2\n\t\tor we can say we are at matrix A or B\n    \tl = 0 -> A\n    \tl = 1 -> B\n    \tso on..\n    \t*/\n        if(l + 1 == r) return {0, \"\" + string(1, l + 'A')};\n        string key = to_string(l) + \";\" + to_string(r);\n        if(dp.count(key)) return dp[key];\n        \n        int currMin = INT_MAX;\n        string minString;\n        for(int k = l + 1; k < r; k++) {\n            auto p1 = matrixChainOrderUtil(p, l, k), p2 = matrixChainOrderUtil(p, k, r);\n            if(p1.first + p2.first + p[l] * p[k] * p[r] < currMin) {\n                currMin = p1.first + p2.first + p[l] * p[k] * p[r];\n                // Multiply te 2 strings\n                minString = p1.second + p2.second;\n            }\n        }\n        // Enclose them in brackets and return\n        return dp[key] = {currMin, \"(\" + minString + \")\"};\n    }\n};\n// { Driver Code Starts.\n\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int p[n];\n        for(int i = 0;i < n;i++)\n            cin>>p[i];\n        \n        Solution ob;\n        cout<<ob.matrixChainOrder(p, n)<<\"\\n\";\n    }\n    return 0;\n}  // } Driver Code Ends"
  },
  {
    "path": "Brackets in Matrix Chain Multiplication - GFG/brackets-in-matrix-chain-multiplication.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            int n = Integer.parseInt(in.readLine());\n            String a[] = in.readLine().trim().split(\"\\\\s+\");\n            int p[] = new int[n];\n            for(int i = 0;i < n;i++)\n                p[i] = Integer.parseInt(a[i]);\n            \n            Solution ob = new Solution();\n            System.out.println(ob.matrixChainOrder(p, n));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static char matrix;\n    static String ans;\n    static String matrixChainOrder(int p[], int n){\n        // code here\n        matrix='A';\n        ans=\"\";\n        int[][]dp=new int[n][n];\n        int[][]path=new int[n][n];\n        for(int pair=2;pair<n;pair++){\n            for(int i=1;i<=n-pair;i++){\n                int j=i+pair-1;\n                dp[i][j]=Integer.MAX_VALUE;\n                for(int k=i;k<j;k++){\n                    int temp= dp[i][k]+dp[k+1][j]+ p[i-1]*p[k]*p[j];\n                    if(temp<dp[i][j]){\n                        dp[i][j]=temp;\n                        path[i][j]=k;\n                    }\n                }\n            }\n        }\n        dfs(1,n-1,path);\n        return ans;\n    }\n    static void dfs(int i,int j,int[][]path){\n        if(i==j){\n            ans+=matrix;\n            matrix++;\n            return;\n        }\n        ans+='(';\n        dfs(i,path[i][j],path);\n        dfs(path[i][j]+1,j,path);\n        ans+=')';\n    }\n}"
  },
  {
    "path": "Brain Game - GFG/README.md",
    "content": "# Brain Game\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">2 players A and&nbsp;B take&nbsp;turns alternatively to play a game in which they have N numbers on a paper. In one turn, a player can replace one of the numbers by any of its factor (except for 1 &amp; the number itself).&nbsp;The player who is unable to make a move looses the game. Find the winner of the game if A starts the game and both play optimally.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>nums = [5, 7, 3]\n<strong>Output: </strong>B\n<strong>Explanation: </strong>Since all the numbers are prime,\n</span><span style=\"font-size:18px\">so A will not be able to make the first move. </span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>nums = [2, 4, 7, 11]\n<strong>Outptut: </strong>A\n<strong>Explanation: </strong>In the first move A will replace 4\nby 2, so the numbers will become [2, 2, 7, 11]\nnow B will not be able to make a move since all \nthe remaining numbers can only be divided by 1 \nor the number itself.  </span>\n\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>brainGame()&nbsp;</strong>which takes the list of numbers as input parameter and returns true if&nbsp;A wins and false if B wins.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(N<sup>2</sup>)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(N)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints</strong><br>\n1 &lt;= N &lt;= 1000<br>\n1 &lt;= nums[i] &lt;= 1000</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Brain Game - GFG/brain-game.cpp",
    "content": "// { Driver Code Starts\n#include<bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\nclass Solution{\n\tpublic:\n    bool brainGame(vector<int>nums) {\n        // Code here.\n        vector<int>a(1005);\n        for(int i=2;i<=1000;i++){\n            for(int j=2*i;j<=1000;j+=i){\n                a[j]=max(a[j],a[i]+1);\n            }\n        }\n        int x=0;\n        for(int i=0;i<nums.size();i++){\n            x=x^a[nums[i]];\n        }\n        if(x==0){\n            return false;\n        }\n        return true;\n    }\n};\n\n// { Driver Code Starts.\nint main(){\n\tint tc;\n\tcin >> tc;\n\twhile(tc--){\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int>nums(n);\n\t\tfor(int i = 0; i < n; i++)cin >> nums[i];\n\t\tSolution ob;\n\t\tbool ans = ob.brainGame(nums);\n\t\tif(ans)\n\t\t\tcout << \"A\\n\";\n\t\telse cout << \"B\\n\";\n\t}  \n\treturn 0;\n}  // } Driver Code Ends"
  },
  {
    "path": "Brain Game - GFG/brain-game.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            int n = Integer.parseInt(br.readLine().trim());\n            String s = br.readLine().trim();\n            String[] S = s.split(\" \");\n            int[] nums = new int[n];\n            for(int i = 0; i < n; i++){\n                nums[i] = Integer.parseInt(S[i]);\n            }\n            Solution ob = new Solution();\n            boolean ans = ob.brainGame(nums);\n            if(ans)\n                System.out.println(\"A\");\n            else \n                System.out.println(\"B\");     \n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n//2\n\n\n//2 4  4  0\n//00010\n\n\nclass Solution\n{\n    public boolean brainGame(int[] nums)\n    {\n        int ans=0;\n        for(int num:nums){\n            if(!isPrime(num))ans=ans^(primeFactors(num)-1);\n        }\n        return ans!=0;\n    }\n    \n    int primeFactors(int n)\n    {\n        int ans = 0;\n        int num =n;\n        for(int i=2; i<=num/2; i++)\n        {\n            while(n%i == 0)\n            {\n                ans++;\n                n/= i;\n            }\n        }\n        return ans;\n    }\n    \n    boolean isPrime(int n){\n        for(int i=2;i<=Math.sqrt(n);i++){\n            if(n%i==0)\n              return false;\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "Breadth first search.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nvoid bfs(int node,vector<int>* adj,vector<int>* visited) \n{\n        queue<int> q;\n        q.push(node);\n        visited[node]=1;\n        \n        while(!q.empty())\n        {\n            int node=q.front();\n            q.pop();\n            cout<<node<<\" \";\n            \n            for(auto it:adj[node])\n            {\n                if(!visited[it])\n                {\n                    visited[it]=1;\n                    q.push(it);\n                }\n            }\n        }\n        \n}\n\nint main()\n{\n    //taking input\n    int n,e;\n    cin>>n>>e; // n is number of vertix\n               // e is number of edges\n    \n    vector<int> adj[n];\n    while(e--)\n    {\n        int u,v;\n        cin>>u>>v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    vector<int> visited(n,0);\n    for(int i=0;i<n;i++)\n    {\n        if(!visited[i])\n        bfs(i,adj,visited);\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "Broken blocks - GFG/README.md",
    "content": "# Broken blocks\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">In the game of Broken Blocks, the player is allowed to move on <strong>m x n</strong>&nbsp;blocks i.e. <strong>m&nbsp;</strong>levels and <strong>n&nbsp;</strong>stone blocks on each level such that one level is vertically above the previous level (as in a staircase), with some of its stone blocks replaced by wooden blocks.<br>\nThe player at the start of the game is present on the ground level (which should&nbsp;be considered as level 0 or it can be considered as level -1). The player can start from <strong>any</strong> of the blocks present on the <strong>level 0</strong> and start moving further to next levels. The player can only move to the stone-block just above to the present stone-block or diagonally to the left or to the right. The player cant move on the same level.<br>\nIf the player steps on any of the wooden block (denoted by <strong>-1</strong>), he will fall off the board and die as the wood-block will not able to hold players weight. Each of the stone-block has some gold coins present on it (wooden blocks doesnt have any coins on them). If at any point the player cant move to further level due to any reason, the game ends and his present total coin score will be considered.<br>\nThe players aim is to collect as many gold coins as he can without falling off the board.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>matrix = {{2,5,6},{-1,3,2},{4,-1,5}}\n<strong>Output: </strong>14\n<strong>Explanation: </strong>Assume 0-based indexing.The matrix \nis:\n2 5 6 (level 0)\n-1 3 2 (level 1)\n4 -1 5 (lever 2)\nThe player can collect maximum number of coins \nby moving through:matrix[0][2] + matrix[1][1] \n+ matrix[2][2] = 6 + 3 + 5 = 14 coins.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>matrix = {{-1,2,3,4},{5,-1,-1,2},\n{4,3,-1,-1}}\n<strong>Output: </strong>11\n<strong>Explanation: </strong></span><span style=\"font-size:18px\">The matrix is:\n-1 2 3 4(level 0)\n5 -1 -1 2(level 1)\n4 3 -1 1(level 2)\nThe player can collect maximum number of coins \nby moving through:a[0][1] + a[1][0] + a[2][0] \n= 2 + 5 + 4 = 11 coins.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>MaxGold()&nbsp;</strong>which takes matrix as input parameter and returns the maximum number of gold coins.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(n*m)</span><br>\n<span style=\"font-size:18px\"><strong>Expected Space Complexity:</strong>&nbsp;O(1)</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Broken blocks - GFG/broken-blocks.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String[] S = br.readLine().trim().split(\" \");\n            int m = Integer.parseInt(S[0]);\n            int n = Integer.parseInt(S[1]);\n            int[][] matrix = new int[m][n];\n            for(int i = 0; i < m; i++){\n                String[] s = br.readLine().trim().split(\" \");\n                for(int j = 0; j < n; j++)\n                    matrix[i][j] = Integer.parseInt(s[j]);\n            }\n            Solution obj = new Solution();\n            int ans = obj.MaxGold(matrix);\n            System.out.println(ans);\n\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n    int[][]dp;\n    public int MaxGold(int[][] a){\n        int ans=0;\n        dp=new int[a.length][a[0].length];\n        for(int i=0;i<a[0].length;i++){\n            ans=Math.max(ans,dfs(a,0,i));\n        }\n        return ans;\n    }\n    public int dfs(int[][]a,int i,int j){\n        if(!valid(a,i,j))return 0;\n        if(dp[i][j]!=0)return dp[i][j];\n        int ans= a[i][j]+Math.max(dfs(a,i+1,j),Math.max(dfs(a,i+1,j-1),dfs(a,i+1,j+1)));\n        dp[i][j]=ans;\n        return ans;\n    }\n    public boolean valid(int[][]a,int i,int j){\n        int n=a.length;\n        int m=a[0].length;\n        if(i<0 || j<0 || i==n || j==m || a[i][j]==-1)return false;\n        return true;\n    }\n}"
  },
  {
    "path": "Burning Tree.cpp",
    "content": "class Solution {\n  public:\n    \n    int minTime(Node* root, int target) \n    {\n        // Your code goes here\n        Node* start;\n        unordered_map<Node*, Node*> parent;\n        \n        queue<Node*> Q;\n        Q.push(root);\n        \n        while(!Q.empty())\n        {\n            int sz = Q.size();\n            \n            while(sz--)\n            {\n                Node* cur = Q.front();\n                Q.pop();\n                \n                if(cur->data == target)\n                start = cur;\n                \n                if(cur->left)\n                {\n                    Q.push(cur->left);\n                    parent[cur->left] = cur;\n                }\n                \n                if(cur->right)\n                {\n                    Q.push(cur->right);\n                    parent[cur->right] = cur;\n                }\n            }\n        }\n        \n        Q.push(start);\n        \n        set<int> burned;\n        \n        int t = -1;\n        \n        while(!Q.empty())\n        {\n            int sz = Q.size();\n            \n            while(sz--)\n            {\n                Node* cur = Q.front();\n                Q.pop();\n                \n                burned.insert(cur->data);\n                \n                if(cur != root and burned.find(parent[cur]->data) == burned.end())\n                    Q.push(parent[cur]);\n                \n                if(cur->left and burned.find(cur->left->data) == burned.end())\n                    Q.push(cur->left);\n                \n                if(cur->right and burned.find(cur->right->data) == burned.end())\n                    Q.push(cur->right);\n            }\n            \n            t++;\n        }\n        \n        return t;\n    }\n};\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at sagar.0dev@gmail.com.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior,  harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# 🔥Best repository for you to start your open source journey!!\n## 🔼 Prerequisite required to Contribute\n\n### Contributing Code\n- Git/GitHub\n- Programming Language\n- Data structures and algorithms\n- Problem solving\n \n### Contributing in docs/repo maintainance/others\n- Git/GitHub\n- Markdown/Html\n- GitHub Actions/Yaml\n- CI/CD\n\n---\n\n## ✅ How to Contribute\n\n### Pull Requests\n\n> **Must Use PR templates according to your requirement.**\n### 💻Code PRs\n- Currently, we only cover problems of [LeetCode](https://leetcode.com/problemset/all/), [GeeksForGeeks](https://practice.geeksforgeeks.org/explore?page=1&sortBy=submissions) and [InterviewBit](https://practice.geeksforgeeks.org/explore?page=1&sortBy=submissions). Problems of other good platforms can be accepted(ONLY AFTER [DISCUSSIONS](https://github.com/Sagar0-0/DsA/discussions)).\n- We maintain the structure of repositroy by creating specific directories corresponding to coding platoforms i.e. [Leetcode](https://github.com/Sagar0-0/DsA/tree/main/Leetcode), [GFG](https://github.com/Sagar0-0/DsA/tree/main/GFG), [Interviewbit](https://github.com/Sagar0-0/DsA/tree/main/Interviewbit).\n- ⚠️Please contribute your code in the right directory!! Example - LeetCode questions should be in the [LeetCode directory](https://github.com/Sagar0-0/DsA/tree/main/Leetcode) and same for others.\n- [LeetHub](https://github.com/QasimWani/LeetHub) users, only you can upload your code in the [main directory](https://github.com/Sagar0-0/DsA) from now.(when using extension)\n- **MUST CHECK** if that question already exists or not!! Follow following steps:  \nExample- A solution named \"Nine divisors.java\" is to be added, then first check if any directory(or new PR) with the name \"Nine divisors\" exists or not and if yes, then move to \"Nine divisors\" directory and then add your code there(if java file exists then append in that file) or if that folder doesn't exists then create a folder/directory with the name \"Nine divisors\" and then add your code. [How to create a folder/directory?](https://stackoverflow.com/a/34259067/16775065)\n- File naming convention: \n  - Every word in the file should be separated by a space. eg. \"Rat in the maze\" , \"19. Remove Nth Node From End of List\", etc.\n  - ❌No other naming format will be accepted from now.(to maintian the structure)\n  - Do not use \"/\" in the name of any file!(this will leads to creating a directory) \n- We strictly avoid removing the code of other contributors.\n- Check [Beginner's Guide](https://youtu.be/7r05126pOk8) for any issues faced.\n\n#### Migration PRs<!--Not applicable for hacktoberfest-->\n> Help us structure this repository.\n- Select a code file from the main/home directory **that was not contributed by LeetHub extension**.\n- Add it to the directory of their corresponding coding platform(with a folder name of that problem). Eg. \"Nine divisors.java\" file should be in the directory \"GFG/Nine divisors\".\n- Delete that file from the home directory.\n\n### ❌Note: Creating multiple wrong PRs can lead to a permanent ban.❌\n"
  },
  {
    "path": "Can Make Triangle.java",
    "content": "class Solution \n{ \n    int[] canMakeTriangle(int A[], int N) \n    { \n        // code here\n        int[]ans=new int[N-2];\n        for(int i=0;i<ans.length;i++){\n            if(isTriangle(A[i],A[i+1],A[i+2])){\n                ans[i]=1;\n            }\n        }\n        return ans;\n    }\n    boolean isTriangle(int a,int b,int c){\n        if(a+b>c && a+c>b && b+c>a){\n            return true;\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "Can Place Flowers.java",
    "content": "class Solution {\n    public boolean canPlaceFlowers(int[] flowerbed, int n) {\n        if(n==0) return true;\n        if(flowerbed.length==1 && flowerbed[0]==0)\n            return true;\n        if(flowerbed[0]==0 && flowerbed[1]==0 && n>0){\n            n--;\n            flowerbed[0]=1;\n        }\n        if(flowerbed[flowerbed.length-1]==0 && flowerbed[flowerbed.length-2]==0 && n>0){     \n            n--;\n            flowerbed[flowerbed.length-1]=1;\n        }\n        \n        for(int i=1;i<flowerbed.length-1 && n>0;i++){\n            //condition when we need to ignore \n            if(flowerbed[i-1] == 1 || flowerbed[i+1]==1 || flowerbed[i]==1)\n                continue;\n  \n            flowerbed[i]=1;\n            n--;\n            if(n==0) return true;\n        }\n        \n        return n==0;\n    }\n}\n"
  },
  {
    "path": "Capacity To Ship Packages Within D Days.java",
    "content": "class Solution {\n    static int leastWeightCapacity(int[] a, int n, int d) {\n        // code here\n        int min=largest(a);\n        int max=sum(a);\n        int res=0;\n        while(min<=max){\n            int mid=(min+max)/2;\n            if(isValid(a,d,mid)){\n                res=mid;\n                max=mid-1;\n            }else{\n                min=mid+1;\n            }\n        }\n        return res;\n    }\n    static boolean isValid(int[]a,int k,int res){\n        int day=1,sum=0;\n        for(int i=0;i<a.length;i++){\n            if(sum+a[i]>res){\n                day++;\n                sum=a[i];\n            }else{\n                sum+=a[i];\n            }\n        }\n        return day<=k;\n    }\n    static int sum(int[]a){\n        int sum=0;\n        for(int i:a){\n            sum+=i;\n        }\n        return sum;\n    }\n    static int largest(int[]arr)\n     {\n         int i;\n          \n         // Initialize maximum element\n         int max = arr[0];\n       \n         // Traverse array elements from second and\n         // compare every element with current max \n         for (i = 1; i < arr.length; i++)\n             if (arr[i] > max)\n                 max = arr[i];\n       \n         return max;\n     }\n};\n"
  },
  {
    "path": "Capitalize the Title",
    "content": "class Solution {\n    public String capitalizeTitle(String s) {\n        List<String> list=new ArrayList<>();\n        String word=\"\";\n        for(int i=0;i<s.length();i++){\n            if(s.charAt(i)==' '){\n                list.add(word);\n                word=\"\";\n            }else{\n                word+=s.charAt(i)+\"\";\n            }\n        }\n        list.add(word);\n        s=\"\";\n        for(int i=0;i<list.size();i++){\n            String str=list.get(i);\n            str=str.toLowerCase();\n            if(str.length()>2){\n                //uppercase first char\n                str=str.substring(0, 1).toUpperCase() + str.substring(1);\n            }\n            if(i==0){\n                s+=str;\n            }else{\n                s+=\" \"+str;\n            }\n        }\n        return s;\n    }\n}\n"
  },
  {
    "path": "Case-specific Sorting of Strings.java",
    "content": "class Solution\n\n{\n    //Function to perform case-specific sorting of strings.\n    public static String caseSort(String str)\n    {\n        // Your code here\n        char[] arr=str.toCharArray();\n        Arrays.sort(arr);\n        \n        int upper=-1;\n        int lower=-1;\n        \n        if(arr[0]<97){\n            upper=0;\n        }\n        for(int i=0;i<arr.length;i++){\n            char ch=arr[i];\n            if(ch>=97){\n                lower=i;\n                break;\n            }\n        }\n        \n        if(upper==-1 || lower==-1)return new String(arr);\n        \n        StringBuilder sb=new StringBuilder();\n        \n        for(int i=0;i<str.length();i++){\n            char ch=str.charAt(i);\n            if(ch>=97){\n                sb.append(arr[lower]);\n                lower++;\n            }else{\n                sb.append(arr[upper]);\n                upper++;\n            }\n        }\n        return sb.toString();\n    }\n}\n"
  },
  {
    "path": "Case-specific Sorting of Strings.py",
    "content": "class Solution:\n\n    #Function to perform case-specific sorting of strings.\n    def caseSort(self,s,n):\n        #code here\n        up,low=[],[]\n        res=[]\n        for i in s:\n            if i.isupper():\n                up.append(i)\n            elif i.islower():\n                low.append(i)\n        up.sort()\n        low.sort()\n        x,y=0,0\n        for i in s:\n            if i.isupper():\n                res.append(up[x])\n                x+=1\n            elif i.islower():\n                res.append(low[y])\n                y+=1\n        ans=''.join(res)\n        return ans\n"
  },
  {
    "path": "Case-specific Sorting string.cpp",
    "content": "include<bits/stdc++.h>\nusing namespace std;\n\n\n// } Driver Code Ends\nclass Solution\n{\n    public:\n    //Function to perform case-specific sorting of strings.\n    string caseSort(string str, int n)\n    {\n       \n        vector<int>small;\n        vector<int>cap;\n        \n        for(int i=0;i<n;i++){\n            if(str[i]>=65&&str[i]<92){\n                cap.push_back(i);\n            }\n            else{\n                small.push_back(i);\n            }\n        }\n        \n        sort(str.begin(),str.end());\n        \n        int s=0,c=0;\n     \n        char ans[n+1];\n        for(int i=0;i<n;i++){\n            if(str[i]>=65&&str[i]<92){\n             ans[cap[c]]=str[i];  \n             c++;\n            }\n            else{\n                ans[small[s]]=str[i];\n                s++;\n            }\n            \n        }\n        ans[n]='\\0';\n        \n        return ans;\n        \n    }\n};\n\n//{ Driver Code Starts.\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tstring str;\n\t\tcin>>str;\n\t\tSolution obj;\n\t\tcout<<obj.caseSort (str, n)<<endl;\n\t}\n}\n// } Driver Code Ends\n"
  },
  {
    "path": "Ceil in BST.java",
    "content": "class Tree {\n    int ans;\n    // Function to return the ceil of given number in BST.\n    int findCeil(Node root, int key) {\n        if (root == null) return -1;\n        // Code here\n        ans=Integer.MAX_VALUE;\n        dfs(root,key);\n        return ans;\n    }\n    void dfs(Node root,int key){\n        if(root==null)return;\n        if(root.data==key){\n            ans=key;\n        }else if(root.data>key){\n            if(root.data<ans){\n                ans=root.data;\n            }\n            dfs(root.left,key);\n        }else{\n            dfs(root.right,key);\n        }\n    }\n}\n"
  },
  {
    "path": "Champagne Tower.java",
    "content": "class Solution {\n    public double champagneTower(int poured, int query_row, int query_glass) {\n        if (poured == 0) return 0;\n        int rows = 100;\n        double[][] champagneTower = new double[rows + 1][rows + 1];\n\n        champagneTower[0][0] = poured;\n\n        for (int row = 0; row <= query_row; row++) {\n            for (int column = 0; column <= row; column++) {\n                double splittingWine = (champagneTower[row][column] - 1.0) / 2.0;\n                if (splittingWine > 0) {\n                    champagneTower[row + 1][column] += splittingWine;\n                    champagneTower[row + 1][column + 1] += splittingWine;\n                }\n            }\n        }\n        return Math.min(1, champagneTower[query_row][query_glass]);\n    }\n} \n\n//======================================================================================================\n\nclass Solution {\n    public double champagneTower(int poured, int queryRow, int queryGlass) {\n\t    if (poured == 0)\n\t\t    return 0;\n\t    var prevRow = new ArrayList<>(List.of((double) poured));\n\n\t    while (queryRow-- > 0) {\n\t\t    var currentRow = new ArrayList<Double>();\n\t\t    var champagneInEnds = Math.max(0, (prevRow.get(0) - 1) / 2);  // min champagne can be 0\n\t\t    currentRow.add(champagneInEnds); // first glass\n\n\t\t    for (var i = 1; i < prevRow.size(); i++)\n\t\t\t    currentRow.add(Math.max(0, (prevRow.get(i - 1) - 1) / 2) + // flow from top-left glass\n\t\t\t\t\t\t   Math.max(0, (prevRow.get(i) - 1) / 2));     // flow from top-right glass\n\n\t\t    currentRow.add(champagneInEnds); // last glass\n\t\t    prevRow = currentRow;\n\t    }\n\t    return Math.min(1, prevRow.get(queryGlass)); // max champagne can be 1\n    }\n} \n"
  },
  {
    "path": "Change Bits - GFG/README.md",
    "content": "# Change Bits\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a number <strong>N,</strong>&nbsp;complete the following&nbsp;tasks,<br>\nTask 1. Generate a new number from&nbsp;N&nbsp;by changing&nbsp;the&nbsp;zeroes in the binary&nbsp;representation of N to 1.<br>\nTask &nbsp;2. Find the difference between N and the newly generated number.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong> </span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> <strong>N = </strong>8 \n<strong>Output: </strong>7 15\n<strong>Explanation:</strong>\nThere are 3 zeroes in binary representation\nof 8. Changing them to 1 will give 15.\nDifference between these two is 7.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong> </span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> <strong>N = </strong>6 \n<strong>Output: </strong>1 7\n<strong>Explanation:</strong>\nThere is 1 zero in binary representation\nof 6. Changing it to 1 will give 7.\nDifference between these two is 1.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>changeBits()</strong> which takes an integer N as input parameter&nbsp;and returns a list of two integers containing the difference and the generated number respectively.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(log(N))<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">0 &lt;= N &lt;= 10<sup>8</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Change Bits - GFG/change-bits.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int N = Integer.parseInt(read.readLine());\n\n            Solution ob = new Solution();\n            int[] ans = ob.changeBits(N);\n            System.out.println(ans[0]+ \" \"+ ans[1]);\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    static int[] changeBits(int N) {\n        int newNum=0;\n        int n=N;\n        while(n>0){\n            newNum|=1;\n            newNum=newNum<<=1;\n            n=n>>1;\n        }\n        newNum=newNum>>1;\n        int diff=Math.abs(N-newNum);\n        int ans[]=new int[]{diff,newNum};\n        return ans;\n    }\n};"
  },
  {
    "path": "Check Mirror in N-ary tree.java",
    "content": "class Solution {\n     static int checkMirrorTree(int n, int e, int[] A, int[] B) {\n       // code here\n        HashMap<Integer,Stack<Integer>> mp = new HashMap<Integer,Stack<Integer>>();\n        for(int i=0;i<A.length-1;i++){\n            if(mp.containsKey(A[i])){\n                Stack<Integer> ls = mp.get(A[i]);\n                ls.push(A[i+1]);\n                mp.put(A[i],ls);\n            }\n            else{\n                Stack<Integer> ls = new Stack<Integer>();\n                ls.push(A[i+1]);\n                mp.put(A[i],ls);\n            }\n            i++;\n        }\n       \n        for(int i=0;i<B.length-1;i++){\n            if(!mp.containsKey(B[i])){\n                return 0;\n            }\n            else{\n                Stack<Integer> ls = new Stack<Integer>();\n                ls = mp.get(B[i]);\n                if(ls.pop()!=B[i+1]){\n                   return 0;\n                }\n                mp.put(B[i],ls);\n            }\n            i++;\n        }\n        return 1;\n   }\n};\n"
  },
  {
    "path": "Check Palindrome!.java",
    "content": "public class Solution {\n    public int solve(String s) {\n        int[]arr=new int[26];\n        for(char c:s.toCharArray()){\n            arr[c-'a']++;\n        }\n        boolean one=false;\n        for(int i:arr){\n            if(i%2==1){\n                if(one){\n                    return 0;\n                }else{\n                    one=true;\n                }\n            }\n        }\n        return 1;\n    }\n}\n"
  },
  {
    "path": "Check if Every Row and Column Contains All Numbers",
    "content": "class Solution {\n    public boolean checkValid(int[][] matrix) {\n        int n=matrix.length;\n        int[][] check=new int[n][n];\n        for(int row=0;row<n;row++){\n            for(int col=0;col<n;col++){\n                int val=matrix[row][col];\n                check[row][val-1]++;\n            }\n        }\n        for(int col=0;col<n;col++){\n            for(int row=0;row<n;row++){\n                int val=matrix[row][col];\n                check[val-1][col]++;\n            }\n        }\n        for(int row=0;row<n;row++){\n            for(int i=0;i<n;i++){\n                if(check[row][i]!=2){\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "Check if subtree",
    "content": "class Solution {\n    public static boolean isSubtree(Node T, Node S) {\n        // add code here\n        if(T==null)return false;\n        boolean check=false;\n        if(T.data==S.data){\n            check=checkSame(T,S);\n        }\n        return check || isSubtree(T.left,S) || isSubtree(T.right,S);\n    }\n    public static boolean checkSame(Node head,Node root){\n        if(head==null && root!=null){\n            return false;\n        }else if(head!=null && root==null){\n            return false;\n        }else if(head==null && root==null){\n            return true;\n        }\n        if(head.data!=root.data){\n            return false;\n        }\n        return checkSame(head.left,root.left) && checkSame(head.right,root.right);\n    }\n}\n"
  },
  {
    "path": "Cherry Pickup II (LC)",
    "content": "class Solution {\n    public int cherryPickup(int[][] grid) {\n        int dir[] = new int[]{-1, 0, 1};\n\n        int row = grid.length;\n        int col = grid[0].length;\n        int dp[][][] = new int[row][col][col]; \n        \n        for(int i = 0; i < row; i++){\n            for(int j = 0; j < col; j++){\n                for(int k = 0; k < col; k++){\n                    dp[i][j][k] = -1;\n                }\n            }\n        }\n        int col1 = 0; \n        int col2 = col - 1; \n        \n        dp[0][col1][col2] = grid[0][col1] + grid[0][col2]; \n        int max = dp[0][col1][col2]; \n        \n        for(int i = 1; i < row; i++){ \n            for(int c1 = 0; c1 < col; c1++){ \n                for(int c2 = 0; c2 < col; c2++){\n                    int prev = dp[i - 1][c1][c2]; \n                    if(prev >= 0){ \n                        for(int d1: dir){ \n                            col1 = d1 + c1;\n                            for(int d2: dir){ \n                                col2 = d2 + c2;\n                                if(inRange(col1, col) && inRange(col2, col)){\n                                    dp[i][col1][col2] = Math.max(dp[i][col1][col2], prev+(col1 == col2 ? grid[i][col1] : (grid[i][col1] + grid[i][col2]))); \n                                    max = Math.max(max, dp[i][col1][col2]); \n                                }\n                            }\n                        }\n                    }\n                    \n                }\n            }\n        }\n        return max;\n    }\n\n    public boolean inRange(int val, int limit){\n        return 0 <= val && val < limit;\n    }\n}\n"
  },
  {
    "path": "Chips Factory.java",
    "content": "public class Solution {\n    public int[] solve(int[] A) {\n        int n=A.length;\n        int[]ans=new int[n];\n        int i=0;\n        for(int num:A){\n            if(num!=0){\n                ans[i]=num;\n                i++;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Chocolate_Distribution_Problem_gfg.cpp",
    "content": "#include<bits/stdc++.h>\nusing  namespace std;\n\n\nclass Solution{\n    public:\n    long long findMinDiff(vector<long long> a, long long n, long long m){\n        // sliding window approach\n        if(n <m) return -1;\n        long long minDiff = INT_MAX; // INT_MAX = +2147483647\n        sort(a.begin(), a.end());\n        int i =0, j =m-1;\n        while(j <n){\n            long long currDiff = a[j] - a[i];\n            minDiff = min(minDiff, currDiff);\n            i++, j++;\n        }\n        return minDiff;\n    }\n};\n"
  },
  {
    "path": "Choose and Swap - GFG/README.md",
    "content": "# Choose and Swap\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">You are given a string <strong>s</strong> of lower case english alphabets. You can choose any two characters in the string and replace all the occurences of the first character with the second character and replace all the occurences of the second character with the first character. Your aim is to find the lexicographically smallest string that can be obtained by doing this operation at most once.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>:\nA = \"ccad\"\n<strong>Output:</strong>&nbsp;\"aacd\"\n<strong>Explanation</strong>:\nIn ccad, we choose a and c and after \ndoing the replacement operation once we get, \naacd and this is the lexicographically\nsmallest string possible. </span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nA = \"abba\"\n<strong>Output: </strong>\"abba\"\n<strong>Explanation:\n</strong>In abba, we can get baab after doing the \nreplacement operation once for a and b \nbut that is not lexicographically smaller \nthan abba. So, the answer is abba. </span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>chooseandswap()</strong>&nbsp;which takes the string A as input parameters and returns the <strong>lexicographically smallest string</strong> that is possible after doing the operation at most once.<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(|A|) length of the string A<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1&lt;= |A| &lt;=10<sup>5</sup></span></p>\n\n<p>&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Choose and Swap - GFG/choose-and-swap.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        \n        Solution obj = new Solution();\n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String A = read.readLine().trim();\n            \n            String ans = obj.chooseandswap(A);\n            System.out.println(ans);\n        }\n    }\n}\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n\n\nclass Solution{\n    String chooseandswap(String A){\n        int hash[] = new int[26]; \n        Arrays.fill(hash, -1);\n        \n        //get first occurence of every char\n        for(int i=A.length()-1; i>=0; i--)\n           hash[A.charAt(i)-97] = i;\n        \n        \n        for(int i=0; i<A.length(); i++){\n            char ch = A.charAt(i);\n            char st = 'a';\n            while(st < ch){\n                if(hash[st-97]!=-1 && hash[st-97]>i){\n                    String temp1 = A.replaceAll(String.valueOf(ch), \"X\");\n                    String temp2 = temp1.replaceAll(String.valueOf(st), String.valueOf(ch));\n                    String temp3 = temp2.replaceAll(\"X\", String.valueOf(st));\n                    return temp3;\n                }\n                st+=1;\n            }\n        }\n        return A;\n    }\n}"
  },
  {
    "path": "Climbing Stairs.java",
    "content": "public class Solution {\n    public int solve(ArrayList<Integer> A) {\n     \n        int n = A.size();\n        int steps = A.get(0);\n        int dp[] = new int[n];\n        dp[0] = steps;\n        dp[1] = steps + A.get(1);\n        for(int i = 2; i < n; i++){\n            dp[i] = Math.min(dp[i-1], dp[i-2]) + A.get(i);\n        }\n       \n        return dp[n-1];\n    }\n}\n"
  },
  {
    "path": "Clone Graph.java",
    "content": "class Solution {\n    Map<Node, Node> map = new HashMap<>(); \n    public Node cloneGraph(Node node) {\n        if (node == null) return node;\n        if(map.containsKey(node)) return map.get(node); \n        Node clonedGraph = new Node(node.val, new ArrayList<>()); \n        map.put(node, clonedGraph); \n        for(Node oldNeb : node.neighbors) {\n                Node clonedNeb = cloneGraph(oldNeb);  \n                clonedGraph.neighbors.add(clonedNeb);\n        }\n        return map.get(node); \n    }\n}\n\n//================================================================================\n\nclass Solution {\n    public Node cloneGraph(Node node) {\n        if(node==null) return null;\n        \n        Map<Node,Node> map = new HashMap();\n        Queue<Node> queue = new LinkedList();\n        \n        queue.add(node);\n        map.put(node,new Node(node.val));\n        \n        while(!queue.isEmpty()){\n            \n            Node curr = queue.poll();\n            \n            for(Node neighbor : curr.neighbors){\n                if(!map.containsKey(neighbor)){\n                    map.put(neighbor,new Node(neighbor.val));\n                    queue.add(neighbor);\n                }\n                map.get(curr).neighbors.add(map.get(neighbor));\n            }\n        }\n        \n        return map.get(node);\n    }\n}\n"
  },
  {
    "path": "Clone a stack without using extra space",
    "content": "class Solution {\n    void clonestack(Stack<Integer> st, Stack<Integer> cloned) {\n       int n=st.size();\n       int i=n;\n       while(n>0){\n           while(!st.isEmpty()){\n               cloned.push(st.pop());\n           }\n           int x=cloned.pop();\n           i=n-1;\n           while(!cloned.isEmpty() && i>0){\n               st.push(cloned.pop());\n               i--;\n           }\n           cloned.push(x);\n           n--;\n       }\n       return ;\n   }\n\n}\n"
  },
  {
    "path": "Closest Palindrome - GFG/README.md",
    "content": "# Closest Palindrome\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a number num,&nbsp;our task is to find the closest Palindrome number whose absolute difference with given number is minimum. If 2 Palindome numbers have same absolute difference from the given number, then find&nbsp;the smaller one.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>num = 9\n<strong>Output: </strong>9\n<strong>Explanation: </strong>9 itself is a palindrome\nnumber.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>num = 489\n<strong>Output: </strong>494\n<strong>Expnataion: </strong>closest palindrome numbers from\n489 are 484 and 494. Absolute difference between\n489 and 494 is equal to the absolute difference\nbetween 484 and 489 but 484 is smaller than 494.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anyhting. Your task is to complete the function&nbsp;<strong>closestPalindrome()&nbsp;</strong>which takes num as input parameter and returns the closest palindrome.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(log<sub>10</sub>num)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(1)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= num &lt;= 10<sup>14</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Closest Palindrome - GFG/closest-palindrome.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            long num = Long.parseLong(br.readLine().trim());\n            Solution obj = new Solution();\n            long ans = obj.closestPalindrome(num);\n            System.out.println(ans);\n\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\nclass Solution\n{\n    public long closestPalindrome(long num)\n    {\n        String number = String.valueOf(num);\n        \n        if(isPalindrome(number))\n        {\n            return num;\n        }\n        \n        if(number.charAt(0)=='1' && Long.parseLong(number.substring(1))==0)\n        {\n            return num-1;\n        }\n        \n        int n = number.length();\n        \n        boolean hasEvenDigits = n%2==0;\n        \n        \n        String palRootStr = hasEvenDigits ? number.substring(0, n/2) : number.substring(0, n/2+1);\n        \n        long palRoot = Long.parseLong(palRootStr);\n        \n        //Equal\n        \n        long equal = toPal(\"\" + palRoot, hasEvenDigits);\n        long diffEqual = Math.abs(num-equal);\n        \n        //Bigger\n        \n        long bigger = toPal(\"\" + (palRoot+1), hasEvenDigits);\n        long diffBigger = Math.abs(num-bigger);\n        \n        //Smaller\n        \n        long smaller = toPal(\"\" + (palRoot-1), hasEvenDigits);\n        long diffSmaller = Math.abs(num-smaller);\n        \n        \n        long closest = diffBigger<diffSmaller ? bigger : smaller;\n        \n        long minDiff = Math.min(diffBigger, diffSmaller);\n        \n        if(diffEqual==minDiff)\n        {\n            closest = Math.min(equal, closest);\n        }\n        else if(diffEqual<minDiff)\n        {\n            closest = equal;\n        }\n        \n        \n        return closest;\n        \n        \n    }\n    \n    private long toPal(String num, boolean isEven)\n    {\n        StringBuilder reverseNum = new StringBuilder(num).reverse();\n        \n        String palDigits = isEven ? num + reverseNum : num + (reverseNum.deleteCharAt(0)).toString();\n        \n        return Long.parseLong(palDigits);\n    }\n    \n    \n    private boolean isPalindrome(String num)\n    {\n        int l=0, r=num.length()-1;\n        \n        while(l<r)\n        {\n            if(num.charAt(l++)!=num.charAt(r--)) return false;\n        }\n        \n        return true;\n    }\n    \n}"
  },
  {
    "path": "Coin Piles - GFG/README.md",
    "content": "# Coin Piles\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">There are <strong>N</strong> piles of coins each containing &nbsp;<strong>Ai</strong> (1&lt;=i&lt;=N) coins. Find the minimum number of coins to be removed such that the absolute difference of coins in any two piles is at most <strong>K.</strong><br>\n<strong>Note</strong>:&nbsp;You can also remove a pile by removing all the coins of that pile.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 4, K = 0\narr[] = {2, 2, 2, 2}\n<strong>Output:\n</strong>0\n<strong>Explanation:</strong>\n</span><span style=\"font-size:18px\">For any two piles the difference in the\nnumber of coins is &lt;=0. So no need to\nremove any coins.</span> \n</pre>\n\n<div><span style=\"font-size:18px\"><strong>Example 2:</strong></span></div>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 6, K = 3\narr[] = {1, 5, 1, 2, 5, 1} \n<strong>Output :</strong>\n2</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\n</span><span style=\"font-size:18px\">If we remove one coin each from both\nthe piles containing 5 coins , then\nfor any two piles the absolute difference\nin the number of coins is &lt;=3.</span> \n\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>minSteps()</strong>&nbsp;which takes 2 integers N, and K and an array A of size N as input and returns the minimum number of coins that need to be removed.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N*logN)<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n0 ≤ K ≤ 10<sup>4</sup></span><br>\n<span style=\"font-size:18px\">1 ≤ A[i] ≤ 10</span><sup style=\"font-size:18px\">3</sup></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Coin Piles - GFG/coin-piles.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            String S1[] = read.readLine().split(\" \");\n            int N = Integer.parseInt(S1[0]);\n            int K = Integer.parseInt(S1[1]);\n            \n            String S[] = read.readLine().split(\" \");\n            int[] A = new int[N];\n            \n            for(int i=0; i<N; i++)\n                A[i] = Integer.parseInt(S[i]);\n\n            Solution ob = new Solution();\n            System.out.println(ob.minSteps(A,N,K));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    static int minSteps(int[] arr, int n, int k) {\n        Arrays.sort(arr);\n        int[] subset = new int[n];\n        subset[n-1] = arr[n-1];\n        for(int i =n-2 ; i >= 0 ; i--){\n            subset[i] = arr[i] + subset[i+1];\n        }\n        \n        int min = Integer.MAX_VALUE;\n        int sum = 0;\n        \n        for(int i =0; i< n; i++){\n            int ind = findUpper(arr , arr[i] + k , i , n-1);\n            if(ind == -1){\n                min = Math.min(min , sum); \n                continue;\n            }\n            \n            int curr = subset[ind] - ((n - ind) *(arr[i]+k));\n            curr += sum;\n            min = Math.min(min , curr);\n            sum += arr[i];\n        }\n        return min;\n    }\n    static int findUpper(int[] arr , int target,  int s , int e){\n        int ans = -1;\n        while(s <= e){\n            int mid = (s+e)/2;\n            if(arr[mid] > target){\n                ans = mid;\n                e = mid - 1;\n            }else{\n                s = mid + 1;\n            }\n        }\n        return ans;\n    }\n};"
  },
  {
    "path": "Coins of Geekland.java",
    "content": "class Solution\n{\n    public int Maximum_Sum(int mat[][],int N,int K){\n        // Your code goes here\n        int max=Integer.MIN_VALUE;\n        for(int i=0;i<=N-K;i++){\n            for(int j=0;j<=N-K;j++){\n                max=Math.max(max,sum(mat,i,j,K));\n            }\n        }\n        return max;\n    }\n    public int sum(int[][]arr,int row, int col, int k){\n        int sum=0;\n        int i=row;\n        while(i<row+k){\n            int j=col;\n            while(j<col+k){\n                sum+=arr[i][j];\n                j++;\n            }\n            i++;\n        }\n        return sum;\n    }\n    \n}\n"
  },
  {
    "path": "Combination Sum II.java",
    "content": "public class Solution {\n\tArrayList<ArrayList<Integer>> ans;\n\tint n;\n\tSet<ArrayList<Integer>> set;\n\tpublic ArrayList<ArrayList<Integer>> combinationSum(ArrayList<Integer> a, int b) {\n\t\tCollections.sort(a);\n\t\tn=b;\n\t\tset=new HashSet<>();\n\t\tans=new ArrayList<>();\n\t\tdfs(0,a,new ArrayList<>(),0);\n\t\treturn ans;\n\t}\n\tvoid dfs(int idx,ArrayList<Integer> a,ArrayList<Integer> curr,int sum){\n\t\tif(sum==n){\n\t\t\tif(!set.contains(curr)){\n\t\t\t\tset.add(curr);\n\t\t\t\tans.add(new ArrayList<>(curr));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif(idx==a.size())return;\n\t\tfor(int i=idx;i<a.size();i++){\n\t\t\tcurr.add(a.get(i));\n\t\t\tsum+=a.get(i);\n\t\t\tif(sum<=n){\n\t\t\t\tdfs(i+1,a,curr,sum);\n\t\t\t\tcurr.remove(curr.size()-1);\n\t\t\t\tsum-=a.get(i);\n\t\t\t}else{\n\t\t\t\tcurr.remove(curr.size()-1);\n\t\t\t\tsum-=a.get(i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "Combination Sum.java",
    "content": "public class Solution {\n    ArrayList<ArrayList<Integer>> ans;\n    ArrayList<Integer> arr;\n    int target;\n    public ArrayList<ArrayList<Integer>> combinationSum(ArrayList<Integer> A, int B){\n        ans=new ArrayList<>();\n        target=B;\n        Collections.sort(A);\n        arr=A;\n        dfs(0,0,new ArrayList<>());\n        return ans;\n    }\n    public void dfs(int sum,int index,ArrayList<Integer> curr){\n        if(sum>target)return;\n        if(sum==target){\n            if(!ans.contains(curr)){\n                ans.add(new ArrayList<>(curr));\n            }\n        }\n        for(int i=index;i<arr.size();i++){\n            int ele=arr.get(i);\n            if(i>index && ele==arr.get(i-1))continue;\n            curr.add(ele);\n            sum+=ele;\n            dfs(sum,i,curr);\n            curr.remove(curr.size()-1);\n            sum-=ele;\n        }\n    }\n}\n"
  },
  {
    "path": "Combinations.java",
    "content": "public class Solution {\n    ArrayList<ArrayList<Integer>> ans;\n    int n;\n    int k;\n    public ArrayList<ArrayList<Integer>> combine(int n, int k) {\n        ans=new ArrayList<>();\n        this.n=n;\n        this.k=k;\n        dfs(1,new ArrayList<>());\n        return ans;\n    }\n    public void dfs(int curr,ArrayList<Integer> curList){\n        if(curList.size()==k){\n            ans.add(new ArrayList<>(curList));\n            return;\n        }\n        for(int i=curr;i<=n;i++){\n            curList.add(i);\n            dfs(i+1,curList);\n            curList.remove(curList.size()-1);\n        }\n    }\n}\n"
  },
  {
    "path": "Compare Version Numbers.java",
    "content": "class Solution {\n    public int compareVersion(String version1, String version2) {\n        String[] str1 = version1.split(\"\\\\.\");\n        String[] str2 = version2.split(\"\\\\.\");\n        int max = Math.max(str1.length,str2.length);\n        for(int i=0;i<max;i++){\n            int num1 = i >= str1.length ? 0 : Integer.parseInt(str1[i]);\n            int num2 = i >= str2.length ? 0 : Integer.parseInt(str2[i]);\n            if(num1 < num2) return -1;\n            if(num1 > num2) return 1;\n        }\n\n        return 0;\n    }\n}\n\n//==================================================================================\n//Two pointer (Faster)\npublic class Solution {\n    public int compareVersion(String version1, String version2) {\n        int i = 0, j = 0;\n        int currentVersion1, currentVersion2;\n        while(i < version1.length() || j < version2.length()) {\n            currentVersion1 = 0;\n            while(i < version1.length() && version1.charAt(i) != '.'){\n                currentVersion1 = currentVersion1 * 10 + (version1.charAt(i) - '0');\n                i++;\n            }\n            \n            currentVersion2 = 0;\n            while(j < version2.length() && version2.charAt(j) != '.'){\n                currentVersion2 = currentVersion2 * 10 + (version2.charAt(j) - '0');\n                j++;\n            }\n            \n            if(currentVersion1 > currentVersion2)\n                return 1;\n            if(currentVersion2 > currentVersion1)\n                return -1;\n            i++;\n            j++;\n        }\n        \n        return 0;\n    }\n}\n"
  },
  {
    "path": "Complete Binary Tree.java",
    "content": "class GfG\n{\n\tboolean isCompleteBT(Node root)\n    {\n          //add code here.\n          Queue<Node> q=new LinkedList<>();\n          q.add(root);\n        boolean foundNull=false;\n          while(!q.isEmpty()){\n              int sz=q.size();\n              while(sz-->0){\n                Node node=q.remove();\n                if(node==null){\n                    foundNull=true;\n                }else{\n                    if(foundNull){\n                        return false;\n                    }else{\n                        q.add(node.left);\n                        q.add(node.right);\n                    }\n                }\n              }\n          }\n          return true;\n\t} \n}\n"
  },
  {
    "path": "Composite And Prime.java",
    "content": "Without using DP\n\n\n\nclass Solution\n\n\n{\n    \n    public boolean isPrime(int a){\n        if(a==1){\n            return false;\n        }\n        else if(a==2 || a==3){\n            return true;\n        }\n        else if(a%2==0 || a%3==0){\n            return false;\n        }\n        else{\n            for(int i=5;i<=Math.sqrt(a);i+=6){\n                if(a%i==0 || a%(i+2)==0){\n                    return false;\n                }\n            }\n            return true;\n        }\n    }\n    public int Count(int l, int r)\n    {\n        \n      \n        long countp=0;\n        long countc=0;\n       for(int i=l;i<=r;i++){\n           if(isPrime(i)==true){\n               countp++;\n           }\n           else{\n               countc++;\n           }\n       }\n      \n     \n      \n      int a=(int)(countc-countp);\n      if(l==1 || r==1){\n          a=a-1;\n      }\n      \n      return a;\n       \n        \n    }\n}\n\n\n//long to avoid integer overflow exception(if exists)\n\n"
  },
  {
    "path": "Composite and Prime gfg med s18.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\n\tpublic:\n\tvector<int>isprime;\n\tvector<int> count;\n\tvoid isPrime(int n){\n\t    bool prime[n+1];\n\t    count.resize(n+1,0);\n\t    memset(prime, true, sizeof(prime));\n\t    \n\t    for(int ip =2; ip*ip<=n; ip++){\n\t        if(prime[ip]== true){\n\t            for(int i=ip*2; i<=n; i+=ip) prime[i] = false;\n\t        }\n\t    }\n\t    int c =0;\n\t    for(int p=2; p<=n; p++){\n\t        c+=(prime[p]== true);\n\t        count[p] = c;\n\t    }\n\t}\n\t\tint Count(int L, int R){\n\t\t    // Code here\n\t\t    isPrime(R);\n\t\t    int ans = (R-L+1)-2*(count[R]-count[L-1]);\n\t\t  //  1 is neither prime or comp\n\t\t  if(L==1) ans--;\n\t\t  return ans;\n\t\t}\n\n};\n\nint main(){\n\tint tc;\n\tcin >> tc;\n\twhile(tc--){\n\t\tint L, R;\n\t\tcin >> L >> R;\n\t\tSolution obj;\n\t\tint ans = obj.Count(L, R);\n\t\tcout << ans << \"\\n\";\n\t}\n\treturn 0;\n}"
  },
  {
    "path": "Composite and Prime.cpp",
    "content": "//{ Driver Code Starts\n#include<bits/stdc++.h>\nusing namespace std;\n\n// } Driver Code Ends\nclass Solution {\n\tpublic:\n\t\tint Count(int L, int R){\n\t\t    // Code here\n\t\t//using the Sieve of Eratosthenes\n    \n\t\tvector<bool>v(R+1, true);       //initially considering all number as prime\n\t\t\n\t\t\n\t\tfor(int i=2; i*i<=R; i++){\n\t\t    for(int j=i*i; j<=R; j+=i){\n\t\t        v[j] = false;           //marking all composite numbers as false\n\t\t    }\n\t\t}\n\t\t\n\t\tint composite=0, prime=0;\n\t\t\n\t\tfor(int i=L; i<=R; i++){\n\t\t    if(i==1)                    //since 1 is neither prime nor composite\n\t\t        continue;\n\t\t    else if(v[i]==true)\n\t\t        prime++;\n\t\t    else\n\t\t        composite++;\n\t\t}\n\t\treturn composite-prime;\n\t}\n};\n\n//{ Driver Code Starts.\nint main(){\n\tint tc;\n\tcin >> tc;\n\twhile(tc--){\n\t\tint L, R;\n\t\tcin >> L >> R;\n\t\tSolution obj;\n\t\tint ans = obj.Count(L, R);\n\t\tcout << ans << \"\\n\";\n\t}\n\treturn 0;\n}\n// } Driver Code Ends\n"
  },
  {
    "path": "Composite and Prime.java",
    "content": "class Solution\n{\n    public int Count(int L, int R)\n    {\n        // code here\n        int primes=0;\n        int comp=0;\n        boolean[]prime=new boolean[R+1];\n        Arrays.fill(prime,true);\n        prime[0]=false;\n        prime[1]=false;\n        for(int i=2;i<=R;i++){\n            if(prime[i]){\n                for(int j=2*i;j<=R;j+=i){\n                    prime[j]=false;\n                }    \n            }\n        }\n        \n        for(int i=L;i<=R;i++){\n            if(prime[i]){\n                primes++;\n            }else{\n                comp++;\n            }\n        }\n        if(L==1){\n            comp--;\n        }\n        return comp-primes;\n    }\n}\n"
  },
  {
    "path": "Composite and Prime.py",
    "content": "#User function Template for python3\n\nclass Solution:\n\tdef Count(self, l, r):\n\t\tsize = r\n        sieve = [i for i in range(size+1)]\n        for i in range(2, size+1):\n            if sieve[i] == i:\n                j = i * 2\n                while j < size+1:\n                    sieve[j] = i\n                    j += i\n        \n        comps = primes = 0\n        for i in range(max(l, 2), r+1):\n            if sieve[i] == i:\n                primes += 1\n            else:\n                comps += 1\n        return comps - primes\n\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n\tT=int(input())\n\tfor i in range(T):\n\t\tL, R = input().split()\n\t\tL = int(L); R = int(R)\n\t\tob = Solution()\n\t\tans = ob.Count(L, R)\n\t\tprint(ans)\n\n# } Driver Code Ends\n"
  },
  {
    "path": "Composite-and-prime.cpp",
    "content": "class Solution{\npublic:\n\t    bool isPrime(int num){\n\t        if(num <= 1) return false;\n\t        int cnt = 0;\n\t        for(int i = 2; i <= sqrt(num); i++){\n\t            if(num % i == 0) return false;\n\t        }\n\t        return true;\n\t    }\n\t\n\t\tint Count(int L, int R){\n\t\t    int p = 0, c = 0;\n\t\t    for(int i = L; i <= R; i++){\n\t\t        if(i == 1) continue;\n\t\t        if(isPrime(i)) p++;\n\t\t        else\n\t\t            c++;\n\t\t    }\n\t\t    return c - p;\n\t\t}\n};\n"
  },
  {
    "path": "Compute Before Matrix.java",
    "content": "class Solution{\n    public int[][] computeBeforeMatrix(int N, int M,int[][] after ){\n        // Code here\n        int[][]before=new int[N][M];\n        for(int row=0;row<N;row++){\n            for(int col=0;col<M;col++){\n                if(row==0 && col==0){\n                    before[row][col]=after[row][col];\n                }else if(row==0 && col>0){\n                    before[row][col]=after[row][col]-after[row][col-1];\n                }else if(col==0 && row>0){\n                    before[row][col]=after[row][col]-after[row-1][col];\n                }else{\n                    before[row][col]=after[row][col]-(after[row-1][col]-after[row-1][col-1]+after[row][col-1] );\n                }\n            }\n        }\n        return before;\n    }\n}\n"
  },
  {
    "path": "Concatenate two numbers.java",
    "content": "class Solution \n{ \n    long countPairs(int N, int X, int numbers[]) \n    { \n        // code here\n        long c=0;\n        Map<String,Integer> a=new HashMap<String,Integer>();\n        for(int i=0;i<N;i++){\n            String h=numbers[i]+\"\";\n            a.put(h,a.getOrDefault(h,0)+1);\n        }\n        String l=X+\"\";\n        int len=l.length();\n        for(int i=1;i<len;i++){\n            String h1=l.substring(0,i);\n            String h2=l.substring(i,len);\n            if(a.containsKey(h1) && a.containsKey(h2)){\n                if(h1.equals(h2)){\n                    int y=a.get(h1);\n                    c+=y*(y-1);\n                }else\n                    c+=a.get(h1)*a.get(h2);\n                }\n        }\n        return c; \n    }\n} \n"
  },
  {
    "path": "Connect Ropes.java",
    "content": "public class Solution {\n    public int solve(ArrayList<Integer> A) {\n        Queue<Integer>pq=new PriorityQueue<>();\n        for(int i:A)pq.add(i);\n        int ans=0;\n        while(pq.size()>1){\n            int sum=pq.remove()+pq.remove();\n            ans+=sum;\n            pq.add(sum);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Consecutive Parent - Child.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    public int consecutiveNodes(TreeNode A) {\n        if(A.left==null && A.right==null)return 0;\n        int ans=0;\n        if(A.left!=null){\n            if(A.left.val==A.val-1 || A.left.val==A.val+1)ans++;\n            ans+=consecutiveNodes(A.left);\n        }\n        if(A.right!=null){\n            if(A.right.val==A.val-1 || A.right.val==A.val+1)ans++;\n            ans+=consecutiveNodes(A.right);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Construct BST from Preorder.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    int i=0;\n    public TreeNode constructBST(int[] A) {\n        return bstFromPreOrder(A,Integer.MAX_VALUE);\n    }\n    \n    public TreeNode bstFromPreOrder(int[] preorder ,int bound){\n        if(i== preorder.length || preorder[i]>=bound) return null;\n        TreeNode root = new TreeNode(preorder[i++]);\n        root.left = bstFromPreOrder(preorder, root.val);\n        root.right = bstFromPreOrder(preorder, bound);\n        return root;\n    }\n}\n\n                                                                       \n\n\n\n"
  },
  {
    "path": "Construct Binary Tree From Inorder And Preorder.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) { val = x; }\n * }\n */\npublic class Solution {\n    \n    ArrayList<Integer> preorder, inorder;\n    \n\tpublic TreeNode buildTree(ArrayList<Integer> preorder, ArrayList<Integer> inorder) {\n\t    \n\t    if (preorder == null || inorder == null || preorder.size() == 0 || inorder.size() == 0)\n\t        return null;\n\t    \n\t    if (preorder.size() != inorder.size())\n\t        return null;\n\t    \n\t    this.preorder = preorder;\n\t    this.inorder = inorder;\n\t    \n\t    return rec(0, preorder.size() - 1, 0);\n\t    \n\t}\n\t\n\t\n\tprivate TreeNode rec(int start, int end, int index) {\n\t    \n\t    if (start > end)\n\t        return null;\n\t    \n\t    TreeNode root = new TreeNode(preorder.get(index));\n\t    \n\t    int i = start;\n\t    \n\t    for (; i <= end; i++) {\n\t        if (inorder.get(i).intValue() == root.val)\n\t            break;\n\t    }\n\t    \n\t    root.left = rec(start, i - 1, index + 1);\n\t    root.right = rec(i + 1, end, index + i - start + 1);\n\t    \n\t    return root;\n\t}\n\t\n}\n"
  },
  {
    "path": "Construct String With Repeat Limit.java",
    "content": "class Solution {\n    public String repeatLimitedString(String s, int repeatLimit) {\n        int [] arr = new int [26];\n        \n        for (char c : s.toCharArray()){\n            arr[c - 'a']++;\n        }\n        \n        StringBuilder sb = new StringBuilder();\n        int r;\n        int nxt = 25;\n        \n        for (int i = 25, j = 25; i >= 0; --i){\n            r = repeatLimit;\n            \n            while (arr[i] > 0 && r > 0 ){\n                --r;\n                --arr[i];\n                sb.append((char)('a' + i));\n            }\n            \n            if (arr[i] > 0){\n                while(nxt >= i || (nxt >= 0 && arr[nxt] == 0) )\n                    --nxt;\n                \n                if (nxt < 0) break;\n                --arr[nxt];\n                sb.append((char)('a' + nxt));\n                ++i;\n            }\n            \n            \n        }\n        \n        return sb.toString();\n    }\n}\n"
  },
  {
    "path": "Construct String from Binary Tree lc easy.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n/**\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 recur(TreeNode* root){\n        if(!root) return;\n        res+=to_string(root->val);\n        if(!root->left && !root->right) return;\n        res+=\"(\";\n        recur(root->left);\n        res+=\")\";\n        if(root->right){\n            res+=\"(\";\n            recur(root->right);\n            res+=\")\";\n        }\n    }\n    string tree2str(TreeNode* root) {\n//         recursion\n        recur(root);\n        return res;\n    }\n//     TC: O(N)\n};\n"
  },
  {
    "path": "Construct String from Binary Tree.java",
    "content": "class Solution {\n    StringBuilder sb=new StringBuilder();\n    public String tree2str(TreeNode root) {\n        str(root);\n        return sb.toString();\n    }\n    public void str(TreeNode root) {\n        if(root==null) {\n            return ;\n        }  \n        if(root.left==null && root.right==null) { //when there is no childs, adding just node value\n            sb.append(\"\"+root.val);\n            return ;\n        }\n        \n        sb.append(\"\"+root.val+\"(\");\n        str(root.left); //irrespective of left child present or not we should add ()-> so calling left child\n        sb.append(\")\");\n        if(root.right!=null) {  //If right child not present no need to add any ()\n            sb.append(\"(\");\n            str(root.right);\n            sb.append(\")\");\n        }\n    }\n}\n"
  },
  {
    "path": "Container With Most Water.java",
    "content": "public class Solution {\n    public int maxArea(int[] A) {\n        if(A.length<=1)return 0;\n        int ans=Integer.MIN_VALUE;\n        int i=0;\n        int j=A.length-1;\n        while(i<j){\n            ans=Math.max(ans,(j-i)*Math.min(A[i],A[j]));\n            if(A[i]<A[j]){\n                i++;\n            }else{\n                j--;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Contiguous Binary Array.java",
    "content": "//using hashmap\npublic class Solution {\n    public int findMaxLength(int[] nums) {\n        Map<Integer, Integer> map = new HashMap<>();\n        map.put(0, -1);\n        int maxlen = 0, count = 0;\n        for (int i = 0; i < nums.length; i++) {\n            count = count + (nums[i] == 1 ? 1 : -1);\n            if (map.containsKey(count)) {\n                maxlen = Math.max(maxlen, i - map.get(count));\n            } else {\n                map.put(count, i);\n            }\n        }\n        return maxlen;\n    }\n}\n\n\n============================================================================================\n  \n//Faster\n//using array\n  \npublic class Solution {\n\n    public int findMaxLength(int[] nums) {\n        int[] arr = new int[2 * nums.length + 1];\n        Arrays.fill(arr, -2);\n        arr[nums.length] = -1;\n        int maxlen = 0, count = 0;\n        for (int i = 0; i < nums.length; i++) {\n            count = count + (nums[i] == 0 ? -1 : 1);\n            if (arr[count + nums.length] >= -1) {\n                maxlen = Math.max(maxlen, i - arr[count + nums.length]);\n            } else {\n                arr[count + nums.length] = i;\n            }\n\n        }\n        return maxlen;\n    }\n}\n"
  },
  {
    "path": "Convert Sorted List to Binary Search Tree.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) { val = x; }\n * }\n */\n/**\n * Definition for singly-linked list.\n * class ListNode {\n *     public int val;\n *     public ListNode next;\n *     ListNode(int x) { val = x; next = null; }\n * }\n */\npublic class Solution {\n\tpublic TreeNode sortedListToBST(ListNode a) {\n        return dfs(a);\n\t}\n    public TreeNode dfs(ListNode a){\n        if(a.next==null)return new TreeNode(a.val);\n        ListNode prev=null;\n        ListNode slow=a;\n        ListNode fast=a;\n        while(fast.next!=null && fast.next.next!=null){\n            prev=slow;\n            slow=slow.next;\n            fast=fast.next.next;\n        }\n        if(prev!=null)prev.next=null;\n        ListNode next=slow.next;\n        slow.next=null;\n        TreeNode root=new TreeNode(slow.val);\n        if(!slow.equals(a))root.left=dfs(a);\n        root.right=dfs(next);\n        return root;\n    }\n}\n"
  },
  {
    "path": "Convert the amount in number to words.java",
    "content": "public class Solution {\n    private static class Place {\n        int unit;\n        String name;\n\n        public Place (int unit, String name) {\n            this.unit = unit;\n            this.name = name;\n        }\n    }\n\n    private static final Place[] places = new Place[]{\n        new Place(10000000, \"crore\"),\n        new Place(100000, \"lakh\"),\n        new Place(1000, \"thousand\"),\n        new Place(100, \"hundred\")\n    };\n\n    private static final String[] tens = new String[]{\n        \"\",\n        \"\",\n        \"twenty\",\n        \"thirty\",\n        \"forty\",\n        \"fifty\",\n        \"sixty\",\n        \"seventy\",\n        \"eighty\",\n        \"ninety\"\n    };\n\n    private static final String[] units = new String[]{\n        \"zero\",\n        \"one\",\n        \"two\",\n        \"three\",\n        \"four\",\n        \"five\",\n        \"six\",\n        \"seven\",\n        \"eight\",\n        \"nine\",\n        \"ten\",\n        \"eleven\",\n        \"twelve\",\n        \"thirteen\",\n        \"fourteen\",\n        \"fifteen\",\n        \"sixteen\",\n        \"seventeen\",\n        \"eighteen\",\n        \"nineteen\"\n    };\n\n    private String f(long amount) {\n        StringBuilder sb = new StringBuilder();\n\n        for (int i = 0; i < places.length; i++) {\n            Place place = places[i];\n            int qty = (int)(amount / place.unit);\n            if (qty > 0) {\n                String toAdd = \"\";\n                if (qty > 10) {\n                    toAdd = f (qty) + \"-\" + place.name;\n                } else {\n                    toAdd = units[qty] + \"-\" + place.name;\n                }\n                if (sb.length() > 0) {\n                    sb.append(\"-\");\n                }\n                sb.append(toAdd);\n            }\n            amount -= (long) qty * place.unit;\n        }\n\n        if (sb.length() > 0 && amount > 0) {\n            sb.append(\"-and-\");\n        }\n\n        int ten = (int)(amount / 10);\n        boolean shouldAddAnd = false;\n        if (ten > 1) {\n            sb.append(tens[ten]);\n            amount -= 10 * ten;\n            shouldAddAnd = true;\n        }\n\n        if (amount > 0) {\n            if (shouldAddAnd) {\n                sb.append(\"-\");\n            }\n            sb.append(units[(int)amount]);\n        }\n\n        return sb.toString();\n    }\n\n    public int solve(String A, String B) {\n\n        long amount = Long.parseLong(A);\n        String b = f(amount);\n        return b.equals(B) ? 1 : 0;\n\n    }\n}\n"
  },
  {
    "path": "Convert to Palindrome.java",
    "content": "public class Solution {\n    public int solve(String A) {\n        int n=A.length();\n        int lo=0,hi=n-1,flag=0;\n        while(lo<hi){\n            if(A.charAt(lo)!=A.charAt(hi)){\n                if(flag!=0)return 0;\n                flag++;\n                if(A.charAt(lo+1)==A.charAt(hi)){\n                    lo++;\n                }else if(A.charAt(hi-1)==A.charAt(lo)){\n                    hi--;\n                }else{\n                    return 0;\n                }\n            }\n            lo++;\n            hi--;\n        }\n        return 1;\n    }\n}\n"
  },
  {
    "path": "Copy List with Random Pointer.java",
    "content": "class Solution {\n    public Node copyRandomList(Node head) {\n        if (head == null){\n            return null;\n        }\n        \n        Node curr = head;\n        while (curr != null){\n            Node tmp = curr.next;\n            curr.next = new Node(curr.val);\n            curr.next.next = tmp;\n            curr = tmp;\n        }\n        \n        curr = head;\n        while (curr != null){\n            if (curr.random != null){\n                curr.next.random = curr.random.next;\n            } \n            curr = curr.next.next;\n        }\n        //extract the copy Node\n        Node newHead = new Node(0);\n        curr = head;\n        Node p = newHead;\n        while (curr != null){\n            Node tmp = curr.next.next;\n            p.next = curr.next;\n            curr.next = tmp;\n            curr = curr.next;\n            p = p.next;\n        }\n        return newHead.next;\n    }\n}\n"
  },
  {
    "path": "Corona Vaccine.java",
    "content": "class Solution{\n    public static int count=0;\n    public static int dfs(Node root){\n        if(root==null)return 1;\n        int left=dfs(root.left);\n        int right=dfs(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    public static int supplyVaccine(Node root){\n        count=0;\n        if(dfs(root)==-1){\n            count++;\n        }\n        return count;\n    }\n    // 0 = no vaccine needed\n    // -1 = need vaccine\n    /// 1 = giving vaccine\n    \n}\n"
  },
  {
    "path": "Count All Valid Pickup and Delivery Options.java",
    "content": "class Solution {\n    public int countOrders(int n) {\n        long ans = 1;\n        int MOD = 1_000_000_007;\n\n        for (int i = 1; i <= n; ++i) {\n            // Ways to arrange all pickups, 1*2*3*4*5*...*n\n            ans = ans * i;\n            // Ways to arrange all deliveries, 1*3*5*...*(2n-1)\n            ans = ans * (2 * i - 1);\n            ans %= MOD;\n        }\n        \n        return (int)ans;\n    }\n}\n"
  },
  {
    "path": "Count And Say.java",
    "content": "public class Solution {\n    public String countAndSay(int n) {\n        if(n==1){\n            return \"1\";\n        }\n        String prev=countAndSay(n-1);\n        StringBuilder ans=new StringBuilder();\n        int i=0;\n        while(i<prev.length()){\n            char c=prev.charAt(i);\n            i++;\n            int count=1;\n            while(i<prev.length() && prev.charAt(i)==c){\n                count++;\n                i++;\n            }\n            ans.append(count);\n            ans.append(c);\n        }\n       return ans.toString();    \n    }\n}\n"
  },
  {
    "path": "Count BST nodes that lie in a given range - GFG/README.md",
    "content": "# Count BST nodes that lie in a given range\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a Binary Search Tree (BST) and a range <strong>l-h(inclusive)</strong>, count the number of nodes in the BST that lie in the given range. </span></p>\n\n<ul>\n\t<li><span style=\"font-size:18px\">The values smaller than root go to the left side</span></li>\n\t<li><span style=\"font-size:18px\">The values greater and equal to the root go to the right side</span></li>\n</ul>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>      10\n&nbsp;    /  \\\n&nbsp;   5    50\n&nbsp;  /    /  \\\n&nbsp; 1    40  100\nl = 5, h = 45\n<strong>Output: </strong>3<strong>\nExplanation: </strong>5 10 40 are the node in the\nrange</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\n     5\n&nbsp;   /  \\\n&nbsp;  4    6\n&nbsp; /      \\\n&nbsp;3        7\nl = 2, h = 8\n<strong>Output: </strong>5<strong>\nExplanation: </strong>All the nodes are in the\ngiven range.</span>\n</pre>\n\n<p><strong><span style=\"font-size:18px\">Your Task:</span></strong><br>\n<span style=\"font-size:18px\">This is a function problem. You don't have to take input. You are required to complete the function&nbsp;<strong>getCountOfNode()&nbsp;</strong>that takes root, l ,h as parameters and returns the <strong>count</strong>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(N)<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(Height of the BST).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= Number of nodes &lt;= 100<br>\n1 &lt;= l &lt; h &lt; 10<sup>3</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Count BST nodes that lie in a given range - GFG/count-bst-nodes-that-lie-in-a-given-range.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.LinkedList; \nimport java.util.Queue; \nimport java.io.*;\nimport java.util.*;\n\nclass Node{\n    int data;\n    Node left;\n    Node right;\n    Node(int data){\n        this.data = data;\n        left=null;\n        right=null;\n    }\n}\n\nclass GfG {\n    \n    static Node buildTree(String str){\n        \n        if(str.length()==0 || str.charAt(0)=='N'){\n            return null;\n        }\n        \n        String ip[] = str.split(\" \");\n        // Create the root of the tree\n        Node root = new Node(Integer.parseInt(ip[0]));\n        // Push the root to the queue\n        \n        Queue<Node> queue = new LinkedList<>(); \n        \n        queue.add(root);\n        // Starting from the second element\n        \n        int i = 1;\n        while(queue.size()>0 && i < ip.length) {\n            \n            // Get and remove the front of the queue\n            Node currNode = queue.peek();\n            queue.remove();\n                \n            // Get the current node's value from the string\n            String currVal = ip[i];\n                \n            // If the left child is not null\n            if(!currVal.equals(\"N\")) {\n                    \n                // Create the left child for the current node\n                currNode.left = new Node(Integer.parseInt(currVal));\n                // Push it to the queue\n                queue.add(currNode.left);\n            }\n                \n            // For the right child\n            i++;\n            if(i >= ip.length)\n                break;\n                \n            currVal = ip[i];\n                \n            // If the right child is not null\n            if(!currVal.equals(\"N\")) {\n                    \n                // Create the right child for the current node\n                currNode.right = new Node(Integer.parseInt(currVal));\n                    \n                // Push it to the queue\n                queue.add(currNode.right);\n            }\n            i++;\n        }\n        \n        return root;\n    }\n    static void printInorder(Node root)\n    {\n        if(root == null)\n            return;\n            \n        printInorder(root.left);\n        System.out.print(root.data+\" \");\n        \n        printInorder(root.right);\n    }\n    \n\tpublic static void main (String[] args) throws IOException{\n\t        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t        \n\t        int t=Integer.parseInt(br.readLine());\n    \n\t        while(t > 0){\n\t            String s = br.readLine();\n\t            String[] ab = br.readLine().trim().split(\" \");\n                int a = Integer.parseInt(ab[0]);\n                int b = Integer.parseInt(ab[1]);\n    \t    \tNode root = buildTree(s);\n        \t    Solution g = new Solution();\n\t\t\t    System.out.println(g.getCount(root,a,b));\n                t--;\n            \n        }\n    }\n  \n}\n\n// } Driver Code Ends\n\n\n// A Binary Search Tree node\n\n\nclass Solution\n{\n    int ans;\n    //Function to count number of nodes in BST that lie in the given range.\n    int getCount(Node root,int l, int h)\n    {\n        //Your code here\n        ans=0;\n        dfs(root,l,h);\n        return ans;\n    }\n    void dfs(Node root,int l,int h){\n        if(root==null)return;\n        if(root.data>=l && root.data<=h){\n            ans++;\n            dfs(root.left,l,h);\n            dfs(root.right,l,h);\n        }else if(root.data<l){\n            dfs(root.right,l,h);\n        }else{\n            dfs(root.left,l,h);\n        }\n    }\n}\n"
  },
  {
    "path": "Count Common Words With One Occurrence",
    "content": "class Solution {\n    public int countWords(String[] words1, String[] words2) {\n        HashSet<String> words1Set=new HashSet<>();\n        HashSet<String> words1Duplicates=new HashSet<>();\n        HashSet<String> words12Set=new HashSet<>();\n        HashSet<String> words12Duplicates=new HashSet<>();\n        for(String s: words1) {\n            if (words1Set.contains(s)) words1Duplicates.add(s);\n            else words1Set.add(s);\n        }\n        for(String s: words1Duplicates) words1Set.remove(s);\n        for(String s: words2) {\n            if (words1Set.contains(s)) {\n                if (words12Set.contains(s)) words12Duplicates.add(s);\n                else words12Set.add(s);\n            }\n        }\n        return words12Set.size()-words12Duplicates.size();\n    }\n}\n"
  },
  {
    "path": "Count Integers With Even Digit Sum.py",
    "content": "def getSum(n):\n        sum = 0\n        for digit in str(n): \n            sum += int(digit)      \n        return sum\n    \nclass Solution:\n    def countEven(self, num: int) -> int:\n        count=0\n        val=2\n        while val<=num:\n            if getSum(val)%2==0:\n                count+=1;\n            val+=1\n        return count\n"
  },
  {
    "path": "Count Operations to Obtain Zero.java",
    "content": "class Solution {\n    public int countOperations(int num1, int num2) {\n        int ans=0;\n        while(num1>0 && num2>0){\n            if(num1>=num2){\n                num1=num1-num2;\n            }else{\n                num2=num2-num1;\n            }\n            ans++;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Count Palindromic  Subsequence.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n// } Driver Code Ends\nclass Solution{\n    #define ll long long int\n\n    \n    private:\n    ll solve(string& s,int i,int j,vector<vector<ll>> &dp){\n         int mod =1e9+7;\n        \n        if(i==j){\n            return 1;\n        }\n        \n        if(i>j){\n            return 0;\n        }\n        \n        if(dp[i][j] != -1){\n            return dp[i][j];\n        }\n        \n        \n        if(s[i] == s[j]){\n            dp[i][j] = ( 1 + solve(s,i+1,j,dp) + solve(s,i,j-1,dp) )%mod;\n        }else{\n            dp[i][j] = ((solve(s,i+1,j,dp) + solve(s,i,j-1,dp) - solve(s,i+1,j-1,dp))%mod+mod)%mod ; \n        }\n        \n        \n        return dp[i][j];\n    }\n    public:\n    /*You are required to complete below method */\n    ll  countPS(string str)\n    {\n       //Your code here\n       int n = str.size();\n       \n       vector<vector<ll>> dp(n,vector<ll>(n,-1));\n       \n       return solve(str,0,n-1,dp);\n       \n    }\n     \n};\n\n//{ Driver Code Starts.\n// Driver program\nint main()\n{\n    int t;\n    cin>>t;\n    while(t--)\n    {\n        string str;\n        cin>>str;\n        Solution ob;\n        long long int ans = ob.countPS(str);\n        cout<<ans<<endl;\n    } \n}\n"
  },
  {
    "path": "Count Palindromic Subsequences.java",
    "content": "class Solution\n{\n    long ans;\n    long dp[][];\n    long mod=1000000007;\n    long countPS(String str)\n    {\n        ans=0;\n        dp=new long[str.length()][str.length()];\n        return dfs(str,0,str.length()-1);\n        // Your code here\n    }\n    long dfs(String s,int i,int j){\n        if(i==j){\n            return 1;\n        }\n        if(i+1==j){\n            return s.charAt(i)==s.charAt(j)?3:2;\n        }\n        if(dp[i][j]!=0)return dp[i][j];\n        \n        if(s.charAt(i)==s.charAt(j)){\n            return dp[i][j]=(1+ dfs(s,i,j-1) + dfs(s,i+1,j))%mod;\n        }else{\n            dp[i][j]=(dfs(s,i,j-1) + dfs(s,i+1,j))%mod;\n            dp[i][j]=(dp[i][j]-dfs(s,i+1,j-1)+mod)%mod;\n            return dp[i][j];\n        }\n    }\n    \n}\n"
  },
  {
    "path": "Count Smaller elements.java",
    "content": "class Solution {\n    int[] constructLowerArray(int[] a, int n) {\n        int[]ans=new int[n];\n        int ii=n-2;\n        List<Integer> arr=new ArrayList<>();\n        arr.add(a[n-1]);\n        for(int i=n-2;i>=0;i--){\n            int idx=dfs(arr,a[i],0,arr.size()-1);\n            ans[ii]=idx;\n            ii--;\n            arr.add(idx,a[i]);\n        }\n        // for(int i:arr)System.out.print(i+\" \");\n        return ans;\n    }\n    int dfs(List<Integer> arr,int key,int l,int h){\n        if(l<=h){\n            int mid=l+(h-l)/2;\n            if(arr.get(mid)>=key){\n                return dfs(arr,key,l,mid-1);\n            }\n            return dfs(arr,key,mid+1,h);\n        }\n        return l;\n    }\n}\n"
  },
  {
    "path": "Count Words Obtained After Adding a Letter",
    "content": "class Solution {\n    public int wordCount(String[] a, String[] b) {\n        int m=a.length;\n        int n=b.length;\n        Set<String> set=new HashSet<>();\n        \n        for(int i=0;i<a.length;i++){\n            char[]chars1=a[i].toCharArray();\n            Arrays.sort(chars1);\n            a[i]=new String(chars1);\n            set.add(a[i]);\n        }\n        \n        for(int i=0;i<b.length;i++){\n            char[]chars2=b[i].toCharArray();\n            Arrays.sort(chars2);\n            b[i]=new String(chars2);\n        }\n        \n        int res=0;\n        \n        for(int i=0;i<b.length;i++){\n            char[]chars=b[i].toCharArray();\n            int length=chars.length;\n            for(int j=0;j<length;j++){\n                StringBuilder s=new StringBuilder();\n                for(int k=0;k<length;k++){\n                    if(k!=j){\n                        s.append(chars[k]);\n                    }\n                }\n                if(set.contains(s+\"\")){\n                    res++;\n                    break;\n                }\n            }\n        }\n        return res;\n        \n    }\n}\n"
  },
  {
    "path": "Count digit groupings of a number - GFG/README.md",
    "content": "# Count digit groupings of a number\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string str consisting of digits, one&nbsp;may group these digits into sub-groups while&nbsp;maintaining their original order.<br>\nThe task is to count number of groupings such that for every sub-group except the last one, sum of digits in a sub-group is less than or equal to sum of the digits in the sub-group immediately on its right.</span></p>\n\n<p><span style=\"font-size:18px\">For example, a valid grouping of digits of number 1119 is (1-11-9). Sum of digits in first subgroup is 1, next subgroup is 2, and last subgroup is 9. Sum of every subgroup is less than or equal to its immediate right.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:&nbsp;</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>str = \"1119\"\n<strong>Output: </strong>7\n<strong>Explanation: </strong></span><span style=\"font-size:18px\">[1-119], [1-1-19], [1-11-9], \n[1-1-1-9], [11-19], [111-9] and [1119] \nare seven sub-groups.</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>str = \"12\"\n<strong>Output: </strong>2\n<strong>Explanation: </strong>[1-2] and [12] are two sub-groups.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>TotalCount()</strong>&nbsp;which takes the string str as input parameter and returns total possible groupings.<br>\n<br>\n<strong>Expected Time&nbsp;Complexity:&nbsp;</strong>O(N * N ) where N is length of string.<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(N * N)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= length of string&nbsp;&lt;= 100</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Count digit groupings of a number - GFG/count-digit-groupings-of-a-number.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String str = br.readLine().trim();\n            Solution ob = new Solution();\n            int ans = ob.TotalCount(str);\n            System.out.println(ans);           \n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\nclass Solution{\n    public int TotalCount(String str){\n        int sum = 0;\n        for(int i=0; i<str.length();i++){\n            sum += str.charAt(i) - '0';\n        }\n        int[][]dp =new int[sum+1][str.length()+1];\n        for(int[]i : dp){\n            Arrays.fill(i,-1);\n        }\n        return backtrack(str, sum, str.length()-1, dp);\n    }\n    public int backtrack(String str, int currsum, int index, int[][]dp){\n        if(index<0)return 1;\n        \n        int curr = 0;\n        int ans = 0;\n        \n        if(dp[currsum][index]!=-1)return dp[currsum][index];\n        \n        for(int i=index;i>=0;i--){\n            curr += str.charAt(i)-'0';\n            if(curr<=currsum)ans += backtrack(str,curr,i-1, dp);\n        }\n        return dp[currsum][index] = ans;\n    }\n}"
  },
  {
    "path": "Count occurrences of a given word in a 2-d array(dynamic programming).cpp",
    "content": "class Solution{\n    public:\n    void solve(int i, int j, vector<vector<char> > &mat, string target,int index, int &ans){\n        int row=mat.size();\n        int col=mat[0].size();\n    if(i<0 or i>=row or j<0 or j>=col or index==target.length() or  mat[i][j]=='1' or target[index]!=mat[i][j])\n            return;\n    if(index==target.length()-1 && target[index]==mat[i][j])\n         ans++;\n    index++;\n    char temp=mat[i][j];\n    mat[i][j]='1';\n        \n         solve(i,j-1,mat,target,index,ans);\n         solve(i,j+1,mat,target,index,ans);\n         solve(i-1,j,mat,target,index,ans);\n         solve(i+1,j,mat,target,index,ans);\n    mat[i][j]=temp;\n    }\n    int findOccurrence(vector<vector<char> > &mat, string target){\n        int row=mat.size();\n        int col=mat[0].size();\n        int ans=0;\n        for(int i=0;i<row;i++){\n            for(int j=0;j<col;j++){\n                solve(i,j,mat,target,0,ans);\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Count occurrences of a given word in a 2-d array.cpp",
    "content": "class Solution{\n    public:\n    int ans = 0;\n    bool isSafe(int i,int j,int m,int n,int x,vector<vector<char>> &mat,string &target)\n    {\n        if(i < 0 || j < 0 || i==m || j==n || x >= target.size() || mat[i][j] != target[x])\n            return false;\n        \n        return true;\n    }\n    \n    void solve(int i,int j,int m,int n,int x,vector<vector<char>> &mat,string &target)\n    {\n        if(isSafe(i,j,m,n,x,mat,target))\n        {\n            if(x == target.size()-1)\n            {\n                ans++;\n                return;\n            }\n            \n            int dx[4] = {1,-1,0,0};\n            int dy[4] = {0,0,1,-1};\n            char temp = mat[i][j];\n            mat[i][j] = '/';\n            for(int k=0; k<4; k++)\n            {\n                int nx = i+dx[k];\n                int ny = j+dy[k];\n               \n                solve(nx,ny,m,n,x+1,mat,target);\n               \n            }\n            mat[i][j] = temp;\n            \n        }\n    }\n    \n    int findOccurrence(vector<vector<char> > &mat, string target){\n        int m = mat.size();\n        int n = mat[0].size();\n        int x = 0;\n        for(int i=0; i<m; i++)\n        {\n            for(int j=0; j<n; j++)\n            {\n                solve(i,j,m,n,x,mat,target);\n            }\n        }\n        return ans;\n        \n    }\n};\n"
  },
  {
    "path": "Count occurrences of a given word in a 2-d array.java",
    "content": "class Solution\n{\n    int ans;\n    public int findOccurrence(char mat[][], String target)\n    {\n        ans=0;\n        for(int i=0;i<mat.length;i++){\n            for(int j=0;j<mat[0].length;j++){\n                dfs(mat,i,j,target,0);\n            }\n        }\n        return ans;\n    }\n    void dfs(char[][]mat,int i,int j,String target,int idx){\n        if(i<0 || j<0 || i==mat.length || j==mat[0].length || idx>=target.length()\n        || target.charAt(idx)!=mat[i][j])return;\n        if(idx==target.length()-1){\n            ans++;\n            return;\n        }\n        char ch=mat[i][j];\n        mat[i][j]='0';\n        dfs(mat,i+1,j,target,idx+1);\n        dfs(mat,i-1,j,target,idx+1);\n        dfs(mat,i,j+1,target,idx+1);\n        dfs(mat,i,j-1,target,idx+1);\n        mat[i][j]=ch;\n    }\n}\n"
  },
  {
    "path": "Count occurrences of a given word in a 2-d array.py",
    "content": "class Solution:\n        def findOccurrence(self,mat,target):\n\n            cnt = 0\n            m, n = len(mat), len(mat[0])\n            seen = set()\n        \n            def dfs(r, c, target):\n                nonlocal cnt, m, n\n            \n                if not target:\n                    cnt += 1\n                    return \n                if r < 0 or r >= m or c < 0 or c >= n or (r, c) in seen or mat[r][c] != target[0]:\n                    return\n                seen.add((r, c))\n                dfs(r+1, c, target[1:])\n                dfs(r-1, c, target[1:])\n                dfs(r, c+1, target[1:])\n                dfs(r, c-1, target[1:])\n                seen.remove((r, c))\n            \n            for r in range(len(mat)):\n                for c in range(len(mat[0])):\n                    if mat[r][c] != target[0]:\n                        continue\n                    dfs(r, c, target)\n            return cnt//4\n"
  },
  {
    "path": "Count pairs in array divisible by K - GFG/README.md",
    "content": "# Count pairs in array divisible by K\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array&nbsp;<strong>A[]&nbsp;</strong>and positive integer&nbsp;<strong>K</strong>, the task is to count total number of pairs in the array whose sum is divisible by&nbsp;<strong>K</strong>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> \nA[] = {2, 2, 1, 7, 5, 3}, K = 4\n<strong>Output :</strong> 5\n<strong>Explanation : </strong>\nThere are five pairs possible whose sum\nis divisible by '4' i.e., (2, 2), \n(1, 7), (7, 5), (1, 3) and (5, 3)</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> \nA[] = {5, 9, 36, 74, 52, 31, 42}, K = 3\n<strong>Output :</strong> 7 \n<strong>Explanation : </strong>\nThere are seven pairs whose sum is divisible by 3, \ni.e, (9, 36), (9,42), </span><span style=\"font-size:18px\">(74, 52), (36, 42), (74, 31), \n(31, 5) and (5, 52).\n</span></pre>\n\n<div><span style=\"font-size:18px\"><strong>Your task :</strong></span></div>\n\n<div><span style=\"font-size:18px\">You don't have to read input or print anything. Your task is to complete the function <strong>countKdivPairs()</strong> which takes the array, it's size and an integer K as input and returns the count of pairs whose sum is divisible by K.</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Time Complexity :</strong> O(n)</span></div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Auxiliary Space :</strong> O(k)</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Constraints :</strong></span></div>\n\n<div><span style=\"font-size:18px\">1 &lt;= N &lt;=10^6</span></div>\n\n<div><span style=\"font-size:18px\">1 &lt;= A[i] &lt;= 10^6</span></div>\n\n<div><span style=\"font-size:18px\">1 &lt;= K &lt;= 100</span></div>\n <p></p>\n            </div>"
  },
  {
    "path": "Count pairs in array divisible by K - GFG/count-pairs-in-array-divisible-by-k.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass GFG\n{\n    public static void main (String[] args) throws IOException {\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\tint t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases\n\t\twhile(t-->0){\n\t\t    \n\t\t    int n = Integer.parseInt(br.readLine().trim());\n\t\t    String inputLine[] = br.readLine().trim().split(\" \");\n\t\t    int arr[] = new int[n];\n\t\t    for(int i=0; i<n; i++){\n\t\t        arr[i] = Integer.parseInt(inputLine[i]);\n\t\t    }\n\t\t    \n\t\t    int k = Integer.parseInt(br.readLine().trim());\n\t\t    \n\t\t    Solution ob= new Solution();\n\t\t    System.out.println(ob.countKdivPairs(arr, n, k));\n\t\t}\n\t}\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n    public static long countKdivPairs(int arr[], int n, int k)\n    {\n        long r=0;\n        int[] c = new int[k];\n        for (int i=0; i<n; i++){\n            r += c[(k-arr[i]%k)%k];\n            c[arr[i]%k]++;\n        }\n        return r;\n    }\n}"
  },
  {
    "path": "Count possible ways to construct buildings - GFG/README.md",
    "content": "# Count possible ways to construct buildings\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given <strong>N</strong>, the number of plots on either sides of the road. Find the total ways to construct buildings in the plots such that there is a space between any 2 buildings. All plots on one side of the road are continuous.<br>\nLets suppose * represents a plot, then for N=3, the plots can be represented as * * * | | * * * &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;</span></p>\n\n<p><span style=\"font-size:18px\">Where | | represents the road. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<br>\nNote: As the answer can be very large, print it mod 1000000007</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>N = 3\n<strong>Output: </strong>25\n<strong>Explanation: </strong>3 plots, which means possible\nways for one side are BSS, BSB, SSS, SBS,\nSSB where B represents a building and S\nrepresents an empty space Total possible \nways are 25, because a way to place on one\nside can correspond to any of 5 ways on other\nside.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>N = 10\n<strong>Output: </strong>20736\n<strong>Explanation: </strong>There are 20736 ways for N = 10.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>ToralWays()</strong>&nbsp;which takes N as input parameter and returns the total possible ways modulo 10<sup>9</sup>&nbsp;+ 7.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(N)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(N)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N &lt;= 100000</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Count possible ways to construct buildings - GFG/count-possible-ways-to-construct-buildings.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            int N = Integer.parseInt(br.readLine().trim());\n            Solution ob = new Solution();\n            int ans = ob.TotalWays(N);\n            System.out.println(ans);           \n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n   public int TotalWays(int N)\n   {\n       // Code here\n       long i,ans=0,inf = 1000000007;\n       long s = 1,b=1;\n       \n       while(N-->1){\n           i = s%inf;\n           s = (s%inf+b%inf);\n           b = i;\n       }\n       s = s%inf + b%inf;\n       return (int)((s*s)%inf);\n   }\n\n}"
  },
  {
    "path": "Count subsequences of type a^i, b^j, c^k - GFG/README.md",
    "content": "# Count subsequences of type a^i, b^j, c^k\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string S, the task is to count number of subsequences of the form a<sup>i</sup>b<sup>j</sup>c<sup>k</sup>, where i &gt;= 1, j &gt;=1 and k &gt;= 1.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Note:</strong>&nbsp;<br>\n1.&nbsp;Two subsequences are considered different if the set of array indexes picked for the 2 subsequences are different.<br>\n2.&nbsp;&nbsp;For large test cases, the output value will be too large, return the answer MODULO 10^9+7</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nS = \"abbc\"\n<strong>Output:</strong> 3\n<strong>Explanation</strong>: Subsequences are abc, abc and abbc.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>:\nS = \"abcabc\"\n<strong>Output:</strong> 7\n<strong>Explanation</strong>: Subsequences are abc, abc,\nabbc, aabc abcc, abc and abc.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>fun()&nbsp;</strong>which takes the string S as input parameter and returns the number of subsequences which follows given condition.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(Length of String).<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(1) .</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= |S| &lt;= 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Count subsequences of type a^i, b^j, c^k - GFG/count-subsequences-of-type-ai-bj-ck.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n\tpublic static void main (String[] args) {\n\t\t\n\t\tScanner sc = new Scanner (System.in);\n\t\tint t = Integer.parseInt(sc.next());\n\t\t\n\t\twhile(t>0)\n\t\t{\n\t\t    String s = sc.next();\n\t\t    \n\t\t    Solution T = new Solution();\n\t\t    System.out.println(T.fun(s));\n\t\t    \n\t\t    t--;\n\t\t}\n\t}\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n   public int fun(String s){\n       HashMap <Character, Integer> mp = new HashMap <>();\n       \n       mp.put('a',0);\n       mp.put('b',0);\n       mp.put('c',0);\n       for(int i = s.length()-1;i >= 0;i--)\n       {\n           if(s.charAt(i) == 'c')\n               mp.put('c', (2*mp.get('c')+1) % 1000000007 );\n           else if(s.charAt(i) == 'b')\n               mp.put('b', ( (2*mp.get('b'))% 1000000007 + mp.get('c') ) % 1000000007 );\n           else if(s.charAt(i) == 'a')\n               mp.put('a', ( (2*mp.get('a'))% 1000000007 + mp.get('b') ) % 1000000007 );\n       }\n             \n       return mp.get('a');\n   }\n}"
  },
  {
    "path": "Count the paths - GFG/README.md",
    "content": "# Count the paths\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a directed acyclic graph(DAG) with n nodes labeled from 0 to n-1. Given edges, s and d ,count the number of ways to reach from s to d.</span><span style=\"font-size:18px\">There is a directed Edge from vertex edges[i][0]&nbsp;to the vertex&nbsp;edges[i][1].</span></p>\n\n<p><span style=\"font-size:18px\">&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>edges = {{0,1},{0,3},{1,2},{3,2}}, \nn = 4, s = 0, d = 2\n<strong>Output: </strong>2\n<strong>Explanation: </strong>There are two ways to reach at \n2 from 0. These are-\n1. 0-&gt;1-&gt;2\n2. 0-&gt;3-&gt;2</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>possible_paths()&nbsp;</strong>which takes edges, n, s and d as input parameter and returns the number of ways to reach from s to d.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Compelxity:&nbsp;</strong>O(2<sup>n</sup>)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(n+e) </span></p>\n\n<p><span style=\"font-size:18px\">where e is the number of edges in the graph.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n &lt;= 15<br>\n0 &lt;= s, d &lt;= n-1</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Count the paths - GFG/count-the-paths.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String[] S = br.readLine().trim().split(\" \");\n            int n = Integer.parseInt(S[0]);\n            int m = Integer.parseInt(S[1]);\n            int s = Integer.parseInt(S[2]);\n            int d = Integer.parseInt(S[3]);\n            int[][] edges = new int[m][2];\n            for(int i = 0; i < m; i++){\n                String[] S1 = br.readLine().trim().split(\" \");\n                edges[i][0] = Integer.parseInt(S1[0]);\n                edges[i][1] = Integer.parseInt(S1[1]);\n            }\n            Solution obj = new Solution();\n            int ans = obj.possible_paths(edges, n, s, d);\n            System.out.println(ans);\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n    Map<Integer,ArrayList<Integer>> map;\n    int ans;\n    int des;\n    public int possible_paths(int[][] edges, int n, int s, int d)\n    {\n        des=d;\n        ans=0;\n        map=new HashMap<>();\n        for(int[]e:edges){\n            int src=e[0];\n            int des=e[1];\n            map.putIfAbsent(src,new ArrayList<>());\n            map.get(src).add(des);\n        }\n        \n        dfs(s);\n        return ans;\n    }\n    void dfs(int curr){\n        if(curr==des){\n            ans++;\n            return;\n        }\n        if(!map.containsKey(curr))return;\n        ArrayList<Integer> arr=map.get(curr);\n        for(int neb:arr){\n            dfs(neb);\n        }\n    }\n}"
  },
  {
    "path": "Count-occurrences-of-a-given-string-in-2d-array.cpp",
    "content": "\nclass Solution{\n    public:\n    \n    int ans = 0;\n    void dfs(int i, int j, vector<vector<char>> &mat, string target, int ind, string s){\n        if(i < 0 || j < 0 || i >= mat.size() || j >= mat[0].size() || mat[i][j] != target[ind])\n            return;\n        if(ind == target.size()-1){\n            ans++;\n            return;\n        }\n        char ch = mat[i][j];\n        mat[i][j] = '0';\n        dfs(i+1,j,mat,target,ind+1,s+mat[i][j]);\n        dfs(i,j+1,mat,target,ind+1,s+mat[i][j]);\n        dfs(i-1,j,mat,target,ind+1,s+mat[i][j]);\n        dfs(i,j-1,mat,target,ind+1,s+mat[i][j]);\n        \n        mat[i][j] = ch;\n        \n    }\n    \n    int findOccurrence(vector<vector<char> > &mat, string target){\n        int n = mat.size();\n        int m = mat[0].size();\n        \n        for(int i = 0; i < n; i++){\n            for(int j = 0; j < m; j++){\n                if(mat[i][j] == target[0]){\n                    dfs(i,j,mat,target,0,\"\");\n                }\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Count_occurences_of_a_given_word_in_a_2-d_array/Solution.java",
    "content": "class Solution\n{\n    // write your code here\n    int result = 0;\n    boolean isSafe(char mat[][],int r,int c)\n    {\n        int rLen = mat.length,cLen = mat[0].length;\n        if((r >= 0 && r < rLen)&&(c >= 0 && c < cLen))\n        return true;\n        return false;\n    }\n    public void dfs(char mat[][],int i,int r, int c,String target)\n    {\n        if(!isSafe(mat,r,c)) return;\n        if(i == target.length()) return;\n        char ch = target.charAt(i);\n        if(ch != mat[r][c]) return;\n \n        if(i == target.length()-1)\n        {\n            result+=1;\n            return;\n        }\n        mat[r][c] = '$';\n         \n        dfs(mat,i+1,r+1,c,target);\n        dfs(mat,i+1,r-1,c,target);\n        dfs(mat,i+1,r,c+1,target);\n        dfs(mat,i+1,r,c-1,target);\n        \n        mat[r][c] = ch;\n        \n    }\n    public int findOccurrence(char mat[][], String target)\n    {\n        for(int i = 0;i < mat.length;i++)\n            for(int j = 0; j < mat[i].length;j++)\n                if(mat[i][j] == target.charAt(0))\n                     dfs(mat,0,i,j,target);\n        return result;\n    }\n}"
  },
  {
    "path": "Count_occurences_of_a_given_word_in_a_2-d_array/question.md",
    "content": "Find the number of occurrences of a given search word in  a 2d-Array of characters where the word can go up, down, left, right and around 90 degree bends.\n\n**Example 1:**\n\n```\nInput: \nR = 4, C = 5\nmat = {{S,N,B,S,N},\n       {B,A,K,E,A},\n       {B,K,B,B,K},\n       {S,E,B,S,E}}\ntarget = SNAKES\nOutput:\n3\nExplanation: \nS N B S N\nB A K E A\nB K B B K\nS E B S E\nTotal occurrence of the word is 3\nand denoted by color.\n```\n\n**Example 2:**\n\n```\nInput:\nR = 3, C = 3 \nmat = {{c,a,t},\n       {a,t,c},\n       {c,t,a}}\ntarget = cat\nOutput:\n5\nExplanation: Same explanation\nas first example.\n```\n\n**Your task:**\nYou dont need to read input or print anything. Your task is to complete the function **findOccurrence()** which takes the mat contaning N*M 2-d array of character and target as input parameters and returns thethe number of occurrences of target.\n\n**Expected Time Complexity: **O(R*C*2 ^2*len^ ), Where len is length of target String.\n**Expected Auxiliary Space: **O(1)\n\n**Constraints:**\n1 ≤ len ≤ 15\n1 ≤ R, C ≤ 50\n"
  },
  {
    "path": "Counting Bits.java",
    "content": "class Solution {\n    public int[] countBits(int n) {\n        int[]ans=new int[n+1];\n        for(int i=1;i<ans.length;i++)\n            ans[i]=ans[i>>1]+(i&1);\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Counts Zeros Xor Pairs - GFG/README.md",
    "content": "# Counts Zeros Xor Pairs\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array A[] of size N. Find the number of pairs (i, j) such that<br>\nA<sub>i&nbsp;</sub>XOR A<sub>j</sub>&nbsp;= 0, and 1 ≤ i &lt; j ≤ N.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>â€‹Input :</strong> arr[ ] = {1, 3, 4, 1, 4}\n<strong>Output :</strong> 2\n<strong>Explanation:</strong>\nIndex( 0, 3 ) and (2 ,&nbsp;4 ) are&nbsp;only&nbsp;pairs \nwhose xors is zero so&nbsp;count&nbsp;is 2.\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>â€‹Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[ ] = {2, 2, 2} <strong>\nOutput :</strong>  3\n\n</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function <strong>calculate()</strong> that takes an array <strong>(arr)</strong>, sizeOfArray <strong>(n)</strong>, and return the count&nbsp;of Zeros Xor's Pairs. The driver code takes care of the printing.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N*Log(N)).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(1).</span></p>\n\n<p><br>\n<br>\n<span style=\"font-size:18px\"><strong>Output:</strong><br>\nFor each test case, output a single integer i.e counts of Zeros Xors Pairs</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints</strong><br>\n2 ≤ N ≤ 10^5<br>\n1 ≤ A[i] ≤ 10^5</span></p>\n\n<p>&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Counts Zeros Xor Pairs - GFG/counts-zeros-xor-pairs.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\n//Initial Template for Java\n\n//Initial Template for Java\n\n//Initial Template for Java\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\n\nclass Array {\n    \n    // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t    String line = br.readLine();\n\t\t    String[] element = line.trim().split(\"\\\\s+\");\n\t\t    int sizeOfArray = Integer.parseInt(element[0]);\n\t\t    \n\t\t    int arr [] = new int[sizeOfArray];\n\t\t    \n\t\t    line = br.readLine();\n\t\t    String[] elements = line.trim().split(\"\\\\s+\");\n\t\t    for(int i = 0;i<sizeOfArray;i++){\n\t\t        arr[i] = Integer.parseInt(elements[i]);\n\t\t    }\n\t\t    \n\t\t    \n\t\t    Complete obj = new Complete();\n\t\t    long res = obj.calculate(arr, sizeOfArray);\n\t\t    System.out.println(res);\n\t\t}\n\t}\n}\n\n\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n\nclass Complete{\n    \n   \n    // Function for finding maximum and value pair\n    public static long calculate (int arr[], int n) {\n        //Complete the function\n        Arrays.sort(arr);\n        int ans=0;\n        int count=1;\n        for(int i=1;i<n;i++){\n            if(arr[i]==arr[i-1]){\n                count++;\n            }else{\n                ans+=(count*(count-1)/2);\n                count=1;\n            }\n        }\n        ans+=(count*(count-1)/2);\n        return ans;\n    }\n    \n    \n}\n\n\n"
  },
  {
    "path": "Course Schedule - GFG/README.md",
    "content": "# Course Schedule\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">There are a total of <strong>n</strong> tasks you have to pick, labeled from 0 to n-1. Some tasks may have <strong>prerequisites </strong>tasks, for example to pick task 0 you have to first finish tasks 1, which is expressed as a pair: [0, 1]<br>\nGiven the total number of <strong>n</strong> tasks and a list of prerequisite pairs of size <strong>m</strong>. Find a ordering of tasks you should pick to finish all tasks.</span><br>\n<span style=\"font-size:18px\"><strong>Note: </strong>There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all tasks, return an empty array. Returning any correct order will give the output as <strong>1</strong>, whereas any invalid order will give the output <strong>0.</strong> </span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>n = 2, m = 1\nprerequisites = {{1, 0}}\n<strong>Output:\n</strong>1<strong>\nExplanation:\n</strong>The output 1 denotes that the order is\nvalid. So, if you have, implemented\nyour function correctly, then output\nwould be 1 for all test cases.</span>\n<span style=\"font-size:18px\">One possible order is [0, 1].</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>n = 4, m = 4\nprerequisites = {{1, 0},\n                 {2, 0},\n                 {3, 1},\n                 {3, 2}}\n<strong>Output:\n</strong>1<strong>\nExplanation:\n</strong>There are a total of 4 tasks to pick.\nTo pick task 3 you should have finished\nboth tasks 1 and 2. Both tasks 1 and 2\nshould be pick after you finished task 0.\nSo one correct task order is [0, 1, 2, 3].\nAnother correct ordering is [0, 2, 1, 3].\nReturning any of these order will result in\na Output of 1.</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThe task is to complete the function <strong>findOrder</strong>() which takes two integers n, and m and a list of lists of size m*2 denoting the prerequisite pairs as input and returns any correct order to finish all the tasks. Return an empty array if it's impossible to finish all tasks.</span></p>\n\n<div><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ n ≤ 10<sup>4</sup></span>\n\n<div><span style=\"font-size:18px\">0 ≤ m ≤ 10<sup>5</sup><br>\n0 ≤&nbsp;prerequisites[0],&nbsp;prerequisites[1] ≤ 10<sup>5</sup><br>\nAll prerequisite pairs are unique</span></div>\n\n<div><span style=\"font-size:18px\">prerequisites[0]&nbsp;≠&nbsp;prerequisites[1]</span></div>\n</div>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(n+m).<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(n+m).</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Course Schedule - GFG/course-schedule.java",
    "content": "// { Driver Code Starts\n//Initial template for JAVA\n\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass Main {\n    public static void main(String[] args) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n\n        while (t-- > 0) {\n            ArrayList<ArrayList<Integer>> list = new ArrayList<>();\n            String st[] = read.readLine().trim().split(\"\\\\s+\");\n            int n = Integer.parseInt(st[0]);\n            int m = Integer.parseInt(st[1]);\n\n            for (int i = 0; i < n; i++)\n                list.add(i, new ArrayList<Integer>());\n\n            ArrayList<ArrayList<Integer>> prerequisites = new ArrayList<>();\n            for (int i = 1; i <= m; i++) {\n                String s[] = read.readLine().trim().split(\"\\\\s+\");\n                int u = Integer.parseInt(s[0]);\n                int v = Integer.parseInt(s[1]);\n                list.get(v).add(u);\n                ArrayList<Integer> pair = new ArrayList<>();\n                pair.add(u);\n                pair.add(v);\n                prerequisites.add(pair);\n            }\n\n            int[] res = new Solution().findOrder(n, m, prerequisites);\n            \n            if(res.length==0)\n                System.out.println(\"No Ordering Possible\");\n            else\n            {\n                if (check(list, n, res) == true)\n                    System.out.println(\"1\");\n                else\n                    System.out.println(\"0\");\n            }\n        }\n    }\n    static boolean check(ArrayList<ArrayList<Integer>> list, int V, int[] res) {\n        int[] map = new int[V];\n        for (int i = 0; i < V; i++) {\n            map[res[i]] = i;\n        }\n        for (int i = 0; i < V; i++) {\n            for (int v : list.get(i)) {\n                if (map[i] > map[v]) return false;\n            }\n        }\n        return true;\n    }\n}\n// } Driver Code Ends\n\nclass Solution{\n    static int[] findOrder(int n, int m, ArrayList<ArrayList<Integer>> prereq){\n        int indegree[] = new int[n];\n        //Calculate the indegree of each node.\n        for(int i=0; i<m; i++)\n        {\n            indegree[prereq.get(i).get(1)]++;\n        }\n        \n        \n        //Create and adjacency list.\n        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n        \n        for(int i=0; i<n; i++)\n        {\n            adj.add(new ArrayList<>());\n        }\n        \n        for(int i=0; i<m; i++)\n        {\n            //The node which has any prerequisite points to its prerequisites.\n            int node1 = prereq.get(i).get(0);\n            int node2 = prereq.get(i).get(1);\n            \n            adj.get(node1).add(node2);\n        }\n        \n        Queue<Integer> queue = new ArrayDeque<>();\n        \n        boolean visited[] = new boolean[n];\n        \n        for(int i=0; i<n; i++)\n        {\n            if(indegree[i]==0)\n            {\n                queue.add(i);\n                visited[i] = true;\n            }\n            \n        }\n        \n        \n        int ans[] = new int[n];\n        int count = 0;\n        \n        while(queue.isEmpty()==false)\n        {\n            int node = queue.poll();\n            ans[count++] = node;\n            visited[node] = true;\n            \n            for(int nei : adj.get(node))\n            {\n                if(visited[nei]==false)\n                {\n                    //Decrease the indegree of each unvisited neighbor.\n                    indegree[nei]--;\n                    \n                    if(indegree[nei]==0)\n                    {\n                        //If the indegree is zero then we can add to the queue.\n                        visited[nei] = true;\n                        queue.add(nei);\n                    }\n                }\n            }\n            \n            \n        }\n        \n        //Check if every node is visited else return an empty array.\n        for(int i=0; i<n; i++)\n        {\n            if(visited[i]==false) return new int[0];\n        }\n        \n        \n        //Reverse the answer\n        for(int i=0; i<n/2; i++)\n        {\n            int temp = ans[i];\n            ans[i] = ans[n-i-1];\n            ans[n-i-1] = temp;\n        }\n        \n        \n        return ans;\n        \n    }\n}"
  },
  {
    "path": "Cousins of a given node.java",
    "content": "class Solution\n{\n    public static ArrayList<Integer> printCousins(Node root, Node find)\n    {\n        //code here\n        Queue<Node> q=new LinkedList<>();\n        ArrayList<Integer> ans=new ArrayList<>();\n        q.offer(root);\n        boolean flag=false;\n        while(!q.isEmpty()){\n            int sz=q.size();\n            if(flag){\n                while(!q.isEmpty()){\n                    ans.add(q.remove().data);\n                }\n                break;\n            }\n            for(int i=0;i<sz;i++){\n                Node node=q.remove();\n                if(node.left==find || node.right==find){\n                    flag=true;\n                    continue;\n                }\n                if(node.left!=null){\n                    q.offer(node.left);\n                }\n                if(node.right!=null){\n                    q.offer(node.right);\n                }\n            }\n        }\n        if(ans.size()==0){\n            ans.add(-1);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Covered-Uncovered Nodes.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    public Long coveredNodes(TreeNode A) {\n        Long cov=0l;\n        Long un=0l;\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(A);\n        while(q.size()>0){\n            int sz=q.size();\n            for(int i=0;i<sz;i++){\n                TreeNode curr=q.remove();\n                if(curr.left!=null)q.add(curr.left);\n                if(curr.right!=null)q.add(curr.right);\n                if(i==0 || i==sz-1){\n                    un+=curr.val;\n                }else{\n                    cov+=curr.val;\n                }\n            }\n        }\n        return (Long)Math.abs(un-cov);\n    }\n}\n"
  },
  {
    "path": "Create number of weak characters in game.java",
    "content": "class Solution {\n    public int numberOfWeakCharacters(int[][] properties) {\n\n         Arrays.sort(properties, (a,b) -> (a[0] == b[0]) ? Integer.compare(b[1], a[1]) : Integer.compare(a[0], b[0]));\n\n        int noOfWeakCharacters = 0;\n        int len = properties.length;\n       // improvization here - // we need to keep track of the max value\n        int max = properties[len-1][1];\n\n        for(int i = len-2; i>=0 ;i--) {\n\n            if(properties[i][1] < max) {\n                noOfWeakCharacters++;\n            } else {\n                max = properties[i][1];\n            }\n        }\n        return noOfWeakCharacters;\n    }\n}\n"
  },
  {
    "path": "Delete and Earn.java",
    "content": "class Solution {\n    private HashMap<Integer, Integer> points = new HashMap<>();\n    private HashMap<Integer, Integer> cache = new HashMap<>();\n    \n    private int maxPoints(int num) {\n        // Check for base cases\n        if (num == 0) {\n            return 0;\n        }\n        \n        if (num == 1) {\n            return points.getOrDefault(1, 0);\n        }\n        \n        if (cache.containsKey(num)) {\n            return cache.get(num);\n        }\n        \n        // Apply recurrence relation\n        int gain = points.getOrDefault(num, 0);\n        cache.put(num, Math.max(maxPoints(num - 1), maxPoints(num - 2) + gain));\n        return cache.get(num);\n    }\n    \n    public int deleteAndEarn(int[] nums) {\n        int maxNumber = 0;\n        \n        // Precompute how many points we gain from taking an element\n        for (int num : nums) {\n            points.put(num, points.getOrDefault(num, 0) + num);\n            maxNumber = Math.max(maxNumber, num);\n        }\n        \n        return maxPoints(maxNumber);\n    }\n}\n\n//==================================================================================\nclass Solution {\n    public int deleteAndEarn(int[] nums) {\n        int[] count = new int[10001];\n        for (int n : nums) {\n            count[n]++;\n        };\n        \n        int withPrev = 0;\n        int withoutPrev = 0;\n        int prev = -1;\n        \n        for (int i = 0; i < count.length; i++) {\n            if (count[i] == 0) continue;\n            \n            int currentMax = Math.max(withPrev, withoutPrev);\n            if (i - prev == 1) {\n                withPrev = withoutPrev + count[i] * i;\n                withoutPrev = currentMax;\n            } else {\n                withPrev = currentMax + count[i] * i;\n                withoutPrev = currentMax;\n            }\n            \n            prev = i;\n        }\n        \n        return Math.max(withPrev, withoutPrev);\n    }\n}\n"
  },
  {
    "path": "Delete nodes greater than k.java",
    "content": "class Solution\n   {\n         public Node deleteNode(Node root,int k)\n         {\n         //add code here.\n         if(root==null)return null;\n         if(root.data>=k){\n             root.left=deleteNode(root.left,k);\n             return root.left;\n         }else{\n             root.right=deleteNode(root.right,k);\n             \n         }\n         return root;\n         }\n   }\n"
  },
  {
    "path": "Deserialize.java",
    "content": "public class Solution {\n    public ArrayList<String> deserialize(String A) {\n        int i=0;\n        ArrayList<String> arr=new ArrayList<>();\n        StringBuilder sb=new StringBuilder();\n        while(i<A.length()){\n            if(A.charAt(i)>='0' && A.charAt(i)<='9'){\n                arr.add(sb.toString());\n                sb.setLength(0);\n                while(A.charAt(i)<'a')i++;\n            }else if(A.charAt(i)=='~'){\n                i++;\n            }else{\n                sb.append(A.charAt(i));\n                i++;\n            }\n        }\n        return arr;\n    }\n}\n"
  },
  {
    "path": "Design Add and Search Words Data Structure.java",
    "content": "class WordDictionary {\n    private WordDictionary[] children;\n    boolean isEndOfWord;\n    // Initialize your data structure here. \n    public WordDictionary() {\n        children = new WordDictionary[26];\n        isEndOfWord = false;\n    }\n    \n    // Adds a word into the data structure. \n    public void addWord(String word) {\n        WordDictionary curr = this;\n        for(char c: word.toCharArray()){\n            if(curr.children[c - 'a'] == null)\n                curr.children[c - 'a'] = new WordDictionary();\n            curr = curr.children[c - 'a'];\n        }\n        curr.isEndOfWord = true;\n    }\n    \n    // Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. \n    public boolean search(String word) {\n        WordDictionary curr = this;\n        for(int i = 0; i < word.length(); ++i){\n            char c = word.charAt(i);\n            if(c == '.'){\n                for(WordDictionary ch: curr.children)\n                    if(ch != null && ch.search(word.substring(i+1))) return true;\n                return false;\n            }\n            if(curr.children[c - 'a'] == null) return false;\n            curr = curr.children[c - 'a'];\n        }\n        return curr != null && curr.isEndOfWord;\n    }\n}\n"
  },
  {
    "path": "Design Bitset.java",
    "content": "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    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}\n"
  },
  {
    "path": "Design Browser History/Design-Browser-History.cpp",
    "content": "#include<bits/stdc++.h>\nclass BrowserHistory {\npublic: \n  // // 1. using 2 stacks\n//     stack<string> ur, fb;\n//     BrowserHistory(string homepage) {\n//         ur.push(homepage);\n//         fb = stack<string>();\n//     }\n    \n//     void visit(string url) {        \n//         ur.push(url);\n//         fb = stack<string>();\n//     }\n    \n//     string back(int steps) {\n//         while(steps>0 and ur.size() > 1){\n//             fb.push(ur.top());\n//             ur.pop();\n//             steps--;\n//         }\n//         return ur.top();\n//     }\n    \n//     string forward(int steps) {\n//         while(steps>0 and fb.size()>0){\n//             ur.push(fb.top());\n//             fb.pop();\n//             steps--;\n//         }\n//         return ur.top();\n//     }\n    \n  \n  // 2. using array of strings more efficient than 1. \n        string ur[5000];\n        int cur=0, end=0;\n        \n        BrowserHistory(string homepage) {\n            ur[0] = homepage;\n        }\n        \n        void visit(string url) {        \n            cur++;\n            ur[cur] = url;\n            end = cur;\n        }\n        \n        string back(int steps) {\n            if(steps>cur) cur=0;\n            else cur-=steps;\n            return ur[cur];\n        }\n        \n        string forward(int steps) {\n            if(cur+steps>end) cur=end;\n            else cur+=steps;\n            return ur[cur];\n        }\n    \n    \n};\n"
  },
  {
    "path": "Diagonal Traversal of Binary Tree - GFG/README.md",
    "content": "# Diagonal Traversal of Binary Tree\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a Binary Tree, print the <strong>diagonal traversal</strong> of the binary tree.</span></p>\n\n<p><span style=\"font-size:18px\">Consider lines of slope -1 passing between nodes. Given a Binary Tree, print all diagonal elements in a binary tree belonging to same line.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong> :\n&nbsp;           8\n&nbsp;        /     \\\n&nbsp;       3      10\n&nbsp;     /   \\      \\\n&nbsp;    1     6     14\n&nbsp;        /   \\   /\n&nbsp;       4     7 13\n<strong>Output</strong> : 8 10 14 3 6 7 13 1 4\n<strong>Explanation</strong>:\n<a href=\"http://d1hyf4ir1gqw6c.cloudfront.net//wp-content/uploads/unnamed1.png\" target=\"_blank\"><img alt=\"unnamed\" class=\"alignnone size-full wp-image-137695 img-responsive\" src=\"https://contribute.geeksforgeeks.org/wp-content/uploads/diagonal.jpg\" style=\"height:264px; width:406px\">\n</a>Diagonal Traversal of binary tree : \n 8 10 14 3 6 7 13 1 4</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. The task is to complete the function<strong> diagonal()&nbsp;</strong>that takes the root node<strong>&nbsp;</strong>as input argumets<strong> </strong>and returns the diagonal traversal of the given tree.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(N).<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(N).</span><br>\n<span style=\"font-size:18px\">Here N is number of nodes.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= Number of nodes&lt;= 10<sup>5</sup><br>\n1 &lt;= Data of a node&lt;= 10<sup>5</sup></span><br>\n&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Diagonal Traversal of Binary Tree - GFG/diagonal-traversal-of-binary-tree.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Contributed by Sudarshan Sharma\nimport java.util.LinkedList; \nimport java.util.Queue; \nimport java.io.*;\nimport java.util.*;\n\nclass Node{\n    int data;\n    Node left;\n    Node right;\n    Node(int data){\n        this.data = data;\n        left=null;\n        right=null;\n    }\n}\nclass GfG {\n    \n    static Node buildTree(String str){\n        \n        if(str.length()==0 || str.charAt(0)=='N'){\n            return null;\n        }\n        \n        String ip[] = str.split(\" \");\n        // Create the root of the tree\n        Node root = new Node(Integer.parseInt(ip[0]));\n        // Push the root to the queue\n        \n        Queue<Node> queue = new LinkedList<>(); \n        \n        queue.add(root);\n        // Starting from the second element\n        \n        int i = 1;\n        while(queue.size()>0 && i < ip.length) {\n            \n            // Get and remove the front of the queue\n            Node currNode = queue.peek();\n            queue.remove();\n                \n            // Get the current node's value from the string\n            String currVal = ip[i];\n                \n            // If the left child is not null\n            if(!currVal.equals(\"N\")) {\n                    \n                // Create the left child for the current node\n                currNode.left = new Node(Integer.parseInt(currVal));\n                // Push it to the queue\n                queue.add(currNode.left);\n            }\n                \n            // For the right child\n            i++;\n            if(i >= ip.length)\n                break;\n                \n            currVal = ip[i];\n                \n            // If the right child is not null\n            if(!currVal.equals(\"N\")) {\n                    \n                // Create the right child for the current node\n                currNode.right = new Node(Integer.parseInt(currVal));\n                    \n                // Push it to the queue\n                queue.add(currNode.right);\n            }\n            i++;\n        }\n        \n        return root;\n    }\n    static void printInorder(Node root)\n    {\n        if(root == null)\n            return;\n            \n        printInorder(root.left);\n        System.out.print(root.data+\" \");\n        \n        printInorder(root.right);\n    }\n    \n\tpublic static void main (String[] args) throws IOException{\n\t        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t        \n\t        int t=Integer.parseInt(br.readLine());\n    \n\t        while(t-- > 0){\n\t            String s = br.readLine();\n    \t    \tNode root = buildTree(s);\n    \t        Tree g = new Tree();\n\t\t\t    ArrayList<Integer> diagonalNode = g.diagonal(root);\n\t\t\t    for(int i = 0 ;i<diagonalNode.size();i++){\n\t\t\t        System.out.print(diagonalNode.get(i)+ \" \");\n\t\t\t    }\n\t\t        System.out.println();\n\t        }\n\t}\n}\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n/* Node is defined as\nclass Node{\n    int data;\n    Node left;\n    Node right;\n    Node(int data){\n        this.data = data;\n        left=null;\n        right=null;\n    }\n}*/\nclass Tree\n{\n     public ArrayList<Integer> diagonal(Node root)\n      {\n           //add your code here.\n           Queue<Node> q=new LinkedList<>();\n           ArrayList<Integer> ans=new ArrayList<>();\n           q.add(root);\n           while(!q.isEmpty()){\n               Node temp=q.remove();\n               while(temp!=null){\n                   if(temp.left!=null){\n                       q.add(temp.left);\n                   }\n                   ans.add(temp.data);\n                   temp=temp.right;\n               }\n           }\n           return ans;\n      }\n}\n"
  },
  {
    "path": "Different Bits Sum Pairwise.java",
    "content": "public class Solution {\n    public int cntBits(ArrayList<Integer> A) {\n    long total = 0, n = A.size();\n   \n    for (int j=0;j<32;j++) {\n        long bitCount = 0;\n        for (int i=0;i<n;i++)\n            bitCount += (A.get(i) >> j) & 1;\n        total += (bitCount % (1000000007) *(n - bitCount) % (1000000007)) % (1000000007) ;\n    }\n    total = (total*2) % (1000000007);\n    return (int)total;\n}\n   \n}\n"
  },
  {
    "path": "Diffk II.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public int diffPossible(final int[] A, int B) {\n        Set<Integer> set=new HashSet<>();\n        for(int i:A){\n            if(set.contains(i-B) || set.contains(B+i))return 1;\n            set.add(i);\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Diffk.java",
    "content": "public class Solution {\n    public int diffPossible(int[] a, int k) {\n        int i=0;\n        int j=1;\n        while(i<j && j<a.length){\n            if(a[j]-a[i]==k)return 1;\n            else if(a[j]-a[i]<k){\n                j++;\n            }else if(a[j]-a[i]>k){\n                if(i==j-1){\n                    j++;\n                }\n                i++;\n            }\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Digital Root.java",
    "content": "public class Solution {\n    public int solve(int A) {\n        while(A>9){\n            int temp=0;\n            while(A!=0){\n                temp+=(A%10);\n                A/=10;\n            }\n            A=temp;\n        }\n        return A;\n    }\n}\n"
  },
  {
    "path": "Dijkstra’s_Algorithm_Shortest_distance.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nvoid dij(vector<pair<int, int>> adj[], int n, int src)\n{\n  vector<int> vis(n, 0);\n  priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n  vector<int> dis(n, INT_MAX);\n\n  pq.push({0, src});\n  dis[src] = 0;\n  while (!pq.empty())\n  {\n    int dist = pq.top().first;\n    int prev = pq.top().second;\n    pq.pop();\n    vector<pair<int, int>>::iterator it;\n    for (it = adj[prev].begin(); it != adj[prev].end(); it++)\n    {\n      int next = it->first;\n      int nextdist=it->second;\n      if (dis[next] > dis[prev] + nextdist)\n      {\n        dis[next] = dis[prev] + nextdist;\n        pq.push({dis[next],next});\n      }\n    }\n  }\n  for (int i = 0; i < dis.size(); i++)\n  {\n    dis[i]==INT_MAX?cout<<\"INF\"<<\" \":cout<<dis[i]<<\" \";\n  }\n  \n}\n\nint main()\n{\n  int m, n;\n  cin >> m >> n;\n  vector<pair<int, int>> adj[m];\n  for (int i = 0; i < n; i++)\n  {\n    int x, y, w;\n    cin >> x >> y >> w;\n    adj[x].push_back({y, w});\n  }\n  int src;\n  cin >> src;\n  dij(adj, m, src);\n}\n"
  },
  {
    "path": "Distance from the Source (Bellman-Ford Algorithm).java",
    "content": "\n\nclass Solution\n{\n    static int[] bellman_ford(int V, ArrayList<ArrayList<Integer>> adj, int S)\n    {\n        // Write your code here\n        int[]distance=new int[V];\n        Arrays.fill(distance,100000000);\n        distance[S]=0;\n        \n        for(int i=1;i<V;i++){\n            for(ArrayList<Integer> a:adj){\n                int src=a.get(0);\n                int des=a.get(1);\n                int weight=a.get(2);\n                if(distance[src] + weight < distance[des]){\n                    distance[des]=distance[src] + weight;\n                }\n            }\n        }\n        return distance;\n    }\n}\n"
  },
  {
    "path": "Distinct Numbers in Window.java",
    "content": "public class Solution {\n    public ArrayList<Integer> dNums(ArrayList<Integer> a, int B) {\n        ArrayList<Integer> ans=new ArrayList<>();\n        int n=a.size();\n        if(B>n)return ans;\n        \n        Map<Integer,Integer> map=new HashMap<>();\n        for(int i=0;i<B;i++){\n            map.put(a.get(i),map.getOrDefault(a.get(i),0)+1);\n        }\n        ans.add(map.size());\n        for(int i=1;i<=n-B;i++){\n            int prev=a.get(i-1);\n            map.put(prev,map.get(prev)-1);\n            if(map.get(prev)==0)map.remove(prev);\n            int last=a.get(i+B-1);\n            map.put(last,map.getOrDefault(last,0)+1);\n            ans.add(map.size());\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Distinct Subsequences.java",
    "content": "public class Solution {\n    public int numDistinct(String s1, String s2) {\n        char[]A=s1.toCharArray();\n        char[]B=s2.toCharArray();\n        int n = A.length, m = B.length;\n        int [][]dp=new int[n+1][m+1];\n        for(int i = 0 ; i <= n ; i++)\n            dp[i][0]=1;\n        for(int i = 1 ; i <= n ; i++){\n            for(int j = 1 ; j <= m ; j++){\n                if(A[i-1] == B[j-1])\n                    dp[i][j] = dp[i-1][j-1]+dp[i-1][j];\n                else\n                    dp[i][j] = dp[i-1][j];\n            }\n        }\n        return dp[n][m];\n    }\n}\n"
  },
  {
    "path": "Distinct palindromic substrings.java",
    "content": "class Solution { \n    int palindromeSubStrs(String s) { \n        // code here      \n        Set<String> set=new HashSet<>();\n        int n=s.length();\n        for(int i=0;i<n;i++){\n            //even palindromes\n            String temp=\"\";\n            int left=i;\n            int right=i+1;\n            while(left>=0 && right<n && s.charAt(left)==s.charAt(right)){\n                temp=s.charAt(left)+temp+s.charAt(right);\n                set.add(temp);\n                left--;\n                right++;\n            }\n            \n            //odd palindromes\n            temp=s.charAt(i)+\"\";\n            set.add(temp);\n            left=i-1;\n            right=i+1;\n            while(left>=0 && right<n && s.charAt(left)==s.charAt(right)){\n                temp=s.charAt(left)+temp+s.charAt(right);\n                set.add(temp);\n                left--;\n                right++;\n            }\n        }\n        return set.size();\n    }\n} \n"
  },
  {
    "path": "Distribute in Circle!.java",
    "content": "public class Solution {\n    public int solve(int A, int B, int C) {\n        A=A%B;\n        C=C%B;\n        while(A!=0){\n            A--;\n            C++;\n        }\n        return C%B-1;\n    }\n}\n"
  },
  {
    "path": "Divisible by 60.java",
    "content": "public class Solution {\n    public int divisibleBy60(ArrayList<Integer> A) {\n        int sum=0;\n        if(A.size()==1 && A.get(0)==0) return 1;\n        boolean zero=false;\n        boolean even=false;\n        for(int i:A){\n            if(i==0)zero=true;\n            if(i%2==0 && i!=0)even=true;\n            sum+=i;\n        }\n        if(sum%3==0 && zero && even)return 1;\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Dungeon Princess.java",
    "content": "public class Solution {\n    public int calculateMinimumHP(int[][] A) {\n        \n        int m=A.length;\n        int n=A[0].length;\n        \n        A[m-1][n-1]=Math.max(1,-1*A[m-1][n-1]+1);\n        \n        for(int i=m-1;i>=0;i--){\n            for(int j=n-1;j>=0;j--){\n                \n                if(i==m-1 && j==n-1){\n                    continue;\n                }else if(i==m-1){\n                    A[i][j]=Math.max(1,A[i][j+1]-A[i][j]);\n                }else if(j==n-1){\n                    A[i][j]=Math.max(1,A[i+1][j]-A[i][j]);\n                }else{\n                    A[i][j]=Math.max(1,Math.min(A[i+1][j],A[i][j+1])-A[i][j]);\n                }\n                \n            }\n        }\n        \n        return A[0][0];\n    }\n}\n\n"
  },
  {
    "path": "Earthquake and the Paint Shop - GFG/README.md",
    "content": "# Earthquake and the Paint Shop\n## Easy\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Geek's&nbsp;Paint Shop is one of the famous shop in Geekland,&nbsp;but 2014 Earthquake caused disarrangement of the items in his shop. Each item in his shop is a 40-digit alpha numeric code .<br>\nNow Chunky wants to retain the reputation of his shop, for that he has to arrange all the distinct items in lexicographical order.<br>\nYour task is to arrange the all the distinct items in lexicographical ascending order and print them along with their count.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 3\nA[] =\n[\"2234597891 zmxvvxbcij 8800654113 jihgfedcba\",\n\"1234567891 abcdefghij 9876543219 jihgfedcba\",\n\"2234597891 zmxvvxbcij 8800654113 jihgfedcba\"]\n<strong>Output:</strong>\n1234567891 abcdefghij 9876543219 jihgfedcba 1\n2234597891 zmxvvxbcij 8800654113 jihgfedcba 2\n<strong>Explanation:</strong>\nWe have 3 items (40 digit alphanumeric codes) \nhere. We arrange the items based on the \nlexicographical order of their alpha-numeric \ncode. Distinct items are printed only once. \nThe count of the items describes how many \nsuch items are there, so items that appear \nmore than once have their count greater than 1.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 2\nA[] =\n[\"3122049353 onafrnbhtr 9822827304 yzfhdgzcvx\", \n\"2992299540 lpvkgykmlk 6946169466 vdqwvywwgg\", \n<strong>Output:</strong>\n2992299540 lpvkgykmlk 6946169466 vdqwvywwgg  1\n3122049353 onafrnbhtr 9822827304 yzfhdgzcvx  1\n<strong>Explanation:</strong>\nOut of the 2 items here no one is repeated.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>sortedStrings()</strong> which takes an integer <strong>N</strong> and an array of strings <strong>A[ ]</strong> and returns the array in sorted order along with the frequency&nbsp;of each distinct string.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>O(NlogN)<br>\n<strong>Expected Auxillary Space:</strong>O(N)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10000</span></p>\n</div>"
  },
  {
    "path": "Earthquake and the Paint Shop - GFG/earthquake-and-the-paint-shop.java",
    "content": "//{ Driver Code Starts\n// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int N = Integer.parseInt(read.readLine());\n            String s[] = new String[N];\n            for (int i = 0; i < N; i++) s[i] = read.readLine();\n            Solution ob = new Solution();\n            alphanumeric ans[] = ob.sortedStrings(N, s);\n            for (int i = 0; i < ans.length; i++)\n                System.out.println(ans[i].name + \" \" + ans[i].count);\n        }\n    }\n}\n// } Driver Code Ends\n\n\n// User function Template for Java\n\nclass alphanumeric {\n    public String name;\n    public int count;\n    alphanumeric(String name, int count) {\n        this.name = name;\n        this.count = count;\n    }\n};\nclass Solution {\n    alphanumeric[] sortedStrings(int N, String A[]) {\n        TreeMap<String,Integer> mp = new TreeMap<>();\n        for(String s: A){\n            mp.put(s,mp.getOrDefault(s,0)+1);\n        }\n        int k = mp.size();\n        alphanumeric[] ans = new alphanumeric[k];\n        int t = 0;\n        for(String s:mp.keySet()){\n            ans[t++] = new alphanumeric(s,mp.get(s));\n        }\n        return ans;\n    }\n};"
  },
  {
    "path": "Egg Dropping Puzzle.java",
    "content": "class Solution \n{\n    //Function to find minimum number of attempts needed in \n    //order to find the critical floor.\n    static int eggDrop(int n, int k) \n\t{\n\t    // Your code here\n\t    int[][]dp=new int[n+1][k+1];\n\t    \n\t    //eggs are 1\n\t    for(int j=1;j<=k;j++){\n\t        dp[1][j]=j;\n\t    }\n\t    \n\t    //f;oors are 1\n\t    for(int i=0;i<=n;i++){\n\t        dp[i][1]=1;\n\t    }\n\t    \n\t    for(int i=2;i<=n;i++){\n\t        for(int j=2;j<=k;j++){\n\t            int res=j;\n\t            \n\t            for(int t=1;t<=j;t++){\n\t                //break\n\t                int temp1=1+ dp[i-1][t-1];\n\t                //not break\n\t                int temp2=1+ dp[i][j-t];\n\t                //worst case  \n\t                int ans=Math.max(temp1,temp2);\n\t                res=Math.min(res,ans);\n\t            }\n\t            dp[i][j]=res;\n\t        }\n\t    }\n\t    \n\t    return dp[n][k];\n\t    \n\t}\n}\n"
  },
  {
    "path": "Elements in the Range.java",
    "content": "class Solution\n{\n    boolean check_elements(int arr[], int n, int A, int B)\n    {\n        if(B-A>=n)return false;\n        for(int i=0;i<n;i++){\n            if(Math.abs(arr[i])>=A && Math.abs(arr[i])<=B){\n                int ind=Math.abs(arr[i])-A;\n                if(arr[ind]>0)arr[ind]*=-1;\n            }\n        }\n        \n        for(int i=0;i<=B-A;i++){\n            if(arr[i]>0)return false;\n        }\n        return true;\n        \n    }\n}\n"
  },
  {
    "path": "Equivalent Sub-Arrays - GFG/README.md",
    "content": "# Equivalent Sub-Arrays\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array arr[] of n integers. Count the total number of sub-array having total distinct elements same as that of total distinct elements of the original array.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N=5\narr[] = {2, 1, 3, 2, 3} \n<strong>Output:</strong> 5\n<strong>Explanation</strong>:\nTotal distinct elements in array is 3\nTotal sub-arrays that satisfy the condition\nare:\nSubarray from index 0 to 2\nSubarray from index 0 to 3\nSubarray from index 0 to 4\nSubarray from index 1 to 3\nSubarray from index 1 to 4</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N=5\narr[] = {2, 4, 4, 2, 4} \n<strong>Output:</strong> 9</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nSince, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function <strong>countDistinctSubarray</strong>() that takes <strong>array arr and integer n&nbsp;</strong> as parameters and returns the desired result.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N).<br>\n<strong>Expected Auxiliary Space:</strong> O(N).</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>4</sup></span></p>\n\n<p>&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Equivalent Sub-Arrays - GFG/equivalent-sub-arrays.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n\n//Initial Template for Java\n\n\nimport java.io.*;\nimport java.util.*;\n\n\n // } Driver Code Ends\n//User function Template for Java\n\n\nclass Solution\n{ \n    // Method to calculate distinct sub-array \n    static int countDistinctSubarray(int arr[], int n) \n    { \n        int res = 0;\n        HashSet<Integer> set = new HashSet<>();\n        HashMap<Integer,Integer> map = new HashMap<>();\n        \n        for(int i : arr)set.add(i);\n            \n        for(int j = 0,i = 0;i < arr.length;i++){\n            map.put(arr[i],map.getOrDefault(arr[i],0) + 1);\n            \n            if(map.size() == set.size())\n                res = res + (arr.length - i);\n                \n            while(map.size() >= set.size() && j <= i){\n                map.put(arr[j],map.get(arr[j]) - 1);\n                \n                if(map.get(arr[j]) <= 0)\n                    map.remove(arr[j]);\n                    \n                if(map.size() == set.size())\n                    res = res + (arr.length - i);\n                    \n                j++;\n            }\n        }\n        \n        return res;\n    }\n}\n\n// { Driver Code Starts.\n\n// Driver class\nclass Array {\n    \n    // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t    int n=Integer.parseInt(br.readLine());\n\t\t    String line1 = br.readLine();\n\t\t    String[] a1 = line1.trim().split(\"\\\\s+\");\n\t\t    int a[]=new int[n];\n\t\t    for(int i=0;i<n;i++)\n\t\t    {\n\t\t        a[i]=Integer.parseInt(a1[i]);\n\t\t    }\n\t\t    Solution ob=new Solution();\n\t\t    int ans=ob.countDistinctSubarray(a,n);\n\t\t    System.out.println(ans);\n\t\t    \n\t\t}\n\t}\n}\n  // } Driver Code Ends"
  },
  {
    "path": "Escape the Forbidden Forest.java",
    "content": "class Sol\n{\n    public static int build_bridges(String str1 , String str2)\n    {\n        int n1 = str1.length(), n2 = str2.length();\n        int[][] dp = new int[n1+1][n2+1];\n        for(int i=0; i<=n1; i++){\n            for(int j=0; j<=n2; j++){\n                if(i==0 || j==0)\n                    dp[i][j] = 0;\n                else 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-1][j],dp[i][j-1]);\n            }\n        }\n        return dp[n1][n2];\n    }\n}\n"
  },
  {
    "path": "Eulerian Path in an Undirected Graph - GFG/README.md",
    "content": "# Eulerian Path in an Undirected Graph\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an adjacency matrix representation of an unweighted undirected graph named&nbsp;<strong>graph</strong>, which has <strong>N</strong> vertices. You have to find out if there is an <a href=\"https://en.wikipedia.org/wiki/Eulerian_path\" target=\"_blank\">eulerian path</a> present in the graph&nbsp;or not.<br>\n<strong>Note:</strong> The graph consists of a single component</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> N = 5\ngraph = {{0, 1, 0, 0, 1}, \n&nbsp;        {1, 0, 1, 1, 0}, \n&nbsp;        {0, 1, 0, 1, 0}, \n&nbsp;        {0, 1, 1, 0, 0}, \n&nbsp;        {1, 0, 0, 0, 0}}\n<strong>Output:</strong> 1\n<strong>Explaination:</strong> There is an eulerian path. \nThe path is 5-&gt;1-&gt;2-&gt;4-&gt;3-&gt;2.</span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> N = 5\ngraph = {{0, 1, 0, 1, 1}, \n&nbsp;        {1, 0, 1, 0, 1}, \n&nbsp;        {0, 1, 0, 1, 1}, \n&nbsp;        {1, 1, 1, 0, 0}, \n&nbsp;        {1, 0, 1, 0, 0}}\n<strong>Output:</strong> 0\n<strong>Explaination:</strong> There is no eulerian path in \nthe graph.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>eulerPath()</strong> which takes N and graph as input parameters and returns 1 if there is an eulerian path. Otherwise returns 0.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N<sup>2</sup>)<br>\n<strong>Expected Auxiliary Space:</strong> O(N<sup>2</sup>)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 50&nbsp;</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Eulerian Path in an Undirected Graph - GFG/eulerian-path-in-an-undirected-graph.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            int N = Integer.parseInt(in.readLine());\n            int graph[][] = new int[N][N];\n            for(int i = 0;i < N;i++){\n                String a[] = in.readLine().trim().split(\"\\\\s+\");\n                for(int j = 0;j < N;j++)\n                    graph[i][j] = Integer.parseInt(a[j]);\n            }\n            \n            Solution ob = new Solution();\n            System.out.println(ob.eulerPath(N, graph));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static int eulerPath(int n, int arr[][]){\n        // code here\n        int count = 0;\n        for(int ar[]: arr){\n            int sum = 0;\n            for(int i: ar){\n                sum+=i;\n            }\n            if(sum%2==0)count++;\n            if(count==(n-2))return 1;\n        }\n        return 0;\n    }\n}"
  },
  {
    "path": "Evaluate Expression To True.java",
    "content": "public class Solution {\n\n    int [][] DT = new int[151][151];\n    int [][] DF = new int[151][151];\n    int mod = 1003;\n\n    public int cnttrue(String A) {\n        for (int[] row: DT) Arrays.fill(row, -1);\n        for (int[] row: DF) Arrays.fill(row, -1);\n        return solveTrue(A, 0, A.length()-1)%1003;\n    }\n\n    int solveTrue(String A, int i, int j){\n        if(i>j) return 0;\n        if(i==j){\n            return A.charAt(i)=='T' ? 1 : 0;\n        } \n        if(DT[i][j] != -1){\n            return DT[i][j];\n        }\n        int count = 0;\n        for(int k=i; k<j; k=k+2){\n            \n            char operator = A.charAt(k+1);\n\n            int leftFalse = DF[i][k] != -1 ? DF[i][k] : solveFalse(A, i, k);\n            int rightFalse = DF[k+2][j] != -1 ? DF[k+2][j] : solveFalse(A, k+2, j);\n\n            int leftTrue = DT[i][k] != -1 ? DT[i][k] : solveTrue(A, i, k);\n            int rightTrue = DT[k+2][j] != -1 ? DT[k+2][j] : solveTrue(A, k+2, j);\n\n            if(operator == '&'){\n                count += leftTrue * rightTrue % mod;  \n            } else if(operator == '^'){\n                count += leftTrue * rightFalse % mod;\n                count += leftFalse * rightTrue % mod;\n            } else if(operator == '|'){\n                count += leftTrue * rightTrue % mod;\n                count += leftTrue * rightFalse % mod;\n                count += leftFalse * rightTrue % mod;\n            }\n        }\n        DT[i][j] = count;\n        return count;\n    }\n\n    int solveFalse(String A, int i, int j){\n        if(i>j) return 0;\n        if(i==j){\n            return A.charAt(i)=='F' ? 1 : 0;\n        } \n        if(DF[i][j] != -1){\n            return DF[i][j];\n        }\n        int count = 0;\n\n        for(int k=i; k<j; k=k+2){\n            \n            char operator = A.charAt(k+1);\n\n            int leftFalse = DF[i][k] != -1 ? DF[i][k] : solveFalse(A, i, k);\n            int rightFalse = DF[k+2][j] != -1 ? DF[k+2][j] : solveFalse(A, k+2, j);\n\n            int leftTrue = DT[i][k] != -1 ? DT[i][k] : solveTrue(A, i, k);\n            int rightTrue = DT[k+2][j] != -1 ? DT[k+2][j] : solveTrue(A, k+2, j);\n\n            if(operator == '|'){\n                count += leftFalse * rightFalse % mod;  \n            } else if(operator == '^'){\n                count += leftTrue * rightTrue % mod;\n                count += leftFalse * rightFalse % mod;\n            } else if(operator == '&'){\n                count += leftFalse * rightFalse % mod;\n                count += leftTrue * rightFalse % mod;\n                count += leftFalse * rightTrue % mod;\n            }\n        }\n        DF[i][j] = count;\n        return count;\n    }\n}\n\n"
  },
  {
    "path": "Evaluate Expression(Postfix).java",
    "content": "public class Solution {\n    public int evalRPN(String[] A) {\n        Deque<Integer> stack=new ArrayDeque<>();\n        int i=0;\n        while(i<A.length){\n            if(A[i].equals(\"+\") || A[i].equals(\"/\")|| A[i].equals(\"-\")|| A[i].equals(\"*\")){\n                int first=stack.pop();\n                int second=stack.pop();\n                if(A[i].equals(\"+\")){\n                    stack.push(first+second);\n                }else if( A[i].equals(\"/\")){\n                    stack.push(second/first);\n                }else if( A[i].equals(\"-\")){\n                    stack.push(second-first);\n                }else{\n                    stack.push(second*first);\n                }\n            }else{\n                stack.push(Integer.parseInt(A[i]));\n            }\n            i++;\n        }\n        return stack.pop();\n    }\n}\n"
  },
  {
    "path": "Even and Odd - GFG/README.md",
    "content": "# Even and Odd\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array <strong>arr[] </strong>of size <strong>N</strong> containing equal number of odd and even numbers. Arrange the numbers in such a way that all the even numbers get the even index and odd numbers get the odd index.<br>\n<strong>Note: </strong>There are multiple possible solutions, Print any one of them. Also, 0-based indexing is considered.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 6\narr[] = {3, 6, 12, 1, 5, 8}\n<strong>Output:</strong></span>\n<span style=\"font-size:18px\">1\n<strong>Explanation:\n</strong>6 3 12 1 8 5 is a possible solution.\nThe output will always be 1 if your\nrearrangement is correct.</span>\n</pre>\n\n<div><span style=\"font-size:18px\"><strong>Example 2:</strong></span></div>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 4\narr[] = {1, 2, 3, 4}\n<strong>Output :</strong>\n1</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>reArrange()</strong>&nbsp;which takes an integer N and an array arr of size N as input and reArranges the array in Place without any extra space.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n1 ≤ arr[i] ≤ 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Even and Odd - GFG/even-and-odd.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int N = Integer.parseInt(read.readLine());\n            \n            String S[] = read.readLine().split(\" \");\n            int[] arr = new int[N];\n            \n            for(int i=0; i<N; i++)\n                arr[i] = Integer.parseInt(S[i]);\n\n            Solution ob = new Solution();\n            ob.reArrange(arr,N);\n            \n            System.out.println(check(arr,N));\n        }\n    }\n    static int check(int arr[], int n)\n    {\n        int flag = 1;\n        int c=0, d=0;\n        for(int i=0; i<n; i++)\n        {\n            if(i%2==0)\n            {\n                if(arr[i]%2==1)\n                {\n                    flag = 0;\n                    break;\n                }\n                else\n                    c++;\n            }\n            else\n            {\n                if(arr[i]%2==0)\n                {\n                    flag = 0;\n                    break;\n                }\n                else\n                    d++;\n            }\n        }\n        if(c!=d)\n            flag = 0;\n                \n        return flag;\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    static void reArrange(int arr[], int N) {\n        int i=0,j=1;\n        while(i<N && j<N){\n            if((arr[i]&1)==0)\n                i+=2;\n            else{\n                if(arr[j]%2!=0)\n                    j=j+2;\n                else{\n                   arr[i]=arr[i]^arr[j];\n                   arr[j]=arr[i]^arr[j];\n                   arr[i]=arr[i]^arr[j];\n                }\n            }\n        }\n    }\n};"
  },
  {
    "path": "Exactly one swap.java",
    "content": "class Solution \n{ \n    long countStrings(String s)\n    { \n        // code here\n        int n=s.length();\n        int freq[]=new int[26];\n        for(char c:s.toCharArray()){\n            freq[c-'a']++;\n        }\n        long ans=0;\n        for(char c:s.toCharArray()){\n            ans+=n-freq[c-'a'];\n        }\n        ans/=2;\n        for(int i=0;i<26;i++){\n            if(freq[i]>=2){\n                ans++;\n                break;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Excel Column Title.java",
    "content": "public class Solution {\n    public String convertToTitle(int n) {\n        String ans=\"\";\n        while(n!=0){\n            n--;\n            int rem=n%26;\n            ans=(char)(rem+65)+ans;\n            n=n/26;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Excel Sheet Column Number.java",
    "content": "class Solution {\n    public int titleToNumber(String columnTitle) {\n        int ans = 0;\n        for(char c : columnTitle.toCharArray()){\n            ans = ans * 26 + (int)(c-'A')+ 1;\n        }\n        return ans;\n    }\n}\n\n//===========================================================\n\nclass Solution {\n    public int titleToNumber(String columnTitle) {\n        if(columnTitle == null || columnTitle.length() == 0){\n            return 0;\n        }\n        int multipier = 0, result = 0;\n        for(int i = columnTitle.length() -1 ; i >= 0 ; i-- ){\n            int val = columnTitle.charAt(i) - 'A'+1;\n            result = (int) (val * Math.pow(26,multipier)) + result;\n            multipier += 1;\n            //System.out.println(val+\"  result : \"+result+\"  multipier :\"+multipier);\n        }\n        return result;\n    }\n}\n"
  },
  {
    "path": "Exceptionally odd.java",
    "content": "\nclass Solution {\n    int getOddOccurrence(int[] arr, int n) {\n        // code here\n        int ans=0;\n        for(int i:arr)ans=ans^i;\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Fact Digit Sum/Fact-Digit-Sum.cpp",
    "content": "class Solution{\n\tpublic:\n\tlong factorial(long n){\n\t    if(n==0) return 1;\n\t    return n*factorial(n-1);\n\t}\n\tvector<int> FactDigit(int N)\n\t{\n\t    // Code here\n\t    vector<int> ans;\n\t    while(N != 0){\n\t        for(int i=9;i>=0;i--){\n\t            if(N >= factorial(i)){\n\t                ans.push_back(i);\n\t                N -= factorial(i);\n\t                break;\n\t            }\n\t        }\n\t    }\n\t    sort(ans.begin(), ans.end());\n\t    return ans;\n\t}\n};\n"
  },
  {
    "path": "Fact Digit Sum.cpp",
    "content": "class Solution{\n\tpublic:\n\tvector<int> FactDigit(int N)\n\t{\n\t    // Code here\n\t    vector<int> fact(10,1);\n\t    \n\t    for(int i=1; i<10; i++)\n\t    fact[i] = (fact[i-1]*i);\n\t    \n\t    vector<int> ans;\n\t    \n\t    int f = 9;\n\t    \n\t    while(N)\n\t    {\n\t        if(fact[f] <= N)\n\t        {\n\t            N -= fact[f];\n\t            ans.push_back(f);\n\t        }\n\t        else\n\t        f--;\n\t    }\n\t    \n\t    sort(ans.begin(), ans.end());\n\t   \n\t    return ans;\n\t}\n};\n"
  },
  {
    "path": "Fact Digit Sum.java",
    "content": "class Solution\n{\n    ArrayList<Integer> FactDigit(int N)\n    {\n        // code here\n        ArrayList<Integer> ans=new ArrayList<>();\n        int[]fact=new int[10];\n        fact[0]=1;\n        for(int i=1;i<10;i++){\n            fact[i]=i*fact[i-1];\n        }\n        \n        for(int i=9;i>=1;i--){\n            while(N>=fact[i]){\n                N-=fact[i];\n                ans.add(i);\n            }\n        }\n        Collections.reverse(ans);\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Farthest number - GFG/README.md",
    "content": "# Farthest number\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array <strong>A</strong><strong>rr[]</strong>&nbsp;of size&nbsp;<strong>N</strong>. For every element in the array, the task is to find the index of the farthest element in the array to the right which is smaller than the current element. If no such number exists then print&nbsp;<strong>-1</strong>.</span><br>\n<strong><span style=\"font-size:18px\">Note: </span></strong><span style=\"font-size:18px\">0 based indexing.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> </span>\n<span style=\"font-size:18px\">N=5</span>\n<span style=\"font-size:18px\">Arr[] = {3, 1, 5, 2, 4}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong> </span>\n<span style=\"font-size:18px\">3 -1 4 -1 -1</span>\n<strong><span style=\"font-size:18px\">Explanation:</span></strong>\n<span style=\"font-size:18px\">Arr[3] is the farthest smallest element\nto the right of Arr[0].\nArr[4] is the farthest smallest element\nto the right of Arr[2].\nAnd for the rest of the elements, there is\nno smaller element to their right.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> </span>\n<span style=\"font-size:18px\">N=5</span>\n<span style=\"font-size:18px\">Arr[] = {1, 2, 3, 4, 0}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong> </span>\n<span style=\"font-size:18px\">4 4 4 4 -1</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;</strong></span><br>\n<span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function<strong> farNumber()</strong>&nbsp;which takes the N&nbsp;(number of elements in Array Arr) ,Arr[], and returns the array&nbsp;of farthest element to the right for&nbsp;every&nbsp;element of the array.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N*logN)<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span></p>\n\n<p><br>\n<strong><span style=\"font-size:18px\">Constraints:</span></strong><br>\n<span style=\"font-size:18px\">1 </span> <span style=\"font-size:18px\">≤ </span> <span style=\"font-size:18px\">N</span> <span style=\"font-size:18px\">≤ </span> <span style=\"font-size:18px\">1e5<br>\n0</span> <span style=\"font-size:18px\">≤ </span> <span style=\"font-size:18px\">Arr[i]</span>&nbsp;<span style=\"font-size:18px\">≤ </span> <span style=\"font-size:18px\">1e9&nbsp;</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Farthest number - GFG/farthest-number.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*; \n\nclass GFG{\n    public static void main(String args[]) throws IOException { \n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); \n        PrintWriter out = new PrintWriter(System.out);\n        \n        int t = Integer.parseInt(br.readLine()); \n\n        while(t > 0){\n        \tint N = Integer.parseInt(br.readLine()); \n        \tint[] Arr = new int[N];\n        \tString line = br.readLine(); \n            String[] strs = line.trim().split(\"\\\\s+\"); \n        \tfor(int i=0; i<N; i++)\n        \t{\n        \t\tArr[i] = Integer.parseInt(strs[i]); \n        \t}\n        \t\n\n            Solution ob = new Solution();\n\t\t\tint[] ans = ob.farNumber(N,Arr);\n  \n            for(int i=0; i<ans.length; i++)\n                out.print(ans[i] + \" \");\n            out.println();\n\n            t--;\n        }\n        out.flush();\n    } \n} \n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution \n{ \n    static int[] farNumber(int N, int a[]){    \n\t    int[]ans=new int[N];\n\t    ans[N-1]=-1;\n\t    for(int i=0;i<a.length-1;i++){\n\t        int ele=a[i];\n\t        int j=N-1;\n\t        while(j>i){\n\t            if(a[j]<ele){\n\t                ans[i]=j;\n\t                break;\n\t            }\n\t            j--;\n\t        }\n\t        if(j==i)ans[i]=-1;\n\t    }\n\t    return ans;\n\t}\n} "
  },
  {
    "path": "File Search.java",
    "content": "public class Solution {\n    \n    public int breakRecords(int A, int[][] B) {\n        UnionFind uf = new UnionFind(A);\n        \n        for (int[] pair : B)\n            uf.union(pair[0]-1, pair[1]-1);\n        \n        return uf.getSets();\n    }\n}\n\nclass UnionFind {\n    \n    private int[] root;\n    private int[] rank;\n    private int size;\n    \n    public UnionFind(int size) {\n        this.root = new int[size];\n        this.rank = new int[size];\n        this.size = size;\n        \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        if (root[x] == x)\n            return x;\n        return root[x] = find(root[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            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[rootY]++;\n            }\n            size--;\n        }\n    }\n    \n    public int getSets() {\n        return size;\n    }\n}\n"
  },
  {
    "path": "Fill the Tank - GFG/README.md",
    "content": "# Fill the Tank\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">In a city,&nbsp;<strong>N</strong> water tanks are connected by pipeline(As a tree) where the <strong>ith</strong> tank has a capacity <strong>cap[i]</strong>. The <strong>ith </strong>element of the given <strong>Edge</strong> array of length <strong>N-1</strong> represents that there is a pipeline between <strong>Edge[i][0]</strong> and <strong>Edge[i][1]</strong> tank.&nbsp;Since people working at the city corporation are lazy they usually select one of the tank and pour complete amount of water into it, <strong>when the tank is filled, the excess water evenly flows to the connected tanks.</strong> The head of city corporation has instructed to <strong>pour minimum amount of water into the selected tank so that all other tank is filled</strong>. As the labours of the corporation are not intelligent enough to figure out the minimum amount of water required to fill all the tanks they have asked your help. Also Maximum amount of water available with city corporation is 10<sup>18</sup>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>NOTE</strong>: If the tank if full, the water flows to all of its connected tanks except the tank from which the water had come to it. i.e, to all tanks except the source for that particular tank. If it has no option to flow the water is considered to be wasted.<strong> S</strong> is the source tank.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>:\nN = 4 and S = 1\nEdges = [[1, 2], [1, 3], [2, 4]]\nCap = [1, 1, 1, 1]\n<strong>Output:</strong>&nbsp;5\n<strong>Explanation</strong>:\nInitially 5 unit of water is poured into \ntank 1. 2 unit of it flows to tank 2 <strong>and</strong> \n2 unit of it flows into tank 3. From 2 \nunit of water in tank 2, 1 unit flows into \ntank 4 <strong>and</strong> 1 unit from tank 3 is wasted.\n<img alt=\"\" src=\"https://contribute.geeksforgeeks.org/wp-content/uploads/fill-the-tank.jpg\" style=\"height:500px; width:667px\" class=\"img-responsive\">\n\n</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 3 and S = 2\nEdges = [[1, 2], [2, 3]]\nCap = [1, 1, 1]\n<strong>Output: </strong>3\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>minimum_amount()</strong>&nbsp;which takes an integer <strong>N</strong>, an&nbsp;integer&nbsp;<strong>S</strong>, 2-d array <strong>Edges</strong>, and an array <strong>Cap</strong>&nbsp;of length&nbsp;N as input parameters and returns the minimum amount of water required to fill all the tanks. If it is not possible to fill all the tanks print -1.<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(N*log(S))<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ n ≤ 100000<br>\n1&nbsp;≤ s,u,v ≤ n<br>\n1 ≤ capacity of each tank ≤ 1000000007</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Fill the Tank - GFG/fill-the-tank.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        \n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n            int N = Integer.parseInt(input_line[0]);\n            int S = Integer.parseInt(input_line[1]);\n            String input_line1[] = read.readLine().trim().split(\"\\\\s+\");\n            int cap[] = new int[N];\n            for(int i=0;i<N;i++){\n                cap[i] = Integer.parseInt(input_line1[i]);\n            }\n            int Edges[][] = new int[N-1][2];\n            for(int i=0;i<N-1;i++){\n                String input_line2[] = read.readLine().trim().split(\"\\\\s+\");\n                Edges[i][0] = Integer.parseInt(input_line2[0]);\n                Edges[i][1] = Integer.parseInt(input_line2[1]);\n            }\n            Solution ob = new Solution();\n            long ans = ob.minimum_amount(Edges, N, S, cap);\n            System.out.println(ans);\n        }\n    }\n}\n\n\n// } Driver Code Ends\n\nclass Solution\n{\n    long minimum_amount(int [][]Edges, int N, int S, int []cap)\n    {\n        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n        for(int i=0; i<=N; i++){\n            adj.add(new ArrayList<>());\n        }\n        for(int i=0; i<Edges.length; i++){\n            adj.get(Edges[i][0]).add(Edges[i][1]);\n            adj.get(Edges[i][1]).add(Edges[i][0]);\n        }\n        boolean[] visited = new boolean[N+1];\n        long ans = ans(adj,S,cap,visited);\n        return visited[0] ? -1 : ans;\n    }\n    long ans(ArrayList<ArrayList<Integer>> adj, int s, int[] cap, boolean[] visited){\n        long res = -1;\n        visited[s] = true;\n        int sz = 0;\n        for(int x: adj.get(s)){\n            if(visited[x])continue;\n            sz++;\n            long cur = ans(adj,x,cap,visited);\n            if(cur>10E17) visited[0] = true;\n            res = Math.max(res,cur);\n        }\n        long curAns = res*sz + cap[s-1];\n        if(curAns>10E17) visited[0] = true;\n        return curAns;\n    }\n}\n"
  },
  {
    "path": "Filling Bucket - GFG/README.md",
    "content": "# Filling Bucket\n## Medium\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Given a Bucket&nbsp;having a capacity of&nbsp;<strong>N</strong>&nbsp;litres and the task is&nbsp;to determine that by how many ways you can fill it using two bottles&nbsp;of capacity of&nbsp;<strong>1 Litre and 2 Litre only</strong>. Find the answer modulo 10<sup>8</sup>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\n3\n<strong>Output:</strong>\n3 </span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\nLet O denote filling by 1 litre bottle and\nT denote filling by 2 litre bottle.\nSo for N = 3, we have :\n{OOO,TO,OT}. Thus there are 3 total ways.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\n4\n<strong>Output:</strong>\n5 </span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\nLet O denote filling by 1 litre bottle and\nT denote filling by 2 litre bottle.\nSo for N = 4, we have :\n{TT,OOOO,TOO,OTO,OOT} thus there are 5 total ways.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>fillingBucket()</strong> which takes an Integer N as input and returns the number of total ways possible.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N)<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 &lt;= N &lt;= 10<sup>5</sup></span></p>\n</div>"
  },
  {
    "path": "Filling Bucket - GFG/filling-bucket.java",
    "content": "//{ Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int N = Integer.parseInt(read.readLine());\n\n            Solution ob = new Solution();\n            System.out.println(ob.fillingBucket(N));\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    static int fillingBucket(int N) {\n        // code here\n        if(N==1)return 1;\n        int prev=2;\n        int secPrev=1;\n        int mod=100000000;\n        for(int i=0;i<N-2;i++){\n            int currAns=(prev%mod+secPrev%mod)%mod;\n            secPrev=prev;\n            prev=currAns;\n        }\n        return prev;\n    }\n};"
  },
  {
    "path": "Find All Anagrams in a String.java",
    "content": "class Solution {\n    public List<Integer> findAnagrams(String s, String p) {\n        int ns = s.length(), np = p.length();\n        List<Integer> results = new ArrayList<>();\n        int[] charMap = new int[26];\n        \n        for (char c:p.toCharArray()) {\n            charMap[c - 'a']++;\n        }\n        \n        for (int i = 0; i < ns; i++) {\n            char c = s.charAt(i);\n            charMap[c - 'a']--;\n            if (i >= np) {\n                char last = s.charAt(i - np);\n                charMap[last - 'a']++;\n            }\n            \n            if (i >= np - 1) {\n                boolean valid = true;\n                for (int j = 0; j < 26; j++) {\n                    if (charMap[j] != 0) {\n                        valid = false;\n                        break;\n                    }\n                }\n                if (valid) {\n                    results.add(i - np + 1);\n                }\n            }\n        }\n        \n        return results;\n    }\n}\n"
  },
  {
    "path": "Find Last Digit.java",
    "content": "import java.math.BigInteger;\npublic class Solution {\n    public int solve(String A, String B) {\n        int n=A.length();\n        if(A.charAt(n-1)=='1'){\n            return 1;\n        }else if(A.charAt(n-1)=='0'){\n            return 0;\n        }else if(A.charAt(n-1)=='5'){\n            return 5;\n        }else if(A.charAt(n-1)=='6'){\n            return 6;\n        }else if(A.charAt(n-1)=='2'){\n            int pattern[]=new int[]{2,4,8,6};\n            BigInteger in=new BigInteger(B);\n            BigInteger sz=BigInteger.valueOf(4);\n            int x=in.mod(sz).intValue();\n            if(x==0)return pattern[3];\n            return pattern[x-1];\n        }else if(A.charAt(n-1)=='3'){\n            int pattern[]=new int[]{3,9,7,1};\n            BigInteger in=new BigInteger(B);\n            BigInteger sz=BigInteger.valueOf(4);\n            int x=in.mod(sz).intValue();\n            if(x==0)return pattern[3];\n            return pattern[x-1];\n        }else if(A.charAt(n-1)=='4'){\n            int pattern[]=new int[]{4,6};\n            BigInteger in=new BigInteger(B);\n            BigInteger sz=BigInteger.valueOf(2);\n            int x=in.mod(sz).intValue();\n            if(x==0)return pattern[1];\n            return pattern[x-1];\n        }else if(A.charAt(n-1)=='7'){\n            int pattern[]=new int[]{7,9,3,1};\n            BigInteger in=new BigInteger(B);\n            BigInteger sz=BigInteger.valueOf(4);\n            int x=in.mod(sz).intValue();\n            if(x==0)return pattern[3];\n            return pattern[x-1];\n        }else if(A.charAt(n-1)=='8'){\n            int pattern[]=new int[]{8,4,2,6};\n            BigInteger in=new BigInteger(B);\n            BigInteger sz=BigInteger.valueOf(4);\n            int x=in.mod(sz).intValue();\n            if(x==0)return pattern[3];\n            return pattern[x-1];\n        }else if(A.charAt(n-1)=='9'){\n            int pattern[]=new int[]{9,1};\n            BigInteger in=new BigInteger(B);\n            BigInteger sz=BigInteger.valueOf(2);\n            int x=in.mod(sz).intValue();\n            if(x==0)return pattern[1];\n            return pattern[0];\n        }\n        return 1;\n    }\n}\n"
  },
  {
    "path": "Find Missing And Repeating.java",
    "content": "class Solve {\n    int[] findTwoElement(int arr[], int n) {\n        // code here\n       int[]ans=new int[2];\n        for(int i=0;i<n;i++){\n            int val=Math.abs(arr[i]);\n            if(arr[val-1]<0){\n                ans[0]=val;\n            }else{\n                arr[val-1]=0-arr[val-1];\n            }\n        }\n        for(int i=0;i<n;i++){\n            if(arr[i]>0){\n                ans[1]=i+1;\n                break;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Find Original Array From Doubled Array.java",
    "content": "class Solution {\n    public int[] findOriginalArray(int[] changed) {\n        int f[]=new int[100001];\n        if(changed.length%2==1) return new int[0]; // if Array Length is odd cant find\n        for(int i=0;i<changed.length;i++) {\n            f[changed[i]]+=1;\n        }\n        int res[]=new int[changed.length/2];\n        int ind=0;\n        for(int i=0;i<100001;i++) {\n            int k=i;\n            if(f[k]==0) continue;\n            while(f[k]>0) {\n                if(k*2>100000 || f[k*2]==0) return new int[0];  //As Array values always <=100000 and cant be greater values cannot find k*2>1000000 which is false and id the frequency of k*2==0 means return false\n                else {\n                    f[k*2]-=1;\n                    f[k]-=1;\n                    res[ind++]=i;\n                }\n            }   \n        }\n        return res;\n    }\n}\n"
  },
  {
    "path": "Find Prime numbers in a range.java",
    "content": "class Solution {\n    ArrayList<Integer> primeRange(int M, int N) {\n        // code here\n        ArrayList<Integer> list=new ArrayList<>();\n        for(int i=M;i<=N;i++){\n            if(isPrime(i))list.add(i);\n        }\n        return list;\n    }\n    boolean isPrime(int n){\n        // Corner cases\n        if (n <= 1)\n            return false;\n        if (n <= 3)\n            return true;\n  \n        // This is checked so that we can skip\n        // middle five numbers in below loop\n        if (n % 2 == 0 || n % 3 == 0)\n            return false;\n  \n        for (int i = 5; i * i <= n; i = i + 6)\n            if (n % i == 0 || n % (i + 2) == 0)\n                return false;\n  \n        return true;\n    }\n}\n"
  },
  {
    "path": "Find Second Smallest and Second Largest Element in an array without sorting/Find-Second-Smallest-and-Second-Largest-Element-in-an-array-with-out-sorting.cpp",
    "content": "// Find Second Smallest and Second Largest Element in an array without sorting\n\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n    int arr[6] = {1, 2, 4, 7, 7, 5};\n    int n = sizeof(arr) / sizeof(arr[0]);\n    int small = INT_MAX, second_small = INT_MAX, large = INT_MIN, second_large = INT_MIN;\n    for (int i = 0; i < n; i++)\n    {\n        if (arr[i] < small) // if any number is still smaller than the current smaller then update second smaller and small number\n        {\n            second_small = small;\n            small = arr[i];            \n        }\n        else if (arr[i] < second_small and arr[i] != small)\n            second_small = arr[i];\n        if (arr[i] > large)\n        {\n            second_large = large; // if any number is still larger thab the current largest then update the second largest and large number\n            large = arr[i];            \n        }\n        else if (arr[i] > second_large and arr[i] != large)\n            second_large = arr[i];\n    }\n    cout << small << \" \" << large << '\\n';\n    cout << second_small << \" \" << second_large << '\\n';\n}\n"
  },
  {
    "path": "Find Three Consecutive Integers That Sum to a Given Number.py",
    "content": "class Solution:\n    def sumOfThree(self, num: int) -> List[int]:\n        x=num//3\n        a=[x-1,x,x+1]\n        if 3*x !=num:\n            return []\n        return a\n        \n"
  },
  {
    "path": "Find Transition Point - GFG/README.md",
    "content": "# Find Transition Point\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a sorted array containing only 0s and 1s, find the transition point.&nbsp;</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 5\narr[] = {0,0,0,1,1}\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> index 3 is the transition \npoint where 1 begins.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4\narr[] = {0,0,0,0}\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> Since, there is no \"1\",\nthe answer is -1.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. The task is to complete the function <strong>transitionPoint()</strong> that takes array and N as input parameters and returns the 0 based index of the position where \"0\" ends and \"1\" begins. If array does not have any 1s, return -1. If array does not have any 0s, return 0.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(LogN)<br>\n<strong>Expected Auxiliary Space: </strong>O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 500000<br>\n0 ≤ arr[i] ≤ 1</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Find Transition Point - GFG/find-transition-point.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\n\nclass Sorted_Array {\n    public static void main(String args[]) {\n        Scanner sc = new Scanner(System.in);\n        int T = sc.nextInt();\n        while (T > 0) {\n            int n = sc.nextInt();\n            int arr[] = new int[n];\n            for (int i = 0; i < n; i++) {\n                arr[i] = sc.nextInt();\n            }\n            GfG obj = new GfG();\n            System.out.println(obj.transitionPoint(arr, n));\n            T--;\n        }\n    }\n}// } Driver Code Ends\n\n\nclass GfG {\n    int transitionPoint(int arr[], int n){\n        int i=0;\n        int j=n;\n        int mid;\n        while(i<j){\n            mid=(i+j)/2;\n            if(arr[mid]==0){\n                i=mid+1;\n            }else{\n                j=mid;\n            }\n        }\n        return i==n?-1:i;\n    }\n}"
  },
  {
    "path": "Find a peak element.java",
    "content": "public class Solution {\n    public int solve(ArrayList<Integer> A) {\n        if(A.size()==1)return A.get(0);\n        for(int i=0;i<A.size();i++){\n            if(i==0){\n                if(A.get(i)>A.get(i+1))return A.get(i);\n            }else if(i==A.size()-1){\n                if(A.get(A.size()-1)>A.get(i-2))return A.get(A.size()-1);\n            }else{\n                if(A.get(i)>A.get(i+1) && A.get(i)>A.get(i-1))return A.get(i);\n            }\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "Find all distinct subset (or subsequence) sums - GFG/Find all distinct subset (or subsequence) sums.cpp",
    "content": "// two solutions:\r\n\r\n\r\n// 1.\r\nclass Solution {\r\npublic:\r\n    set<int> s;\r\n    int dp[101][10001];\r\n\tvector<int> DistinctSum(vector<int>nums){\r\n\t    int n = nums.size();\r\n\t    memset(dp, -1, sizeof(dp));\r\n\t    solve(0, nums, n);\r\n\t    vector<int> ans;\r\n\t    for(auto& val: s) {\r\n\t        ans.push_back(val);\r\n\t    }\r\n\t    return ans;\r\n\t}\r\n\tvoid solve(int sum, vector<int>& nums, int n) {\r\n\t    if(n==0) {\r\n\t        s.insert(sum);\r\n\t        return;\r\n\t    }\r\n\t    if(dp[n][sum]==1) return;\r\n\t    solve(sum+nums[n-1], nums, n-1);\r\n\t    solve(sum, nums, n-1);\r\n\t    dp[n][sum] = 1;\r\n\t}\r\n};\r\n\r\n\r\n// 2. \r\nclass Solution {\r\npublic:\r\n\tvector<int> DistinctSum(vector<int> nums){\r\n\t    // Code here\r\n\t    set<int> st;\r\n\t    st.insert(0);\r\n\t    for(auto num : nums){\r\n\t        vector<int> v;\r\n\t        for(auto i : st) v.push_back(i + num);\r\n\t        for(auto vv : v) st.insert(vv);\r\n\t    }\r\n\t    nums.clear();\r\n\t    for(auto it : st) nums.push_back(it);\r\n\t    return nums;\r\n\t}\r\n};\r\n"
  },
  {
    "path": "Find all distinct subset (or subsequence) sums.java",
    "content": "class Solution\n{\n    public int[] DistinctSum(int[] nums)\n    {\n        // Code here\n        boolean[][]dp=new boolean[101][10001];\n        Set<Integer> set=new HashSet<>();\n        dfs(nums,0,0,set,dp);\n        int[] ans=new int[set.size()];\n        int i=0;\n        for(int ele:set){\n            ans[i]=ele;\n            i++;\n        }\n        Arrays.sort(ans);\n        return ans;\n    }\n    void dfs(int[]nums,int i,int sum,Set<Integer> set,boolean[][]dp){\n        if(i==nums.length){\n            set.add(sum);\n            return;\n        }\n        if(dp[i][sum])return;\n        dp[i][sum]=true;\n        dfs(nums,i+1,sum,set,dp);\n        dfs(nums,i+1,sum+nums[i],set,dp);\n    }\n}\n"
  },
  {
    "path": "Find all possible paths from top to bottom - GFG/README.md",
    "content": "# Find all possible paths from top to bottom\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a N x M grid. Find All possible paths from top left to bottom right.F<em>rom each cell you can either move only to right or down</em>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong></span><span style=\"font-size:18px\">1 2 3</span>\n<span style=\"font-size:18px\">       4 5 6</span>\n<span style=\"font-size:18px\"><strong>Output: </strong></span><span style=\"font-size:18px\">1 4 5 6</span>\n<span style=\"font-size:18px\">        1 2 5 6 </span>\n<span style=\"font-size:18px\">        1 2 3 6</span>\n<span style=\"font-size:18px\"><strong>Explanation: </strong>We can see that there are 3 </span>\n<span style=\"font-size:18px\">paths from the cell (0,0) to (1,2).</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong></span><span style=\"font-size:18px\">1 2</span>\n<span style=\"font-size:18px\">       3 4</span>\n<span style=\"font-size:18px\"><strong>Output: </strong></span><span style=\"font-size:18px\">1 2 4</span>\n<span style=\"font-size:18px\">        1 3 4</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>findAllPossiblePaths()&nbsp;</strong>which takes&nbsp;two integers n,m and grid[][]&nbsp;&nbsp;as input parameters and returns all possible paths from the top left cell to bottom right cell&nbsp;in a 2d array.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(2^N*M)<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(N)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n,m &lt;= 10<sup>&nbsp;</sup><br>\n1 &lt;= grid[i][j] &lt;= n*m<br>\nn * m &lt;&nbsp;20</span><br>\n&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Find all possible paths from top to bottom - GFG/find-all-possible-paths-from-top-to-bottom.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\n\nclass IntArray\n{\n    public static int[] input(BufferedReader br, int n) throws IOException\n    {\n        String[] s = br.readLine().trim().split(\" \");\n        int[] a = new int[n];\n        for(int i = 0; i < n; i++)\n            a[i] = Integer.parseInt(s[i]);\n        \n        return a;\n    }\n    \n    public static void print(int[] a)\n    {\n        for(int e : a)\n            System.out.print(e + \" \");\n        System.out.println();\n    }\n    \n    public static void print(ArrayList<Integer> a)\n    {\n        for(int e : a)\n            System.out.print(e + \" \");\n        System.out.println();\n    }\n}\n\n\nclass IntMatrix\n{\n    public static int[][] input(BufferedReader br, int n, int m) throws IOException\n    {\n        int[][] mat = new int[n][];\n        \n        for(int i = 0; i < n; i++)\n        {\n            String[] s = br.readLine().trim().split(\" \");\n            mat[i] = new int[s.length];\n            for(int j = 0; j < s.length; j++)\n                mat[i][j] = Integer.parseInt(s[j]);\n        }\n        \n        return mat;\n    }\n    \n    public static void print(int[][] m)\n    {\n        for(var a : m)\n        {\n            for(int e : a)\n                System.out.print(e + \" \");\n            System.out.println();\n        }\n    }\n    \n    public static void print(ArrayList<ArrayList<Integer>> m)\n    {\n        for(var a : m)\n        {\n            for(int e : a)\n                System.out.print(e + \" \");\n            System.out.println();\n        }\n    }\n}\n\nclass GFG {\n    public static void main(String[] args) throws IOException {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int t;\n        t = Integer.parseInt(br.readLine());\n        while(t-- > 0){\n            \n            int[] a = IntArray.input(br, 2);\n            \n            \n            int[][] grid = IntMatrix.input(br, a[0], a[1]);\n            \n            Solution obj = new Solution();\n            ArrayList<ArrayList<Integer>> res = obj.findAllPossiblePaths(a[0],a[1], grid);\n            \n            IntMatrix.print(res);\n            \n        }\n    }\n}\n// } Driver Code Ends\n\n\nclass Solution {\n    public static ArrayList<ArrayList<Integer>> findAllPossiblePaths(int n,int m, int[][] grid) {\n        // code here\n        ArrayList<ArrayList<Integer>> ans=new ArrayList<>();\n        ArrayList<Integer> curr=new ArrayList<>();\n        int i=0;\n        int j=0;\n        curr.add(grid[0][0]);\n        dfs(ans,curr,i,j,grid);\n        return ans;\n    }\n    static void dfs(ArrayList<ArrayList<Integer>> ans,ArrayList<Integer>curr,int i,int j,int[][]grid){\n        if(i==grid.length-1 && j==grid[0].length-1){\n            ans.add(new ArrayList<>(curr));\n            return;\n        }\n        \n        \n        if(valid(i+1,j,grid)){\n            curr.add(grid[i+1][j]);\n            dfs(ans,curr,i+1,j,grid);\n            curr.remove(curr.size()-1);\n        }\n        if(valid(i,j+1,grid)){\n            curr.add(grid[i][j+1]);\n            dfs(ans,curr,i,j+1,grid);\n            curr.remove(curr.size()-1);\n        }\n    }\n    static boolean valid(int i,int j,int[][]grid){\n        if(i==grid.length || j==grid[0].length)return false;\n        return true;\n    }\n}\n        \n"
  },
  {
    "path": "Find an Replace in String - GFG/README.md",
    "content": "# Find an Replace in String\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string <strong>S </strong>on which you need to perform <strong>Q</strong> replace operations.</span><br>\n<span style=\"font-size:18px\">Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if x starts at position i in the <strong>original</strong> <strong>string S</strong>, then we will replace that occurrence of x with y. If not, we do nothing.<br>\n<strong>Note: </strong></span> <span style=\"font-size:18px\">All these operations occur simultaneously. It's guaranteed that there won't be any overlap in replacement: for example, S = \"abc\", indexes = [0,1], sources = [\"ab\", \"bc\"] is not a valid test case. </span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>: \nS = \"gforks\"\nQ = 2\nindex[] = {0, 4}\nsources[] = {\"g\", \"ks\"}\ntargets[] = {\"geeks\", \"geeks\"}\n<strong>Output</strong>: \ngeeksforgeeks\n<strong>Explanation</strong>:\n\"g\" starts at index 0, so, it's reaplaced by\n\"geeks\". Similarly, \"ks\" starts at index 4,\nand is replaced by \"geeks\".</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>: \nS = \"gforks\"\nQ = 2\nindex[] = {0, 3}\nsources[] = {\"g\", \"ss\"}\ntargets[] = {\"geeks\", \"geeks\"}\n<strong>Output</strong>: \ngeeksforks\n<strong>Explanation</strong>:\n\"g\" starts at index 0, so, it's reaplaced by\n\"geeks\". \"ss\" doesn't start at index 3 in\n<strong>original</strong> <strong>S, </strong>so it's not replaced.</span></pre>\n\n<p><br>\n<strong><span style=\"font-size:18px\">Your Task:</span></strong><br>\n<span style=\"font-size:18px\">You don't need to read input or print anything.&nbsp;You only need to complete the function<strong> findAndReplace()&nbsp;</strong>that takes a string S, an integer Q, and 3 arrays index, sources, and targets of size Q, as input and returns the new string after all the operations. index[i], sources[i], and targets[i] denotes the index, sources, and targets for i<sub>th</sub> query.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> &nbsp;O(|S| * Q)<br>\n<strong>Expected Auxilliary Space:</strong> O(Q)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 ≤ |S| ≤ 10<sup>4</sup><br>\n1 ≤ Q ≤ 100<br>\n1 ≤ length of sources<sub>i</sub>, targets<sub>i</sub> ≤ 100</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Find an Replace in String - GFG/find-an-replace-in-string.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            String S = read.readLine();\n            \n            int Q = Integer.parseInt(read.readLine());\n            \n            int[] index = new int[Q];\n            String[] sources = new String[Q];\n            String[] targets = new String[Q];\n            \n            String S1[] = read.readLine().split(\" \");\n            String S2[] = read.readLine().split(\" \");\n            String S3[] = read.readLine().split(\" \");\n            \n            for(int i=0 ; i<Q ; i++) {\n                index[i] = Integer.parseInt(S1[i]);\n                sources[i] = S2[i];\n                targets[i] = S3[i];\n            }\n\n            Solution ob = new Solution();\n            System.out.println(ob.findAndReplace(S,Q,index,sources,targets));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    static String findAndReplace(String s, int q, int[] ind, String[] src, String[] tar) {\n        // code here\n        String ans = \"\";\n        int last = 0;\n        for(int i=0;i<q;i++){\n            ans += s.substring(last,ind[i]);\n            last = ind[i];\n            if(src[i].equals(s.substring(ind[i],ind[i]+src[i].length()))){\n                ans += tar[i];\n                last += src[i].length();\n            }\n        }\n        ans += s.substring(last);\n        return ans;\n    }\n};"
  },
  {
    "path": "Find length of Loop - GFG/README.md",
    "content": "# Find length of Loop\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a linked list of size <strong>N</strong>. The task is to complete the function&nbsp;<strong>countNodesinLoop()&nbsp;</strong>that checks whether a given Linked List contains a&nbsp;<strong>loop or not&nbsp;</strong>and if the&nbsp;<strong>loop </strong>is present then<strong> return the count of nodes</strong> in a loop or else <strong>return 0. C&nbsp;</strong>is the position of the node to which the last node is connected. If it is 0 then no loop.</span></p>\n\n<p><span style=\"font-size:18px\"><img alt=\"\" src=\"https://contribute.geeksforgeeks.org/wp-content/uploads/linkedlist.png\" style=\"height:236px; width:512px\" class=\"img-responsive\"> </span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 10\nvalue[]={25,14,19,33,10,21,39,90,58,45}\nC = 4\n<strong>Output: </strong>7<strong>\nExplanation: </strong>The loop is 45-&gt;33. So\nlength of loop is 33-&gt;<em>10</em>-&gt;21-&gt;39-&gt;\n90-&gt;58-&gt;<em>45</em> = <strong>7. </strong>The number 33&nbsp;is\nconnected to the last node to form the\nloop because according to the input the\n4<sup>th</sup> node from the beginning(1&nbsp;based\nindex) will be connected to the last\nnode for the loop.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 2\nvalue[] = {1,0}\nC = 1\n<strong>Output: </strong>2<strong>\nExplanation: </strong>The length of the loop\nis 2.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThe task is to complete the function <strong>countNodesinLoop</strong>() which contains the only argument as reference to head of<strong> linked list&nbsp;</strong>and return the lenght of the loop ( 0 if there is no loop).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N)<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(1)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N &lt;= 500<br>\n0 &lt;= C &lt;= N-1</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Find length of Loop - GFG/find-length-of-loop.java",
    "content": "// { Driver Code Starts\n// driver code\n\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass Node\n{\n    int data;\n    Node next;\n    \n    Node(int x)\n    {\n        data = x;\n        next = null;\n    }\n}\n\nclass GFG\n{\n    public static void makeLoop(Node head, Node tail, int x){\n        if (x == 0) return;\n        \n        Node curr = head;\n        for(int i=1; i<x; i++)\n            curr = curr.next;\n        \n        tail.next = curr;\n    }\n    \n    public static void main (String[] args){\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n        \n        while(t--> 0)\n        {\n            int n = sc.nextInt();\n            \n            int num = sc.nextInt();\n            Node head = new Node(num);\n            Node tail = head;\n            \n            for(int i=0; i<n-1; i++)\n            {\n                num = sc.nextInt();\n                tail.next = new Node(num);\n                tail = tail.next;\n            }\n            \n            int pos = sc.nextInt();\n            makeLoop(head, tail, pos);\n            \n            Solution x = new Solution();\n            System.out.println( x.countNodesinLoop(head) );\n        }\n    }\n}\n// } Driver Code Ends\n\n\n/*\n\nclass Node\n{\n    int data;\n    Node next;\n    Node(int d) {data = d; next = null; }\n}\n\n*/\n\n//Function should return the length of the loop in LL.\n\nclass Solution\n{\n    //Function to find the length of a loop in the linked list.\n    static int countNodesinLoop(Node head){\n        Node fast=head;\n        Node slow=head;\n        boolean has=false;\n        while(fast != null && fast.next != null){\n            fast=fast.next.next;\n            slow=slow.next;\n            if(fast==slow){\n                int res=1;\n                Node temp=slow;\n                while(temp.next!=slow){\n                    res++;\n                    temp=temp.next;\n                }\n                return res;\n            }\n        }\n        return 0;\n    }\n}"
  },
  {
    "path": "Find pairs with given sum in doubly linked list.cpp",
    "content": "class Solution\n{\npublic:\n    vector<pair<int, int>> findPairsWithGivenSum(Node *head, int target)\n    {\n        // code here\n        vector<pair<int,int>> ans;\n        \n        Node* front = head;\n        Node* rear = head;\n        \n        while(rear->next)\n        rear = rear->next;\n        \n        while(front->data < rear->data)\n        {\n            int num1 = front->data, num2 = rear->data;\n            \n            if(num1 + num2 == target)\n            {\n                ans.push_back({num1, num2});\n                front = front->next;\n            }\n            \n            else if(num1 + num2 > target)\n                rear = rear->prev;\n                \n            else\n                front = front->next;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "Find pairs with given sum in doubly linked list.java",
    "content": "\nclass Solution {\n    public static ArrayList<ArrayList<Integer>> findPairsWithGivenSum(int target, Node head) {\n        // code here\n        Node tail=head;\n        while(tail.next!=null)tail=tail.next;\n        ArrayList<ArrayList<Integer>> ans=new ArrayList<>();\n        while(head!=tail){\n            if(head.data+tail.data==target){\n                ArrayList<Integer> pair=new ArrayList<>();\n                pair.add(head.data);\n                pair.add(tail.data);\n                ans.add(pair);\n                tail=tail.prev;\n            }else if(head.data+tail.data>target){\n                tail=tail.prev;\n            }else{\n                head=head.next;\n            }\n        }\n        return ans;\n    }\n"
  },
  {
    "path": "Find rectangle with corners as 1.java",
    "content": "public class Solution { \n    static boolean ValidCorner(int mat[][]) { \n        int n=mat.length;\n        int m=mat[0].length;\n        for(int i=0;i<n-1;i++){\n            for(int j=i+1;j<n;j++){\n                int cnt=0;\n                for(int k=0;k<m;k++){\n                    if((mat[i][k]+mat[j][k])==2){\n                        cnt++;\n                    }\n                }\n                if(cnt>=2){\n                    return true;\n                }\n            }\n        }\n        return false;\n        \n    }\n}\n"
  },
  {
    "path": "Find the Difference.java",
    "content": "class Solution {\n    public char findTheDifference(String s, String t) {\n        int diff = 0;\n        int i = 0;\n        for( i = 0; i < s.length(); i++) {\n            diff = diff ^ s.charAt(i) ^ t.charAt(i);\n        }\n        diff = diff ^ t.charAt(i);\n        return (char) diff;\n    }\n}\n"
  },
  {
    "path": "Find the Maximum Flow - GFG/README.md",
    "content": "# Find the Maximum Flow\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a graph with N vertices numbered 1 to N and M edges, The task is to find the max flow from vertex 1 to vertex N.</span></p>\n\n<p><span style=\"font-size:18px\">In a flow network, the maximum flow of a path can't exceed the flow-capacity of an edge in the path.<br>\n<br>\n<strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 5, M =  4\nEdges[]= { {1, 2, 1} , {3, 2, 2}, {4, 2, 3}, {2, 5, 5} }\n<strong>Output:</strong>\n1 \n<strong>Explanation: </strong>\n1 - 2 - 3\n   / \\\n  4   5 \n1 unit can flow from 1 -&gt; 2 - &gt;5 </span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4 , M = 4\nEdges[] = { {1, 2, 8}, {1, 3, 10}, {4, 2, 2}, {3, 4, 3} }\n<strong>Output:</strong>\n5 \n<strong>Explanation:</strong>\n  1 - 2 \n  |   |\n  3 - 4\n3 unit can flow from 1 -&gt; 3 -&gt; 4\n2 unit can flow from 1 -&gt; 2 -&gt; 4\nTotal max flow from 1 to N = 3+2=5</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function<strong>&nbsp;solve()</strong>&nbsp;which takes the <strong>N&nbsp;</strong>(the number of vertices) ,<strong>M </strong>(the number of Edges) and the array <strong>Edges</strong>[]&nbsp;(Where Edges[i]&nbsp;denoting an undirected edge between&nbsp;Edges[i][0] and&nbsp;Edges[i][1]&nbsp;with a flow capacity of Edges[i][2]&nbsp;),&nbsp;and returns the&nbsp;integer&nbsp;denoting the maximum flow from 1 to N.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O( max_flow* M)<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(N+M)</span></p>\n\n<p><span style=\"font-size:18px\">Where max_flow is the maximum flow from&nbsp;1 to N</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N,M,Edges[i][2] &lt;= 1000</span><br>\n<span style=\"font-size:18px\">1 &lt;= Edges[i][0],Edges[i][1] &lt;= N</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Find the Maximum Flow - GFG/find-the-maximum-flow.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\nimport java.io.*;\nimport java.util.*; \nclass GFG{\n    public static void main(String args[]) throws IOException { \n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        \n        while(t-- > 0){\n    \n            String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n            int N = Integer.parseInt(input_line[0]);\n            int M = Integer.parseInt(input_line[1]);\n            \n            ArrayList<ArrayList<Integer>> Edges = new ArrayList<ArrayList<Integer>>();\n            input_line = read.readLine().trim().split(\"\\\\s+\");\n            for(int i=0;i<M;i++)\n            {\n                ArrayList<Integer> e = new ArrayList<Integer>();\n                e.add(Integer.parseInt(input_line[3*i]));\n                e.add(Integer.parseInt(input_line[3*i+1]));\n                e.add(Integer.parseInt(input_line[3*i+2]));\n                Edges.add(e);\n            }\n            Solution ob = new Solution();\n            int ans = ob.solve(N, M, Edges); \n            System.out.println(ans);\n        }\n    } \n} // } Driver Code Ends\n\n\n//User function Template for Java\nclass Solution \n{ \n    int bfs(int[][] g,int[] p,int source,int sink,int n){\n        int mn=Integer.MAX_VALUE;\n        Arrays.fill(p,-1);\n        boolean[] vis=new boolean[n];\n        Queue<Integer> q=new LinkedList<>();\n        q.add(source);\n        vis[source]=true;\n        p[source]=-1;\n        while(!q.isEmpty()){\n            int u = q.remove();\n            for(int v=0;v<n;v++){\n                if(vis[v]==false && g[u][v]!=0){\n                    if(v==sink){\n                        p[v]=u;\n                        mn = Math.min(mn,g[u][v]);\n                        return mn;\n                    }\n                    q.add(v);\n                    vis[v]=true;\n                    mn=Math.min(mn,g[u][v]);\n                    p[v]=u;\n                }\n            }\n        }\n        return 0;\n    }\n    int ford(int[][] g,int source,int sink,int n){\n        int[] p=new int[n];\n        Arrays.fill(p,-1);\n        int res=0;\n        while(bfs(g,p,source,sink,n)!=0){\n            int mn = bfs(g,p,source,sink,n);\n            res+=mn;\n            int v= sink;\n            while(v!=source){\n                int u=p[v];\n                g[u][v]-=mn;\n                g[v][u]+=mn;\n                v=p[v];\n            }\n        }\n        return res;\n    }\n    int solve(int N, int M, ArrayList<ArrayList<Integer>> Edges) \n    { \n        // code here\n        int g[][] = new int[N][N];\n        for(int i=0;i<Edges.size();i++){\n            int u = Edges.get(i).get(0)-1;\n            int v = Edges.get(i).get(1)-1;\n            int w = Edges.get(i).get(2);\n            g[u][v]+=w;\n            g[v][u]+=w;\n        }\n        return ford(g,0,N-1,N);\n    }\n}"
  },
  {
    "path": "Find the nearest smaller number in left.cpp",
    "content": "// User function Template for C++\n\nclass Solution{\npublic:\n    vector<int> leftSmaller(int n, int a[]){\n        // code here\n        \n        vector<int> ans(n);\n        stack<int> s;\n        s.push(-1);\n        \n        \n        for(int i=0;i<n;i++){\n            \n            if(s.top() < a[i]){\n                ans[i] = s.top();\n            }else{\n                \n                while(s.top()>=a[i]){\n                    s.pop();\n                }\n                ans[i] = s.top();\n                \n            }\n            s.push(a[i]);\n            \n            \n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "Find the number of islands.java",
    "content": "class axis{\n    int x;\n    int y;\n    public axis(int x,int y){\n        this.x=x;\n        this.y=y;\n    }\n    @Override\n    public boolean equals(Object o){\n        if (o == this)\n            return true;\n        if (!(o instanceof axis))\n            return false;\n        axis a = (axis) o;\n        return x==a.x && y==a.y;\n    }\n}\nclass Solution {\n    // Function to find the number of islands.\n    public int numIslands(char[][] grid) {\n        // Code here\n        int count=0;\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                    count++;\n                    axis a=new axis(i,j);\n                    clearIsland(grid,a);\n                }\n            }\n        }\n        return count;\n    }\n    public void clearIsland(char[][]grid,axis ax){\n        Deque<axis> stack=new ArrayDeque<>();\n        stack.push(ax);\n        while(!stack.isEmpty()){\n            axis a=stack.pop();\n            int i=a.x;\n            int j=a.y;\n            grid[i][j]='0';\n            if((i-1)>=0){\n                if(grid[i-1][j]=='1'){\n                    stack.push(new axis(i-1,j));\n                }\n            }\n            if((i-1)>=0 && j+1<grid[0].length){\n                if(grid[i-1][j+1]=='1'){\n                    stack.push(new axis(i-1,j+1));\n                }\n            }\n            if(j+1<grid[0].length){\n                if(grid[i][j+1]=='1'){\n                    stack.push(new axis(i,j+1));\n                }\n            }\n            if(i+1<grid.length && j+1<grid[0].length){\n                if(grid[i+1][j+1]=='1'){\n                    stack.push(new axis(i+1,j+1));\n                }\n            }\n            if(i+1<grid.length){\n                if(grid[i+1][j]=='1'){\n                    stack.push(new axis(i+1,j));\n                }\n            }\n            if(i+1<grid.length && j-1>=0){\n                if(grid[i+1][j-1]=='1'){\n                    stack.push(new axis(i+1,j-1));\n                }\n            }\n            if(j-1>=0){\n                if(grid[i][j-1]=='1'){\n                    stack.push(new axis(i,j-1));\n                }\n            }\n            if(j-1>=0 && i-1>=0){\n                if(grid[i-1][j-1]=='1'){\n                    stack.push(new axis(i-1,j-1));\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Find whether path exist - GFG/README.md",
    "content": "# Find whether path exist\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a grid of size n*n&nbsp;filled with 0, 1, 2, 3. Check whether there is a path possible from the source to destination.&nbsp;You can traverse up, down, right and left.<br>\nThe description of cells is as follows:</span></p>\n\n<ul>\n\t<li><span style=\"font-size:18px\">A value of cell&nbsp;<strong>1</strong>&nbsp;means Source.</span></li>\n\t<li><span style=\"font-size:18px\">A value of cell&nbsp;<strong>2</strong>&nbsp;means Destination.</span></li>\n\t<li><span style=\"font-size:18px\">A value of cell&nbsp;<strong>3</strong>&nbsp;means Blank cell.</span></li>\n\t<li><span style=\"font-size:18px\">A value of cell <strong>0&nbsp;</strong>means&nbsp;Wall.</span></li>\n</ul>\n\n<p><span style=\"font-size:18px\"><strong>Note</strong>: There are only a single source and a single destination.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>grid = {{3,0,3,0,0},{3,0,0,0,3}\n,{3,3,3,3,3},{0,2,3,0,0},{3,0,0,1,3}}\n<strong>Output: </strong>0\n<strong>Explanation: </strong>The grid is-\n3 0 3 0 0&nbsp;\n3 0 0 0 3&nbsp;\n3 3 3 3 3&nbsp;\n0 2 3 0 0&nbsp;\n3 0 0 1 3&nbsp;\nThere is no path to reach at (3,1) i,e at \ndestination from (4,3) i,e source.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>grid = {{1,3},{3,2}}\n<strong>Output: </strong>1\n<strong>Explanation: </strong>The grid is-\n<span style=\"color:#FF0000\">1 3\n</span>3<span style=\"color:#FF0000\"> 2\n</span>There is a path from (0,0) i,e source to (1,1) \ni,e destination.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function <strong>is_Possible()&nbsp;</strong>which takes the grid as input parameter and returns boolean value true if there is a path otherwise returns false.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(n<sup>2</sup>)<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(n<sup>2</sup>)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ n ≤ 500</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Find whether path exist - GFG/find-whether-path-exist.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            int n = Integer.parseInt(br.readLine().trim());\n            int[][] grid = new int[n][n];\n            for(int i = 0; i < n; i++){\n                String[] S = br.readLine().trim().split(\" \");\n                for(int j = 0; j < n; j++){\n                    grid[i][j] = Integer.parseInt(S[j]);\n                }\n            }\n            Solution obj = new Solution();\n            boolean ans = obj.is_Possible(grid);\n            if(ans)\n                System.out.println(\"1\");\n            else \n                System.out.println(\"0\");\n        }\n    }\n}// } Driver Code Ends\n\n\n\n\nclass Solution\n{\n    boolean res=false;\n    //Function to find whether a path exists from the source to destination.\n    public boolean is_Possible(int[][] grid){\n        int n=grid.length;\n        int m=grid[0].length;\n        boolean vis[][]=new boolean[n][m];\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(grid[i][j]==1){\n                    bfs(grid,vis,i,j);\n                    return res;\n                }\n            }\n        }\n        return res;\n    }\n    public void bfs(int[][]a,boolean[][]vis,int i,int j){\n        if(res)return;\n        if(!valid(a,vis,i,j))return;\n        if(a[i][j]==2){\n            res=true;\n            return;\n        }\n        vis[i][j]=true;\n        bfs(a,vis,i+1,j);\n        bfs(a,vis,i-1,j);\n        bfs(a,vis,i,j+1);\n        bfs(a,vis,i,j-1);\n    }\n    public boolean valid(int[][]a,boolean[][]vis,int i,int j){\n        int n=a.length;\n        int m=a[0].length;\n        if(i<0 || j<0)return false;\n        if(i==n || j==m)return false;\n        if(vis[i][j])return false;\n        if(a[i][j]==0)return false;\n        return true;\n    }\n}"
  },
  {
    "path": "Find-Pattern/find_patter.java",
    "content": "// driver code start\nimport java.io.*;\nclass GFG{\n    // driver code ends\npublic static int findPattern(String s, String p){\n    // code here\n    int s_index =0;\n    int p_index=0;\n    int flag=0;\n    int start = 0;\n    while(s_index<s.length())\n    {\n        if(p_index==p.length())\n        {\n            break;\n        }\n        if(p.charAt(p_index)==s.charAt(s_index))\n        {\n            if(p_index==0)\n            {\n                start=s_index;\n            }\n            flag++;\n            p_index++;\n            \n        }\n        s_index++;\n    }\n    if(flag==p.length())\n    {\n        return start;\n    }\n    return -1;\n}\n}"
  },
  {
    "path": "Find-Pattern/question.md",
    "content": "Given a string  **s** , and a pattern ** p** . You need to find if p exists in s or not and return the starting index of p in s. If p does not exist in s then -1 will be returned.\nHere p and s both are case-sensitive.\n\n**Example 1:**\n\n```\nInput:\ns = \"Hello\"\np = \"llo\"\nOutput: \n2\nExplanation: llo starts from the second\nindex in Hello.\n```\n\n**Example 2:**\n\n```\nInput:\ns = \"World\"\np = \"Doodle\"\nOutput:\n-1\nExplanation: Both are different.\n```\n\n**Your Task: **\nYour task is to complete the function **findPattern() ** which takes two string **s **and **p **as parameter and **returns** an integer.\n"
  },
  {
    "path": "Finding Profession - GFG/README.md",
    "content": "# Finding Profession\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Consider a special family of <strong>Engineers</strong> and <strong>Doctors</strong> with following rules :</span></p>\n\n<ol>\n\t<li><span style=\"font-size:18px\">Everybody has two children.</span></li>\n\t<li><span style=\"font-size:18px\">First child of an Engineer is an Engineer and second child is a Doctor.</span></li>\n\t<li><span style=\"font-size:18px\">First child of an Doctor is Doctor and second child is an Engineer.</span></li>\n\t<li><span style=\"font-size:18px\">All generations of Doctors and Engineers start with Engineer.</span></li>\n</ol>\n\n<p><span style=\"font-size:18px\">We can represent the situation using below diagram:</span></p>\n\n<pre><span style=\"font-size:18px\">                E\n           /        \\\n          E          D\n        /   \\       /  \\\n       E     D     D    E\n      / \\   / \\   / \\   / \\\n     E   D D   E  D  E  E  D\n</span></pre>\n\n<p><span style=\"font-size:18px\">Given <strong>level</strong> and position(<strong>pos</strong>) of a person in above ancestor tree, find profession of the person.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> level = 4, pos = 2\n<strong>Output:</strong> Doctor\n<strong>Explaination:</strong> It is shown in the tree given \nin question.</span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> level = 3, pos = 4\n<strong>Output:</strong> Engineer\n<strong>Explaination:</strong> Already given in the tree in \nquestion.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>profession()</strong> which takes level and pos as input parameters and returns 'd' if it is a doctor. Otherwise return 'e'. The driver code will output Doctor for 'd' and Engineer for 'e' itself.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity: </strong>O(log(pos))<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ level ≤ 10<sup>9</sup><br>\n1 ≤ pos ≤ min(10<sup>9</sup>, 2<sup>level-1</sup>)</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Finding Profession - GFG/finding-profession.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            String a[] = in.readLine().trim().split(\"\\\\s+\");\n            int level = Integer.parseInt(a[0]);\n            int pos = Integer.parseInt(a[1]);\n            \n            Solution ob = new Solution();\n            if(ob.profession(level, pos) == 'd')\n                System.out.println(\"Doctor\");\n            else\n                System.out.println(\"Engineer\");\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\nclass Solution{\n   static int countSetBits(int n)\n   {\n       int count = 0;\n       while (n != 0)\n       {\n         n &= (n-1) ;\n         count++;\n       }\n       return count;\n   }\n   static char profession(int level, int pos){\n       // Count set bits in 'pos-1'\n       int c = countSetBits(pos-1);\n    \n       // If set bit count is odd, then doctor, else engineer\n       return (c%2 == 1)?  'd' : 'e';\n   }\n}"
  },
  {
    "path": "Firing employees.java",
    "content": "class Solution {\n    static int firingEmployees(int arr[], int n) { \n        // code here\n        int ans=0;\n        int[]dp=new int[n];\n        for(int i=0;i<n;i++){\n            if(arr[i]==0)continue;\n            int rank=i+1;\n            int val=rank+dfs(arr,i,dp);\n            if(isPrime(val))ans++;\n        }\n        return ans;\n    } \n    \n    static int dfs(int[]arr,int ind,int[]dp){\n        if(arr[ind]==0)return 0;\n        if(dp[ind]!=0)return dp[ind];\n        int seniors=1 + dfs(arr,arr[ind]-1,dp);\n        return dp[ind]=seniors;\n    }\n    \n    static boolean isPrime(int n)\n    {\n \n        // Check if number is less than\n        // equal to 1\n        if (n <= 1)\n            return false;\n \n        // Check if number is 2\n        else if (n == 2)\n            return true;\n \n        // Check if n is a multiple of 2\n        else if (n % 2 == 0)\n            return false;\n \n        // If not, then just check the odds\n        for (int i = 3; i <= Math.sqrt(n); i += 2)\n        {\n            if (n % i == 0)\n                return false;\n        }\n        return true;\n    }\n\n}\n"
  },
  {
    "path": "First Missing Integer.java",
    "content": "public class Solution {\n    public int firstMissingPositive(ArrayList<Integer> A) {\n        A.removeIf(val -> val <=0);\n        Collections.sort(A);\n        for(int j = 0;j<A.size();j++)if(A.get(j)!=j+1)return j+1;\n        return A.size()+1;\n    }\n}\n"
  },
  {
    "path": "First Repeating element.java",
    "content": "public class Solution {\n    public int solve(ArrayList<Integer> A) {\n        Set<Integer> set=new HashSet<>();\n        int ans=-1;\n        for(int i=A.size()-1;i>=0;i--){\n            int num=A.get(i);\n            if(set.contains(num)){\n                ans=num;\n            }else{\n                set.add(num);\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Flip.java",
    "content": "public class Solution {\n    public ArrayList<Integer> flip(String A) {\n        ArrayList<Integer> al = new ArrayList<>();\n        int max = 0;\n        int diff = 0;\n        int start = 0;\n        boolean solFound = false;\n        int[] ans = new int[2];\n        for(int i = 0; i < A.length(); i++) {\n            char c = A.charAt(i);\n            diff += (c == '0') ? 1 : -1;\n            if(diff < 0) {\n                diff = 0;\n                start = (c == '0') ? i : i + 1;\n            } else {\n                if(max < diff) {\n                    max = diff;\n                    if(al.isEmpty()){\n                        al.add(start);\n                        al.add(i);\n                    } else {\n                        al.set(0, start);\n                        al.set(1, i);\n                    }\n                    solFound = true;\n                }\n            }\n        }\n\n        if(!solFound) {\n            return new ArrayList<>();\n        }\n        \n        al.set(0, al.get(0)+1);\n        al.set(1, al.get(1)+1);\n        return al;\n    \n    }\n}\n"
  },
  {
    "path": "Foldable Binary Tree.cpp",
    "content": "<<<<<<< HEAD\n// function that checks it tree with roots are mirror of each other\nbool isFoldableUtil(Node *n1, Node *n2){\n    // if both left and right subtrees are null\n    if(!n1 && !n2) return true;\n    // if one tree is null and not other return false\n    if(!n1 || !n2) return false;\n    \n    // check whether left and right subtrees are mirror \n    return isFoldableUtil(n1->left, n2->right) && isFoldableUtil(n1->right, n2->left);\n}\n=======\n>>>>>>> upstream/main\n//Function to check whether a binary tree is foldable or not.\nbool IsFoldable(Node* root)\n{\n    // Your code goes here\n<<<<<<< HEAD\n    if(!root) return true;\n    return isFoldableUtil(root->left, root->right); \n}\n\n// TC: O(n) -> where n is the number of nodes in binary tree\n=======\n    if(!root)\n        return true;\n        \n    return checkMirror(root->left, root->right);\n}\n\nbool checkMirror(Node* root1, Node* root2)\n{\n    if(!root1 and !root2)\n        return true;\n    \n    if(!root1 or !root2)\n        return false;\n    \n    return checkMirror(root1->left, root2->right) and checkMirror(root1->right, root2->left);\n}\n\n////Another approach but takes more space than above solution\n\n/*\n    bool IsFoldable(Node* root)\n    {\n        // Your code goes here\n        queue<Node*> Q;\n        Q.push(root);\n\n        while(!Q.empty())\n        {\n            int sz = Q.size();\n            vector<bool> arr;\n\n            while(sz--)\n            {\n                Node* cur = Q.front();\n                Q.pop();\n\n                if(cur)\n                {\n                    arr.push_back(true);\n                    Q.push(cur->left);\n                    Q.push(cur->right);\n                }\n                else\n                    arr.push_back(false);\n            }\n\n            int n = arr.size();\n\n            for(int i=0; i<n/2; i++)\n                if(arr[i] ^ arr[n-i-1])\n                    return false;\n        }\n\n        return true;\n    }\n*/\n>>>>>>> upstream/main\n"
  },
  {
    "path": "Foldable Binary Tree.java",
    "content": "class Tree\n{\n    //Function to check whether a binary tree is foldable or not.\n    boolean IsFoldable(Node node) \n\t{ \n\t\t// your code\n\t\tif(node==null)return true;\n\t\treturn dfs(node.left,node.right);\n\t} \n\tboolean dfs(Node a,Node b){\n\t    if(a==null && b==null)return true;\n\t    if(a==null || b==null)return false;\n\t    return dfs(a.left,b.right) && dfs(a.right,b.left);\n\t}\n}\n"
  },
  {
    "path": "Form a palindrome - GFG/README.md",
    "content": "# Form a palindrome\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string, find the minimum number of characters to be inserted to convert it to palindrome.<br>\nFor Example:<br>\nab: Number of insertions required is 1.&nbsp;<strong>b</strong>ab or aba<br>\naa: Number of insertions required is 0. aa<br>\nabcd: Number of insertions required is 3.&nbsp;<strong>dcb</strong>abcd</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nabcd</span>\n<span style=\"font-size:18px\"><strong>Output:</strong>\n3</span>\n<span style=\"font-size:18px\"><strong>Explanation:\n</strong>Here we can append 3 characters in the \nbeginning,and the resultant string will \nbe a palindrome (\"dcbabcd\").</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\naba</span>\n<span style=\"font-size:18px\"><strong>Output:</strong>\n0</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\nGiven string is already a pallindrome hence\nno insertions are required.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>findMinInsertions()</strong>&nbsp;which takes string S<strong> </strong>as input parameters&nbsp;and returns minimimum numser of insertions required.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(|S|<sup>2</sup>)<br>\n<strong>Expected Auxiliary Space:</strong> O(|S|<sup>2</sup>)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ |S| ≤ 500</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Form a palindrome - GFG/form-a-palindrome.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            \n            String S = read.readLine().trim();\n            Solution ob = new Solution();\n            System.out.println(ob.findMinInsertions(S));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    private static Integer[][] dp;\n    private static int find(int l, int r, String s){\n        if(l > r){\n            return 0;\n        }\n        if(dp[l][r] != null){\n            return dp[l][r];\n        }\n        \n        if(s.charAt(l) == s.charAt(r)){\n            return dp[l][r] = find(l+1, r-1, s);\n        }else{\n            return dp[l][r] = 1 + Math.min(find(l+1, r, s), find(l, r-1, s));\n        }\n    }\n    \n    int findMinInsertions(String S){\n        dp = new Integer[S.length()][S.length()];    \n        return find(0, S.length()-1, S);    \n    }\n}"
  },
  {
    "path": "Form coils in a matrix - GFG/README.md",
    "content": "# Form coils in a matrix\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a positive integer <strong>n</strong> that represents dimensions of a 4n x 4n matrix with values from 1 to 4*n*4*n filled from left to right and top to bottom. Your task is to form two coils from matrix and print the coils.</span></p>\n\n<p><span style=\"font-size:18px\">Follow the given examples for better understanding.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>n = </strong>1</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">10 6 2 3 4 8 12 16\n7 11 15 14 13 9 5 1</span> \n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">The matrix is </span>\n<span style=\"font-size:18px\">1  2  3  4\n5  6  7  8\n9  10 11 12\n13 14 15 16</span>\n<span style=\"font-size:18px\">So, the two coils are as given in the Ouput.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>n = </strong>2</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">36 28 20 21 22 30 38 46\n54 53 52 51 50 42 34 26\n18 10 2 3 4 5 6 7 8\n16 24 32 40 48 56 64\n\n29 37 45 44 43 35 27 19\n11 12 13 14 15 23 31 39\n47 55 63 62 61 60 59 58\n57 49 41 33 25 17 9 1 </span> \n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\"><img alt=\"\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/MatrixCoil.jpg\" style=\"height:266px; width:400px\" class=\"img-responsive\">\n</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>formCoils()</strong> which takes an Integer n as input and returns a vector of two vectors representing coil1 and coil2.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(n<sup>2</sup>)<br>\n<strong>Expected Auxiliary Space:</strong> O(n<sup>2</sup>)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 &lt;= n &lt;= 20</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Form coils in a matrix - GFG/form-coils-in-a-matrix.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int n = Integer.parseInt(read.readLine());\n\n            Solution ob = new Solution();\n            int[][] ptr = ob.formCoils(n);\n            \n            for(int i=0; i<2; i++)\n            {\n                for(int j=0; j<ptr[i].length; j++)\n                {\n                    System.out.print(ptr[i][j] + \" \");\n                }\n                System.out.println();\n            }\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static int[][] formCoils(int n){\n        int [][]arr = new int[4*n][4*n];\n        int val = 1;\n        for(int i = 0 ; i < arr.length ; i ++){\n            for(int j = 0 ; j < arr[0].length ; j ++){\n                arr[i][j] = val;\n                val++;\n            }\n        }\n        int []ans = new int[8*n*n];\n        int idx = 0;\n        int top = 0, down = 4*n-1, left = 1, right = 4*n-1, dir = 0;\n        while (top <= down && right >= left){\n            if(dir == 0){\n                for(int i = down ; i >= top ; i --){\n                    ans[idx] = arr[i][right];\n                    idx++;\n                }\n                right--;\n                down--;\n            }\n            else if(dir == 1){\n                for(int i = right ; i >= left ; i --){\n                    ans[idx] = arr[top][i];\n                    idx++;\n                }\n                right--;\n                top++;\n            }\n            else if(dir == 2){\n                for(int i = top ; i <= down ; i ++){\n                    ans[idx] = arr[i][left];\n                    idx++;\n                }\n                top++;\n                left++;\n            }\n            else if(dir == 3){\n                for(int i = left ; i <= right ; i ++){\n                    ans[idx] = arr[down][i];\n                    idx++;\n                }\n                down--;\n                left++;\n            }\n            dir = (dir+1)%4;\n        }\n        int [][]res = new int[2][8*n*n];\n        int x = ans.length-1;\n        \n        for(int j = 0 ; j < res[0].length ; j ++) {\n            res[0][j] = ans[x];\n            x--;\n        }\n\n        top = 0; down = 4*n-1; left = 0; right = 4*n-2; dir = 0; idx = 0;\n        while (top <= down && right >= left){\n            if(dir == 0){\n                for(int i = top ; i <= down ; i ++){\n                    ans[idx] = arr[i][left];\n                    idx++;\n                }\n                top++;\n                left++;\n            }\n            else if(dir == 1){\n                for(int i = left ; i <= right ; i ++){\n                    ans[idx] = arr[down][i];\n                    idx++;\n                }\n                down--;\n                left++;\n            }\n            else if(dir == 2){\n                for(int i = down ; i >= top ; i --){\n                    ans[idx] = arr[i][right];\n                    idx++;\n                }\n                right--;\n                down--;\n            }\n            else if(dir == 3){\n                for(int i = right ; i >= left ; i --){\n                    ans[idx] = arr[top][i];\n                    idx++;\n                }\n                right--;\n                top++;\n            }\n            dir = (dir+1)%4;\n        }\n        x = ans.length-1;\n        for(int j = 0 ; j < res[0].length ; j ++) {\n            res[1][j] = ans[x];\n            x--;\n        }\n        return res;\n    }\n }"
  },
  {
    "path": "Fraction Trouble - GFG/README.md",
    "content": "# Fraction Trouble\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Consider the set of irreducible fractions A = {n/d | n≤d and d ≤ 10000 and gcd(n,d) = 1}.You are given a member of this set and your task is to find the largest fraction in this set less than the given fraction.<br>\n<strong>Note</strong>&nbsp;: this&nbsp;is a set and all the members are unique.</span><br>\n<br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>: n = 1, d = 4\n<strong>Output:</strong>&nbsp;{2499, 9997}&nbsp; \n<strong>Explanation</strong>: 2499/9997 is the largest fraction.\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>n = 2, d = 4\n<strong>Output:&nbsp;</strong>{4999, 9999}\n<strong>Explanation</strong>: 4999/9999 is the largest fraction. \n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou dont need to read input or print anything. Complete the function <strong>numAndDen()&nbsp;</strong>which takes n&nbsp;and d&nbsp;as input parameter and returns&nbsp;the numerator and the denominator of the required irreducible fraction.<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(n)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)<br>\n<br>\n<strong>Constraints:</strong><br>\n1 &lt;= n&nbsp;&lt;= d&nbsp;&lt;=1000</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Fraction Trouble - GFG/fraction-trouble.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String[] input = new String[2]; \n            input = br.readLine().split(\" \"); \n            int n = Integer.parseInt(input[0]); \n            int d = Integer.parseInt(input[1]); \n            Solution ob = new Solution();\n            int[] ans = ob.numAndDen(n,d);\n            for(int i = 0; i < ans.length; i++)\n            {\n                System.out.print(ans[i] + \" \");\n            }\n            System.out.println();\n        }\n    }\n}\n// } Driver Code Ends\n\n\nclass Solution\n{\n    public int[] numAndDen(int n, int d)\n    {\n        int num = 0;\n        int den = 1;\n        for (int q = 10000; q >= 2; q--){\n            int p = (n * q - 1) / d;\n            if (p * den >= num * q){\n                den = q;\n                num = p;\n            }\n        }\n        int tot = gcdnumber(num,den);\n        int [] ans = new int[2];\n        ans[0] = num/tot;\n        ans[1] = den/tot;\n        return ans;\n    }\n    \n    static int gcdnumber(int a, int b)\n    {\n        if (b == 0)\n            return a;\n        return gcdnumber(b, a % b);\n    }\n}"
  },
  {
    "path": "Fraction.java",
    "content": "public class Solution {\n\tpublic String fractionToDecimal(int numerator, int denominator) {\n        long a=numerator,b=denominator;\n        if(a%b==0) return String.valueOf(a/b);\n        Map<Long,Integer> map=new HashMap<>();\n        StringBuilder res=new StringBuilder();\n        if((a>0&&b<0)||(a<0&&b>0)) res.append(\"-\");\n        a=Math.abs(a);\n        b=Math.abs(b);\n        res.append(a/b+\".\");\n        a=(a%b)*10;\n        while(!map.containsKey(a)){\n            map.put(a,res.length());\n            res.append(String.valueOf(a/b));\n            a=(a%b)*10;\n            if(a==0) return res.toString();\n        }\n        return res.insert(map.get(a),\"(\").append(\")\").toString();\n\t}\n}\n\n"
  },
  {
    "path": "Friends Pairing Problem DP.java",
    "content": " class Solution\n{\n    public long countFriendsPairings(int n) \n    {\n       long mod = 1000000007;\n       long[] dp = new long[n+1];\n       return helper(n,dp,mod);\n    }\n    long helper(int n,long[] dp,long mod){\n        if(n<=2) return n;\n        if(dp[n]!=0) return dp[n];\n        return dp[n] = (helper(n-1,dp,mod) + ((n-1)*helper(n-2,dp,mod)))%mod;\n    }\n    \n}   \n"
  },
  {
    "path": "Friends Pairing Problem.cpp",
    "content": "class Solution\n{\npublic:\n\n    //defining mod\n    long long MOD = 1000000007;\n    \n    int countFriendsPairings(int n) \n    { \n        //numbers less than 3 will have the same answer\n        if(n < 3) return n;\n        \n        //defining and storing base conditions\n        long long prev1 = 1;\n        long long prev2 = 2;\n        \n        //using tabulation based on the pattern observed\n        for(long long i = 3; i <= n; i++)\n        {\n            long long temp = prev2 % MOD;\n            \n            prev2 = (((((i-1) % MOD)*(prev1 % MOD))%MOD) + (prev2 % MOD))%MOD;\n            prev1 = temp;\n        }\n        \n        return prev2;\n    }\n};\n"
  },
  {
    "path": "Friends Pairing Problem.java",
    "content": "class Solution\n{\n    public long countFriendsPairings(int n) \n    { \n       //code here\n       if(n<=2)return n;\n       long mod=(int)Math.pow(10,9)+7;\n       long secPrev=1;\n       long prev=2;\n       long curr=0;\n       for(int i=3;i<=n;i++){\n           curr=(prev+(((i-1)%mod)*(secPrev%mod))%mod)%mod;\n           secPrev=prev;\n           prev=curr;\n       }\n       return curr;\n    }\n}    \n"
  },
  {
    "path": "GFG/0 -1 Knapsack Problem/0 - 1 Knapsack Problem.java",
    "content": "class Solution \n{ \n    //Function to return max value that can be put in knapsack of capacity W.\n    \n  \n  // below function is recursion+dp version of the problem, problem can be solved using only this function also\n    static int myfunc(int w, int wt[], int val[], int n, int[][] ans){\n        if(w==0 || n==0) return 0;\n         if(ans[w][n]!=-1) return ans[w][n];\n         if(wt[n-1]>w){\n             return ans[w][n]=myfunc(w,wt,val,n-1,ans);\n         }\n         \n         return ans[w][n] = Math.max(val[n-1] + myfunc(w-wt[n-1],wt,val,n-1,ans), myfunc(w,wt,val,n-1,ans));\n    }\n    static int knapSack(int W, int wt[], int val[], int n) \n    { \n         // your code here\n         int[][] ans = new int[W+1][n+1];\n         \n        // below is the memoization version (iterative approach) of the problem \n         for(int i=1;i<W+1;i++){   \n             for(int j=1;j<n+1;j++){\n                 if(wt[j-1]>i){\n                     ans[i][j] = ans[i][j-1];\n                 }else{\n                     ans[i][j] = Math.max(val[j-1]+ans[i-wt[j-1]][j-1],ans[i][j-1]);\n                 }\n             }\n         }\n        \n        //  return myfunc(W, wt, val, n, ans);      // call for using recursion + dp approach\n        return ans[W][n];\n    } \n}\n"
  },
  {
    "path": "GFG/2D Hopscotch/2D Hopscotch.java",
    "content": "class Solution{\n    static int hopscotch(int n, int m, int mat[][], int ty, int i, int j) \n    {\n        // code here\n        int ans=0;\n        if(ty==0) {\n            if(isValid(i+1,j,n,m)) ans+=mat[i+1][j];    //down\n            if(isValid(i-1,j,n,m)) ans+=mat[i-1][j];    //up\n            if(isValid(i,j+1,n,m)) ans+=mat[i][j+1];    //right\n            if(isValid(i,j-1,n,m)) ans+=mat[i][j-1];    //left\n            if(j%2==0) {\n                if(isValid(i-1,j+1,n,m)) ans+=mat[i-1][j+1];    // right-up\n                if(isValid(i-1,j-1,n,m)) ans+=mat[i-1][j-1];    // left-up\n            } else {\n                if(isValid(i+1,j+1,n,m)) ans+=mat[i+1][j+1];    // right-down\n                if(isValid(i+1,j-1,n,m)) ans+=mat[i+1][j-1];    // left-down\n            }\n        } else {\n            if(isValid(i+2,j,n,m)) ans+=mat[i+2][j];    // down\n            if(isValid(i-2,j,n,m)) ans+=mat[i-2][j];    // up\n            if(isValid(i,j+2,n,m)) ans+=mat[i][j+2];    // front\n            if(isValid(i,j-2,n,m)) ans+=mat[i][j-2];    // back\n            if(j%2==0) {\n                if(isValid(i+1,j+1,n,m)) ans+=mat[i+1][j+1];    // right-down\n                if(isValid(i-2,j+1,n,m)) ans+=mat[i-2][j+1];    // right-up\n                if(isValid(i+1,j-1,n,m)) ans+=mat[i+1][j-1];    // left-down\n                if(isValid(i-2,j-1,n,m)) ans+=mat[i-2][j-1];    // left-up\n                \n                if(isValid(i+1,j+2,n,m)) ans+=mat[i+1][j+2];    // right-down-right-down\n                if(isValid(i+1,j-2,n,m)) ans+=mat[i+1][j-2];    // left-down-left-down\n                if(isValid(i-1,j+2,n,m)) ans+=mat[i-1][j+2];    // right-up-right-up\n                if(isValid(i-1,j-2,n,m)) ans+=mat[i-1][j-2];    // left-up-left-up\n            } else {\n                if(isValid(i-1,j+1,n,m)) ans+=mat[i-1][j+1];    // right-up\n                if(isValid(i+2,j+1,n,m)) ans+=mat[i+2][j+1];    // right-down\n                if(isValid(i-1,j-1,n,m)) ans+=mat[i-1][j-1];    // left-up\n                if(isValid(i+2,j-1,n,m)) ans+=mat[i+2][j-1];    // left-down\n                \n                if(isValid(i-1,j+2,n,m)) ans+=mat[i-1][j+2];    // right-up-right-up\n                if(isValid(i-1,j-2,n,m)) ans+=mat[i-1][j-2];    // left-up-left-up\n                if(isValid(i+1,j+2,n,m)) ans+=mat[i+1][j+2];    // right-down-right-down\n                if(isValid(i+1,j-2,n,m)) ans+=mat[i+1][j-2];    // left-down-left-down\n            }\n        }\n        return ans;\n    }\n    static boolean isValid(int i,int j,int n,int m){\n        return i>=0 && j>=0 && i<n && j<m;\n    }\n}\n"
  },
  {
    "path": "GFG/3 Divisors/3 Divisors.java",
    "content": "class Solution{\n    static ArrayList<Integer> threeDivisors(ArrayList<Long> query, int qn){\n        // code here\n        int n=0;\n        for(Long q:query){\n            n=Math.max(n,(int)Math.sqrt(q));\n        }\n        boolean[] prime=new boolean[n+1];\n        Arrays.fill(prime,true);\n        for(int i=2;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        \n        int[]dp=new int[n+1];\n        for(int i=2;i<=n;i++){\n            dp[i]=dp[i-1];\n            if(prime[i]){\n                dp[i]++;\n            }\n        }\n        ArrayList<Integer> ans=new ArrayList<>();\n        for(Long q:query){\n            int root=(int)Math.sqrt(q);\n            ans.add(dp[root]);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/A Game of LCM/A Game of LCM.java",
    "content": "\nclass Solution {\n    long maxGcd(int N) {\n        // code here\n        return Math.max(solve(N),solve(N-1));\n    }\n    long solve(int n){\n        long ans=n;\n        int added=0;\n        for(int i=n-1;i>=1;i--){\n            if(gcd(ans,i)==1L){\n                ans*=i;\n                added++;\n            }\n            if(added==3)return ans;\n        }\n        return ans;\n    }\n    long gcd(long a,long b){\n        if(a==0)return b;\n        return gcd(b%a,a);\n    }\n    \n}\n"
  },
  {
    "path": "GFG/A difference of values and indexes/A difference of values and indexes.java",
    "content": "class Solution{\n    \n   \n    // Function for finding maximum and value pair\n    public static int maxDistance (int arr[], int n) {\n        //Complete the function\n        int max=Integer.MIN_VALUE;\n        int min=Integer.MAX_VALUE;\n        int max2=Integer.MIN_VALUE;\n        int min2=Integer.MAX_VALUE;\n        \n        for(int i=0;i<n;i++){\n            max=Math.max(max,arr[i]+i);\n            min=Math.min(min,arr[i]+i);\n            \n            max2=Math.max(max2,arr[i]-i);\n            min2=Math.min(min2,arr[i]-i);\n            \n        }\n        return Math.max(max-min,max2-min2);\n    }\n    \n    \n}\n"
  },
  {
    "path": "GFG/Absolute List Sorting/Absolute List Sorting.java",
    "content": "class Solution\n{\n\tNode sortList(Node head) {\n\t\t// Your code here\n\t\tNode curr=head;\n\t\tNode prev=null;\n\t\twhile(curr!=null){\n\t\t    if(curr.data<0 && curr!=head){\n\t\t        prev.next=curr.next;\n\t\t        curr.next=head;\n\t\t        head=curr;\n\t\t        curr=prev.next;\n\t\t    }else{\n\t\t        prev=curr;\n\t\t        curr=curr.next;\n\t\t    }\n\t\t}\n\t\treturn head;\n\t}\n}\n"
  },
  {
    "path": "GFG/Absolute difference divisible by K/Absolute difference divisible by K.java",
    "content": "class Solution {\n\tstatic long countPairs(int n, int[] arr, int k) {\n\t\t// code here\n\t\tint[]mod=new int[k];\n\t\tfor(int i:arr){\n\t\t    int rem=i%k;\n\t\t    mod[rem]++;\n\t\t}\n\t\tint ans=0;\n\t\tfor(int i:mod){\n\t\t    if(i!=0)ans+=(i)*(i-1)/2;\n\t\t}\n\t\treturn ans;\n\t}\n}\n"
  },
  {
    "path": "GFG/Add Binary Strings/Add Binary Strings.java",
    "content": "class Solution {\n    String addBinary(String A, String B) {\n        // code here\n        int i=A.length()-1;\n        int j=B.length()-1;\n        int carry=0;\n        StringBuilder sb=new StringBuilder();\n        while(i>=0 || j>=0){\n            int a= i>=0?A.charAt(i)-'0':0;\n            int b= j>=0?B.charAt(j)-'0':0;\n            int total=a+b+carry;\n            if(total==0){\n                carry=0;\n                sb.append('0');\n            }else if(total==1){\n                carry=0;\n                sb.append('1');\n            }else if(total==2){\n                carry=1;\n                sb.append('0');\n            }else{\n                carry=1;\n                sb.append('1');\n            }\n            i--;\n            j--;\n        }\n        \n        if(carry==1)sb.append('1');\n        \n        while(sb.charAt(sb.length()-1)=='0')sb.setLength(sb.length()-1);\n        \n        return sb.reverse().toString();\n    }\n}\n"
  },
  {
    "path": "GFG/Aggressive Cows/Aggressive Cows.java",
    "content": "class Solution {\n    public static int solve(int n, int k, int[] stalls) {\n        Arrays.sort(stalls);\n        int l=1;\n        int h=stalls[n-1]-stalls[0];\n        while(l<=h){//log (10^9)== 9*log(10) = 30\n            int mid=(l+h)/2;\n            if(isPossible(k,stalls,mid)){\n                l=mid+1;\n            }else{\n                h=mid-1;\n            }\n        }\n        return h;// (n)\n    }\n    static boolean isPossible(int k,int[]arr,int minDis){\n        int cnt=1;\n        int prevCow=arr[0];\n        for(int i=1;i<arr.length;i++){\n            if(arr[i]-prevCow>=minDis){\n                prevCow=arr[i];\n                cnt++;\n            }\n        }\n        return cnt>=k;\n    }\n}\n"
  },
  {
    "path": "GFG/Akku and Binary Numbers/Akku and Binary Numbers.java",
    "content": "class Solution{\n    \n    void precompute(){\n        // Code Here\n    }\n    long solve(long L, long R){\n        // Code here\n        long ans=0;\n        \n        for(int i=0;i<63;i++){\n            for(int j=i+1;j<63;j++){\n                for(int k=j+1;k<63;k++){\n                    long curr=0;\n                    curr|=(1L<<i);\n                    curr|=(1L<<j);\n                    curr|=(1L<<k);\n                    if(curr>=L && curr<=R){\n                        ans++;\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n    \n}\n"
  },
  {
    "path": "GFG/Alex Travelling/Alex Travelling.cpp",
    "content": "class Solution {\n   \n  public:\n    int minimumCost(vector<vector<int>>& flights, int n, int k) {\n        // code here\n        \n        unordered_map<int,list<pair<int,int>> > adj;\n        for(int i = 0; i < flights.size(); i++)\n        {\n            int u = flights[i][0];\n            int v = flights[i][1];\n            int w = flights[i][2];\n            \n            adj[u].push_back({v,w});\n            \n        }\n        \n        vector<int> dist(n+1, INT_MAX);\n        \n        set<pair<int,int>> s; //distNode, node\n        \n        dist[k] = 0;\n        s.insert({0, k});\n        \n        while(!s.empty())\n        {\n            auto top = *(s.begin());\n            s.erase(s.begin());\n            \n            int distNode = top.first;\n            int node = top.second;\n            \n            for(auto neigh : adj[node])\n            {\n                if(distNode + neigh.second < dist[neigh.first])\n                {\n                    dist[neigh.first] = distNode + neigh.second;\n                    \n                    s.insert({dist[neigh.first], neigh.first});\n                }\n            }\n        }\n        \n        int ans = 0;\n        \n        for(int i = 1; i <= n; i++)\n        {\n            if(dist[i] == INT_MAX) return -1;\n            \n            ans = max(ans, dist[i]);\n              \n            // cout<<dist[i]<<\" \";\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "GFG/Alex Travelling/Alex Travelling.java",
    "content": "class Solution {\n    class Pair{\n        int node;\n        int weight;\n        Pair(int n,int w){\n            node=n;\n            weight=w;\n        }\n    }\n    int minimumCost(int[][] flights, int n, int k) {\n        // Your code here\n        Map<Integer,ArrayList<Pair>> map=new HashMap<>();\n        for(int[]i:flights){\n            int u=i[0];\n            int v=i[1];\n            int w=i[2];\n            map.putIfAbsent(u,new ArrayList<>());\n            map.get(u).add(new Pair(v,w));\n        }                    \n        \n        int[]dis=new int[n+1];\n        int ans=0;\n        Queue<Pair> q=new LinkedList<>();\n        q.add(new Pair(k,dis[k]));\n        \n        while(!q.isEmpty()){\n            Pair curr=q.remove();\n            int node=curr.node;\n            int cost=curr.weight;\n            if(!map.containsKey(node))continue;\n            for(Pair p:map.get(node)){\n                int neb=p.node;\n                int nebCost=p.weight;\n                if((dis[neb]==0 || dis[neb]>cost+nebCost) && neb!=k){\n                    dis[neb]=cost+nebCost;\n                    q.add(new Pair(neb,dis[neb]));\n                }\n            }\n        }\n        \n        for(int i=1;i<dis.length;i++){\n            if(dis[i]!=0){\n                ans=Math.max(ans,dis[i]);\n            }else if(i!=k){\n                return -1;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Alternate Vowel and Consonant String/Alternate Vowel and Consonant String.java",
    "content": "class Solution{\n    public String rearrange(String S, int N){\n        int[]vowels=new int[26];\n        int[]cosonants =new int[26];\n        int noOfVowels=0;\n        int noOfCons=0;\n        char smallestVowel='u';\n        char smallestCons='z';\n        \n        for(char c:S.toCharArray()){\n            if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){\n                vowels[c-'a']++;\n                noOfVowels++;\n                smallestVowel=(char)Math.min((int)smallestVowel,(int)c);\n            }else{\n                cosonants[c-'a']++;\n                noOfCons++;\n                smallestCons=(char)Math.min((int)smallestCons,(int)c);\n            }\n        }\n        \n        if(Math.abs(noOfVowels-noOfCons)>1)return \"-1\";\n        \n        boolean isVowel=false;\n        \n        if(noOfVowels>noOfCons){\n            isVowel=true;\n        }else if(noOfCons>noOfVowels){\n            isVowel=false;\n        }else{\n            if(smallestVowel<smallestCons){\n                isVowel=true;\n            }else{\n                isVowel=false;    \n            }\n        }\n        \n        StringBuilder sb=new StringBuilder();\n        int i=0;\n        int j=0;\n        while(i<26 && j<26){\n            if(isVowel){\n                while(i<26 && vowels[i]==0)i++;\n                if(i==26)break;\n                sb.append((char)('a'+i));\n                vowels[i]--;\n                isVowel=false;\n            }else{\n                while(j<26 && cosonants[j]==0)j++;\n                if(j==26)break;\n                sb.append((char)('a'+j));\n                cosonants[j]--;\n                isVowel=true;\n            }\n        }\n        return sb.toString();\n    }\n}\n\n//User function Template for Java\n\nclass Solution{\n    public String rearrange(String S, int N){\n        int vowels = countVowels(S, true);\n        int consonants = countVowels(S, false);\n        \n        int f[]=new int[26];\n        char firstVowel=Character.MAX_VALUE;\n        char firstConsonant=Character.MAX_VALUE;\n        for(int i=0;i<S.length();i++) {\n            f[S.charAt(i)-'a'] += 1;\n            if(S.charAt(i)=='a' || S.charAt(i)=='e' || S.charAt(i)=='i'|| S.charAt(i)=='o' || S.charAt(i)=='u') {\n                if(firstVowel > S.charAt(i)) {\n                    firstVowel = S.charAt(i);\n                }\n            }\n            else {\n                if(firstConsonant > S.charAt(i)) {\n                    firstConsonant = S.charAt(i);\n                }\n            }\n        }\n        \n        int j=firstConsonant -'a';\n        int i=firstVowel -'a';\n        \n        StringBuilder sb = new StringBuilder();\n        \n        if(S.length()%2==0) {\n            if(vowels!=consonants) return \"-1\";\n            if(firstVowel < firstConsonant) {\n                sb.append(firstVowel);\n                f[firstVowel - 'a']-=1;\n            }\n            return getRes(f, i, j, sb);\n        }\n        else {\n           \n            if(Math.abs(vowels-consonants) > 1) {\n                return \"-1\";\n            }\n            \n            if(vowels-consonants==1) {\n                sb.append(firstVowel);\n                f[firstVowel - 'a']-=1;\n            }\n            \n            return getRes(f, i, j, sb);\n        }\n    }\n    \n    public String getRes(int []f, int i, int j, StringBuilder sb) {\n        while(j<26) {\n                if(f[j]==0) {\n                    j+=1;\n                    continue;\n                }\n                else {\n                    if(j==0 || j==4 || j==8 || j==14 || j==20) {\n                        j+=1;\n                        continue;\n                    }\n                    else {\n                        sb.append((char)('a'+j));\n                        f[j]-=1;\n                    }\n                }\n                \n                \n                \n                if(f[i]==0) {\n                    i=getNextVowel(f);\n                }\n                if(i!=-1) {\n                    sb.append((char)('a'+i));\n                    f[i]-=1;\n                }\n                else {\n                    break;\n                }\n                \n        }\n        return sb.toString();\n    }\n    \n    public int getNextVowel(int f[]) {\n        if(f[0]!=0) return 0;\n        if(f[4]!=0) return 4;\n        if(f[8]!=0) return 8;\n        if(f[14]!=0) return 14;\n        if(f[20]!=0) return 20;\n        return -1;\n    }\n    public int countVowels(String s, boolean isVowel) {\n        int count = 0;\n        for(int i=0;i<s.length();i++) {\n            if(isVowel && (s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i'|| s.charAt(i)=='o' || s.charAt(i)=='u')) {\n                count+=1;\n            }\n            else if(!isVowel && !(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u')) {\n                count+=1;\n            }\n        }\n        return count;\n    }\n}\n"
  },
  {
    "path": "GFG/Alternate Vowel and Consonant String/ReadMe.md",
    "content": "**Alternate Vowel and Consonant String**\n--------------------\n\nGiven a string **S** of lowercase english characters. Rearrange characters of the given string such that the vowels and consonants occupy alternate positions and the string so formed should be lexicographically (alphabetically) smallest. \nNote: Vowels are 'a', 'e', 'i', 'o' and 'u'. \n\n**Example 1**:\n\n```\nInput:\nS = \"aeroplane\"\nOutput: alanepero\nExplanation: alanepero  \nThe vowels and cosonants are arranged \nalternatively with vowels shown in bold.\nAlso, there's no lexicographically smaller\nstring possible with required conditions.\n```\n\n**Example 2**:\n\n```\nInput: \nS = \"mississippi\"\nOutput: -1\nExplanation: The number of vowels is 4 \nwhereas the number of consonants is 7.\nHence, there's no way to arrange the\nvowels and consonants alternatively.\n```\n\n**Your Task**:\nYou don't need to read input or print anything. Your task is to complete the function rearrange() which takes the string S and its size N as inputs and returns the modified string as stated in the description. If such a modification is not possible, return the string \"-1\".\n\n```\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(2*26).\n\n\nConstraints:\n1 <= N <= 10^6\n'a' <= S[ i ] <= 'z'\n```\n"
  },
  {
    "path": "GFG/Array Pair Sum Divisibility Problem/Array Pair Sum Divisibility Problem.java",
    "content": "class Solution {\n    public boolean canPair(int[] nums, int k) {\n        // Code here\n        if(nums.length%2!=0)return false;\n        int[]freq=new int[k];\n        \n        for(int i:nums){\n            int y=i%k;\n            if(freq[(k-y)%k]!=0){\n                freq[(k-y)%k]--;\n            }else{\n                freq[y]++;\n            }\n        }\n        for(int i:freq){\n            if(i!=0)return false;\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "GFG/Array Removals/Array Removals.cpp",
    "content": "class Solution{\n    public:\n    int removals(vector<int>& arr, int k){\n        sort(arr.begin(), arr.end());\n        \n        int l = 0, r = 0, len = 0;\n        \n        while(r<arr.size()){\n            if(arr[r]-arr[l]<=k){\n                r++;\n                len = max(len, r-l);\n            }else l++;\n        }\n        \n        return arr.size()-len;\n    }\n};\n"
  },
  {
    "path": "GFG/Array Removals/Array Removals.java",
    "content": "class Solution {\n    int removals(int[] arr, int n, int k) {\n        // code here\n        Arrays.sort(arr);\n        int i=0;\n        int j=0;\n        int maxSize=0;\n        while(j<n){\n            if(arr[j]-arr[i]<=k)j++;\n            else if(i<j)i++;\n            maxSize=Math.max(maxSize,j-i);\n        }\n        return n-maxSize;\n    }\n}\n"
  },
  {
    "path": "GFG/Articulation Point - I/Articulation Point - I.java",
    "content": "class Solution\n{\n    int time;\n    //Function to return Breadth First Traversal of given graph.\n    public ArrayList<Integer> articulationPoints(int V,ArrayList<ArrayList<Integer>> adj)\n    {\n        // Code here\n        time=0;\n        ArrayList<Integer> ans=new ArrayList<>();\n        boolean[]ap=new boolean[V];\n        int[]parent=new int[V];\n        boolean[]vis=new boolean[V];\n        int[]minDis=new int[V];\n        int[]dis=new int[V];\n        Arrays.fill(parent,-1);\n        for(int i=0;i<V;i++){\n            dfs(i,ap,adj,parent,vis,minDis,dis);\n        }\n        for(int i=0;i<V;i++){\n            if(ap[i]){\n                ans.add(i);\n            }\n        }\n        \n        if(ans.size()==0){\n            ans.add(-1);\n        }\n        return ans;\n    }\n    void dfs(int u,boolean[]ap,ArrayList<ArrayList<Integer>> adj,int[]parent,boolean[]vis,\n    int[]minDis,int[]dis){\n        vis[u]=true;\n        int children=0;\n        dis[u]=minDis[u]=time;\n        time++;\n        for(int v:adj.get(u)){\n            if(!vis[v]){\n                children++;\n                parent[v]=u;\n                dfs(v,ap,adj,parent,vis,minDis,dis);\n                minDis[u]=Math.min(minDis[u],minDis[v]);\n                if(parent[u]==-1 && children>1){\n                    ap[u]=true;\n                }else if(parent[u]!=-1 && minDis[v]>=dis[u]){\n                    ap[u]=true;\n                }\n            }else{\n                minDis[u]=Math.min(minDis[u],dis[v]);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "GFG/Asteroid Collision/Asteroid Collision.cpp",
    "content": "class Solution {\n  public:\n    vector<int> asteroidCollision(int N, vector<int> &asteroids) {\n        stack<int> s;\n        int i = 0;\n        while(i < N){\n            if(s.empty()){\n                s.push(asteroids[i]);\n                ++i;\n            }\n            else{\n                if((asteroids[i] > 0 && s.top() > 0) || \n                (asteroids[i] < 0 && s.top() < 0) ||\n                (asteroids[i] > 0 && s.top() < 0)){\n                    s.push(asteroids[i]);\n                    ++i;\n                }\n                else if(asteroids[i] < 0 && s.top() > 0){\n                    int a = s.top();\n                    s.pop();\n                    \n                    if(a == abs(asteroids[i]))\n                        ++i;\n                    else if(a > abs(asteroids[i])){\n                        s.push(a);\n                        ++i;\n                    }\n                    else if(a < abs(asteroids[i])){\n                        continue;\n                    }\n                }\n            }\n        }\n        vector<int> ans;\n        while(!s.empty()){\n            int a = s.top();\n            s.pop();\n            ans.push_back(a);\n        }\n        \n        reverse(ans.begin(), ans.end());\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "GFG/Asteroid Collision/Asteroid Collision.java",
    "content": "\nclass Solution {\n    public static int[] asteroidCollision(int N, int[] arr) {\n        // code here\n        Stack<Integer> st=new Stack<>();\n        for(int num:arr){\n            if(num<0){\n                while(!st.isEmpty() && st.peek()>0 && st.peek()<Math.abs(num)){\n                    st.pop();\n                }\n                \n                if(!st.isEmpty()){\n                    if(st.peek()==Math.abs(num)){\n                        st.pop();\n                    }else if(st.peek()<0){\n                        st.push(num);\n                    }\n                }else if(st.isEmpty()){\n                    st.push(num);\n                }\n            }else{\n                st.push(num);\n            }\n        }\n        int[] ans =new int[st.size()];\n        int i=st.size()-1;\n        while(st.size()>0)ans[i--]=st.pop();\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Balanced string/Balanced string.java",
    "content": "class Solution {\n    static String BalancedString(int N) {\n        // code here\n        StringBuilder ans=new StringBuilder();\n        String full=\"abcdefghijklmnopqrstuvwxyz\";\n        int n=N;\n        while(N>26){\n            ans.append(full);\n            N-=26;\n        }\n        \n        if(N%2==0){//even\n            for(int i=0;i<N/2;i++)ans.append((char)('a'+i));\n            for(int i=26-N/2;i<26;i++)ans.append((char)('a'+i));\n        }else{//odd\n            int sum=0;\n            while(n>0){\n                sum+=(n%10);\n                n/=10;\n            }\n            if(sum%2==0){//even\n                for(int i=0;i<(N+1)/2;i++)ans.append((char)('a'+i));\n                for(int i=26-N/2;i<26;i++)ans.append((char)('a'+i));\n            }else{//odd\n                for(int i=0;i<N/2;i++)ans.append((char)('a'+i));\n                for(int i=26-(N+1)/2;i<26;i++)ans.append((char)('a'+i));\n            }\n            \n        }\n        return ans.toString();\n    }\n}\n"
  },
  {
    "path": "GFG/Base Equivalance/Base Equivalence.java",
    "content": "/* \nQuestion to Problem:\n\nGiven a number (n) and no. of digits (m) to represent the number, we have to check if we can represent n \nusing exactly m digits in any base from 2 to 32.\n\nExample 1:\n\nInput: n = 8, m = 2\nOutput: Yes \nExplanation: Possible in base 3 as 8 in base 3 is 22.  \n\nExample 2:\n\nInput: n = 8, m = 3\nOutput: No\nExplanation: Not possible in any base. \n\n*/\nclass Solution\n{\n    String baseEquiv(int n, int m)\n    {\n        // code here \n        int start=2;\n        int end=32;\n        while(start<=end) {\n            int mid=(start+end)/2;\n            int digits=calculateDigits(n, mid);\n            if(digits<m) end=mid-1;\n            else if(digits>m) start=mid+1;\n            else return \"Yes\";\n        }\n        return \"No\";\n    }\n    public int calculateDigits(int n, int m) {\n        int dig=0;\n        while(n>0) {\n            dig+=1;\n            n=n/m;\n        }\n        return dig;\n    }\n}\n"
  },
  {
    "path": "GFG/Base Equivalence/Base Equivalence.java",
    "content": "//User function Template for Java\nclass Solution\n{\n    String baseEquiv(int n, int m)\n    {\n        // code here\n        int i=2;\n        while(i<=32){\n            int digit=(int)(Math.log(n)/Math.log(i))+1;\n            if(digit==m)return \"Yes\";\n            i++;\n        }\n        return \"No\";\n    }\n}\n"
  },
  {
    "path": "GFG/Binary Tree to DLL/Binary Tree to DLL.cpp",
    "content": "/* This code is contributed by -\n   Aman Bhatt (https://github.com/bhattaman0001)\n   Anish Mandal (https://github.com/AnishMandal939)\n*/\n\n// there are 2 approaches another one is below\n\nNode * bToDLL(Node *root)\n    {\n        // your code here\n        // TC: O(1) using morris inorder traversal\n\n        Node* curr = root, *head = NULL;\n\n        while(curr != NULL){\n            if(curr->left != NULL){\n                Node* traversal = curr->left;\n                while(traversal->right != NULL && traversal->right != curr)\n                    traversal = traversal->right;\n\n                if(traversal->right == NULL){\n                    traversal->right = curr;\n\n                    Node *tmp = curr->left;\n                    curr->left = traversal;\n                    curr=tmp;\n                    continue;\n                }\n            }    \n            if(head == NULL) head = curr;\n            //cout<<curr->right->data<<endl;\n\n            Node *traversal = curr->right;\n            if(traversal != NULL && traversal->left != curr){\n                while(traversal->left != NULL)\n                    traversal = traversal->left;\n\n                Node* tmp = curr->right;\n                traversal->left = curr;\n                curr->right = traversal;\n                curr = tmp;\n            }\n            else curr = curr->right;\n\n\n        }\n        return head;\n    }\n\n\n\n\n// 2. another approach\n// it is not complex just added comments that's why it is looking big\nstruct Node\n{\n    int data;\n    struct Node* left;\n    struct Node* right;\n\n    Node(int x){\n        data = x;\n        left = right = NULL;\n    }\n};\n\n// This function should return head to the DLL\nclass Solution\n{\n    public: \n    Node *p = NULL, *h = NULL;\n    void inorder(Node* root){\n        if(!root) return;\n        inorder(root->left);\n        root->left = p;\n        p = root;\n        inorder(root->right);\n    }\n    //Function to convert binary tree to doubly linked list and return it.\n    Node * bToDLL(Node *root)\n    {\n        // your code here\n        inorder(root); // making one traversal from left to right of doubly linkedList\n\n      // making another traversal from right to left of DLL\n      // if you are heading from right to left then for DLL your next is right and prev is left\n        // if you are heading from left to right then for DLL your next is left and prev is right\n        Node* t = p, *p1 = NULL;\n        t->right = p1;\n        while(t->left != NULL){\n            p1 = t;\n            t = t->left;\n            t->right = p1;\n        }\n        h = t;\n        return h;\n    }\n};\n"
  },
  {
    "path": "GFG/Binary Tree to DLL/Binary Tree to DLL.java",
    "content": "class Solution\n{\n    //Function to convert binary tree to doubly linked list and return it.\n    Node bToDLL(Node root)\n    {\n\t//  Your code here\t\n\t    Node[] arr=dfs(root);\n\t    return arr[0];\n    }\n    Node[] dfs(Node root){\n        if(root.left==null && root.right==null){\n            return new Node[]{root,root};\n        }\n        \n        if(root.left==null){\n            Node[] righty=dfs(root.right);\n            root.right=righty[0];// 10 -> 36\n            righty[0].left=root;// 10 <- 36\n            return new Node[]{root,righty[1]};//10,15\n        }\n        \n        Node[] lefty=dfs(root.left);\n        lefty[1].right=root;//30 -> 10\n        root.left=lefty[1];// 30 <-10\n        \n        if(root.right==null){\n            return new Node[]{lefty[0],root};//25,10\n        }\n        Node[] righty=dfs(root.right);\n        root.right=righty[0];// 10 -> 36\n        righty[0].left=root;// 10 <- 36\n        \n        return new Node[]{lefty[0],righty[1]};//25,15\n    }\n}\n\n\n\nApproach 2: \n\nSolution Explain:\n\n    1. make an arraylist\n    2. put all the elements of the tree in inorder fashion\n    3. now traverse that arraylist and construct left as prev and right as arraylist next element\n    4. Time complexity= o(N)(inorder and traversal of arraylist) and space = O(N) bez of arraylist\n\n\n class Solution\n{\n    Node bToDLL(Node root)\n    {\n        if(root==null || root.left==null && root.right==null){\n            return root;\n        }\n\n\n\t    //make ArrayList\n\t    ArrayList<Node> al=new ArrayList<>();\n\n\t    //put all the element's in inorder to al\n\t    inorder(root,al);\n\n\t    Node dummy=al.get(0);\n\n\n\t    //take two nodes prev and curr for doubly linked list\n\t    Node prev=null;\n\t    Node curr=null;\n\n\t    //counter for traversing arraylist\n\t    int i=0;\n\n\n\t    //create doubly linked list\n\t    while(i<al.size()){\n\n\t        curr=al.get(i);\n\t        curr.left=prev;\n\n\t        if(i+1<al.size())\n\t            curr.right=al.get(i+1);\n\t        else\n\t            curr.right=null;\n\n\t        prev=curr;\n\t        i++;\n\n\t    }\n\n\t    return dummy;\n    }\n\n    public void inorder(Node root,ArrayList<Node> al){\n\n        if(root==null)\n            return;\n\n        inorder(root.left,al);\n        al.add(root);\n        inorder(root.right,al);\n    }\n}\n\nContributed by @Jay-Thesia\n"
  },
  {
    "path": "GFG/Black and White/Black and White.java",
    "content": "class BlackAndWhite\n{\n    //Function to find out the number of ways we can place a black and a \n    //white Knight on this chessboard such that they cannot attack each other.\n    static long numOfWays(int N, int M)\n    {\n        // add your code here\n        long ans=0L;\n        long mod=1000000007;\n        int[][]dirs=new int[][]{{1,2},{-1,2},{1,-2},{-1,-2},{2,1},{-2,1},{2,-1},{-2,-1}};\n        for(int i=0;i<N;i++){\n            for(int j=0;j<M;j++){\n                long total=N*M;\n                long minus=1L;\n                for(int[]dir:dirs){\n                    if(valid(i+dir[0],j+dir[1],N,M))minus++;\n                }\n                total-=minus;\n                ans=(ans+total)%mod;\n            }\n        }\n        return ans%mod;\n    }\n    static boolean valid(int i,int j,int n,int m){\n        return i>=0 && j>=0 && i<n && j<m;\n    }\n}\n"
  },
  {
    "path": "GFG/Break a number/Break a number.java",
    "content": "class Solution{\n    int waysToBreakNumber(int N){\n        // code here\n        long n=N;\n        return (int)(((3*n)+(n-1)*(n-2)/2)%1000000007);\n    }\n}\n"
  },
  {
    "path": "GFG/Build the smallest/Build the smallest.java",
    "content": "class Solution {\n    static String buildLowestNumber(String str, int k) {\n        // code here\n        Stack<Character> st=new Stack<>();\n        for(char c:str.toCharArray()){\n            while(!st.isEmpty() && st.peek()>c && k>0){\n                st.pop();\n                k--;\n            }\n            st.push(c);\n        }\n        \n        while(!st.isEmpty() && k>0){\n            st.pop();\n            k--;\n        }\n        \n        StringBuilder sb=new StringBuilder();\n        while(!st.isEmpty()){\n            sb.append(st.pop());\n        }\n        \n        while(sb.length()>0 && sb.charAt(sb.length()-1)=='0'){\n            sb.setLength(sb.length()-1);\n        }\n        if(sb.length()==0)return \"0\";\n        return sb.reverse().toString();\n    }\n}\n"
  },
  {
    "path": "GFG/Burst Balloons/Burst Balloons.java",
    "content": "class Solution {\n    static Integer[][]dp;\n  public static int maxCoins(int N, int[] arr) {\n    // code here\n    dp=new Integer[N+3][N+3];\n    int[]newArr=new int[N+2];\n    newArr[0]=1;\n    newArr[N+1]=1;\n    for(int i=0;i<N;i++){\n        newArr[i+1]=arr[i];\n    }\n    return dfs(0,N+1,newArr);\n  }\n  static int dfs(int l,int r,int[]arr){\n      int ans=0;\n      if(dp[l][r]!=null)return dp[l][r];\n      for(int i=l+1;i<r;i++){\n          int temp= arr[l]*arr[i]*arr[r] + dfs(i,r,arr) + dfs(l,i,arr);\n          ans=Math.max(ans,temp);\n      }\n      return dp[l][r]=ans;\n  }\n}\n"
  },
  {
    "path": "GFG/Check for BST/Check for BST.java",
    "content": "public class Solution\n{\n    //Function to check whether a Binary Tree is BST or not.\n    boolean isBST(Node root, int minValue, int maxValue) {\n        if(root==null) return true;\n        if(root.data<=minValue || root.data>=maxValue) return false;\n        return isBST(root.left,minValue,root.data)&&isBST(root.right,root.data,maxValue);\n    }\n    boolean isBST(Node root)\n    {\n        // code here.\n        return isBST(root,Integer.MIN_VALUE,Integer.MAX_VALUE);\n    }\n}\n"
  },
  {
    "path": "GFG/Check if all levels of two trees are anagrams or not/Check if all levels of two trees are anagrams or not.java",
    "content": "class Solution {\n    public static boolean areAnagrams(Node node1, Node node2) {\n        // code here\n        Queue<Node> q1=new LinkedList<>();\n        Queue<Node> q2=new LinkedList<>();\n        q1.add(node1);\n        q2.add(node2);\n        while(!q1.isEmpty() && !q1.isEmpty()){\n            int sz1=q1.size();\n            int sz2=q2.size();\n            if(sz1!=sz2)return false;\n            Map<Integer,Integer> map=new HashMap<>();\n            for(int i=0;i<sz1;i++){\n                Node a=q1.remove();\n                Node b=q2.remove();\n                map.merge(a.data,1,Integer::sum);\n                map.merge(b.data,-1,Integer::sum);\n                if(a.left!=null)q1.add(a.left);\n                if(b.left!=null)q2.add(b.left);\n                if(a.right!=null)q1.add(a.right);\n                if(b.right!=null)q2.add(b.right);\n                \n            }\n            \n            for(int key:map.keySet()){\n                if(map.get(key)!=0)return false;\n            }\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "GFG/Check if it is possible to convert one string into another with given constraints/Check if it is possible to convert one string into another with given constraints.java",
    "content": "class Solution {\n    int isItPossible(String S, String T, int M, int N) {\n        // code here\n        if(M!=N)return 0;\n        int a=0;\n        int b=0;\n        for(int i=0;i<N;i++){\n            if(S.charAt(i)=='A'){\n                a++;\n            }else if(S.charAt(i)=='B'){\n                b++;\n            }\n            if(T.charAt(i)=='A'){\n                a--;\n            }else if(T.charAt(i)=='B'){\n                b--;\n            }\n        }\n        if(a!=0 || b!=0)return 0;\n        \n        \n        int i=0;\n        int j=0;\n        while(i<N && j<N){\n            while(i<N && S.charAt(i)=='#')i++;\n            while(j<N && T.charAt(j)=='#')j++;\n            if(i==N || j==N)break;\n            if(S.charAt(i)=='A'){\n                if(T.charAt(j)=='A'){\n                    if(j>i)return 0;\n                    else{\n                        i++;\n                        j++;\n                    }\n                }else{\n                    return 0;\n                }\n            }else{\n                if(T.charAt(j)=='B'){\n                    if(j<i)return 0;\n                    else{\n                        i++;\n                        j++;\n                    }\n                }else{\n                    return 0;\n                }\n            }\n        }\n        return 1;\n    }\n};\n"
  },
  {
    "path": "GFG/Chicks in a Zoo/Chicks in a Zoo.cpp",
    "content": "class solution{\n  public:\nlong long int NoOfChicks(int n){\n\t    // Code here\n\t  long long int popn[36];\n\t  long long int brth[36];\n\t  \n\t  popn[0]=0;popn[1]=1;\n\t  brth[0]=0;brth[1]=1;\n\t  \n\t  for(int i=2;i<=6;i++){\n\t      brth[i]=2*(popn[i-1]-0);\n\t      popn[i]=brth[i]+popn[i-1];\n\t  }\n\t  \n\t  for(int i=7;i<=n;i++){\n\t      brth[i]=2*(popn[i-1]-brth[i-6]);\n\t      popn[i]=popn[i-1]+brth[i]-brth[i-6];\n\t  }\n\t  return popn[n];\n\t}\n};\n"
  },
  {
    "path": "GFG/Chicks in a Zoo/Chicks in a Zoo.java",
    "content": "class Solution\n{\n    public long NoOfChicks(int N)\n    {\n        // Code here\n        long[]dp=new long[N+1];//new born\n        dp[1]=1;\n        long total=1;\n        for(int i=2;i<=N;i++){\n            if(i>6){\n                total-=dp[i-6];\n            }\n            dp[i]=total*2;\n            total+=(total*2);\n        }\n        return total;\n    }\n}\n"
  },
  {
    "path": "GFG/Complement/Complement.java",
    "content": "\n//GFG dsa self-paced Coupon code: SAGARGFGPOTD\n\nclass Solve {\n\n    Vector<Integer> findRange(String str, int n) {\n        // code here\n        int count=0;\n        int l=-1;\n        int max=0;\n        int ansL=-1;\n        int ansR=-1;\n        for(int i=0;i<n;i++){\n            if(str.charAt(i)=='0'){\n                count++;\n            }else{\n                count--;\n                if(count<0){\n                    count=0;\n                    l=-1;\n                }\n            }\n            \n            if(count==1 && l==-1){\n                l=i;\n            }\n            \n            if(count>max){\n                max=count;\n                ansL=l;\n                ansR=i;\n            }\n        }\n        Vector<Integer> ans=new Vector<>();\n        if(ansL==-1){\n            ans.add(-1);\n        }else{\n            ans.add(ansL+1);\n            ans.add(ansR+1);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Construct Binary Tree from String with bracket representation/Construct Binary Tree from String with bracket representation.cpp",
    "content": "class Solution{\n    \n    int ind = 0;\n    Node* solve(string str)\n    {\n        if(str.length() == 0 || ind >= str.length())\n           return NULL;\n          \n        //calculate num\n        int num = 0;\n        while(ind < str.length() && str[ind] != '(' && str[ind] != ')')\n        {\n            int val = (int)(str[ind]-'0');\n            num = num*10 + val;\n            ind++;\n        }\n        \n        //create new root\n        Node* root = NULL;\n        if(num > 0)\n          root = new Node(num);\n        \n       //for left child\n       if(ind < str.length() && str[ind] == '(')\n       {\n           ind++;\n           root->left = solve(str);\n       }\n        \n       if(ind < str.length() && str[ind] == ')')\n       {\n           ind++;\n           return root;\n       }\n       \n       //for right child\n       if(ind < str.length() && str[ind] == '(')\n       {\n           ind++;\n           root->right = solve(str);\n       }\n        \n       if(ind < str.length() && str[ind] == ')')\n       {\n           ind++;\n           \n       }\n        return root;  \n        \n    }\n    \npublic:\n    // function to construct tree from string\n    Node *treeFromString(string str){\n      \n        if(str.length() == 0) return NULL;\n        \n         return solve(str);\n          \n    }\n};\n"
  },
  {
    "path": "GFG/Construct Binary Tree from String with bracket representation/Construct Binary Tree from String with bracket representation.java",
    "content": "class Solution {\n    public static Node treeFromString(String s) {\n        // code here\n        int[] idx=new int[]{0};\n        return dfs(idx,s);\n    }\n    static Node dfs(int[] idx,String s){\n        if(idx[0]>=s.length() || s.charAt(idx[0])==')'){\n            idx[0]++;\n            return null;\n        }\n        \n        int num=0;\n        while(idx[0]<s.length() && Character.isDigit(s.charAt(idx[0]))){\n            num=num*10+(s.charAt(idx[0])-'0');\n            idx[0]++;\n        }\n        Node head=new Node(num);\n        if(idx[0]<s.length() && s.charAt(idx[0])=='('){\n            idx[0]++;\n            head.left=dfs(idx,s);\n        }\n        if(idx[0]<s.length() && s.charAt(idx[0])=='('){\n            idx[0]++;\n            head.right=dfs(idx,s);\n        }\n        idx[0]++;\n        \n        return head;\n    }\n}\n     \n"
  },
  {
    "path": "GFG/Container With Most Water/Container With Most Water.cpp",
    "content": "long long maxArea(long long A[], int len)\n{\n    // Your code goes here\n    int i = 0;\n    int j = len-1;\n    \n    long long maxArea = 0;\n    \n    long long base,height, currArea;\n    while(i < j)\n    {\n        base = j-i;\n        height = min(A[i], A[j]);\n        currArea = base*height;\n        \n        maxArea = max(maxArea, currArea);\n        \n        if(A[i] <= A[j]) i++;\n        else j--;\n    }\n    \n    return maxArea;\n}\n"
  },
  {
    "path": "GFG/Container With Most Water/Container With Most Water.java",
    "content": "\nclass Solve{\n    \n    long maxArea(int A[], int len){\n        // Code Here\n        long ans=0;\n        int i=0;\n        int j=len-1;\n        while(i<j){\n            ans=Math.max(ans,Math.min(A[i],A[j])*(j-i));\n            if(A[i]<A[j]){\n                i++;\n            }else{\n                j--;\n            }\n        }\n        return ans;\n    }\n    \n}\n"
  },
  {
    "path": "GFG/Count Lucky Permutations/Count Lucky Permutations.java",
    "content": "//dp[i][j] = total no. of permutation that ends with i and contain all set bit of j\n//i = node\n//j = visited array like\n\nclass Solution {\n    long luckyPermutations(int N, int M, int arr[], int[][] graph) {\n        // Code here\n        long[][] dp=new long[N][1<<N];\n        \n        boolean[][]adj=new boolean[N][N];\n        for(int i=0;i<M;i++){\n            adj[graph[i][0]-1][graph[i][1]-1]=true;\n            adj[graph[i][1]-1][graph[i][0]-1]=true;\n        }\n        \n        for(int i=0;i<N;i++){\n            dp[i][1<<i]=1;\n        }\n        \n        for(int bitmask=1;bitmask<(1<<N);bitmask++){\n            for(int i=0;i<N;i++){\n                for(int j=0;j<N;j++){\n                    if(i!=j && adj[arr[i]-1][arr[j]-1] && arr[i]!=arr[j]\n                    && (1 & (bitmask>>j))>0){\n                        dp[i][bitmask]+=dp[j][bitmask ^ (1<<i)];\n                    }\n                }\n            }\n        }\n        \n        long ans=0;\n        for(int i=0;i<N;i++){\n            ans+=dp[i][(1<<N)-1];\n        }\n        return ans;\n        \n    }\n}\n"
  },
  {
    "path": "GFG/Count all possible paths from top left to bottom right/Count all possible paths from top left to bottom right oc4.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n  public:\n        int mod = 1e9+7;\n        long long int mem(int i, int j, int m, int n, vector<vector<long long int>> &dp){\n            if(i== m-1 and j == n-1) return 1;\n            if(i >=m or j >=n) return 0;\n            if(dp[i][j]!=-1) return dp[i][j];\n            return dp[i][j] = (mem(i+1,j,m,n, dp)+ mem(i,j+1,m,n,dp))%mod;\n            \n        };\n    long long int numberOfPaths(int m, int n){\n        // code here\n        vector<vector<long long int>> dp(m, vector<long long int>(n,-1));\n        return mem(0,0,m,n,dp)%mod;\n\n    }\n};\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> m >> n;\n        Solution ob;\n        cout<<ob.numberOfPaths(m,n)<<endl;\n    }\n    return 0;\n}"
  },
  {
    "path": "GFG/Count all possible paths from top left to bottom right/Count all possible paths from top left to bottom right.cpp",
    "content": "class Solution {\n  public:\n    long long int numberOfPaths(int m, int n){\n        // code here\n       \n      vector<vector<long long int> > dp(m+1,vector<long long int> (n+1,1));\n       \n       \n       \n       for(int i=1; i<m; i++)\n          for(int j=1; j<n; j++)\n            {\n                    \n                    dp[i][j]=(dp[i-1][j]+dp[i][j-1])%1000000007;\n                    \n                \n            }\n  \n       \n       \n       return dp[m-1][n-1];\n       \n    }\n};\n"
  },
  {
    "path": "GFG/Count all possible paths from top left to bottom right/README.md",
    "content": "## Count all possible paths from top left to bottom right\n\nThe task is to count all the possible paths from top left to bottom right of a **m X n** matrix with the constraints that from each cell you can either move only to right or down.\n\n**Example 1:**\n\n\n```\nInput:\nm = 2, n = 2\n\nOutput: 2 \n\nExplanation: Two possible ways are\nRD and DR.  \n```\n\n**Example 2**:\n\n```\nInput: m = 3, R = 3\n\nOutput: 6\n\nExplanation: Six possible ways are\nRRDD, DDRR, RDDR, DRRD, RDRD, DRDR.\n```\n\n**Your Task:**  \n\nYou dont need to read input or print anything. Complete the function **numberOfPaths()** which takes m and n as input parameter and returns count all the possible paths.The answer may be very large, compute the answer modulo **10^9 + 7**.\n\n\n**Expected Time Complexity:** O(m*n)\n\n**Expected Auxiliary Space:** O(m*n)\n\n**Constraints:**\n\n1 <= m <=100\n1 <= n <=100\n"
  },
  {
    "path": "GFG/Count even length/Count even length.java",
    "content": "class Solution\n{\n    final long mod=1000000007;\n    public int  compute_value(int n)\n    {\n        // code here\n        \n        long ans=0;\n        long n_fact = 1;\n        for(int i=1;i<=n;i++)n_fact = (n_fact%mod*i%mod)%mod;//O(n)\n        long r_fact=1;\n        long n_r_fact=n_fact;\n        for(int r=0;r<=n;r++){//O(n)\n            long denom = (r_fact%mod * n_r_fact%mod)%mod;\n            long nCr = (n_fact%mod * power(denom,mod-2))%mod;//O(log10^9)\n            ans= (ans%mod + ((nCr%mod*nCr%mod)%mod)%mod);\n            r_fact=(r_fact%mod*(r+1)%mod)%mod;\n            if(n!=r)n_r_fact = (n_r_fact%mod * power((n-r),mod-2))%mod;\n        }\n        return (int)ans;\n    }\n    long power(long a,long b){\n        if(b==0)return 1;\n        long half= power(a,b/2);\n        long full = (half%mod*half%mod)%mod;\n        if(b%2==1)full = (full%mod*a%mod)%mod;\n        return full;\n    }\n}\n"
  },
  {
    "path": "GFG/Count of Subarrays/Count of Subarrays.cpp",
    "content": "class Solution{\npublic:\n\t// #define ll long long\n\n\tll countSubarray(int arr[], int n, int k) {\n\t       // code here\n\n     ll ans = (ll)n*(n+1)/2;\n\n        ll l =0;\n\n        for(int i=0;i<n;i++) {\n\n            if(arr[i]<=k) {\n\n                l++;\n\n            } else {\n\n                ans-=(l*(l+1)/2);\n\n                l=0;\n\n            }\n\n        }\n\n        ans-=(l*(l+1)/2);\n\n        return ans;\n\t}\n};\n"
  },
  {
    "path": "GFG/Count of Subarrays/Count of Subarrays.java",
    "content": "class Solution {\n\n    long countSubarray(int arr[], int n, int k) {\n        long ans=0;\n        int recent=-1;\n        for(int i=0;i<n;i++){\n            if(arr[i]>k){\n                ans++;\n                int left=i-(recent+1);\n                int right=n-1-i;\n                ans+=left;\n                ans+=right;\n                ans+=(left*right);\n                recent=i;\n            }\n        }\n        return ans;\n    }\n}\n\n\n\n// Method 2\n\nclass Solution {\n\n    long countSubarray(int arr[], int n, int k) {\n\n        // code here\n        int dy[]=new int[n];\n        int zero=-1;\n        for(int i=0;i<n;i++) {\n            if(arr[i]>k) dy[i]=n-i;\n            else {\n                dy[i]=zero;\n                zero-=1;\n            }\n        }\n        \n        long ans=0;\n        long curZero=0;\n        long zeros=0;\n        for(int i=0;i<n;i++) {\n            if(dy[i]>0)  {\n                curZero=zeros;\n                ans+=dy[i]+curZero;\n            }\n            else  {\n                ans+=curZero;\n                zeros=Math.abs(dy[i]);\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Count of Subarrays/README.md",
    "content": "# Count of Subarrays\n\n\nGiven an array of N positive integers  Arr1, Arr2 ............ Arrn. The value of each contiguous subarray of given array is the maximum element present in that subarray. The task is to return the number of subarrays having value strictly greater than K.\n\n**Example 1:**\n\n ```\nInput:\nN = 3, K = 2\nArr[] = {3, 2, 1}\nOutput: 3\nExplanation: The subarrays having value\nstrictly greater than K are: [3], [3, 2]\nand [3, 2, 1]. Thus there are 3 such\nsubarrays.\n```\n\n**Example 2:**\n\n```\n\nInput:\nN = 4, K = 1\nArr[] = {1, 2, 3, 4}\nOutput: 9\nExplanation: There are 9 subarrays having\nvalue strictly greater than K.\n```\n***\n\n\n**Your Task:**\nComplete the function **countSubarray()** which takes an array arr, two integers n, k, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs.\n\n*Expected Time Complexity:* O(N)\n*Expected Auxiliary Space:* O(1)\n\nConstraints:\n1 <= N <= 105\n1 <= Arr[i] <= 105\n"
  },
  {
    "path": "GFG/Count the Substring/Count the Substring.cpp",
    "content": "class Solution{\npublic:\n  long long countSubstring(string s){\n    // start writing from here\n    long long ans=0;\n    unordered_map<long long,long long> help; // start unodering     \n    vector<long long> dp(s.size(),0); // define the vector size\n    long long sum=-1;\n    if(s[0]=='1'){\n         dp[0]=1;\n         ans=1;\n         sum=1;\n    }\n    help[sum]=0;\n    help[0]=-1;\n    for(int i=1;i<s.size();i++){\n        long long temp=0;\n        if(s[i]=='0')\n            sum-=1;\n        else\n            sum+=1;\n        if(s[i]=='0'){\n            if(help.find(sum)!=help.end()) {\n                if(help[sum]!=-1){\n                    temp+=dp[help[sum]];\n                }\n            }\n        }\n        else{\n            if(help.find(sum)!=help.end()){\n                if(help[sum]!=-1){\n                    temp=dp[help[sum]]+i-help[sum]-1;\n                }\n                else{\n                    temp=i-help[sum]-1;\n                }\n            }\n            else{\n                temp+=i+1;\n            }\n        }\n        help[sum]=i;\n        dp[i]=temp;\n        ans+=temp;\n    }\n    return ans;\n  }\n};\n"
  },
  {
    "path": "GFG/Count the Substring/Count the Substring.java",
    "content": "class Solution {\n    long countSubstring(String S){\n        \n        int n=S.length();\n        long[]dp=new long[2*n+1];// no. of substring with >= zeroes\n        int cnt=n;\n        int minus=0;\n        for(int i=0;i<n;i++){\n            if(S.charAt(i)=='0'){\n                cnt--;\n            }else{\n                cnt++;\n            }\n            if(cnt<=n){\n                minus++;\n            }\n            dp[cnt]++;\n        }\n        \n        \n        long ans=0L;\n        int idx=n;\n        for(int i=0;i<n;i++){\n           ans+=(n-i - minus)*1l;\n           if(S.charAt(i)=='1'){\n               idx++;\n               dp[idx]--;\n               minus+=dp[idx];\n           }else{\n               minus--;\n               minus-=dp[idx];\n               idx--;\n               dp[idx]--;\n           }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Counting Elements in Two Arrays/Counting Elements in Two Arrays.cpp",
    "content": "class Solution{\n  public:\n    vector<int> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n)\n    {\n        //Your code goes here\n        vector<int> ans;\n        \n        sort(arr2, arr2+n);\n        \n        for(int i=0; i<m; i++)\n        {\n            int cnt = upper_bound(arr2, arr2+n, arr1[i]) - arr2;\n            \n            ans.push_back(cnt);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "GFG/Counting Elements in Two Arrays/Counting Elements in Two Arrays.java",
    "content": "class Solution\n{\n    public static ArrayList<Integer> countEleLessThanOrEqual(int arr1[], int arr2[], int m, int n)\n    {\n       // add your code here\n       Arrays.sort(arr2);//O(nlogn)\n       ArrayList<Integer> ans=new ArrayList<>();\n       for(int i=0;i<arr1.length;i++){\n           ans.add(binarySearch(arr2,arr1[i],0,arr2.length));\n       }\n       return ans;\n    }\n    static int binarySearch(int[]arr,int target,int i,int j){\n        if(i<j){\n            int mid=(i+j)/2;\n            if(arr[mid]<=target){\n                return binarySearch(arr,target,mid+1,j);\n            }else{\n                return binarySearch(arr,target,i,mid);\n            }\n        }\n        return i;\n    }\n}\n"
  },
  {
    "path": "GFG/Counting Elements in Two Arrays/Counting Elements in Two Arrays.py",
    "content": "from bisect import bisect_right\nclass Solution:\n    def countEleLessThanOrEqual(self,arr1,n1,arr2,n2):\n        arr2.sort()\n        res = []\n        \n        for num in arr1:\n            res.append(bisect_right(arr2,num))\n        return res\n"
  },
  {
    "path": "GFG/Cycle in Directed Graph/Cycle in Directed Graph.java",
    "content": "public class Solution {\n    public int solve(int vtces, ArrayList<ArrayList<Integer>> B) {\n        ArrayList<Edge>[] graph=new ArrayList[vtces];\n        int edge=B.size();\n        for(int i=0;i<vtces;i++){\n            graph[i]=new ArrayList<>();\n        }\n        //make 0 base vertex\n        for(int i=0;i<edge;i++){\n           int v1=B.get(i).get(0);\n           int v2=B.get(i).get(1);\n           graph[v1-1].add(new Edge(v1-1,v2-1));\n        }\n        boolean [] visited=new boolean[vtces];\n        for(int v=0;v<vtces;v++){\n            if(visited[v]==false){\n                boolean cycle=isCycle(graph,v,visited);\n                if(cycle){\n                    return 1;\n                }\n            }\n        }\n        return 0;\n\n    }\n    public static boolean isCycle(ArrayList<Edge> [] graph,int src,boolean[] visited){\n\n        visited[src]=true;\n        for(Edge e:graph[src]){\n            if(visited[e.nbr]==false){\n                isCycle(graph,e.nbr,visited);\n            }else{\n                return true;\n            }\n        }\n        visited[src]=false;\n\n        return false;\n    }\n}\nclass Edge{\n    int src;\n    int nbr;\n    Edge(int src,int nbr){\n        this.src=src;\n        this.nbr=nbr;\n    }\n}\n"
  },
  {
    "path": "GFG/Cycle in Undirected Graph/Cycle in Undirected Graph.java",
    "content": "public class Solution {\n    public int solve(int A, ArrayList<ArrayList<Integer>> B) {\n        ArrayList<ArrayList<Integer>> adj =  new ArrayList<>();\n        boolean vis[] = new boolean[A+1];\n        for(int i=0;i<=A;i++){\n            adj.add(new ArrayList<Integer>());\n        }\n        for(ArrayList<Integer> edge:B){\n            adj.get(edge.get(0)).add(edge.get(1));\n            adj.get(edge.get(1)).add(edge.get(0));\n        }\n        for(int i=1;i<=A;i++){\n            if(vis[i]==false){\n                if(dfs(adj,vis,i,-1))return 1;\n            }\n        }\n        return 0;\n    }\n    public boolean dfs(ArrayList<ArrayList<Integer>> adj, boolean vis[],int node,int parent){\n        vis[node] = true;\n        for(int it:adj.get(node)){\n            if(!vis[it]){\n                if(dfs(adj,vis,it,node))return true;\n            }else{\n                if(it!=parent)return true;\n            }\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "GFG/Decode the string/Decode the string.cpp",
    "content": "class Solution{\npublic:\n    string decodedString(string s){\n\n        string res=\"\";\n\n        stack<char> st;\n\n        st.push(s[0]);\n\n        for(int i=1;i<s.size();i++){\n\n            if(s[i]==']'){\n\n                while(!st.empty()&&st.top()!='['){\n\n                    res=st.top()+res;\n\n                    st.pop();\n\n                }\n\n                if(!st.empty())\n\n                    st.pop();\n\n                string rnum=\"\";\n\n                while(!st.empty()&&st.top()>='0'&&st.top()<='9'){\n\n                    rnum=st.top()+rnum;\n\n                    st.pop();\n\n                }\n\n                string sr=res;\n\n                for(int j=0;j<stoi(rnum)-1;j++){\n\n                    res+=sr;\n\n                }\n\n                for(auto x:res){\n\n                    st.push(x);\n\n                }\n\n                res=\"\";\n\n            }\n\n            else{\n\n                st.push(s[i]);\n\n            }\n\n        }\n\n        res=\"\";\n\n        while(!st.empty()){\n\n            res=st.top()+res;\n\n            st.pop();\n\n        }\n\n        return res;\n\n    }\n};\n"
  },
  {
    "path": "GFG/Decode the string/Decode the string.java",
    "content": "class Solution{\n    static String decodedString(String s){\n        // code here\n        Stack<Integer> nums=new Stack<>();\n        Stack<String> st=new Stack<>();\n        int i=0;\n        while(i<s.length()){\n            if(s.charAt(i)>='0' && s.charAt(i)<='9'){\n                int n=0;\n                while(s.charAt(i)>='0' && s.charAt(i)<='9'){\n                    n=n*10+(s.charAt(i)-'0');\n                    i++;\n                }\n                nums.push(n);\n            }else{\n                if(s.charAt(i)==']'){\n                    int n=nums.pop();\n                    StringBuilder inner=new StringBuilder();\n                    while(!st.peek().equals(\"[\")){\n                        inner.append(st.pop());\n                    }\n                    st.pop();\n                    StringBuilder newStr=new StringBuilder();\n                    while(n>0){\n                        newStr.append(inner);\n                        n--;\n                    }\n                    st.push(newStr.toString());\n                }else{\n                    st.push(\"\"+s.charAt(i));\n                }\n                i++;\n            }\n        }\n        \n        StringBuilder sb=new StringBuilder();\n        while(st.size()>0){\n            sb.append(st.pop());\n        }\n        return sb.reverse().toString();\n    }\n}\n\n\n//Method 2 Using single stack\n\n\nclass Solution{\n    static String decodedString(String s){\n        // code here\n        Stack<StringBuilder> st=new Stack<>();\n        \n        for(int i=0;i<s.length();i++) {\n            if(s.charAt(i)!=']') {\n                StringBuilder sb1=new StringBuilder(\"\"+s.charAt(i));\n                st.push(sb1);\n            }\n            else {\n                StringBuilder sb=new StringBuilder();\n                StringBuilder num=new StringBuilder();\n                while(!st.isEmpty() && (st.peek().length()>1 || (st.peek().length()==1 && st.peek().charAt(0)!='['))) { //popping all and adding to sb until we come across '['\n                    sb.append(st.pop());\n                }\n                st.pop();\n                while(!st.isEmpty() && \n                    (st.peek().length()==1 && st.peek().charAt(0)>='0' && st.peek().charAt(0)<='9')) { \n                    num.append(\"\"+st.pop());\n                }\n               \n                int times=1;\n                if(num.length()>0)\n                    times=Integer.valueOf(num.reverse().toString());\n                    \n                StringBuilder toAppend=new StringBuilder();\n                for(int j=0;j<times;j++) {\n                    toAppend.append(sb);\n                }\n                st.push(toAppend);\n            }\n        }\n        StringBuilder res=new StringBuilder();\n        while(!st.isEmpty()) {\n            res.append(st.pop());\n        }\n        return res.reverse().toString();\n    }\n}\n"
  },
  {
    "path": "GFG/Decode the string/README.md",
    "content": "## Decode the string\n\nAn encoded string (s) is given, the task is to decode it. The encoding pattern is that the occurance of the string is given at the starting of the string and each string is enclosed by square brackets.\n\n**Example 1:**\n\n```\nInput: s = 1[b]\n\nOutput: b\n\nExplaination: 'b' is present only one time.\n\n```\n**Example 2:**\n\n```\nInput: s = 3[b2[ca]]\n\nOutput: bcacabcacabcaca\n\nExplaination: 2[ca] means 'ca' is repeated \ntwice which is 'caca' which concatenated with \n'b' becomes 'bcaca'. This string repeated \nthrice becomes the output.\n\n```\n***\n\n**Your Task:**\nYou do not need to read input or print annything. Your task is to complete the function **decodedString()** which takes s as input parameter and returns the decoded string.\n\n**Expected Time Complexity:** O(|s|)\n**Expected Auxiliary Space:** O(|s|)\n\n**Constraints:**\n1 ≤ |s| ≤ 103 \n"
  },
  {
    "path": "GFG/Distance of nearest cell having 1/Distance of nearest cell having 1.java",
    "content": "class Solution\n{\n    //Function to find distance of nearest 1 in the grid for each cell.\n    public int[][] nearest(int[][] grid)\n    {\n        // Code here\n        int n=grid.length;\n        int m=grid[0].length;\n        boolean[][]vis=new boolean[n][m];\n        Queue<int[]> q=new LinkedList<>();\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 int[]{i,j});\n                    vis[i][j]=true;\n                }\n            }\n        }\n        int[][]ans=new int[n][m];\n        int[][]dirs={{1,0},{0,1},{-1,0},{0,-1}};\n        \n        int dis=0;\n        while(!q.isEmpty()){\n            int sz=q.size();\n            while(sz-->0){\n                int[]idx=q.remove();\n                int x=idx[0];\n                int y=idx[1];\n                ans[x][y]=dis;\n                for(int[]dir:dirs){\n                    int i=x+dir[0];\n                    int j=y+dir[1];\n                    if(i>=0 && j>=0 && i<n && j<m && !vis[i][j]){\n                        q.add(new int[]{i,j});\n                        vis[i][j]=true;\n                    }\n                }\n            }\n            dis++;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Earthquake and the Paint Shop/Earthquake and the Paint Shop.cpp",
    "content": "struct alphanumeric {\n    string name;\n    int count;\n};\nclass Solution {\n  public:\n    vector<alphanumeric> sortedStrings(int N, vector<string> A) {\n      \n        // code here\n        \n         vector<alphanumeric>ans;\n        map<string,int>mp;\n        for(int i=0;i<N;i++){\n            mp[A[i]]++;\n        }\n        for(auto i:mp){\n            ans.push_back({i.first,i.second});\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "GFG/Earthquake and the Paint Shop/README.md",
    "content": "## Earthquake and the Paint Shop\n\nGeek's Paint Shop is one of the famous shop in Geekland, but 2014 Earthquake caused disarrangement of the items in his shop. Each item in his shop is a 40-digit alpha numeric code .\nNow Chunky wants to retain the reputation of his shop, for that he has to arrange all the distinct items in lexicographical order.\nYour task is to arrange the all the distinct items in lexicographical ascending order and print them along with their count.\n\n**Example 1:**\n\n```\nInput:\nN = 3\n\nA[] =\n[\"2234597891 zmxvvxbcij 8800654113 jihgfedcba\",\n\"1234567891 abcdefghij 9876543219 jihgfedcba\",\n\"2234597891 zmxvvxbcij 8800654113 jihgfedcba\"]\n\nOutput:\n1234567891 abcdefghij 9876543219 jihgfedcba 1\n2234597891 zmxvvxbcij 8800654113 jihgfedcba 2\n\nExplanation:\nWe have 3 items (40 digit alphanumeric codes) \nhere. We arrange the items based on the \nlexicographical order of their alpha-numeric \ncode. Distinct items are printed only once. \nThe count of the items describes how many \nsuch items are there, so items that appear \nmore than once have their count greater than 1.\n\n```\n**Example 2:**\n\n```\nInput:\nN = 2\n\nA[] =\n[\"3122049353 onafrnbhtr 9822827304 yzfhdgzcvx\", \n\"2992299540 lpvkgykmlk 6946169466 vdqwvywwgg\", \n\nOutput:\n2992299540 lpvkgykmlk 6946169466 vdqwvywwgg  1\n3122049353 onafrnbhtr 9822827304 yzfhdgzcvx  1\n\nExplanation:\nOut of the 2 items here no one is repeated.\n\n```\n\n***\n\n**Your Task:**\nYou don't need to read input or print anything. Your task is to complete the function **sortedStrings()** which takes an integer N and an array of strings A[ ] and returns the array in sorted order along with the frequency of each distinct string.\n\n**Expected Time Complexity:** O(NlogN)\n\n**Expected Auxillary Space:** O(N)\n\n**Constraints:**\n1 ≤ N ≤ 10000\n"
  },
  {
    "path": "GFG/Enemy/Enemy.cpp",
    "content": "class Solution\n{\n    public:\n        int largestArea(int n,int m,int k,vector<vector<int>> &enemy)\n        {\n            if(k==0) return n*m;\n            vector<bool> r(n+1,false), c(m+1, false);\n            \n            \n            for(int i=0;i<enemy.size();i++){\n                int dr = enemy[i][0], dc = enemy[i][1];\n                r[dr] = true, c[dc] = true;\n            }\n            int ans = 0, tmp = 0, dx = 0, dy = 0, mx = 0, my = 0;\n            \n            for(int i=1;i<=n;i++){\n                if(r[i]==false) dx++;\n                else dx = 0;\n                mx = max(mx, dx);\n            }\n            \n            for(int i=1;i<=m;i++){\n                if(c[i]==false) dy++;\n                else dy = 0;\n                my = max(my, dy);\n            }\n            \n            return mx*my;\n        }\n};\n"
  },
  {
    "path": "GFG/Enemy/Enemy.java",
    "content": "class Solution {\n    public static int largestArea(int n,int m,int k,int[][] enemy) {\n        // code here\n        ArrayList<Integer> rows=new ArrayList<>();\n        \n        rows.add(-1);\n        for(int[]i:enemy){\n            rows.add(i[0]-1);\n        }\n        rows.add(n);\n        Collections.sort(rows);\n        \n        int maxRow=0;\n        for(int i=1;i<rows.size();i++){\n            int prev=rows.get(i-1);\n            int curr=rows.get(i);\n            maxRow=Math.max(maxRow,curr-prev-1);\n        }\n        \n        \n        ArrayList<Integer> cols=new ArrayList<>();\n        cols.add(-1);\n        for(int[]i:enemy){\n            cols.add(i[1]-1);\n        }\n        cols.add(m);\n        Collections.sort(cols);\n        \n        \n        int maxCol=0;\n        for(int i=1;i<cols.size();i++){\n            int prev=cols.get(i-1);\n            int curr=cols.get(i);\n            maxCol=Math.max(maxCol,curr-prev-1);\n        }\n        \n        // System.out.println(maxRow);\n        // System.out.println(maxCol);\n        \n        return maxRow*maxCol;\n        \n    }\n}\n \n"
  },
  {
    "path": "GFG/Fill up buckets/Fill up buckets.cpp",
    "content": "\n    }\n};\n\n\n//2nd Solution\n\nclass Solution{\npublic:\nint totalWays(int n, vector<int>capacity) {\n        long mod=1e9+7;\n       sort(capacity.begin(),capacity.end());\n       \n       long  ans=1;\n       \n       for(int i=0;i<n;i++)\n           ans=(ans*(capacity[i]-i))%mod;\n           \n        return ans;\n           \n       \n    }\n};\n"
  },
  {
    "path": "GFG/Fill up buckets/Fill up buckets.java",
    "content": "class Solution{\n    public int totalWays(int n, int[] arr) {\n        // code here\n        Arrays.sort(arr);\n        int mod=1000000007;\n        long ans=1;\n        for(int i=0;i<n;i++){\n            ans=(ans*(arr[i]-i))%mod;\n        }\n        return (int)ans%mod;\n    }\n}\n"
  },
  {
    "path": "GFG/Filling Bucket/Filling Bucket.cpp",
    "content": "class Solution {\n  public:\n    int fillingBucket(int N) {\n        // code here\n        \n         if(N<4) return N;\n         \n        long long mod=1e8;\n        vector<long long> dp(N+1);\n        dp[0]=0;\n        dp[1]=1;\n        dp[2]=2;\n        for(int i=3;i<=N;i++)\n            dp[i]=(dp[i-1]+dp[i-2])%mod;\n        return dp[N];\n    }\n};\n"
  },
  {
    "path": "GFG/Filling Bucket/Filling Bucket.java",
    "content": "class Solution {\n    static int fillingBucket(int N) {\n        // code here\n        if(N==1)return 1;\n        int prev=2;\n        int secPrev=1;\n        int mod=100000000;\n        for(int i=0;i<N-2;i++){\n            int currAns=(prev%mod+secPrev%mod)%mod;\n            secPrev=prev;\n            prev=currAns;\n        }\n        return prev;\n    }\n};\n"
  },
  {
    "path": "GFG/Filling Bucket/README.md",
    "content": "## Filling Bucket\n\nGiven a Bucket having a capacity of N litres and the task is to determine that by how many ways you can fill it using two bottles of capacity of 1 Litre and 2 Litre only. Find the answer modulo 10^8.\n\n**Example 1:**\n\n```\nInput:\n3\n\nOutput:\n3 \n\nExplanation:\nLet O denote filling by 1 litre bottle and\nT denote filling by 2 litre bottle.\nSo for N = 3, we have :\n{OOO,TO,OT}. Thus there are 3 total ways.\n\n```\n\n**Example 2:**\n\n```\nInput:\n4\n\nOutput:\n5 \n\nExplanation:\nLet O denote filling by 1 litre bottle and\nT denote filling by 2 litre bottle.\nSo for N = 4, we have :\n{TT,OOOO,TOO,OTO,OOT} thus there are 5 total ways.\n\n```\n\n***\n\n**Your Task:**\nYou don't need to read input or print anything. Your task is to complete the function **fillingBucket()** which takes an Integer N as input and returns the number of total ways possible.\n\n\n**Expected Time Complexity:** O(N)\n**Expected Auxiliary Space:** O(N)\n\n**Constraints:**\n1 <= N <= 105\n"
  },
  {
    "path": "GFG/Find The Safe Position/Find The Safe Position s30.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n  public:\n    int safePos(int n, int k) {\n        // code here\n        if(n==1) return 1;\n        int p = safePos(n-1, k);\n        return (p+k-1)%n +1;\n    }\n};\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n,k;\n        \n        cin>>n>>k;\n\n        Solution ob;\n        cout << ob.safePos(n,k) << endl;\n    }\n    return 0;\n}"
  },
  {
    "path": "GFG/Find The Safe Position/Find the Safe Position.java",
    "content": "class Solution {\n    static int safePos(int n, int k) {\n        ArrayList<Integer>aa=new ArrayList<Integer>();\n        for(int i=0;i<n;i++){\n            aa.add(i+1);\n        }\n        int a=0;\n        while(aa.size()!=1){\n            a=(a+(k-1))%aa.size();\n            aa.remove(a);\n            \n        }\n        return aa.get(0);\n    }\n};\n"
  },
  {
    "path": "GFG/Find minimum number of Laptops required/Find minimum number of Laptops required.cpp",
    "content": "class Solution {\n  public:\n    int minLaptops(int N, int start[], int end[]) {\n        // Code here\n        map<int,int> m;\n        \n        for(int i = 0; i < N; i++)\n          m[start[i]]++;\n          \n        for(int i = 0; i < N; i++)\n          m[end[i]]--;\n          \n          int cnt = 0;\n          int sum = 0;\n        for(auto i : m)\n        {\n            sum += i.second;\n            cnt = max(cnt , sum);\n            \n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "GFG/Find minimum number of Laptops required/Find minimum number of Laptops required.java",
    "content": "//1. sort according to our starting time\n//2. use priorityq to check minimum end time of previous laptop to be free\n//3. compare that with start time of our new job\n\nclass Solution {\n    public int minLaptops(int n, int[] start, int[] end) {\n        // code here\n        int[][] arr=new int[n][2];\n        for(int i=0;i<n;i++){\n            arr[i]=new int[]{start[i],end[i]};\n        }\n        \n        Arrays.sort(arr,(a,b)->{\n            if(a[0]!=b[0])return a[0]-b[0];\n            return a[1]-b[1];\n        });\n        \n        int ans=1;\n        PriorityQueue<Integer> pq=new PriorityQueue<>();\n        pq.add(arr[0][1]);\n        int i=1;\n        while(i<n){\n            int s=arr[i][0];\n            int e=arr[i][1];\n            if(pq.peek()<=s){\n                pq.remove();\n            }else{\n                ans++;\n            }\n            pq.add(e);\n            i++;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Find patterns/Find patterns.cpp",
    "content": "class Solution{   \npublic:\n    int numberOfSubsequences(string S, string W){\n        // code here \n        int k,c=0;\n        for(int i=0;i<S.size();i++) {\n            if(S[i]==W[0]) {\n                k=0;\n                for(int j=0;j<S.size() && k<W.size();j++) {\n                    if(S[j]==W[k])\n                    { S[j]='@'; k++; }\n                }\n                if(k==W.size()) c++;\n            }\n        }\n        return c;\n    }\n};\n"
  },
  {
    "path": "GFG/Find patterns/Find patterns.java",
    "content": "class Solution{\n    static int numberOfSubsequences(String S, String W){\n        // code here\n        int ans=0;\n        boolean[]vis=new boolean[S.length()];\n        for(int i=0;i<S.length();i++){\n            if(S.charAt(i)==W.charAt(0) && !vis[i]){\n                vis[i]=true;\n                int j=i+1;\n                int k=1;\n                while(j<S.length() && k<W.length()){\n                    if(S.charAt(j)==W.charAt(k) && !vis[j]){\n                        vis[j]=true;\n                        k++;\n                    }\n                    j++;\n                }\n                \n                if(k==W.length()){\n                    ans++;\n                }else{\n                    break;\n                }\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Find patterns/README.md",
    "content": "## Find patterns\n\nGiven two strings S and W. Find the number of times W appears as a subsequence of string S where every character of string S can be included in forming at most one subsequence.\n \n\n**Example 1:**\n\n```\n\nInput: \n S = \"abcdrtbwerrcokokokd\" \n W = \"bcd\" \n \nOutput: \n 2\n \nExplanation: \nThe two subsequences of string W are\n{ S1 , S2 , S3 } and { S6 , S11 , S18 }\n(Assuming 0- based indexing).\n``` \n\n**Example 2:**\n\n```\nInput: \nS = \"ascfret\" \nW = \"qwer\"\n\nOutput: \n0\n\nExplanation:\nNo valid subsequences are possible.\n```\n***\n\n\n**Your Task:**  \nYou don't need to read input or print anything. Your task is to complete the function *numberOfSubsequences()* which takes the string S and string W as input parameters and returns the number of subsequences of string W in string S.\n\n \n\n**Expected Time Complexity:** O(N^2)\n**Expected Auxiliary Space:** O(N)\n \n\n**Constraints:**\n1<=|S|<=1000\n1<=|W|<=|S|\n"
  },
  {
    "path": "GFG/Find the N-th character/Find the N-th character.cpp",
    "content": "class Solution{\n  public:\n    char nthCharacter(string S, int R, int N) {\n        bool flip = false;\n  \n        while (R --){\n            flip ^= N & 1;\n            N >>= 1;\n        }\n           \n        return S[N] ^ flip;\n    }\n};\n"
  },
  {
    "path": "GFG/Find the first node of loop in linked list/Find the first node of loop in linked list.java",
    "content": "class Solution {\n    //Function to find first node if the linked list has a loop.\n    public static int findFirstNode(Node head){\n        //code here\n        Node slow=head;\n        Node fast=head;\n        while(fast!=null && fast.next!=null){\n            slow=slow.next;\n            fast=fast.next.next;\n            if(slow==fast)break;\n        }\n        if(fast==null || fast.next==null)return -1;\n        Node temp=head;\n        while(temp!=slow){\n            temp=temp.next;\n            slow=slow.next;\n        }\n        return slow.data;\n    }\n}\n"
  },
  {
    "path": "GFG/Find the longest string/Find the longest string.java",
    "content": "class TrieNode{\n    boolean isEnd;\n    TrieNode[] arr;\n    TrieNode(){\n        isEnd=false;\n        arr = new TrieNode[26];\n    }\n}\n\n\nclass Solution {\n    static TrieNode root;\n    public static String longestString(int n, String[] arr) {\n        // code here\n        root=new TrieNode();\n        for(String s:arr){\n            insert(s);\n        }\n        String ans=\"\";\n        for(String s:arr){\n            if(s.length()<ans.length()){\n                continue;\n            }else{\n                if(isPresent(s)){\n                    if(s.length()>ans.length()){\n                        ans=s;\n                    }else if(s.length()==ans.length()){\n                        if(s.compareTo(ans)<0){\n                            ans=s;\n                        }\n                    }\n                }\n            }\n        }\n        return ans;\n        \n    }\n    \n    static boolean isPresent(String s){\n        TrieNode curr=root;\n        for(char c:s.toCharArray()){\n            int index=c-'a';\n            curr=curr.arr[index];\n            if(curr.isEnd==false)return false;\n        }\n        return true;\n    }\n    \n    static void insert(String s){\n        TrieNode curr=root;\n        for(char c:s.toCharArray()){\n            int index=c-'a';\n            if(curr.arr[index]==null){\n                curr.arr[index]=new TrieNode();\n            }\n            curr=curr.arr[index];\n        }\n        curr.isEnd=true;\n    }\n}\n"
  },
  {
    "path": "GFG/Find the maximum GCD of the siblings of a Binary Tree/Find the maximum GCD of the siblings of a Binary Tree.java",
    "content": "class Solution {\n    int max_gcd;\n    int ans;\n    int maxGCD(Node root) {\n        // code here \n        ans=0;\n        max_gcd=0;\n        dfs(root);\n        return ans;\n    }\n    int dfs(Node root){\n        if(root==null)return 0;\n        int left=dfs(root.left);\n        int right=dfs(root.right);\n        if(left!=0 && right!=0){\n            int gcd=gcd(left,right);\n            if(gcd>max_gcd){\n                max_gcd=gcd;\n                ans=root.data;\n            }else if(gcd==max_gcd && root.data>ans){\n                ans=root.data;\n            }\n        }\n        return root.data;\n    }\n    int gcd(int a,int b){\n        if(a==0)return b;\n        return gcd(b%a,a);\n    }\n}\n"
  },
  {
    "path": "GFG/Fitting The Array/Fitting The Array s28.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nclass Solution{\npublic:\n    \n    bool isFit(int arr[], int brr[], int n){\n        // code here\n        sort(arr, arr+n);\n        sort(brr, brr+n);\n        \n        for(int i=0; i<n; i++){\n            if(arr[i] <= brr[i]) continue;\n            else return false;\n        }\n        return true;\n    }\n};\nint main()\n{\n    int i,j,z,t,n,flag;\n    cin>>t;\n    for(z=0;z<t;z++)\n    {\n        flag=0;\n        cin>>n;\n        int arr[n+1], brr[n+1];\n        \n        for(i=0;i<n;i++)\n            cin>>arr[i];\n        for(i=0;i<n;i++)\n            cin>>brr[i];\n        \n        Solution ob;\n        \n        if(ob.isFit(arr, brr, n))  cout<<\"YES\\n\";\n        else\n            cout << \"NO\\n\";\n            \n        \n    }\n    return 0;\n}"
  },
  {
    "path": "GFG/Fitting The Array/Fitting The Array.cpp",
    "content": "class Solution{\npublic:\n    \n    bool isFit(int arr[], int brr[], int n){\n        // code here\n        sort(arr, arr+n);\n        sort(brr, brr+n);\n        \n        for(int i=0; i<n; i++)\n            if(arr[i] > brr[i])\n                return false;\n                \n        return true;\n    }\n};\n"
  },
  {
    "path": "GFG/Fitting The Array/Fitting The Array.java",
    "content": "class Solution{\n    \n   \n    // Function for finding maximum and value pair\n    public static boolean isFit (int arr[], int brr[], int n) {\n        //Complete the function\n        Arrays.sort(arr);\n        Arrays.sort(brr);\n        for(int i=0;i<n;i++){\n            if(arr[i]>brr[i]){\n                return false;\n            }\n        }\n        return true;\n    }\n    \n}\n"
  },
  {
    "path": "GFG/Flatten binary tree to linked list/Flatten binary tree to linked list.java",
    "content": "class Solution\n{\n    static Node curr;\n    public static void flatten(Node root)\n    {\n        //code here\n        curr=new Node(-1);\n        dfs(root);\n    }\n    static void dfs(Node root){\n        if(root==null)return;\n        Node leftSubtree=root.left;\n        root.left=null;\n        Node rightSubtree=root.right;\n        root.right=null;\n        \n        curr.right=root;\n        curr=curr.right;\n        \n        dfs(leftSubtree);\n        dfs(rightSubtree);\n        \n    }\n}\n"
  },
  {
    "path": "GFG/Flatten binary tree to linked list/Readme.md",
    "content": "Given the root of a binary tree, flatten the tree into a \"linked list\":\n\nThe \"linked list\" should use the same Node class where the right child pointer points to the next   node in the list and the left child pointer is always null.\nThe \"linked list\" should be in the same order as a pre-order traversal of the binary tree.\nExample 1:\n\nInput : \n          1\n        /   \\\n       2     5\n      / \\     \\\n     3   4     6\nOutput :\n1 2 3 4 5 6 \nExplanation: \nAfter flattening, the tree looks \nlike this\n    1\n     \\\n      2\n       \\\n        3\n         \\\n          4\n           \\\n            5\n             \\\n              6 \nHere, left of each node points \nto NULL and right contains the \nnext node in preorder.The inorder \ntraversal of this flattened tree \nis 1 2 3 4 5 6.\nExample 2:\n\nInput :\n        1\n       / \\\n      3   4\n         /\n        2\n         \\\n          5 \nOutput : \n1 3 4 2 5  \nExplanation : \nAfter flattening, the tree looks \nlike this \n     1\n      \\\n       3\n        \\\n         4\n          \\\n           2\n            \\ \n             5 \nHere, left of each node points \nto NULL and right contains the \nnext node in preorder.The inorder \ntraversal of this flattened tree \nis 1 3 4 2 5.\nYour task:\nYou don't have to read input or print anything. Your task is to complete the function flatten() which takes the root of the tree and flattens the tree into a linkes list without using any auxiliary space.\nNote : The driver code prints the inorder traversal of the flattened binary tree.\n \nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(1)\n \nConstraints :\n1<=n<=10^5\n"
  },
  {
    "path": "GFG/Flattening a Linked List/Flattening a Linked List.java",
    "content": "class GfG\n{\n    Node flatten(Node root)\n    {\n\t// Your code here\n\t   Node nexty=root.next;\n\t   while(nexty!=null){\n\t       Node second=nexty;\n\t       nexty=nexty.next;\n\t       second.next=null;\n\t       root=merge(root,second);\n\t   }\n\t   return root;\n    }\n    Node merge(Node l1,Node l2){\n        Node head=new Node(0);\n        Node curr=head;\n        while(l1!=null && l2!=null){\n            if(l1.data<=l2.data){\n                curr.bottom=l1;\n                l1=l1.bottom;\n            }else{\n                curr.bottom=l2;\n                l2=l2.bottom;\n            }\n            curr=curr.bottom;\n        }\n        \n        if(l1!=null)curr.bottom=l1;\n        if(l2!=null)curr.bottom=l2;\n        \n        return head.bottom;\n    }\n}\n"
  },
  {
    "path": "GFG/Floyd Warshall/Floyd Warshall.java",
    "content": "class Solution\n{\n    public void shortest_distance(int[][] mat)\n    {\n        // Code here \n        int n=mat.length;\n        for(int k=0;k<n;k++){\n            for(int i=0;i<n;i++){\n                for(int j=0;j<n;j++){\n                    if(mat[i][k]==-1 || mat[k][j]==-1)continue;\n                    if(mat[i][j]==-1 || mat[i][k]+mat[k][j]<mat[i][j]){\n                        mat[i][j]=mat[i][k]+mat[k][j];\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "GFG/Floyd Warshall/FloydWarshall.cpp",
    "content": "class Solution {\n  public:\n void shortest_distance(vector<vector<int>>&mat)\n     int n = mat.size();\n     for(int i = 0;i<n;i++)\n     {\n         for(int j = 0;j<n;j++)\n         {\n             for(int k = 0;k<n;k++)\n             {\n                 if(mat[j][k] == -1)\n                 {\n                     if(mat[j][i] != -1 && mat[i][k] != -1)\n                     mat[j][k] = mat[j][i] + mat[i][k];\n                 }\n                 else \n                {\n                     if(mat[j][i] != -1 && mat[i][k] != -1)\n                     mat[j][k] = min(mat[j][k] , mat[j][i]+mat[i][k]);\n                }              \n             }\n         }\n     }\n }\n};\n"
  },
  {
    "path": "GFG/Floyd Warshall/README.md",
    "content": "## Floyd Warshall\n\nThe problem is to find the shortest distances between every pair of vertices in a given edge-weighted directed graph. The graph is represented as an adjacency matrix of size n*n. Matrix[i][j] denotes the weight of the edge from i to j. If Matrix[i][j]=-1, it means there is no edge from i to j.\nDo it in-place.\n\n**Example 1:**\n\n```\nInput: matrix = {{0,25},{-1,0}}\n```\n![WhatsAppImage20221106at82359PM](https://user-images.githubusercontent.com/76674591/200365930-d55ea884-7801-49f7-b06e-bf694223f9d4.jpg)\n```\nOutput: {{0,25},{-1,0}}\n```\n![WhatsAppImage20221106at82359PM](https://user-images.githubusercontent.com/76674591/200365962-8ac32eb0-a3b2-4f26-87f5-17a9dcdc8a92.jpg)\n```\nExplanation: The shortest distance between\nevery pair is already given(if it exists).\n```\n\n**Example 2:**\n\n```\n\nInput: matrix = {{0,1,43},{1,0,6},{-1,-1,0}}\n```\n![WhatsAppImage20221106at83711PM](https://user-images.githubusercontent.com/76674591/200366016-0a4cbfaf-518b-4017-95e6-3350c2c63b13.jpg)\n```\nOutput: {{0,1,7},{1,0,6},{-1,-1,0}}\n```\n![WhatsAppImage20221106at84031PM](https://user-images.githubusercontent.com/76674591/200366037-b6da38af-f845-48c9-9bba-de345ec295ed.jpg)\n```\nExplanation: We can reach 2 from 0 as 0->1->2\nand the cost will be 1+6=7 which is less than \n43.\n\n```\n***\n\n**Your Task:**\nYou don't need to read, return or print anything. Your task is to complete the function **shortest_distance()** which takes the matrix as input parameter and modifies the distances for every pair in-place.\n\n**Expected Time Complexity:** O(n3)\n**Expected Space Complexity:** O(1)\n\n**Constraints:**\n1 <= n <= 100\n-1 <= matrix[ i ][ j ] <= 1000\n"
  },
  {
    "path": "GFG/Form a palindrome/Form a palindrome.py",
    "content": "#User function Template for python3\n\nclass Solution:\n    def countMin(self, Str):\n        arr = Str\n        brr = arr[::-1]\n        \n        m = len(arr)\n        n = len(brr)\n        lcs = [[0]*(n+1) for _ in range(m+1)]\n        \n        for i in range(1,m+1):\n            for j in range(1,n+1):\n                if arr[i-1] == brr[j-1]:\n                    lcs[i][j] = 1 + lcs[i-1][j-1]\n                else:\n                    lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1])\n        return n - lcs[m][n]\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n\n    t = int(input())\n\n    for _ in range(t):\n        Str = input()\n        \n\n        solObj = Solution()\n\n        print(solObj.countMin(Str))\n# } Driver Code Ends\n"
  },
  {
    "path": "GFG/GCD Array/GCD Array.java",
    "content": "class Solution {\n    public static int solve(int N, int K, int[] arr) {\n        // code here\n        for(int i=1;i<N;i++) arr[i]+=arr[i-1];\n        ArrayList<Integer> factor = new ArrayList<>();\n        for(int i=1;i*i<=arr[N-1];i++) {\n            if(arr[N-1]%i==0) {\n                factor.add(i);\n                factor.add(arr[N-1]/i);\n            }\n        }\n        \n        int ans=1;\n        for(int fact : factor) {\n            int count=0;\n            for(int a : arr) {\n                if(a%fact==0) {\n                    count++;\n                }\n            }\n            if(count>=K) ans=Math.max(ans,fact);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Geek and Number String/Geek and Number Str.cpp",
    "content": "int minLength(string s, int n) {\n        string temp=\"12 21 34 43 56 65 78 87 09 90\";\n      stack<char>st;\n      st.push(s[0]);\n      for(int i=1;i<n;i++){\n          if(st.size()>0){\n              string str;\n               str+=st.top();\n              str+=s[i];\n              if(temp.find(str)!=string::npos){\n                  st.pop();\n              }else{\n                  st.push(s[i]);\n              }\n          }else\n          st.push(s[i]);\n      }\n      return st.size();\n    } "
  },
  {
    "path": "GFG/Geek and Strings/Geek and Strings.java",
    "content": "class Solution{\n    static class Trie {\n        Trie child[]=new Trie[26];\n        int count[]=new int[26];\n    }\n    static List<Integer> prefixCount(int N, int Q, String li[], String query[])\n    {\n        // code here\n        List<Integer> res=new ArrayList<>();\n        Trie head=null;\n        head=new Trie();\n        Trie cur=head;\n        for(int i=0;i<li.length;i++) {\n            String s=li[i];\n            cur=head;\n            for(int j=0;j<s.length();j++) {  //inserting every string into the trie\n                if(cur.child[s.charAt(j)-'a']!=null) {\n                    cur=cur.child[s.charAt(j)-'a'];\n                }\n                else {\n                    cur.child[s.charAt(j)-'a']=new Trie();\n                    cur=cur.child[s.charAt(j)-'a'];\n                }\n                cur.count[s.charAt(j)-'a']+=1;\n            }\n        }\n        \n        for(int i=0;i<query.length;i++) {\n            String s=query[i];\n            cur=head;\n            int exist=1;\n            for(int j=0;j<s.length();j++) {\n                cur=cur.child[s.charAt(j)-'a'];\n                if(cur==null) { // if cur==null then there is no prefix with string breaking\n                    exist=0;\n                    break;\n                }\n            }\n            if(exist==1) //if string exist then adding count of last character(how many strings present until last character) to res\n                res.add(cur.count[s.charAt(s.length()-1)-'a']);\n            else //else adding 0 as there is no prefix with string\n                res.add(0);\n        }\n        return res;\n    }\n}\n"
  },
  {
    "path": "GFG/Geek and Strings/ReadMe.md",
    "content": "# Geek and Strings\n\nGeek has a list Li containing (not necessarily distinct) N words and Q queries. Each query consists of a string x. For each query, find how many strings in the List Li has the string x as its prefix. \n\nExample 1:\n\nInput: \nN = 5, Q = 5\nli[] = {'abracadabra', 'geeksforgeeks', \n      'abracadabra', 'geeks', 'geeksthrill'}\nquery[] = {'abr', 'geeks', 'geeksforgeeks', \n         'ge', 'gar'}\n\nOutput: 2 3 1 3 0\n\nExplaination: \nQuery 1: The string 'abr' is prefix of \ntwo 'abracadabra'. \nQuery 2: The string 'geeks' is prefix of three \nstrings 'geeksforgeeks', 'geeks' and 'geeksthrill'. \nQuery 3: The string 'geeksforgeeks' is prefix \nof itself present in li. \nQuery 4: The string 'ge' also is prefix of three \nstrings 'geeksforgeeeks', 'geeks', 'geeksthrill'. \nQuery 5: The string 'gar' is not a prefix of any \nstring in li.\n\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function prefixCount() which takes N, Q, li[] and query[] as input parameters and returns a list containing the count of prefixes for each query. \n\n\nExpected Time Complexity: O(Q*x)\nExpected Auxiliary Space: O(N*li [i])\n\n\nConstraints:\n1 ≤ N ≤ 3 x 104\n1 ≤ Q ≤ 104\n1 ≤ |li[i]|, |x| ≤ 100  \n"
  },
  {
    "path": "GFG/Geek in a Maze/Geek in a maze.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\n // } Driver Code Ends\n//User function Template for Java\nclass Pair\n{\n    int x, y, u_left, d_left;\n    \n    Pair(int x, int y, int u_left, int d_left)\n    {\n        this.x = x;\n        this.y = y;\n        this.u_left = u_left;\n        this.d_left = d_left;\n    }\n}\n\n\nclass Solution\n{\n    \n    private static boolean isValid(int x, int y, boolean visited[][], char mat[][], int n, int m)\n    {\n        if(x<0 || x>=n || y<0 || y>=m || visited[x][y]==true || mat[x][y]=='#') return false;\n        else return true;\n    }\n    \n\n\tpublic static int numberOfCells(int n, int m, int r, int c, int u, int d, char mat[][])\n\t{\n\t    Queue<Pair> queue = new ArrayDeque<>();\n\t    \n\t    boolean visited[][] = new boolean[n][m];\n\t    \n\t    queue.offer(new Pair(r, c, u, d));\n\t    \n\t    visited[r][c] = true;\n\t    \n\t    if(mat[r][c]=='#') return 0;\n\t    \n\t    int total_count = 1;\n\t    \n\t    while(!queue.isEmpty())\n\t    {\n\t        Pair p = queue.poll();\n\t        \n\t        \n\t        if(isValid(p.x, p.y+1, visited, mat, n, m))\n\t        {\n\t            total_count++;\n\t            visited[p.x][p.y+1] = true;\n\t            queue.offer(new Pair(p.x, p.y+1, p.u_left, p.d_left));\n\t        }\n\t        \n\t        if(isValid(p.x, p.y-1, visited, mat, n, m))\n\t        {\n\t            total_count++;\n\t            visited[p.x][p.y-1] = true;\n\t            queue.offer(new Pair(p.x, p.y-1, p.u_left, p.d_left));\n\t        }\n\t        \n\t        if(p.d_left>0 && isValid(p.x+1, p.y, visited, mat, n, m))\n\t        {\n\t            total_count++;\n\t            visited[p.x+1][p.y] = true;\n\t            queue.offer(new Pair(p.x+1, p.y, p.u_left, p.d_left-1));\n\t        }\n\t        \n\t        if(p.u_left>0 && isValid(p.x-1, p.y, visited, mat, n, m))\n\t        {\n\t            total_count++;\n\t            visited[p.x-1][p.y] = true;\n\t            queue.offer(new Pair(p.x-1, p.y, p.u_left-1, p.d_left));\n\t        }\n\t        \n\t    }\n\t    \n\t    return total_count;\n\t\t\n\t}\n\n}\n\n\n// { Driver Code Starts.\n\npublic class GFG {\n\tpublic static void main (String[] args) {\n\t    Scanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();\n\t\twhile (t-- > 0)\n\t\t{\n\t\t    int n = sc.nextInt();\n\t\t    int m = sc.nextInt();\n\t\t    int r = sc.nextInt();\n\t\t    int c = sc.nextInt();\n\t\t    int u = sc.nextInt();\n\t\t    int d = sc.nextInt();\n\t\t    \n\t\t    char mat[][] = new char[n][m];\n\n            for(int i = 0; i < n; i++)\n            {\n                String s = sc.next();\n                for(int j = 0; j < m; j++)\n                {\n                    mat[i][j] = s.charAt(j);\n                }\n            }\n            \n            Solution obj = new Solution();\n            System.out.println(obj.numberOfCells(n, m, r, c, u, d, mat));\n\t\t    \n\t\t}\n\t}\n}\n\n  // } Driver Code Ends"
  },
  {
    "path": "GFG/Geek in a Maze/README.md",
    "content": "# Geek in a Maze\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Geek is in a maze of size N * M. Each cell in the maze is made of either '.' or '#'. An empty cell is represented by '.' and an obstacle is represented by '#'. If Geek starts at cell (R, C), find how many different empty cells&nbsp;he can pass through while avoiding the obstacles. He can move in any of the four directions but he can move up at most U times and he can move down atmost D times. </span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> \nN = 3, M = 3\nR = 1, C = 0\nU = 1, D = 1\nmat = {{'.', '.', '.'},\n       {'.', '#', '.'},\n       {'#', '.', '.'}}\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> Geek can reach \n(1, 0), (0, 0), (0, 1), (0, 2), (1, 2) \n\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> \nN = 3, M = 4\nR = 1, C = 0\nU = 1, D = 2 \nmat = {{'.', '.', '.'}, \n       {'.', '#', '.'}, \n       {'.', '.', '.'},\n       {'#', '.', '.'}} \n<strong>Output:</strong> 10\n<strong>Explanation:</strong> Geek can reach all the \ncells except for the obstacles.\n</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task: &nbsp;</strong><br>\nYou don't need to read input or print anything. Complete the function <strong>numberOfCells()&nbsp;</strong>which takes&nbsp;<strong>N, M, R, C, U, D</strong> and the&nbsp;two dimensional character array&nbsp;<strong>mat[][]</strong> as input parameters and returns the number of cells geek can visit( If he is standing on obstacle he can not move). </span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N*M ≤ 10<sup>6</sup><br>\nmat[i][j] = '#\" or '.'<br>\n0 ≤ R ≤ N-1<br>\n0 ≤ C ≤ M-1</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "GFG/Grouping Of Numbers/Grouping Of Numbers.java",
    "content": "class Solution {\n    static int maxGroupSize(int[] a, int N, int k) {\n        // code here\n        int[]dp=new int[k];\n        for(int i:a){\n            dp[i%k]++;\n        }\n        \n        int maxSize=0;\n        int i=1;\n        int j=k-1;\n        while(i<j){\n            maxSize+=Math.max(dp[i],dp[j]);\n            i++;\n            j--;\n        }\n        if(dp[0]>0){\n            maxSize++;\n        }\n        if(i==j && dp[i]>0){\n            maxSize++;\n        }\n        return maxSize;\n    }\n};\n\n\n// Method 2:\n\nclass Solution {\n    static int maxGroupSize(int[] arr, int N, int K) {\n        // code here\n        int freq[]=new int[K];\n        for(int i=0;i<N;i++) {\n            freq[arr[i]%K]+=1;\n        }\n        int start=1;\n        int end=K-1;\n        while(start<=end) {\n            if(start!=end) {\n                if(freq[start]!=0 && freq[end]!=0) {\n                    if(freq[start]>freq[end]) {\n                        freq[end]=0;\n                    }\n                    else {\n                        freq[start]=0;\n                    }\n                }\n            }\n            else {\n                if(freq[start]>0) freq[start]=1;\n            }\n            start+=1;\n            end-=1;\n        }\n        \n        if(freq[0]>0) freq[0]=1;\n        \n        int count=0;\n        for(int i=0;i<K;i++) {\n            if(freq[i]>0) count+=freq[i];\n        }\n        return count;\n    }\n};\n"
  },
  {
    "path": "GFG/Hamiltonian Path/Hamiltonian Path.cpp",
    "content": "\n    }\n};\n"
  },
  {
    "path": "GFG/Hamiltonian Path/Hamiltonian Path.java",
    "content": "class Solution \n{ \n    int n;\n    boolean check(int N, int M, ArrayList<ArrayList<Integer>> Edges) \n    { \n        // code here\n        n=N;\n        Map<Integer,ArrayList<Integer>> map=new HashMap<>();\n        for(ArrayList<Integer> edge:Edges){\n            int src=edge.get(0);\n            int des=edge.get(1);\n            map.putIfAbsent(src,new ArrayList<>());\n            map.putIfAbsent(des,new ArrayList<>());\n            map.get(src).add(des);\n            map.get(des).add(src);\n        }\n        \n        Set<Integer> set=new HashSet<>();\n        for(int node=1;node<=N;node++){\n            if(dfs(node,set,map)){\n                return true;\n            }\n        }\n        return false;\n    }\n    boolean dfs(int curr,Set<Integer> set,Map<Integer,ArrayList<Integer>> map){\n        set.add(curr);\n        if(set.size()==n){\n            return true;\n        }\n        \n        for(int neb:map.get(curr)){\n            if(!set.contains(neb) && dfs(neb,set,map)){\n                return true;\n            }\n        }\n        \n        set.remove(curr);//back..\n        return false;\n    }\n} \n"
  },
  {
    "path": "GFG/Hamiltonian Path/README.md",
    "content": "## Hamiltonian Path\n\nA Hamiltonian path, is a path in an undirected graph that visits each vertex exactly once. Given an undirected graph, the task is to check if a Hamiltonian path is present in it or not.\n\n**Example 1:**\n\n```\nInput:\nN = 4, M = 4\n\nEdges[][]= { {1,2}, {2,3}, {3,4}, {2,4} }\n\nOutput:\n1 \nExplanation: \n\nThere is a hamiltonian path: \n1 -> 2 -> 3 -> 4 \n\n```\n**Example 2:**\n\n```\nInput:\nN = 4, M = 3 \n\nEdges[][] = { {1,2}, {2,3}, {2,4} } \n\nOutput: \n0 \n\nExplanation: \nIt can be proved that there is no \nhamiltonian path in the given graph\n```\n\n***\n\n**Your task:**\nYou don't need to read input or print anything. Your task is to complete the function **check()** which takes the N (the number of vertices), M (Number of edges) and the list of Edges[][] (where Edges[i] denotes the undirected Edge between vertices Edge[i][0] and Edges[i][1] ) as input parameter and returns true (boolean value) if the graph contains Hamiltonian path,otherwise returns false. \n\n\n**Expected Time Complexity:** O(N!).\n**Expected Auxiliary Space:** O(N+M).\n\n\n**Constraints:**\n1 ≤ N ≤ 10\n1 ≤ M ≤ 15\nSize of Edges[i] is 2\n1 ≤ Edges[i][0],Edges[i][1] ≤ N\n"
  },
  {
    "path": "GFG/Help Ishaan/Help Ishaan.cpp",
    "content": "\tpublic:\n\tbool isPrime(int x){\n\n         if(x==1)return false;\n\n         if(x==2||x==3)\n\n          return true;\n\n         if(x%2==0||x%3==0)\n\n          return false;\n\n         for(int i=5;i*i<=x;i+=6){\n\n             if(x%i==0||x%(i+2)==0)\n\n               return false;\n\n         }\n\n       return true;\n\n     }\n\t\tint NthTerm(int N){\n\t\t    // Code here\n\t\t    if(isPrime(N))\n\n     return 0;\n\n    int n1,n2;\n\n    n1=N-1,n2=N+1;\n\n    while(n1>1 && isPrime(n1)==0)\n\n     n1--;\n\n    while(isPrime(n2)==0)\n\n     n2++;\n\n    \n\n    return (n1>1)?min(N-n1,n2-N):(n2-N);  \n\t\t}\n\n};\n"
  },
  {
    "path": "GFG/Help Ishaan/Help Ishaan.java",
    "content": "class Solution\n{\n    public static boolean isPrime(int n){\n        if(n==1){\n            return false;\n        }\n        else if(n==2 || n==3){\n            return true;\n        }\n        else if(n%2==0 || n%3==0){\n            return false;\n        }\n        else{\n            for(int i=5;i<=Math.sqrt(n);i+=6){\n                if(n%(i)==0 || n%(i+2)==0){\n                    return false;\n                }\n            }\n            return true;\n        }\n        \n    }\n    public int NthTerm(int n)\n    {\n        if(isPrime(n)==true){\n            return 0;\n        }\n        else{\n          \n            int diff=0;\n            if(n-19<=0){\n                diff=0;\n            }\n            else{\n                diff=n-19;\n            }\n            int min=Integer.MAX_VALUE;\n            for(int i=diff;i<(n+19);i++){\n                if(isPrime(i)){\n                    min=Integer.min((int)Math.abs(i-n),min);\n                }\n            }\n            return min;\n            \n          \n        }\n    }\n}\n\n\n// A different code for the same solution\n\nclass Solution\n{\n    public static boolean isPrime(int num){\n        if(num<2){\n            return false;\n        }\n        for(int i = 2; i<= Math.sqrt(num); i++){\n            if(num % i == 0){\n                return false;\n            }\n        }\n        return true;\n    }\n    public int NthTerm(int n)\n    {\n        // code here\n        int diff = 0;\n        if(isPrime(n)){\n            return diff;\n        }\n        while(true){\n            if(isPrime(n+diff) || isPrime(n-diff)){\n                break;\n            }\n            diff++;\n        }\n        return diff;\n        \n    }\n}\n"
  },
  {
    "path": "GFG/Help Ishaan/README.md",
    "content": "## Help Ishaan\n\nIshaan has been given a task by his teacher. He needs to find the **Nth** term of a series. His teacher gives him some examples to help him out (Refer examples below). He is a bit weak in pattern searching so to help him his teacher told him that the **Nth term is related to prime numbers**. The Nth term is the **difference of N and the closest prime number to N.** Help him find the Nth term for a given N.\n \n\n**Example 1:**\n```\nInput: N = 10\n\nOutput: 1\n\nExplanation: Closest prime to 10 is 11.\n```\n\n**Example 2:**\n```\nInput: N = 7\n\nOutput: 0\n\nExplanation: Closest prime to 7 is 7.\n \n```\n**Your Task:**\n\nYou don't need to read or print anything. Your task is to complete the function **NthTerm()** which takes **N** as input paramater and returns **Nth** term.\n \n\n**Expected Time Complexity:** O(N* √ N)\n**Expected Space Complexity:** O(1)\n\n**Constraints:**\n1 <= N <= 100000\n"
  },
  {
    "path": "GFG/Help a Thief/Help a thief.cpp",
    "content": "// { Driver Code Starts\n//Initial Template for C++\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\n//User function Template for C++\n\nclass Solution\n{\npublic:\n    int maxCoins(int A[], int B[], int T, int N)\n    {\n        // code here\n        vector<pair<int, int>> v;\n        for (int i = 0; i < N; i++)\n        {\n            v.push_back({B[i], A[i]});\n        }\n        sort(v.rbegin(), v.rend());\n        int k = 0;\n        for (int i = 0; i < N; i++)\n        {\n            if (T == 0)\n            {\n                return k;\n            }\n            int p = min(v[i].second, T);\n            k += p * v[i].first;\n            T -= p;\n        }\n        return k;\n    }\n};\n\n// { Driver Code Starts.\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int T,N;\n        cin>>T>>N;\n        \n        int A[N], B[N];\n        \n        for(int i=0; i<N; i++)\n            cin>>A[i];\n        for(int i=0; i<N; i++)\n            cin>>B[i];\n\n        Solution ob;\n        cout << ob.maxCoins(A,B,T,N) << endl;\n    }\n    return 0;\n}  // } Driver Code Ends"
  },
  {
    "path": "GFG/Help a Thief/README.md",
    "content": "# Help a Thief!!!\n## Easy\n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">You have to help a thief to steal as many as GoldCoins as possible from a GoldMine. There he saw <strong>N</strong> Gold Boxes an each Gold Boxes consists of <strong>A<sub>i</sub></strong> Plates each plates consists of <strong>B<sub>i</sub></strong> Gold Coins. Your task is to print the maximum gold coins theif can steal if he can take a maximum of T plates.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>T = </strong>3, <strong>N = </strong>3</span><strong> </strong>\n<span style=\"font-size:18px\"><strong>A[] = </strong>{1, 2, 3}\n<strong>B[] = </strong>{3, 2, 1}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">7</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">The thief will take 1 plate of coins\nfrom the first box and 2 plate of coins\nfrom the second plate. 3 + 2*2 = 7.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>T = </strong>0, <strong>N = </strong>3</span><strong> </strong>\n<span style=\"font-size:18px\"><strong>A[] = </strong>{1, 3, 2}</span>\n<span style=\"font-size:18px\"><strong>B[] = </strong>{2, 3, 1}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">0</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">The thief can't take any plates.\nSo he can't steal any coins.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>maxCoins()</strong> which takes 2 Integers T, and N and two arrays A and B of size N as input and returns the maximum number of gold coins the thief can steal if he can take a maximum of T plates.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N*logN)<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">0 &lt;= T,N &lt;= 10<sup>4</sup><br>\n1 &lt;= A[i] &lt;= 10<sup>4</sup></span><br>\n<span style=\"font-size:18px\">1 &lt;= B[i] &lt;= 10<sup>4</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "GFG/Help the Old Man/Help the old man.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            String a[] = in.readLine().trim().split(\"\\\\s+\");\n            int N = Integer.parseInt(a[0]);\n            int n = Integer.parseInt(a[1]);\n            \n            Solution ob = new Solution();\n            List<Integer> ans = new ArrayList<Integer>();\n            ans = ob.shiftPile(N, n);\n            System.out.println(ans.get(0)+\" \"+ans.get(1));\n        }\n    }\n}// } Driver Code Ends\n\nclass Solution{\n    public static void hanoi(int N,int A,int B,int C,ArrayList<ArrayList<Integer>> r){\n            if(N==0)return;\n            hanoi(N-1,A,C,B,r);\n            ArrayList<Integer> z=new ArrayList<Integer>();\n            z.add(A);\n            z.add(B);\n            r.add(z);\n            hanoi(N-1,C,B,A,r);\n    }\n    static List<Integer> shiftPile(int N, int n){\n        ArrayList<ArrayList<Integer>> r=new ArrayList<ArrayList<Integer>>();\n        hanoi(N,1,3,2,r);\n        return r.get(n-1);\n    }\n}"
  },
  {
    "path": "GFG/Help the Old Man/README.md",
    "content": "# Help the Old Man!!!\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">A poor old man works in a palace for a living. One day the old man's wife met with an accident. She needed an immediate operation but the old man's savings were not enough for the operation. He went running to the king to beg for money. The king told that he will not only pay the full amount for the operation but also double his salary. But for that the old man had to pass a test. The king showed him a pile of glass plates kept one above another, each one being smaller than the one beneath. The plates were kept in box 1. He had to transfer the plates to box 3 using box 2. However, there were some constraints. The old man could only take one plate at a time and he could only place a&nbsp;smaller plate on top of a larger plate. He could take a plate only from the top. Help the old man do so. There are <strong>N</strong> plates and he has to tell the <strong>n</strong>th move in the format <strong>(i, j)</strong> where a plate is being moved <strong>from ith box to jth box.</strong></span></p>\n\n<p><span style=\"font-size:18px\"><strong>Note:</strong><br>\nGiven any number of plates, they can be transferred from box 1 to box 3 using box 2 using the following steps.<br>\nStep 1: Transfer first N-1 plates from box 1 to box 2 using box 3.<br>\nStep 2: Transfer the remaining plate from box 1 to box 3.<br>\nStep 3: Transfer the first N-1 plates from box 2 to box 3 using box 1.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> N = 2, n = 2\n<strong>Output:</strong> 1 3\n<strong>Explaination:</strong>  The plate on top of box 1 is \nfirst transferred to box 2. The second plate \nfrom box 1 is transferred to box 3 and finally \nthe plate from box 2 is transferred to box 3. \nIn each situation, all the constraints are \nsatisfied. You are required to print the 2nd \nmove which is \"Move plate from box 1 to box 3\", \nhence 1 3.</span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> N = 3, n = 4.\n<strong>Output:</strong> 1 3\n<strong>Explaination:</strong> The movements of plates will \nbe from 1 to 3. Then from 1 to 2. Then from \n3 to 2. And finally 4th move from 1 to 3.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anyting. Your task is to complete the function <strong>shiftPile()</strong> which takes N and n as input parameters and returns the nth move in a list.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(2<sup>N</sup>)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 20<br>\n1 ≤ n ≤ 1000&nbsp;</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "GFG/Hungry Pizza Lovers/Hungry pizza lovers.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\n\nclass Array {\n    \n    // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t    String line = br.readLine();\n\t\t    String[] element = line.trim().split(\"\\\\s+\");\n\t\t    int sizeOfArray = Integer.parseInt(element[0]);\n\t\t    \n\t\t    int arr [][] = new int[sizeOfArray][2];\n\t\t    \n\t\t    for(int i = 0;i<sizeOfArray;i++){\n    \t\t    line = br.readLine();\n    \t\t    String[] elements = line.trim().split(\"\\\\s+\");\n\t\t        arr[i][0] = Integer.parseInt(elements[0]);\n\t\t        arr[i][1] = Integer.parseInt(elements[1]);\n\t\t    }\n\t\t    \n\t\t    Complete obj = new Complete();\n\t\t    ArrayList<Integer> ans;\n\t\t    ans = obj.permute(arr, sizeOfArray);\n\t\t    for(int i: ans)\n\t\t        System.out.println(i);\n\t\t}\n\t}\n}\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Complete{\n    \n   \n    // Function for finding maximum and value pair\n    public static ArrayList<Integer> permute (int arr[][], int n) {\n        Map<int[],Integer> map=new HashMap<>();\n        for(int i=0;i<arr.length;i++){\n            map.put(arr[i],i+1);\n        }\n        Arrays.sort(arr,(a,b)->Integer.compare(a[0]+a[1],b[0]+b[1]));\n        ArrayList<Integer> ans=new ArrayList<>();\n        \n        for(int i=0;i<arr.length;i++){\n            ans.add(map.get(arr[i]));\n        }\n        return ans;\n    }\n    \n    \n}\n\n\n"
  },
  {
    "path": "GFG/Hungry Pizza Lovers/README.md",
    "content": "# Hungry Pizza Lovers\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Dominos Pizza has&nbsp;hungry customers waiting in the queue. Each unique order&nbsp;is placed by a customer at time&nbsp;x[i], and the order takes&nbsp;y[i]&nbsp;units of time to complete.<br>\nYou have information on all&nbsp;n&nbsp;orders, Find the order in which all&nbsp;customers will receive their pizza and return it. If two or more orders are completed at the same time&nbsp;then sort them by non-decreasing order number.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[ ] = {{4,1}, {6,2}, {7,6}, \n                       {8,1}, {1,3}}\n<strong>Output :</strong> 5 1 2 4 3\n<strong>Explanation:</strong>\nHere an array can be transform to \n{5, 8, 13, 9, 4}. Here 5<sup>th</sup>&nbsp;index order \nreceived first then 1<sup>st</sup>&nbsp;order, 2<sup>nd</sup>&nbsp;order...\nreturn {5, 1, 2, 4, 3}\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[ ] = {{1,1}, {1,1}, {1,1}} <strong>\nOutput :</strong>  1 2 3 </span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function <strong>permute()</strong> that takes 2-d array <strong>(arr)</strong>, sizeOfArray <strong>(n)</strong>, and return the array of order in which customers will receive their pizza. The driver code takes care of the printing.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N*LOG(N)).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(N).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n1 ≤ arr[i][0], arr[i][1] ≤ 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "GFG/IPL/IPL.cpp",
    "content": "vector<int> max_of_subarrays(vector<int> arr, int n, int k) {\n        \n        deque<int>pq;\n        vector<int>ans;\n        \n        for(int i=0;i<n;i++)\n       {\n            if(!pq.empty() && pq.front()==i-k){ \n                pq.pop_front();\n            }\n             while(!pq.empty() && arr[pq.back()]<=arr[i]){ \n                        pq.pop_back();\n             }\n          pq.push_back(i);\n            if(i>=k-1){ \n            ans.push_back(arr[pq.front()]);\n            }\n        }\n        \n        return ans;\n    }"
  },
  {
    "path": "GFG/IPL 2021 - Match Day 2/IPL 2021 - Match Day 2 gfg med s22.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\n  public:\n    vector<int> max_of_subarrays(vector<int> arr, int n, int k) {\n        // your code here\n        vector<int>res;\n        multiset<int>m;\n\n        for(int i =0; i<k; i++) m.insert(arr[i]);\n        res.push_back(*(--m.end()));\n        for(int i =k;i<n; i++){\n            m.erase(m.lower_bound(arr[i-k]));\n            m.insert(arr[i]);\n            res.push_back(*(--m.end()));\n        }\n        return res;\n       \n    }\n};\n\nint main() {\n\n    int t;\n    cin >> t;\n\n    while (t--) {\n\n        int n, k;\n        cin >> n >> k;\n\n        vector<int> arr(n);\n        for (int i = 0; i < n; i++) cin >> arr[i];\n        Solution ob;\n        vector<int> res = ob.max_of_subarrays(arr, n, k);\n        for (int i = 0; i < res.size(); i++) cout << res[i] << \" \";\n        cout << endl;\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "GFG/Ishaan Loves Chocolates/Ishaan loves chocolates.py",
    "content": "#User function Template for python3\n\ndef chocolates (arr, n):\n    return min(arr)\n    \n\n\n#{ \n#  Driver Code Starts\n#Initial Template for Python 3\n\n\nfor _ in range(0,int(input())):\n    n = int(input())\n    arr = list(map(int, input().strip().split()))\n    ans = chocolates(arr, n)\n    print(ans)\n    \n\n\n\n\n\n# } Driver Code Ends"
  },
  {
    "path": "GFG/Ishaan Loves Chocolates/README.md",
    "content": "# Ishaan Loves Chocolates\n## Easy\n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">As we know, Ishaan has a love for chocolates. He has bought a huge chocolate bar that contains N chocolate squares. Each of the squares has a tastiness level which is denoted by an array A[].<br>\nIshaan can eat the first or the last square of the chocolate at once. Ishaan has a sister who loves chocolates too and she demands the last chocolate square. Now, Ishaan being greedy eats the more tasty square first.&nbsp;<br>\nDetermine the tastiness level of the square which his sister gets.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[ ] = {5, 3, 1, 6, 9}\n<strong>Output :</strong> 1\n<strong>Explanation:\nInitially: 5 3 1 6 9</strong>\nIn first step: 5 3 1 6\nIn Second step: 5 3 1\nIn Third step: 3 1\nIn Fourth step: 1\nReturn 1</span></pre>\n\n<p><br>\n<br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[ ] = {5, 9, 2, 6} <strong>\nOutput :</strong>  2\n\n</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function <strong>chocolates()</strong> that takes an array <strong>(arr)</strong>, sizeOfArray <strong>(n)</strong>&nbsp;and return the tastiness level of the square which his sister gets. The driver code takes care of the printing.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(1).</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints :&nbsp;</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n1 ≤ A[i] ≤ 10<sup>9</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "GFG/Josephus problem/Josephus problem.java",
    "content": "class Solution\n{\n   public int josephus(int n, int k)\n    {\n        //Your code here\n        if(n==1)return n;\n        return (josephus(n-1,k)+(k-1))%n +1;\n    }\n\n}\n"
  },
  {
    "path": "GFG/Jump Game/Jump game.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int N = Integer.parseInt(read.readLine());\n            \n            String S1[] = read.readLine().split(\" \");\n            \n            int[] A = new int[N];\n            \n            for(int i=0; i<N; i++)\n                A[i] = Integer.parseInt(S1[i]);\n\n            Solution ob = new Solution();\n            System.out.println(ob.canReach(A,N));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    static int canReach(int A[], int N) {\n        int step=0;\n        for(int i=N-2;i>=0;i--)\n        {\n            step++;\n            if(A[i]>=step)step=0;\n        }\n        if(step==0)return 1;\n        return 0;\n    } \n}"
  },
  {
    "path": "GFG/Jump Game/README.md",
    "content": "# Jump Game\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an positive integer N and a list of N integers A[]. Each element in the array denotes the maximum length of jump you can cover. Find out if you can make it to the last index if you start at the first index of the list.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>N = </strong>6\n<strong>A[] = </strong>{1, 2, 0, 3, 0, 0}</span><strong> </strong>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">1</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">Jump 1 step from first index to\nsecond index. Then jump 2 steps to reach \n4<sub>th </sub>index, and now jump 2 steps to reach\nthe end.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>N = </strong>3\n<strong>A[] </strong><strong>=  </strong>{1, 0, 2}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">0</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">You can't reach the end of the array.</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>canReach()</strong> which takes a Integer N and a list A of size N as input and returns 1 if the end of the array is reachable, else return 0.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 &lt;= N &lt;= 10<sup>5</sup><br>\n0 &lt;= A[i] &lt;= 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "GFG/Jumping Numbers/Jumping Numbers.cpp",
    "content": "class Solution {\n  public:\n    long long jumpingNums(long long x) {\n        // code here\n        if(x<=9)return x;\n        \n        queue<int>q;\n        \n        for(int i=0; i<=9; i++)q.push(i);\n        \n        int ans = INT_MIN;\n        \n        while(q.size()>0){\n            \n            int digit = q.front();\n            q.pop();\n            \n            \n            ans = max(ans,digit);\n            \n            int rem = digit%10;\n            \n            int num1 = digit*10 + rem - 1;\n            \n            int num2 = digit*10 + rem + 1;\n            \n            if(rem == 0){\n                if(num2<=x)\n                    q.push(num2);\n                \n            }\n            \n            else if(rem==9){\n                if(num1<=x)q.push(num1);\n            }\n            \n            else{\n\n                if(num1<=x) q.push(num1);\n\n                 \n\n                 if(num2<=x)q.push(num2);\n\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "GFG/Jumping Numbers/README.md",
    "content": "## Jumping Numbers\n\n\nGiven a positive number X. Find the largest Jumping Number which is smaller than or equal to X. \nJumping Number: A number is called Jumping Number if all adjacent digits in it differ by only 1. All single-digit numbers are considered as Jumping Numbers. For example 7, 8987 and 4343456 are Jumping numbers but 796, 677 and 89098 are not.\n\n \n\n**Example 1:**\n\n```\n\nInput:\nX = 10\n\nOutput:\n10\n\nExplanation:\n10 is the largest Jumping Number\npossible for X = 10.\n\n```\n\n**Example 2:**\n\n```\nInput:\nX = 50\n\nOutput:\n45\n\nExplanation:\n45 is the largest Jumping Number\npossible for X = 50.\n ```\n\n**Your Task:**\nYou don't need to read input or print anything. Your task is to complete the function **jumpingNums()** which takes an Integer X as input and returns the largest Jumping Number less than or equal to X.\n\n \n\nExpected Time Complexity: O(k), where k is no of jumping numbers\nExpected Auxiliary Space: O(k), where k is no of jumping numbers\n\n \n\nConstraints:\n1 <= X <= 109\n"
  },
  {
    "path": "GFG/K-Ary Tree/README.md",
    "content": "# K-Ary Tree\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Find the number of leaf nodes in a full <strong>k</strong>-ary tree of height <strong>m</strong>.<br>\n<strong>Note:</strong> You have to return the answer module 10<sup>9</sup>+7.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>k = </strong>2, <strong>m = </strong>2</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">4</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">A full Binary tree of height 2 has 4 leaf nodes.</span> </pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>k = </strong>2, <strong>m = </strong>1</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">2</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">A full Binary tree of height 1 has 2 leaf nodes.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>karyTree()</strong> which takes 2 Integers k, and m as input and returns the number of leaf nodes in a full k-ary Tree.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(log(m))<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 &lt;= k,m &lt;= 10<sup>8</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "GFG/Knight Walk/Knight Walk.cpp",
    "content": "/*\n  This code is contributed by:\n  - Shubham Kumar Jha (https://github.com/Shubhamjha1710)\n  - Adarsh Urmaliya (https://github.com/Satellite-system)\n*/\nclass Solution {\npublic:\n\tint minStepToReachTarget(vector<int>&KnightPos, vector<int>&TargetPos, int N)\n\t{\n\t    queue<vector<int>> q;\n\t    vector<vector<bool>> visit(N+1 , vector<bool>(N+1, false));\n\t    \n\t    q.push({KnightPos[0] , KnightPos[1]});\n\t    visit[KnightPos[0]][KnightPos[1]] = 1;\n\t    \n\t    \n\t    int lvl = -1;\n\t    vector<vector<int>> dir = {{-1,-2},{-2,-1},{-2,1},{-1,2},{1,-2},{2,-1},{2,1},{1,2}};\n\t    while(q.empty() == false)\n\t    {\n\t        lvl += 1;\n\t        int sz = q.size();\n\t        for(int k = 0;k<sz;k++)\n\t        {\n\t            int x = q.front()[0] , y = q.front()[1];\n\t            q.pop();\n\t            if(x == TargetPos[0] && y == TargetPos[1])\n\t            {\n\t                return lvl;\n\t            }\n\t            \n\t            for(int i = 0;i<8;i++)\n\t            {\n\t                int nx = x+dir[i][0] , ny = y+dir[i][1];\n\t                if((nx >= 1 && ny >= 1 && nx <= N && ny <= N) && visit[nx][ny] == false)\n\t                {\n\t                    q.push({nx , ny});\n\t                    visit[nx][ny] = true;\n\t                }\n\t            }\n\t        }\n\t    }\n\t    \n\t    return -1;\n\t    // Code here\n\t}\n};\n\n/*\nAnother Approach : Store the number of steps it taken to each square and from them find the minimum Distance Steps needed to reach Target Position.\nSteps to reach other squares from starting Square could be find By BFS Algorithm, so we will use this Algorithm.\nFirst initialize Stating position as steps 0, now from each position we have total 8 Possible pos(positions), where we could traverse(given that those\nare valid positions, and have never been visited before), and store stps in vector.\nWhenever we encounter the target positon, we return it as we are using BFS algorithm, that's why whenever we react to target position,\nthen that would be our First time when we have reached that position, hence will be in shortest steps.\n*/\n\nclass Solution {\npublic:\n   bool isValid(int r, int c, int n){\n    if(r<=0 || c<=0 || r>n || c>n) return false;\n    return true;\n}\n\tint minStepToReachTarget(vector<int>&KnightPos, vector<int>&TargetPos, int N){\n\t    if(KnightPos[0]==TargetPos[0] && KnightPos[1]==TargetPos[1]){\n\t        return 0;\n\t    }\n\t    \n\t    queue<pair<int, int>> st;\n\t    vector<vector<int>> dis(N+2, vector<int>(N+2, -1));\n\t    \n\t    st.push({KnightPos[0], KnightPos[1]});\n\t    dis[KnightPos[0]][KnightPos[1]] = 0;\n\t    \n\t   vector<vector<int>> pos={{1,2}, {2,1}, {-1,2}, {1,-2}, {-1,-2}, {-2,-1}, {-2,1}, {2,-1}};\n\t    \n\t    while(!st.empty()){\n\t        pair<int,int> tp = st.front();\n\t        st.pop();\n    \t        \n\t        \n\t        for(int j=0;j<8; ++j){\n\t            int nr = tp.first + pos[j][0], nc = tp.second+pos[j][1];\n\t \n    \t        if(isValid(nr, nc, N) && dis[nr][nc]==-1){\n    \t            st.push({nr, nc});\n    \t            dis[nr][nc] = 1 + dis[tp.first][tp.second];\n    \t        }\n    \t        if(nr==TargetPos[0] && nc==TargetPos[1])\n    \t            return 1 + dis[tp.first][tp.second];\n\t        }\n    \t        \n\t    }\n\t    \n\t    return dis[TargetPos[0]][TargetPos[1]];\n\t}\n};\n"
  },
  {
    "path": "GFG/Knight Walk/Knight Walk.java",
    "content": "class Pair{\n    int i;\n    int j;\n    int dist;\n    Pair(int i,int j,int d){\n        this.i=i;\n        this.j=j;\n        this.dist=d;\n    }\n}\nclass Solution\n{\n    public int minStepToReachTarget(int KnightPos[], int TargetPos[], int N)\n    {\n        // Code here\n        int[] x=new int[]{1,1,2,2,-1,-1,-2,-2};\n        int[]y=new int[]{2,-2,1,-1,2,-2,1,-1};\n        \n        Queue<Pair> q=new LinkedList<>();\n        q.add(new Pair(KnightPos[0],KnightPos[1],0));\n        boolean [][]vis=new boolean[N+1][N+1];\n        vis[KnightPos[0]][KnightPos[1]]=true;\n        while(q.size()>0){\n            int sz=q.size();\n            while(sz-->0){\n                Pair curr=q.remove();\n                int i=curr.i;\n                int j=curr.j;\n                int dist=curr.dist;\n                if(i==TargetPos[0] && j==TargetPos[1])return dist;\n                for(int k=0;k<8;k++){\n                    if(isValid(i+x[k],j+y[k],vis,N)){\n                        q.add(new Pair(i+x[k],j+y[k],dist+1));\n                        vis[i+x[k]][j+y[k]]=true;\n                    }\n                }\n            }\n        }\n        return -1;\n    }\n    boolean isValid(int i,int j,boolean[][]vis,int N){\n        if(i<1 || j<1 || i>N || j>N || vis[i][j]){\n            return false;\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "GFG/Kth smallest element/Kth smallest element.py",
    "content": "#User function Template for python3\nimport heapq\n\nclass Solution:\n    def kthSmallest(self,arr, l, r, k):\n        '''\n        arr : given array\n        l : starting index of the array i.e 0\n        r : ending index of the array i.e size-1\n        k : find kth smallest element and return using this function\n        '''\n        heap = []\n        for i in arr:\n            heapq.heappush(heap, i)\n        for i in range(k-1):\n            heapq.heappop(heap)\n        return heapq.heappop(heap)\n\n#{ \n#  Driver Code Starts\n#Initial Template for Python 3\n\n#contributed by RavinderSinghPB\nif __name__ == '__main__': \n    import random \n    t=int(input())\n    for tcs in range(t):\n        n=int(input())\n        arr=list(map(int,input().strip().split()))\n        k=int(input())\n        ob=Solution()\n        print(ob.kthSmallest(arr, 0, n-1, k))\n        \n# } Driver Code Ends\n"
  },
  {
    "path": "GFG/LCM Triplet/LCM Triplet.java",
    "content": "class Solution {\n    long lcmTriplets(long N) {\n        // code here\n        if(N<=2)return N;\n        if((N&1)==1)return N*(N-1)*(N-2);\n        if(N%3==0)return (N-1)*(N-3)*(N-2);\n        return N*(N-1)*(N-3);\n    }\n}\n"
  },
  {
    "path": "GFG/Largest subtree sum in a tree/Largest subtree sum in a tree.cpp",
    "content": "class Solution {\n  public:\n    int subtree(Node* root, int& ans){\n        if(root==NULL){\n            return 0;\n        }\n        int lsum = subtree(root->left,ans);\n        int rsum = subtree(root->right,ans);\n        int tot = root->data + lsum + rsum;\n        ans = max(ans,tot);\n        return tot;\n    }\n    int findLargestSubtreeSum(Node* root){\n        int ans = INT_MIN;\n        subtree(root,ans);\n        return ans;\n        \n    }\n};\n"
  },
  {
    "path": "GFG/Largest subtree sum in a tree/Largest subtree sum in a tree.java",
    "content": "class Solution {\n    static int ans;\n    public static int findLargestSubtreeSum(Node root) {\n        // code here\n        ans=Integer.MIN_VALUE;\n        dfs(root);\n        return ans;\n    }\n    static int dfs(Node root){\n        int sum=root.data;\n        if(root.left!=null){\n            sum+=dfs(root.left);\n        }\n        if(root.right!=null){\n            sum+=dfs(root.right);\n        }\n        ans=Math.max(ans,sum);\n        return sum;\n    }\n}\n"
  },
  {
    "path": "GFG/Last modified ball/Last modified ball.java",
    "content": "class Solution {\n    int solve(int N, int[] A) {\n        // code here\n        for(int i=N-1;i>=0;i--){\n            if(A[i]<9)return i+1;\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "GFG/Longest Bitonic subsequence/Longest Bitonic subsequence.java",
    "content": "class Solution\n{\n    public int LongestBitonicSequence(int[] nums)\n    {\n        // Code here\n        int n=nums.length;\n        int[]inc=new int[n];\n        for(int i=0;i<n;i++){\n            inc[i]=1;\n            for(int j=i-1;j>=0;j--){\n                if(nums[j]<nums[i] && inc[j]+1>inc[i]){\n                    inc[i]=inc[j]+1;\n                }\n            }\n        }\n        int[]dec=new int[n];\n        for(int i=n-1;i>=0;i--){\n            dec[i]=1;\n            for(int j=i+1;j<n;j++){\n                if(nums[j]<nums[i] && dec[j]+1>dec[i]){\n                    dec[i]=dec[j]+1;\n                }\n            }\n        }\n        \n        int ans=0;\n        for(int i=0;i<n;i++){\n            ans=Math.max(ans,inc[i]+dec[i]-1);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Longest Perfect Piece/Longest Perfect Piece.java",
    "content": "class Solution {\n    static int longestPerfectPiece(int[] arr, int N) {\n        // code here\n        PriorityQueue<Integer> max=new PriorityQueue<>(Collections.reverseOrder());\n        PriorityQueue<Integer> min=new PriorityQueue<>();\n        int ans=0;\n        for(int i=0,j=0;i<N;i++){\n            min.add(arr[i]);\n            max.add(arr[i]);\n            \n            while(j<N && max.peek()-min.peek()>1){\n                min.remove(arr[j]);\n                max.remove(arr[j]);\n                j++;\n            }\n            \n            ans=Math.max(ans,i-j+1);\n        }\n        return ans;\n        \n    }\n};\n"
  },
  {
    "path": "GFG/Magic Triplets/Magic Triplets.java",
    "content": "class Solution{\n    public int countTriplets(int[] nums){\n        // code here\n        int ans=0;\n        int n=nums.length;\n        for(int j=1;j<n-1;j++){\n            int smaller=0;\n            for(int i=j-1;i>=0;i--){\n                if(nums[i]<nums[j])smaller++;\n            }\n            int larger=0;\n            for(int k=j+1;k<n;k++){\n                if(nums[k]>nums[j])larger++;\n            }\n            ans+=smaller*larger;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Majority Element/Majority Element.java",
    "content": "//Boyer-Moore Voting Algorithm\n\nclass Solution {\n    public int majorityElement(int[] nums) {\n        int count = 0;\n        Integer candidate = null;\n\n        for (int num : nums) {\n            if (count == 0) {\n                candidate = num;\n            }\n            count += (num == candidate) ? 1 : -1;\n        }\n\n        return candidate;\n    }\n}\n\n//=================================================================\n\n//recursive\nclass Solution {\n\npublic int majorityElement(int[] nums) {\n        return recurse(nums, 0);\n    }\n    \n    public int recurse(int[] nums, int start){\n        int n = nums.length;\n        int tracker= 1;\n        for(int i=start+1;i<n;i++){\n            if(nums[start]==nums[i]){\n                tracker++;\n            }else{\n                tracker--;\n            }\n            if(tracker==0){\n                return recurse(nums, i+1);\n            }\n        }\n        return nums[start];\n    }\n}\n\n//=====================================================================\n//Naive approach using map\n    class Solution {\n    public int majorityElement(int[] nums) {\n        Map<Integer,Integer> map=new  HashMap<>();\n        for(int i=0;i<nums.length;i++){\n            if(!map.containsKey(nums[i])){\n                map.put(nums[i],1);\n            }else{\n                int count = map.get(nums[i]);\n                map.put(nums[i], count + 1);\n            }\n        }\n        return Collections.max(map.entrySet(),Comparator.comparingInt(Map.Entry::getValue))\n            .getKey();\n    }\n}\n"
  },
  {
    "path": "GFG/Majority Element/Majority Element.py",
    "content": "# Using Boyer-Moore Voting Algorithm\n# Returning the element only if the count is more than n/2 or else -1\n#\nclass Solution:\n    def majorityElement(self, arr, n):\n        #Your code here\n        majorityNum = -1\n        numCount = 0\n        for index in range(n):\n            if numCount == 0:\n                majorityNum = arr[index]\n                numCount += 1\n            else:\n                if arr[index] == majorityNum:\n                    numCount += 1\n                else:\n                    numCount -= 1\n        \n        count = 0\n        for i in range(n):\n            if (arr[i] == majorityNum):\n                count += 1\n\n        if (count > n // 2):\n            return majorityNum\n        else:\n            return -1"
  },
  {
    "path": "GFG/Majority Element/README.md",
    "content": "# Majority Element\n\n### Medium\n\nGiven an array **A** of **N** elements. Find the majority element in the array. A majority element in an array A of size N is an **element that appears more than N/2 times in the array.**\n\n### Example 1:\n<pre>\n<strong>Input:</strong>\nN = 3 \nA[] = {1,2,3} \n<strong>Output:</strong>\n-1\n<strong>Explanation:</strong>\nSince, each element in \n{1,2,3} appears only once so there \nis no majority element.\n</pre>\n\n### Example 2:\n<pre>\n<strong>Input:</strong>\nN = 5 \nA[] = {3,1,3,3,2} \n<strong>Output:</strong>\n3\n<strong>Explanation:</strong>\nSince, 3 is present more\nthan N/2 times, so it is \nthe majority element.\n</pre>\n\n\n\n**Your Task:**\nThe task is to complete the function **majorityElement()** which returns the majority element in the array. If no majority exists, return -1.\n \n\n\n**Expected Time Complexity:** O(N).\n\n**Expected Auxiliary Space:** O(1).\n \n\n\n**Constraints:**\n\n1 ≤ N ≤ 107\n\n0 ≤ Ai ≤ 106"
  },
  {
    "path": "GFG/Make array elements unique/Make array elements unique.java",
    "content": "class Solution {\n    public long minIncrements(int[] arr, int N) {\n        // Code here\n        Arrays.sort(arr);\n        int ans=0;\n        for(int i=1;i<N;i++){\n            if(arr[i-1]>=arr[i]){\n                ans+=arr[i-1]-arr[i]+1;\n                arr[i]=arr[i-1]+1;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Max Min/Max Min.cpp",
    "content": "class Solution\n{\n   public:\n    int findSum(int A[], int N)\n    {\n    \t//code here.\n    \t\n    \tint maxVal=INT_MIN;\n    \tint minVal=INT_MAX;\n    \tfor(int i=0;i<N;i++){\n    \t    maxVal=max(maxVal,A[i]);\n    \t    minVal=min(minVal,A[i]);\n    \t}\n    \treturn maxVal+minVal;\n    }\n\n};\n"
  },
  {
    "path": "GFG/Max Min/Max Min.java",
    "content": "\nclass Solution\n{ \n    public static int findSum(int A[],int N) \n    {\n        //code here\n        int min=Integer.MAX_VALUE;\n        int max=Integer.MIN_VALUE;\n        for(int x:A){\n            min=Math.min(min,x);\n            max=Math.max(max,x);\n        }\n        return min+max;\n    }\n}\n"
  },
  {
    "path": "GFG/Max Min/Max Min.py",
    "content": "class Solution:\n    def findSum(self,A,N): \n        #code here\n        min = A[0]\n        max = A[0]\n        for x in range(1,N):\n            if(min>A[x]):min=A[x]\n            if(max<A[x]):max=A[x]\n        return max+min;"
  },
  {
    "path": "GFG/Max Min/README.md",
    "content": "# Max Min\n## Easy\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Given an array<strong> A</strong> of size <strong>N</strong> of integers. Your task is to find the sum of&nbsp;<strong>minimum and maximum </strong>element&nbsp;in the&nbsp;array.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 5\nA[] = {</span><span style=\"font-size:18px\">-2, 1, -4, 5, 3}\n<strong>Output: </strong>1\n<strong>Explanation:</strong> min = -4, max =  5. Sum = -4 + 5 = 1</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4\nA[]  = {</span><span style=\"font-size:18px\">1, 3, 4, 1}\n<strong>Output: 5\nExplanation:</strong> min = 1, max = 4. Sum = 1 + 4 = 5\n</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>findSum()</strong>&nbsp;which takes the array <strong>A[]</strong> and its size <strong>N</strong><strong> </strong>as inputs and returns the <strong>summation of</strong>&nbsp;<strong>minimum and maximum</strong> element of the&nbsp;array.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N &lt;= 10<sup>5</sup><br>\n-10<sup>9</sup> &lt;= A<sub>i</sub> &lt;= 10<sup>9</sup></span></p>\n</div>\n"
  },
  {
    "path": "GFG/Maximize the sum of selected numbers from an array to make it empty/Maximize the sum of selected numbers from a sorted array to make it empty.cpp",
    "content": "class Solution{\n    public:\n    int maximizeSum(int a[], int n) \n    {\n        // Complete the function\n        \n          unordered_map<int, int> ans;\n        int sum=0;\n        bool arr[n];\n        for(int i=0;i<n;i++){\n            arr[i]=false;\n        }\n        for (int i = 0; i < n; i++)\n        \tans[a[i]]++;\n        \n        for(int i=n-1;i>=0;i--)\n        {\n            if(arr[i] == false)\n            {\n                arr[i]=true;\n                sum+= a[i];\n                if(ans[a[i]-1] > 0)\n                {\n                    arr[i-ans[a[i]]]=true;\n                    ans[a[i]-1]--;\n                }\n            }\n        }\n        return sum;\n    }\n\n};\n"
  },
  {
    "path": "GFG/Maximize the sum of selected numbers from an array to make it empty/Maximize the sum of selected numbers from an array to make it empty.java",
    "content": "class Complete{\n    \n   \n    // Function for finding maximum and value pair\n    public static int maximizeSum (int arr[], int n) {\n        //Complete the function\n        int[] map=new int[100001];\n        for(int x:arr){\n            map[x]++;\n        }\n        int sum=0;\n        for(int i=n-1;i>=0;i--){\n            int curr=arr[i];\n            if(map[curr]!=0){\n                sum+=curr;\n                map[curr]--;\n                if(map[curr-1]!=0){\n                    map[curr-1]--;\n                }\n            }\n            \n        }\n        return sum;\n    }\n    \n    \n"
  },
  {
    "path": "GFG/Maximize the sum of selected numbers from an array to make it empty/README.md",
    "content": "## Maximize the sum of selected numbers from a sorted array to make it empty\n\n\n\n\nGiven a array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete one occurrence of Ai-1 (if exists), and Ai each from the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of the selected numbers.\n\n**Note:** Numbers need to be selected from maximum to minimum.\n\n```\nExample 1:\n\nInput : arr[ ] = {1, 2, 2, 2, 3, 4}\n\nOutput : 10\n\nExplanation:\nWe select 4, so 4 and 3 are deleted leaving us with {1,2,2,2}.\nThen we select 2, so 2 & 1 are deleted. We are left with{2,2}.\nWe select 2 in next two steps, thus the sum is 4+2+2+2=10.\n```\n\n```\nExample 2:\n\nInput : arr[ ] = {1, 2, 3} \n\nOutput :  4\n\nExplanation: We select 3, so 3 and 2 are deleted leaving us with {1}.\nThen we select 1, 0 doesn't exist so we delete 1. thus the sum is 3+1=4.\n``` \n\n**Your Task:**\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function **maximizeSum()** that takes an array (arr), sizeOfArray (n), and return the maximum sum of the selected numbers. The driver code takes care of the printing.\n\n**Expected Time Complexity:** O(N).\n**Expected Auxiliary Space:** O(N).\n\n\n**Constraints:**\n1 ≤ N ≤ 105\n1 ≤ A[i] ≤ 105\n"
  },
  {
    "path": "GFG/Maximum Number of Toys/Maximum Number of Toys.java",
    "content": "// Nlogn + Q(K + logN)\n\nclass Pair<K,V>{\n    private K cost;\n    private V index;\n    public Pair(K a,V b){\n        this.cost=a;\n        this.index=b;\n    }\n    public K getCost(){\n        return this.cost;\n    }\n    public V getIndex(){\n        return this.index;\n    }\n}\n\n\nclass Solution {\n    ArrayList<Integer> maximumToys(int N, int A[],\n    int Q, ArrayList<Integer> Queries[]){\n        ArrayList<Pair<Integer,Integer>> arr=new ArrayList<>(N);\n        for(int i=0;i<N;i++){\n            arr.add(new Pair<Integer,Integer>(A[i],i));\n        }\n        \n        Collections.sort(arr,(a,b)->a.getCost()-b.getCost());//Nlogn\n        \n        HashMap<Integer,Integer> map=new HashMap<>();\n        for(int i=0;i<N;i++){\n            map.put(arr.get(i).getIndex(),i);\n        }\n        \n        long[]prefix=new long[N+1];\n        for(int i=1;i<=N;i++){\n            prefix[i]=prefix[i-1]+arr.get(i-1).getCost();\n        }\n        \n        ArrayList<Integer> res=new ArrayList<>(Q);\n        \n        for(int i=0;i<Q;i++){//Q\n            long c=Queries[i].get(0);\n            int k=Queries[i].get(1);\n            int l=0;\n            int r=N;\n            int ans=0;\n            while(l<=r){//logn\n                int mid=l + (r-l)/2;\n                if(prefix[mid]<=c){\n                    ans=mid;\n                    l=mid+1;\n                }else{\n                    r=mid-1;\n                }\n            }\n            if(ans==0){\n                res.add(0);\n                continue;\n            }\n            int idx=ans-1;\n            long rem = c-prefix[ans];\n            HashSet<Integer> damaged=new HashSet<>();\n            for(int j=0;j<k;j++){//k\n                int damagedToyIndex=map.get(Queries[i].get(j+2)-1);\n                if(damagedToyIndex<=idx){\n                    ans--;\n                    rem+=arr.get(damagedToyIndex).getCost();\n                }else{\n                    damaged.add(damagedToyIndex);\n                }\n            }\n            int s=idx+1;\n            while(s<N && rem>=arr.get(s).getCost()){\n                if(!damaged.contains(s)){\n                    ans++;\n                    rem-=arr.get(s).getCost();\n                }\n                s++;\n            }\n            res.add(ans);\n        }\n        return res;\n    }\n}\n"
  },
  {
    "path": "GFG/Maximum Profit By Choosing A Subset Of Intervals/Maximum Profit By Choosing A Subset Of Intervals.java",
    "content": "class Solution {\n    public static int maximum_profit(int n, int[][] arr) {\n        // code here\n        Arrays.sort(arr,(a,b)->{\n           if(a[0]!=b[0]) return a[0]-b[0];\n           return a[1]-b[1];\n        });\n        int[]dp=new int[n];\n        return rec(0,arr,n,dp);\n    }\n    static int rec(int index,int[][]arr,int n,int[]dp){\n        if(index>=n)return 0;\n        if(dp[index]!=0)return dp[index];\n        int not_select=rec(index+1,arr,n,dp);\n        int nextIndex = findNext(index+1,arr[index][1],arr,n);\n        int select = arr[index][2] + rec(nextIndex,arr,n,dp);\n        return dp[index]=Math.max(select,not_select);\n    }\n    static int findNext(int i,int prevEnd,int[][]arr,int n){\n        while(i<n){\n            if(arr[i][0]>=prevEnd){\n                break;\n            }else{\n                i++;\n            }\n        }\n        return i;\n    }\n}\n"
  },
  {
    "path": "GFG/Maximum Sub Array/Maximum Sub Array.java",
    "content": "class Solution {\n\n    ArrayList<Integer> findSubarray(int a[], int n) {\n        // code here\n        int maxSum=0;\n        int maxStart=0;\n        int maxEnd=0;\n        int currSum=0;\n        int currStart=0;\n        for(int i=0;i<n;i++){\n            if(a[i]<0){\n                currSum=0;\n                currStart=i+1;\n            }else{\n                currSum+=a[i];\n            }\n            \n            if(currSum>maxSum){\n                maxSum=currSum;\n                maxStart=currStart;\n                maxEnd=i+1;\n            }else if(currSum==maxSum){\n                int currDis=i+1-currStart;\n                int maxDis=maxEnd-maxStart;\n                if(currDis>maxDis){\n                    maxStart=currStart;\n                    maxEnd=i+1;\n                }\n            }\n            \n        }\n        \n        ArrayList<Integer> ans=new ArrayList<>();\n        for(int i=maxStart;i<maxEnd;i++){\n            ans.add(a[i]);\n        }\n        if(ans.size()==0)ans.add(-1);\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Maximum Sub-String after at most K changes/Maximum Sub-String after at most K changes.cpp",
    "content": "class Solution {\n\tpublic:\n\t\tint characterReplacement(string s, int k){\n\t\t    // Code here\n\t\t    \n\t\t      int ans = 0;\n\t\t  int l = 0;\n\t\t  vector<int>temp(26);\n\t\t  for(int i=0;i<s.size();i++){\n\t\t      temp[s[i]-'A']++;\n\t\t      int operation = i-l+1-*max_element(temp.begin(),temp.end());\n\t\t      if(operation>k){\n\t\t       temp[s[l]-'A']--;\n\t\t       l++;\n\t\t      }\n\t\t      else ans = max(ans,i-l+1);\n\t\t  }\n\t\t return ans;\n\t\t}\n\n};\n"
  },
  {
    "path": "GFG/Maximum Sub-String after at most K changes/Maximum Sub-String after at most K changes.java",
    "content": "class Solution\n{\n    public int characterReplacement(String s, int k)\n    {\n        // code here\n        int[]arr=new int[26];\n        int prev=0;\n        int ans=0;\n        for(int i=0;i<s.length();i++){\n            arr[s.charAt(i)-'A']++;\n            int curr=find(arr,k);\n            if(curr==-1){\n                arr[s.charAt(prev++)-'A']--;\n            }else{\n                ans=Math.max(ans,curr);\n            }\n        }\n        return ans;\n        \n    }\n    int find(int[]arr,int k){\n        int same=0;\n        int diff=0;\n        for(int i:arr){\n            if(i>same){\n                diff+=same;\n                same=i;\n            }else{\n                diff+=i;\n            }\n        }\n        return diff<=k? same+diff : -1;\n    }\n}\n"
  },
  {
    "path": "GFG/Maximum Sub-String after at most K changes/README.md",
    "content": "## Maximum Sub-String after at most K changes\n\n\nWe have a string s of length n, which contains only UPPERCASE characters and we have a number k (always less than n). We can make at most k changes in our string. In one change, you can replace any s[i] (0<= i < n) with any uppercase character (from 'A' to 'Z'). After k changes, find the maximum possible length of the sub-string which have all same characters.\n\n**Example 1:**\n\n```\nInput: s = \"ABAB\", k = 2\nOutput: 4\nExplanation: Change 2 'B' into 'A'. \nNow s = \"AAAA\"\n\n```\n\nExample:2\n\n```\n\nInput: s = \"ADBD\", k = 1\nOutput: 3\nExplanation: Change 'B' into 'D'.\nNow s = \"ADDD\"\n```\n***\n\n**Your Task:**\nYou don't need to read or print anything. Your task is to complete the function **characterReplacement()** which takes s and k as input parameters and returns the maximum length of sub-string after doing k changes.\n \n\n**Expected Time Complexity:** O(n)\n**Expected Space Complexity:** O(26)\n"
  },
  {
    "path": "GFG/Maximum Sum LCM/Maximum Sum LCM.java",
    "content": "//User function Template for Java\nclass Solution {\n    static long maxSumLCM(int n) {\n        // code here\n        long ans=0;\n        for(int i=1;i<=(int)Math.sqrt(n);i++){\n            if(n%i==0){\n                ans+=i;\n                if(n/i!=i)ans+=(n/i);\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Maximum Value/Maximum Value.java",
    "content": "class Solution {\n    ArrayList<Integer> maximumValue(Node node) {\n       //code here\n       Queue<Node> q=new LinkedList<>();\n       ArrayList<Integer> ans=new ArrayList<>();\n       q.add(node);\n       while(!q.isEmpty()){\n           int currLevelSize = q.size();\n           int max=0;\n           while(currLevelSize-->0){\n               Node curr=q.remove();\n               max=Math.max(max,curr.data);\n               if(curr.left!=null)q.add(curr.left);\n               if(curr.right!=null)q.add(curr.right);\n           }\n           ans.add(max);\n       }\n       return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Maximum of all subarrays of size k/Maximum of all subarrays of size k.java",
    "content": "class Solution\n{\n    //Function to find maximum of each subarray of size k.\n    static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k)\n    {\n        // Your code here\n        Deque<Integer> q=new ArrayDeque<>();\n        for(int i=0;i<k;i++){\n            while(q.size()>0 && q.peekLast()<arr[i]){\n                q.removeLast();\n            }\n            q.addLast(arr[i]);\n        }\n        ArrayList<Integer> ans =new ArrayList<>();\n        ans.add(q.peekFirst());\n        int x=0;\n        for(int i=k;i<n;i++){\n            if(q.peekFirst()==arr[x]){\n                q.removeFirst();\n            }\n            x++;\n            while(q.size()>0 && q.peekLast()<arr[i]){\n                q.removeLast();\n            }\n            q.addLast(arr[i]);\n            \n            ans.add(q.peekFirst());\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Median in a row-wise sorted Matrix/Median in a row-wise sorted Matrix.java",
    "content": "class Solution {\n    int median(int matrix[][], int R, int C) {\n        // code here \n        int min=Integer.MAX_VALUE;\n        int max=Integer.MIN_VALUE;\n        for(int i=0;i<R;i++){\n            if(matrix[i][0]<min)min=matrix[i][0];\n            if(matrix[i][C-1]>max)max=matrix[i][C-1];\n        }\n        \n        int desired=(R*C +1)/2;\n        \n        while(min<max){\n            int mid=(min+max)/2;\n            \n            int smaller=0;\n            for(int i=0;i<R;i++){\n                int l=0;\n                int r=C-1;\n                while(l<r){\n                    int m=(l+r)/2;\n                    if(matrix[i][m]<=mid){\n                        l=m+1;\n                    }else{\n                        r=m;\n                    }\n                }\n                smaller+=l;\n                if(matrix[i][l]<=mid)smaller++;\n            }\n            \n            if(smaller<desired){\n                min=mid+1;\n            }else{\n                max=mid;\n            }\n        }\n        return min;\n    }\n}\n"
  },
  {
    "path": "GFG/Merge Sort/Merge Sort.java",
    "content": "\n\nclass Solution\n{\n    void merge(int arr[], int l, int m, int r)\n    {\n         // Your code here\n         int[] a = new int[r-l+1];\n         int id1 = l;\n         int id2 = m+1;\n         int c = 0;\n         while(id1<=m && id2<=r){\n             if(arr[id1]<=arr[id2]){\n                 a[c++] = arr[id1++];\n             }else{\n                 a[c++] = arr[id2++];\n             }\n         }\n         while(id1<=m){\n             a[c++] = arr[id1++];\n         }\n         while(id2<=r){\n             a[c++] = arr[id2++];\n         }\n         for(int i=0,j=l;i<a.length;i++,j++){\n             arr[j] = a[i];\n         }\n    }\n    void mergeSort(int arr[], int l, int r)\n    {\n        //code here\n        if(l>=r){\n            return;\n        }\n        int mid = l + (r-l)/2;\n        mergeSort(arr,l,mid);\n        mergeSort(arr,mid+1,r);\n        merge(arr,l,mid,r);\n    }\n}\n"
  },
  {
    "path": "GFG/Merge two BST 's/Merge two BST.cpp",
    "content": "\n//This Approch uses Recursuion \n\nclass Solution\n{\n    public:\n    //Function to return a list of integers denoting the node \n    //values of both the BST in a sorted order.\n    void inorder1(Node* root, vector<int> &v1){\n        if(root){\n            inorder1(root->left,v1);\n            v1.push_back(root->data);\n            inorder1(root->right,v1);\n        }\n    }\n  \n  //calling Inorder\n    void inorder2(Node* root, vector<int> &v1){\n        if(root){\n            inorder2(root->left,v1);\n            v1.push_back(root->data);\n            inorder2(root->right,v1);\n        }\n    }\n    vector<int> merge(Node *root1, Node *root2)\n    {\n       vector<int> v1;\n       inorder1(root1,v1);//we are calling this inorder to add all the element in the main vector so that at the end we get a sorted array by merging both element in the main vector\n       inorder2(root2,v1);\n       sort(v1.begin(),v1.end());\n       return v1;\n    }\n};\n"
  },
  {
    "path": "GFG/Min operations/Min operations.java",
    "content": "class Solution {\n\n    public static int solve(int a, int b) {\n\n        // code here\n\n        if(a==b)return 0;\n\n        if((a & b) == a || (a & b) == b)return 1;\n\n        return 2;\n\n    }\n\n}    \n"
  },
  {
    "path": "GFG/Minimize number of Students to be removed/Minimize number of Students to be removed.java",
    "content": "class Solution {\n    public int removeStudents(int[] H, int n) {\n        // code here\n        ArrayList<Integer> dp=new ArrayList<>();\n        for(int i=0;i<n;i++){\n            int idx=binarySearch(H[i],dp);\n            if(idx==dp.size()){\n                dp.add(H[i]);\n            }else{\n                dp.set(idx,H[i]);\n            }\n        }\n        return n-dp.size();\n    }\n    int binarySearch(int ele,ArrayList<Integer> arr){\n        int l=0;\n        int h=arr.size()-1;\n        while(l<=h){\n            int mid=(l+h)/2;\n            if(arr.get(mid)>=ele){\n                h=mid-1;\n            }else{\n                l=mid+1;\n            }\n        }\n        return l;\n    }\n};\n"
  },
  {
    "path": "GFG/Minimize the sum/Minimize the sum.java",
    "content": "class Solution {\n    long minimizeSum(int N, int arr[]) {\n        // code here\n        long ans=0;\n        PriorityQueue<Integer> pq=new PriorityQueue<>();\n        for(int i:arr){\n            pq.add(i);\n        }\n        while(pq.size()>1){\n            int curr=pq.remove()+pq.remove();\n            ans+=curr;\n            pq.add(curr);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Minimum Cost of ropes/Minimum Cost of ropes.java",
    "content": "class Solution\n{\n    //Function to return the minimum cost of connecting the ropes.\n    long minCost(long arr[], int n) \n    {\n        // your code here\n        long cost = 0;\n        if(n < 2){\n            return cost;\n        }\n        PriorityQueue<Long> pq = new PriorityQueue<Long>();\n        for(int i = 0; i < n; i++){\n            pq.add(arr[i]);\n        }\n        while(true){\n            long first = pq.peek();\n            pq.remove();\n            long second = pq.peek();\n            pq.remove();\n            long temp = first + second;\n            cost = cost + temp;\n            if(pq.isEmpty()){\n                break;\n            }\n            pq.add(temp);\n        }\n        return cost;\n    }\n}\n"
  },
  {
    "path": "GFG/Minimum Costs of Ropes/Minimum Costs of Ropes.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution\n{\n    public:\n    //Function to return the minimum cost of connecting the ropes.\n    long long minCost(long long arr[], long long n) {\n        // Your code here\n        if(n==1) return 0; // base case if 1 rope is only given then we don't have to add so return 0\n        \n        priority_queue<long long, vector<long long>, greater<long long>> pq; // taking priority_queue in main_heap\n        for(int i=0; i<n; i++) pq.push(arr[i]); // using loop pushing every elem into priority_queue\n        long long res =0; // initializing res with 0\n        \n        long long x = pq.top(); \n        // running a loop if we get only 1 elems then come out of loop\n        while(pq.size()>1){\n            // getting 1st elem mini from top and popping out from priority_queue\n            long long x = pq.top(); pq.pop();\n            // getting 2nd elem mini from top and popping out from priority_queue\n            long long y = pq.top(); pq.pop();\n            // adding 1st mini and 2nd mini\n            res+=(x+y);\n            // pushing to Priority queue to add with other numbers also\n            pq.push(x+y);\n        }\n        return res;\n        // TC: O(N log N) -> pq takes log n and loop is running for n times so it becomes nlogn\n        // SC: O(N) - pq is taking N Space to store\n    }\n};\nint main() {\n    long long t;\n    cin >> t;\n    while (t--) {\n        long long n;\n        cin >> n;\n        long long i, a[n];\n        for (i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n        Solution ob;\n        cout << ob.minCost(a, n) << endl;\n    }\n    return 0;\n}"
  },
  {
    "path": "GFG/Minimum characters to be added at front to make string palindrome/Minimum characters to be added at front to make string palindrome oc2.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n    int minChar(string str){\n        //Write your code here\n        int i =0, j = str.length()-1;\n        int temp_j =j, res =0;       \n        while(i <=j){\n            // to check curr with reverse, if matches incr\n            if(str[i]== str[j]){\n                i++; j--;\n            }else{\n                // otherwise\n                res++;\n                i=0;\n                j=--temp_j;\n            }\n        }\n        return res;\n    }\n};\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t    string str;\n\t    cin >> str;\n\t    Solution ob;\n\t    int ans = ob.minChar(str);\n\t    cout << ans<<endl;\n\t}\n\treturn 0;\n}"
  },
  {
    "path": "GFG/Minimum characters to be added at front to make string palindrome/Minimum characters to be added at front to make string palindrome.cpp",
    "content": "class Solution {\npublic:\n    int minChar(string str){\n        //Write your code here\n        \n        int i=0, j=str.length() - 1, last = j, ans = 0;\n        \n        while(i<j){\n            \n             //check for palindrome\n             \n             if(str[i] == str[j]){\n                 \n                 i++;\n                 j--;\n                 \n             }\n             \n             //if characters dos not match decrease the value of last \n             //and put it into j , and increase value of ans'\n             //start from 0\n             \n             else{\n                 ans++;\n                 i=0;\n                 j= --last;\n             }\n            \n            \n        }\n        \n        //return ans\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "GFG/Minimum characters to be added at front to make string palindrome/Minimum characters to be added at front to make string palindrome.java",
    "content": "class Solution {\n    public static int minChar(String str) {\n       //Write your code here\n      int i =0, j = str.length()-1, last = j, ans =0;\n      while(i < j){\n          if(str.charAt(i) == str.charAt(j)){\n              i++;\n              j--;\n          }else{\n              ans++;\n              i = 0;\n              j = --last;\n          }\n      }\n      return ans;\n    }\n    \n}\n\n//=====================================================\n// class Solution {\n//     public static int minChar(String s) {\n//        //Write your code here\n//        int i=0;\n//        int j=s.length()-1;\n//        int ans=0;\n//        while(i<j){\n//            if(s.charAt(i)==s.charAt(j)){\n//                i++;\n//                j--;\n//            }else{\n//                ans=s.length()-j;\n//                i=0;\n//                //reduce add\n//                 while(s.charAt(i)==s.charAt(j)){\n//                     ans--;\n//                     i++;\n//                 }\n//                j--;\n//            }\n//        }\n//        return ans;\n//     }\n// }\n"
  },
  {
    "path": "GFG/Minimum characters to be added at front to make string palindrome/Minimum characters to be added at front to make string palindrome.py",
    "content": "class Solution:\n    def minChar(self,str):\n        n = len(str)\n        i = 0\n        j = n-1\n        ans=n-1\n        while (i<j):\n            if str[i]==str[j]:\n                i+=1\n                j-=1\n            else:\n                i=0\n                ans-=1\n                j=ans\n        return n-ans-1\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nif __name__==\"__main__\":\n    for _ in range(int(input())):\n        s=input()\n        obj=Solution()\n        ans=obj.minChar(s)\n        print(ans)\n# } Driver Code Ends\n"
  },
  {
    "path": "GFG/Minimum characters to be added at front to make string palindrome/README.md",
    "content": "Given string **str** of length **N**. The task is to find the minimum characters to be added at the front to make string palindrome.\n\n**Note**: A palindrome is a word which reads the same backward as forward. Example: \"madam\".\n\n## Example 1:\n\n```\nInput:\nS = \"abc\"\n\nOutput: 2\n\nExplanation: \nAdd 'b' and 'c' at front of above string to make it\npalindrome : \"cbabc\"\n\n```\n\n## Example 2:\n\n```\nInput:\nS = \"aacecaaa\"\n\nOutput: 1\n\nExplanation: Add 'a' at front of above string\nto make it palindrome : \"aaacecaaa\"\n\n```\n\n**Your Task:**\n\nYou don't need to read input or print anything. Your task is to complete the function **minChar()** which takes a string S and returns an integer as output.\n\n**Expected Time Complexity:** O(N)\n\n**Expected Auxiliary Space:** O(N)\n\n**Constraints:**\n\n1 <= S.length <= 106\n\n"
  },
  {
    "path": "GFG/Minimum number of Coins/Minimum number of Coins.cpp",
    "content": "class Solution{\npublic:\n    vector<int> minPartition(int N)\n    {\n        vector<int> v;\n        \n        if(N>=2000){\n            int cnt = N/2000;\n            for(int i=0;i<cnt;i++) v.push_back(2000);\n            N %= 2000;\n        } if(N>=500){\n            int cnt = N/500;\n            for(int i=0;i<cnt;i++) v.push_back(500);\n            N %= 500;\n        } if(N>=200){\n            int cnt = N/200;\n            for(int i=0;i<cnt;i++) v.push_back(200);\n            N %= 200;\n        } if(N>=100){\n            int cnt = N/100;\n            for(int i=0;i<cnt;i++) v.push_back(100);\n            N %= 100;\n        } if(N>=50){\n            int cnt = N/50;\n            for(int i=0;i<cnt;i++) v.push_back(50);\n            N %= 50;\n        } if(N>=20){\n            int cnt = N/20;\n            for(int i=0;i<cnt;i++) v.push_back(20);\n            N %= 20;\n            // cout<<N<<\"\\n\";\n        } if(N>=10){\n            int cnt = N/10;\n            for(int i=0;i<cnt;i++) v.push_back(10);\n            N %= 10;\n        } if(N>=5){\n            int cnt = N/5;\n            for(int i=0;i<cnt;i++) v.push_back(5);\n            N %= 5;\n        } if(N>=2){\n            int cnt = N/2;\n            for(int i=0;i<cnt;i++) v.push_back(2);\n            N %= 2;\n        } if(N>=1){\n            int cnt = N;\n            for(int i=0;i<cnt;i++) v.push_back(1);\n            N %= 1;\n        }\n        \n        return v;\n    }\n};\n"
  },
  {
    "path": "GFG/Minimum number of Coins/Minimum number of Coins.java",
    "content": "class Solution{\n    static List<Integer> minPartition(int N)\n    {\n        // code here\n        int[]a=new int[]{1,2,5,10,20,50,100,200,500,2000};\n        List<Integer> ans=new ArrayList<>();\n        int i=9;\n        while(i>=0){\n            if(a[i]>N){\n                i--;\n            }else{\n                while(N>=a[i]){\n                    ans.add(a[i]);\n                    N-=a[i];\n                }\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Minimum sum partition/Minimum sum partition.cpp",
    "content": "\n};\n"
  },
  {
    "path": "GFG/Minimum sum partition/Minimum sum partition.java",
    "content": "class Solution\n{\n\n\tpublic int minDifference(int arr[], int n) \n\t{ \n\t    // Your code goes here\n\t    Map<String,Integer> map=new HashMap<>();\n\t    return dfs(arr,n-1,0,0,map);\n\t} \n\tpublic int dfs(int[]arr,int n,int s1,int s2,Map<String,Integer> map){\n\t    if(n<0){\n\t        return Math.abs(s1-s2);\n\t    }\n\t    String key=n+\",\"+s1;\n\t    if(!map.containsKey(key)){\n\t        int first=dfs(arr,n-1,s1+arr[n],s2,map);\n\t        int sec=dfs(arr,n-1,s1,s2+arr[n],map);\n\t        map.put(key,Math.min(first,sec));\n\t    }\n\t    return map.get(key);\n\t}\n}\n"
  },
  {
    "path": "GFG/Minimum sum partition/README.md",
    "content": "## Minimum sum partition\n\n\nGiven an array arr of size n containing non-negative integers, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum and find the minimum difference\n\n\n**Example 1:**\n\n```\nInput: N = 4, arr[] = {1, 6, 11, 5}\n\nOutput: 1\n\nExplanation: \nSubset1 = {1, 5, 6}, sum of Subset1 = 12 \nSubset2 = {11}, sum of Subset2 = 11  \n```\n\n**Example 2:**\n\n```\nInput: N = 2, arr[] = {1, 4}\n\nOutput: 3\n\nExplanation: \nSubset1 = {1}, sum of Subset1 = 1\nSubset2 = {4}, sum of Subset2 = 4\n```\n\n**Your Task:** \n\nYou don't need to read input or print anything. Complete the function **minDifference()** which takes N and array arr as input parameters and returns the integer value\n\n\n**Expected Time Complexity:** O(N*|sum of array elements|)\n**Expected Auxiliary Space:** O(N*|sum of array elements|)\n\n\n**Constraints:**\n1 ≤ N*|sum of array elements| ≤ 106\n0 < arr[i] <= 105\n"
  },
  {
    "path": "GFG/Missing number in matrix.java/Missing number in matrix.java",
    "content": "class Solution\n{\n    public long  MissingNo(int[][] mat)\n    {\n        // code here\n        int n=mat.length;\n        int x=-1;\n        int y=-1;\n        long rowSum[]=new long[n];\n        long colSum[]=new long[n];\n        long leftDia=0;\n        long rightDia=0;\n        \n        for(int i=0;i<n;i++){\n            leftDia+=mat[i][i];\n            rightDia+=mat[i][n-i-1];\n            for(int j=0;j<n;j++){\n                if(mat[i][j]==0){\n                    x=i;\n                    y=j;\n                }\n                rowSum[i]+=mat[i][j];\n                colSum[j]+=mat[i][j];\n            }\n        }\n        \n        long rowSumOriginal = x==0? rowSum[x+1] : rowSum[x-1];\n        long colSumOriginal = y==0? colSum[y+1] : colSum[y-1];\n        long diff = colSumOriginal - colSum[y];\n        if(diff<=0 || diff!=rowSumOriginal-rowSum[x]){\n            return -1;\n        }\n        \n        if(x==y){\n            leftDia+=diff;\n        }\n        \n        if(x==n-y-1){\n            rightDia+=diff;\n        }\n        \n        if(leftDia!=rightDia)return -1;\n        rowSum[x]+=diff;\n        colSum[y]+=diff;\n        for(int i=0;i<n;i++){\n            if(rowSum[i]!=leftDia || colSum[i]!=rightDia){\n                return -1;\n            }\n        }\n        return diff;\n        \n    }\n}\n"
  },
  {
    "path": "GFG/Modified Numbers and Queries/Modified Numbers And Queries.java",
    "content": "class Solution\n{\n    public int sumOfAll(int l, int r)\n    {\n        // code here\n        int f[]=new int[r+1];\n        int ans=0;\n        if(l<=1) ans+=1;\n        for(int i=2;i<=r;i++) {\n            if(f[i]==0) {\n                for(int j=i;j<=r;j+=i) {\n                    f[j]+=i;\n                }\n            }\n            if(i>=l) {\n                if(f[i]==0) ans+=i;\n                else ans+=f[i];\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Modified Numbers and Queries/Modified Numbers and Queries oc3.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\n    private:void Sieve(vector<int> &Primes, int n){\n        Primes[1]=1;\n        for(int i =2; i<=n; i++)\n            if(Primes[i] ==0)\n                for(int j =i; j<=n; j+=i)\n                    Primes[j]+=i;\n    };\n  public:\n    int sumOfAll(int l, int r){\n        // code here\n        vector<int>Primes(r+1, 0);\n        Sieve(Primes, r);\n        int sum=0;\n        for(int i =l; i<=r; i++)\n        sum+=Primes[i];\n        return sum;\n    }\n};\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int l, r;\n        cin>>l>>r;\n        Solution ob;\n        cout<<ob.sumOfAll(l,r)<<endl;\n    }\n    return 0;\n}\n\n"
  },
  {
    "path": "GFG/Modified Numbers and Queries/Modified Numbers and Queries.py",
    "content": "class Solution:\n\tdef sumOfAll(self, l, r):\n\t\t# code here\n        arr=[0]*(r+1)\n        arr[1]=1\n        \n        for i in range(2,r+1):\n            if arr[i]!=0:\n                continue\n        \n            for j in range(i,r+1,i):\n                if j%i==0:\n                    arr[j]+=i\n        \n        count=0\n        \n        for i in range(l,r+1):\n            count+=arr[i]\n        \n        return count\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\nif __name__ == '__main__':\n\tT=int(input())\n\tfor i in range(T):\n\t\tl,r = input().split()\n\t\tl=int(l)\n\t\tr=int(r)\n\t\tob = Solution();\n\t\tprint(ob.sumOfAll(l,r))\n\n# } Driver Code Ends\n"
  },
  {
    "path": "GFG/Modified Numbers and Queries/README.md",
    "content": "## Modified Numbers and Queries\n\nFind the sum of all the numbers between the range l and r. Here each number is represented by the sum of its prime factors. \n\n**Note**:  For example, 6 is represented by 5 because 6 has two prime factors 2 and 3 and 2 + 3 = 5.\n\n## Example 1:\n\n```\nInput:\nl = 1, r = 2\n\nOutput: 3\n\nExplanation: \n1->1, 2->2 and 1+2=3.  \n\n```\n\n## Example 2:\n\n```\nInput:\nl = 1, r = 6\n\nOutput: 18\n\nExplanation:1->1, 2->2, 3->3, 4->2\n5->5, 6->2+3=5, 1+2+3+2+5+5 = 18. \n\n```\n\n**Your Task:**\nYou dont need to read input or print anything. Complete the function **sumOfAll()** which takes l and r as input parameter and returns sum all the numbers ( as represented ) in the given range both L and R included.\n\n**Expected Time Complexity:** O(nloglogn)\n\n**Expected Auxiliary Space:** O(N)\n\n**Constraints:**\n\n1 <= l <= r <=104\n\n"
  },
  {
    "path": "GFG/Move Last Element to Front of a Linked List/Move Last Element to Front of a Linked List 2 different approaches.java",
    "content": "First Approach:\n\nTime Complexity:O(N)\nAuxiliary Space:O(N)\n  \n  \nCode:\n\n\nclass Solution {\n    public static Node moveToFront(Node head) {\n        if(head==null || head.next==null){\n            return head;\n        }\n        \n        ArrayList<Integer>aa=new ArrayList<Integer>();\n        Node temp=head;\n        while(temp!=null){\n            aa.add(temp.data);\n            temp=temp.next;\n        }\n        int a=aa.get(aa.size()-1);\n        aa.remove(aa.size()-1);\n        aa.add(0,a);\n        Node temp2=new Node(-1);\n        Node temp3=temp2;\n        \n       for(int a1:aa){\n           temp2.next=new Node(a1);\n           temp2=temp2.next;\n       }\n       \n       return temp3.next;\n        \n    }\n}\n\n\n\n\n=======================================================================================================================================================================\n  \n\nSecond Approach:\n\nTime Complexity:O(N)\nAuxiliary Space:O(1)\n  \n\nCode:\n\nclass Solution {\n    public static Node moveToFront(Node head) {\n       if(head==null){\n           return null;\n       }\n       else if(head.next==null){\n           return head;\n       }\n        Node temp=head;\n        Node prev=null;\n        Node current=head;\n        while(current.next!=null){\n            prev=current;\n            current=current.next;\n        }\n        current.next=head;\n        prev.next=null;\n        return current;\n    }\n}\n     \n\n\n\n\n\n"
  },
  {
    "path": "GFG/Move Last Element to Front of a Linked List/Move Last Element to Front of a Linked List.cpp",
    "content": "class Solution{\npublic:\n    ListNode *moveToFront(ListNode *head){\n        \n        if(head->next == NULL) return head;\n        \n        ListNode *temp = head;\n        \n        while(head->next->next!=NULL)\n     \n        head = head->next;\n        head->next->next = temp;\n        temp = head->next;\n        head->next = NULL;\n        \n        return temp;\n        \n    }\n};\n"
  },
  {
    "path": "GFG/Move Last Element to Front of a Linked List/Move Last Element to Front of a Linked List.java",
    "content": "class Solution {\n    public static Node moveToFront(Node head) {\n        // code here\n        if(head.next==null)return head;\n        Node temp=head;\n        while(temp.next.next!=null){\n            temp=temp.next;\n        }\n        Node last=temp.next;\n        temp.next=null;\n        last.next=head;\n        return last;\n    }\n}\n"
  },
  {
    "path": "GFG/Move Last Element to Front of a Linked List/README.md",
    "content": "## Move Last Element to Front of a Linked List\n\n\nYou are given the head of a Linked List. You have to move the last element to the front of the Linked List and return the list.\n\n \n\n**Example 1:**\n\n```\nInput:\nN = 5\n\nList = {2,5,6,2,1}\n\nOutput:\n{1,2,5,6,2}\n\nExplanation:\nIn the given linked list, the last element is 1,\nafter moving the last element to the front the\nlinked list will be {1,2,5,6,2}.\n \n```\n\n**Example 2:**\n\n```\nInput:\nN = 1\n\nList = {2}\n\nOutput:\n{2}\n\nExplanation:\nHere 2 is the only element so, the linked list\nwill remain the same.\n \n```\n\n***\n\n**Your Task:**\n\nYou don't need to read input or print anything. Your task is to complete the function **moveToFront()** which takes the address of the head of the linked list and returns the modified linked list.\n\n \n\n**Expected Time Complexity:** O(N)\n**Expected Auxiliary Space:** O(1)\n\n \n\n**Constraints:**\n1 <= N <= 105\n0 <= Elements of List <= 109\nSum of N over all test cases doesn't exceeds 106\n"
  },
  {
    "path": "GFG/Next Greater Element/Next Greater Element.java",
    "content": "class Solution{\n    public static long[] nextLargerElement(long[] arr, int n) { \n        // Your code here\n        long[]ans=new long[n];\n        Stack<Long> st=new Stack<>();\n        for(int i=n-1;i>=0;i--){\n            while(!st.isEmpty() && st.peek()<arr[i]){\n                st.pop();\n            }\n            if(st.isEmpty()){\n                ans[i]=-1;\n            }else{\n                ans[i]=st.peek();\n            }\n            st.push(arr[i]);\n        }\n        return ans;\n    } \n}\n"
  },
  {
    "path": "GFG/Next Happy Number/Next Happy Number.java",
    "content": "class Solution{\n\n    static int nextHappy(int N){\n        for(int i=N+1; i<=1005; i++)\n        {\n            ArrayList<Integer> ar=new ArrayList<Integer>();\n            if(isHappyNumber(i, ar))\n            {\n                return i;\n            }\n        }\n        return -1;\n    }\n    public static boolean isHappyNumber(int n, ArrayList<Integer> ar)\n    {\n        if(ar.contains(n))\n        {\n            return false;\n        }\n        if(n==1)\n        {\n            return true;\n        }\n        ar.add(n);\n        n=findSquareNumber(n);\n        boolean res=isHappyNumber(n, ar);\n        return res;\n    }\n    public static int findSquareNumber(int n)\n    {\n        int newNumber=0;\n        while(n>0)\n        {\n            int rem=n%10;\n            newNumber+=(rem*rem);\n            n=n/10;\n        }\n        return newNumber;\n    }\n}\n"
  },
  {
    "path": "GFG/Nine Divisors/Nine Divisors.cpp",
    "content": "class Solution{   \npublic:\n    long long int nineDivisors(long long int N){\n        //Code Here\n        if(N < 36) return 0;\n        \n        long long size = sqrt(N);\n        \n        long long count = 0;\n        \n        vector<long long> sieve(size+1);\n        \n        for(int i = 1; i <= size; i++)\n        {\n            sieve[i] = i;\n        }\n        \n        for(long long i = 2; i*i <= size; i++)\n        {\n            if(sieve[i] != i) continue;\n            for(long long j = i*i; j <= size; j+=i)\n            {\n                if(sieve[j] == j)\n                sieve[j] = i;\n            }\n        }\n        \n        for(long long i = 2; i <= size; i++)\n        {\n            long long p = sieve[i];\n            \n            long long q = sieve[i/p];\n            \n            if((p!=q && p*q == i && q !=1) || (sieve[i] == i && pow(i,8) <= N))\n            {\n                count++;\n            }\n        }\n        return count;\n    }\n};\n"
  },
  {
    "path": "GFG/Nine Divisors/Nine Divisors.java",
    "content": "class Solution{\n    static long nineDivisors(long N){\n        //Code Here\n        long ans=0;\n        int size=(int)Math.sqrt(N);\n        int prime[]=new int[size+1];\n        for(int i=1;i<=size;i++){\n            prime[i]=i;\n        }\n        \n        //fill sieve\n        for(int i=2;i*i<=size;i++){\n            if(prime[i]==i){\n                for(int j=i*i;j<=size;j+=i){\n                    if(prime[j]==j){\n                        prime[j]=i;\n                    }\n                }\n            }\n        }\n        //check for root n\n        for(int i=2;i<=size;i++){\n            int p=prime[i];\n            \n            int q=prime[i/p];\n            \n            if((p!= q && p*q==i && q!=1) ||\n            (prime[i]==i && Math.pow(i,8)<=N)){\n                ans+=1;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Number Formation/Number Formation.cpp",
    "content": "class Solution {\n\n \n\n   public:\n   const int mod=1e9+7;\n    int getSum(int X, int Y, int Z) {\n        // Your code goes here\n        long long exactsum[X+1][Y+1][Z+1],exactnum[X+1][Y+1][Z+1];\n        for (int i = 0; i <=X; i++){\n            for (int j = 0; j <= Y; j++) {\n                for (int k = 0; k <= Z; k++) {\n                    exactsum[i][j][k] = 0;\n                    exactnum[i][j][k] = 0;\n                }\n            }\n        }\n        long long ans=0;\n        exactnum[0][0][0] = 1LL;\n        for (int i = 0; i <= X; ++i){\n            for (int j = 0; j <= Y; ++j){\n                for (int k = 0; k <= Z; ++k) {\n                    if (i > 0){\n                        exactsum[i][j][k] += (exactsum[i - 1][j][k] * 10 + 4 * exactnum[i - 1][j][k]) % mod;\n                        exactnum[i][j][k] += exactnum[i - 1][j][k] % mod;\n                    }\n                    if (j > 0) {\n                        exactsum[i][j][k] += (exactsum[i][j - 1][k] * 10 + 5 * exactnum[i][j - 1][k]) % mod;\n                        exactnum[i][j][k] += exactnum[i][j - 1][k] % mod;\n                    }\n                    if (k>0){\n                        exactsum[i][j][k] += (exactsum[i][j][k-1] * 10 + 6 * exactnum[i][j][k-1]) % mod;\n                        exactnum[i][j][k] += exactnum[i][j][k-1] % mod;\n                    }\n               ans+=exactsum[i][j][k]%mod;\n               ans=ans%mod;\n                }\n            }\n        }\n        return ans;\n    }\n};\n\n"
  },
  {
    "path": "GFG/Number Formation/Number Formation.java",
    "content": "class Solution {\n\n    public int getSum(int X, int Y, int Z) {\n        // Your code goes here\n        int mod=1000000007;\n        long[][][] exactSum=new long[X+1][Y+1][Z+1];\n        long[][][] num=new long[X+1][Y+1][Z+1];\n        num[0][0][0]=1L;\n        \n        long ans=0L;\n        for(int i=0;i<=X;i++){\n            for(int j=0;j<=Y;j++){\n                for(int k=0;k<=Z;k++){\n                    if(i>0){\n                        exactSum[i][j][k]+=(exactSum[i-1][j][k]*10 +4*num[i-1][j][k])%mod;\n                        num[i][j][k]+=num[i-1][j][k]%mod;\n                    }\n                    if(j>0){\n                        exactSum[i][j][k]+=(exactSum[i][j-1][k]*10 +5*num[i][j-1][k])%mod;\n                        num[i][j][k]+=num[i][j-1][k]%mod;\n                    }\n                    if(k>0){\n                        exactSum[i][j][k]+=(exactSum[i][j][k-1]*10 +6*num[i][j][k-1])%mod;\n                        num[i][j][k]+=num[i][j][k-1]%mod;\n                    }\n                    ans+=exactSum[i][j][k]%mod;\n                    ans%=mod;\n                }\n            }\n        }\n        return (int)ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Number Formation/README.md",
    "content": "## Number Formation\n\nGiven three integers x, y, and z, the task is to find the sum of all the numbers formed by \nhaving 4 at most x times, having 5 at most y times, and having 6 at most z times as a digit.\n\n**Note:** Output the sum modulo 109+7.\n\n**Example 1:**\n\n```\nInput: X = 1, Y = 1, Z = 1 \n\nOutput: 3675\n\nExplanation: 4 + 5 + 6 + 45 + 54 + 56 \n+ 65 + 46 + 64 + 456 + 465 \n+ 546 + 564 + 645 + 654 = 3675\n```\n**Example 2:**\n\n```\nInput: X = 0, Y = 0, Z = 0\n\nOutput: 0\n\nExplanation: No number can be formed\n\n```\n\n***\n\n**Your Task:**  \nYou don't need to read input or print anything. Complete the function **getSum()** which takes X, Y and Z as input parameters and returns the integer value\n\n**Expected Time Complexity:** O(X*Y*Z)\n**Expected Auxiliary Space:** O(X*Y*Z)\n\nConstraints:\n0 ≤ X, Y, Z ≤ 60\n\n"
  },
  {
    "path": "GFG/Number Of Islands/Number Of Islands.cpp",
    "content": "class Solution {\n  public:\n  \n    //dfs function for finding island\n    \n   void dfs(vector<vector<int>>&v,int l,int i,int j,int n,int m){\n\n        if(i>n-1||j>m-1||i<0||j<0){\n\n            return;\n\n        }\n\n        if(v[i][j]!=l){\n\n            return;\n\n        }\n      \n     // update number\n     \n        v[i][j]+=1;\n\n        dfs(v,l,i-1,j,n,m); // up\n\n        dfs(v,l,i+1,j,n,m); // down\n\n        dfs(v,l,i,j-1,n,m); // left\n\n        dfs(v,l,i,j+1,n,m); // right\n\n    }\n\n  \n\n    vector<int> numOfIslands(int n, int m, vector<vector<int>> &operators) {\n\n        int k=operators.size();\n      \n      //flag\n\n        int l=1;\n\n        vector<int> ans;\n\n        vector<vector<int>> v(n,vector<int>(m,0));\n      \n      // iterate around the number of operations\n\n        for(int i=0;i<k;i++){\n\n            int count=0;\n\n            v[operators[i][0]][operators[i][1]]=l;\n\n            for(int t=0;t<n;t++){\n\n                for(int j=0;j<m;j++){\n\n                    if(v[t][j]==l){\n\n                        dfs(v,l,t,j,n,m);\n\n                        count++;\n\n                    }\n\n                }\n\n            }\n          \n     // update flag\n          \n            l++;\n\n            ans.push_back(count);\n\n        }\n\n        return ans;\n\n    }\n};\n"
  },
  {
    "path": "GFG/Number Of Islands/Number Of Islands.java",
    "content": "class UnionFind{\n    int[]parent;\n    int size;\n    UnionFind(int row,int col){\n        size=row*col;\n        parent=new int[size];\n        for(int i=0;i<size;i++){\n            parent[i]=i;\n        }\n    }\n    void union(int x,int y){\n        int px=findParent(x);\n        int py=findParent(y);\n        parent[py]=px;\n    }\n    int findParent(int x){\n        if(parent[x]==x)return x;\n        return parent[x]=findParent(parent[x]);\n    }\n    int count(int [][]mat){\n        int col=mat[0].length;\n        int cnt=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                    if(parent[i*col+j]==i*col+j){\n                        cnt++;\n                    }\n                }\n            }\n        }\n        return cnt;\n    }\n}\n\nclass Solution {\n    \n    public List<Integer> numOfIslands(int rows, int cols, int[][] operators) {\n        //Your code here\n        int[][] mat=new int[rows][cols];\n        List<Integer> ans=new ArrayList<>();\n        UnionFind uf=new UnionFind(rows,cols);\n        int[] dx=new int[]{1,0,-1,0};\n        int[] dy=new int[]{0,1,0,-1};\n        \n        for(int[]operator:operators){\n            int x=operator[0];\n            int y=operator[1];\n            mat[x][y]=1;\n            for(int i=0;i<4;i++){\n                int nx=x+dx[i];\n                int ny=y+dy[i];\n                if(nx>=0 && ny>=0 && nx<rows && ny<cols && mat[nx][ny]==1){\n                    uf.union(x*cols+y,nx*cols+ny);\n                }\n            }\n            ans.add(uf.count(mat));\n        }\n        return ans;\n    }\n    \n}\n"
  },
  {
    "path": "GFG/Number Of Islands/README.md",
    "content": "## Number Of Islands\n\nYou are given a **n,m** which means the row and column of the 2D matrix and an array of  **size k** denoting the number of operations. Matrix elements is 0 if there is water or 1 if there is land. Originally, the 2D matrix is all 0 which means there is no land in the matrix. The array has k operator and each operator has two integer A[i][0], A[i][1] means that you can change the cell matrix[A[i][0]][A[i][1]] from sea to island. Return how many island are there in the matrix after each operator.You need to return an array of size k.\n\n \n\n**Example 1:**\n\n```\nInput: n = 4\nm = 5\nk = 4\n\nA = {{1,1},{0,1},{3,3},{3,4}}\n\nOutput: 1 1 2 2\n\nExplanation:\n\n0.  00000\n    00000\n    00000\n    00000\n1.  00000\n    01000\n    00000\n    00000\n2.  01000\n    01000\n    00000\n    00000\n3.  01000\n    01000\n    00000\n    00010\n4.  01000\n    01000\n    00000\n    00011\n \n```\n \n\n**Example 2:**\n\n```\nInput: n = 4\nm = 5\nk = 4\nA = {{0,0},{1,1},{2,2},{3,3}}\n\n\nOutput: 1 2 3 4\n\n\nExplanation:\n\n\n0.  00000\n    00000\n    00000\n    00000\n1.  10000\n    00000\n    00000\n    00000\n2.  10000\n    01000\n    00000\n    00000\n3.  10000\n    01000\n    00100\n    00000\n4.  10000\n    01000\n    00100\n    00010\n``` \n\n***\n\n**Your Task:**\nYou don't need to read or print anything. Your task is to complete the function **numOfIslands()** which takes an integer **n** denoting no. of rows in the matrix, an integer **m** denoting the number of columns in the matrix and a 2D array of size k denoting  the number of operators.\n\n**Expected Time Complexity:** O(m * n)\n**Expected Auxiliary Space:** O(m * n)\n\n**Constraints:**\n\n1 <= n,m <= 100\n1 <= k <= 1000\n"
  },
  {
    "path": "GFG/Number Of Open Doors/Number Of Open Doors.java",
    "content": "class Solution {\n    static int noOfOpenDoors(Long N) {\n        // code here\n        return (int)Math.sqrt(N);   \n    }\n};\n"
  },
  {
    "path": "GFG/Number of Distinct Islands/Number of Distinct Islands oct1.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\n  public:\n  void dfs(vector<vector<int>>& grid, int i, int j, int xi, int xj, int n, int m, vector<int>&ans){\n      if(i<0 || j<0 || i>=n || j>=m || grid[i][j]==0) return;\n      \n      ans.push_back(i-xi);\n      ans.push_back(j-xj);\n      grid[i][j] =0;\n      dfs(grid, i-1, j, xi, xj, n,m, ans);\n      dfs(grid, i+1, j, xi, xj, n,m, ans);\n      dfs(grid, i, j-1, xi, xj, n,m, ans);\n      dfs(grid, i, j+1, xi, xj, n,m, ans);\n  }\n    int countDistinctIslands(vector<vector<int>>& grid) {\n        // code here\n        set<vector<int>>st;\n        int n = grid.size(), m= grid[0].size();\n        for(int i =0; i<n; i++){\n            for(int j =0; j<m; j++){\n                if(grid[i][j]==1){\n                    vector<int>ans;\n                    dfs(grid,i,j,i,j,n,m,ans);\n                    st.insert(ans);\n                }\n            }\n        }\n        return st.size();\n    }\n};\nint main() {\n\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> n >> m;\n        vector<vector<int>> grid(n, vector<int>(m));\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                cin >> grid[i][j];\n            }\n        }\n        Solution obj;\n        cout << obj.countDistinctIslands(grid) << endl;\n    }\n}\n\n\n// Another Approach :\n/*\n  Instead of changing the original content/values of grid vector, we can also use a different vector storing each visited indexes,\n  while keeping grid vector intact, as in general it's not recommended to change values of original vector.\n  \n  Below is my Code class implementing my logic, I hope it will help,\n*/\n\nclass Solution {\n  public:\nvoid dfs(int i,int j,int r,int c,vector<vector<int>> &vis, vector<vector<int>> &v,vector<vector<int>>&a){\n    int n = v.size(), m = v[0].size();\n    if(r>=n || c>=m || r<0 || c<0 || v[r][c]==0 || vis[r][c]==1) return;\n    \n    a.push_back({i,j});\n    vis[r][c] = 1;\n    \n    dfs(i+1,j,r+1,c,vis,v,a);\n    dfs(i,j+1,r,c+1,vis,v,a);\n    dfs(i-1,j,r-1,c,vis,v,a);\n    dfs(i,j-1,r,c-1,vis,v,a);\n    \n}  \n    int countDistinctIslands(vector<vector<int>>& grid) {\n        set<vector<vector<int>>> st;\n        \n        vector<vector<int>> vis(grid.size(),vector<int>(grid[0].size(),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]==1 && vis[i][j]==0){\n                    vector<vector<int>> v;\n                    dfs(0,0,i,j,vis,grid,v);\n                    if(v.size()>0)  st.insert(v);\n                }\n            }\n        }\n        \n        \n        return st.size();\n    }\n};\n"
  },
  {
    "path": "GFG/Number of Distinct Islands/Number of Distinct Islands.py",
    "content": "import sys\nclass Solution:\n  sys.setrecursionlimit(10**8)\n  def countDistinctIslands(self, grid : List[List[int]]) -> int:\n        ans = set()\n        n=len(grid)\n        m=len(grid[0])\n\n        def dfs(r,c,ans):\n            if r<0 or c<0 or r>=n or c>=m or grid[r][c]!=1:\n                return\n            grid[r][c] = 0\n            dfs(r, c-1, arr)\n            arr.append('R')\n            dfs(r, c+1, arr)\n            arr.append('D')\n            dfs(r+1, c, arr)\n            arr.append('U')\n            dfs(r-1, c, arr)\n            arr.append('L')\n\n        for i in range(n):\n            for j in range(m):\n                if grid[i][j] == 1:\n                    arr = []\n                    dfs(i,j,arr)\n                    ans.add(tuple(arr))\n        return len(ans)\n"
  },
  {
    "path": "GFG/Number of turns in binary tree/Number of turns in binary tree.cpp",
    "content": "/*\n  This code is contributed by-->\n  - Abhishek Kumar (https://github.com/Abhi2061)\n  - Adarsh Urmaliya (https://github.com/Satellite-system)\n*/\n\nclass Solution{\n  public:\n  \n    // function should return the number of turns required to go from first node to second node \n    int NumberOFTurns(struct Node* root, int first, int second)\n    {\n      // Your code goes here\n      Node *head = lca(root, first, second);\n      \n      int F = countTurns(head, first, ' ');\n      int S = countTurns(head, second, ' ');\n      \n      int ans = F + S;\n      \n      if(head->data != first and head->data != second)\n      ans++;\n      \n      return ans;\n    }\n    \n    //Function to return the lowest common ancestor in a Binary Tree.\n    Node* lca(Node* root ,int n1 ,int n2 )\n    {\n       //Your code here \n       \n        if(!root)\n        return root;\n        \n        if(root->data == n1 or root->data == n2)\n        return root;\n        \n        Node *Left = lca(root->left, n1, n2);\n        Node *Right = lca(root->right, n1, n2);\n        \n        if(Left and !Right)\n        return Left;\n        \n        else if(!Left and Right)\n        return Right;\n        \n        else if(Left and Right)\n        return root;\n        \n        else\n        return nullptr;\n    }\n    \n    // function should return the minimum number of turn to reach a node.\n    int countTurns(Node* root, int n, char d)\n    {\n        if(!root)\n        return 1e5;\n        \n        if(root->data == n)\n        return 0;\n        \n        int Left = countTurns(root->left, n, 'L');\n        int Right = countTurns(root->right, n, 'R');\n        \n        if(d == 'L')\n        Right++;\n        if(d == 'R')\n        Left++;\n        \n        return min(Left, Right);\n    }\n};\n\n\n// Another Approach :: \n\n// We can use Vector, and store the char as 'L' when we move to left of node in 'R' when me move to right of node, in a common vector, \n// when we got to find first number, we then store all that data to vector named First, similarily for second number we save to vector named Second,\n// now in main function we would traverse through, First and Second vector so as to remove common char stored for common Nodes, then after the common \n// nodes have been filtered, we travese in both vectors separately so as to count number of points when char has been changed from the previous char, as that\n// would mean a turn from LEFT to RIGHT or from RIGHT to LEFT, also just after removing the common nodes we would check if we have traversed any vector completely, \n// that would mean that one of the node is ancestor to other, in that case we would not increment an extra for a turn at an ancestor node..\n  \n//   MY code : \n\nclass Solution{\n  public:\nvoid traverseHelper(Node* root, int first, int second, vector<char> &FirstSeries, \n            vector<char> &SecondSeries, vector<char> &cmn, int num){\n    if(!root || num ==2) return;\n    if(root->data==first){\n        num++;\n        FirstSeries = cmn;\n    }\n    if(root->data==second){\n        num++;\n        SecondSeries = cmn;\n    }\n    \n    cmn.push_back('L');\n    traverseHelper(root->left, first, second, FirstSeries, SecondSeries, cmn, num);\n    cmn.pop_back();\n    \n    if(num==2) return;\n    \n    cmn.push_back('R');\n    traverseHelper(root->right, first, second, FirstSeries, SecondSeries, cmn, num);\n    cmn.pop_back();\n}  \n    // function should return the number of turns required to go from first node to second node \n    int NumberOFTurns(struct Node* root, int first, int second)\n    {\n        vector<char> FirstSeries, SecondSeries, cmn;\n        traverseHelper(root, first, second, FirstSeries, SecondSeries, cmn, 0);\n        \n        int i=0;\n        for(; i< min(FirstSeries.size(), SecondSeries.size()); i++){\n            if(FirstSeries[i] != SecondSeries[i]) break;\n        }\n        \n        int cnt = 0;\n        if(i == FirstSeries.size() && i == SecondSeries.size()) return cnt;\n      \n        // For the case of Different Ancestors\n        if(i<FirstSeries.size() && i<SecondSeries.size()) cnt++;\n        \n        // cout<<\"1-Series----------------\\n\";\n        for(int j=i+1; j<FirstSeries.size(); j++){\n            // cout<<FirstSeries[j]<<\" \";\n            if(FirstSeries[j]!=FirstSeries[j-1]){\n                cnt++;}\n        }\n        \n        // cout<<\"2-Series----------------\\n\";\n        for(int j=i+1; j<SecondSeries.size(); j++){\n            if(SecondSeries[j]!=SecondSeries[j-1]){\n                cnt++;\n            }\n        }\n        \n        return cnt;\n    }\n};\n"
  },
  {
    "path": "GFG/Number of turns in binary tree/Number of turns in binary tree.java",
    "content": "/*\n  This code is contributed by:- Pulkit Malhotra (https://github.com/PulkitMalhotra161001)\n*/\n\nclass Solution\n{\n    static int ans;\n    static int NumberOfTurns(Node root, int first, int second)\n    {\n        //your code here\n        ans=0;\n        Node lca=findLCA(root,first,second);\n        boolean left=true;\n        if(lca.data==first){\n            findCount(lca.left,left,second);\n            findCount(lca.right,!left,second);\n        }else if(lca.data==second){\n            findCount(lca.left,left,first);\n            findCount(lca.right,!left,first);\n        }else{\n            findCount(lca.left,left,first);\n            findCount(lca.right,!left,first);\n            findCount(lca.left,left,second);\n            findCount(lca.right,!left,second);\n            return ans+1;\n        }\n        return ans;\n    }\n    \n    static boolean findCount(Node node,boolean left,int key){\n        if(node==null)return false;\n        if(node.data==key)return true;\n        \n        if(left){\n            if(findCount(node.left,left,key)){\n                return true;\n            }\n            if(findCount(node.right,!left,key)){\n                ans++;\n                return true;\n            }\n        }else{\n            if(findCount(node.right,left,key)){\n                return true;\n            }\n            if(findCount(node.left,!left,key)){\n                ans++;\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    static Node findLCA(Node root,int first,int second){\n        if(root==null)return null;\n        if(root.data==first || root.data==second){\n            return root;\n        }\n        \n        Node left_lca=findLCA(root.left,first,second);\n        Node right_lca=findLCA(root.right,first,second);\n        if(left_lca!=null && right_lca!=null){\n            return root;\n        }else{\n            return left_lca==null?right_lca:left_lca;\n        }\n    }\n}\n\n\n\n\n//Easy to understand code without repetition of similar cases\n\nclass Solution\n{\n    static int ans;\n    static int NumberOfTurns(Node root, int first, int second)\n    {\n        ans=0;\n        Node lca=lca(root,first,second);\n        if(lca.data==first){\n            solve(lca,second,null);\n            return ans;\n        }else if(lca.data==second){\n            solve(lca,first,null);\n            return ans;\n        }\n        solve(lca,first,null);\n        solve(lca,second,null);\n        return ans+1;\n    }\n\n    static boolean solve(Node root,int x,Boolean left){\n        if(root==null)  return false;\n        if(root.data==x)     return true;\n        \n        if(left==null){\n            solve(root.left,x,true);\n            solve(root.right,x,false);\n            return true;\n        }else if(left){\n            if(solve(root.left,x,true)){\n                return true;\n            }\n            if(solve(root.right,x,false)){\n                ans++;\n                return true;\n            }\n        }else{\n            if(solve(root.right,x,false)){\n                return true;\n            }if( solve(root.left,x,true) ){\n                ans++;\n                return true;\n            }\n        }\n        \n        return false;\n    }\n    static Node lca(Node root, int n1,int n2)\n\t{\n\t    if(root==null)  return root;\n\t    if(root.data==n1 || root.data==n2)    return root;\n\t    \n\t    Node left=lca(root.left,n1,n2);\n\t    Node right=lca(root.right,n1,n2);\n\t    \n\t    if(left!=null && right!=null){\n\t        return root;\n\t    }\n\t    \n\t    return left==null?right:left;\n\t}\n}\n"
  },
  {
    "path": "GFG/Phone directory/Phone directory.cpp",
    "content": "class Solution{\npublic:\n    vector<vector<string>> displayContacts(int n, string contact[], string s)\n    {\n        // code here\n        //tried to make it as simple as possible\n        sort(contact,contact+n);\n\n        set<string> st;\n\n        for(int i=0;i<n;i++) st.insert(contact[i]);\n\n        vector<vector<string>> ans;\n\n           for(int j=0;j<s.size();j++){\n\n                vector<string> temp;\n\n                for(auto it:st){\n\n                    if(s.substr(0,j+1)==it.substr(0,j+1)) temp.push_back(it);\n\n                }\n\n                if(temp.size()==0) temp.push_back(\"0\");\n\n                ans.push_back(temp);\n\n           }\n\n        return ans;\n    }\n    };\n"
  },
  {
    "path": "GFG/Phone directory/Phone directory.java",
    "content": "class Trie{\n    Map<Character,Set<String>> map;\n    Map<Character,Trie> next;\n    Trie(){\n        map=new HashMap<>();\n        next=new HashMap<>();\n    }\n}\n\n\nclass Solution{\n    static ArrayList<ArrayList<String>> displayContacts(int n, \n                                        String contact[], String s)\n    {\n        // code here \n        ArrayList<ArrayList<String>> ans=new ArrayList<>();\n        Trie head=new Trie();\n        \n        //create trie\n        for(String st:contact){\n            Trie curr=head;\n            for(char c:st.toCharArray()){\n                curr.map.putIfAbsent(c,new TreeSet<>());\n                curr.map.get(c).add(st);\n                curr.next.putIfAbsent(c,new Trie());\n                curr=curr.next.get(c);\n            }\n        }\n        \n        Trie curr=head;\n        for(int i=0;i<s.length();i++){\n            ArrayList<String> list=new ArrayList<>();\n            if(curr.map.containsKey(s.charAt(i))){\n                for(String str:curr.map.get(s.charAt(i))){\n                    list.add(str);\n                }\n            }\n            if(list.size()==0)list.add(\"0\");\n            ans.add(list);\n            \n            if(curr.next.containsKey(s.charAt(i))){\n                curr=curr.next.get(s.charAt(i));\n            }else{\n                break;\n            }\n        }\n        while(ans.size()!=s.length()){\n            ArrayList<String> list=new ArrayList<>();\n            list.add(\"0\");\n            ans.add(list);\n        }\n        return ans;\n        \n    }\n}\n\n\n\n\n//Method 2\n\nclass Solution{\n    static class Trie {\n        Trie child[]=new Trie[26];\n        Boolean word[]=new Boolean[26];\n    }\n    static ArrayList<ArrayList<String>> displayContacts(int n, \n                                        String contact[], String s)\n    {\n        // code here\n        ArrayList<ArrayList<String>> res=new ArrayList<>();\n        Trie head = new Trie();\n        for(int i=0;i<contact.length;i++) {\n            Trie cur = head;\n            for(int j=0;j<contact[i].length();j++) {\n                if(cur.child[contact[i].charAt(j)-'a'] != null) {\n                    cur=cur.child[contact[i].charAt(j)-'a'];\n                }\n                else {\n                    cur.child[contact[i].charAt(j)-'a'] = new Trie();\n                    cur=cur.child[contact[i].charAt(j)-'a'];\n                }\n            }\n            cur.word[contact[i].charAt(contact[i].length()-1)-'a'] = true;  // For last character in word made it to true \n        }\n        \n        for(int i=0;i<s.length();i++) {\n            StringBuilder sb=new StringBuilder();\n            Trie cur = head;\n            int flag=0;\n            for(int j=0;j<=i;j++) {\n                if(cur.child[s.charAt(j)-'a']!=null) {\n                    sb.append(s.charAt(j));\n                    cur=cur.child[s.charAt(j)-'a'];\n                }\n                else {\n                    flag=1;\n                    break;\n                }\n            }\n            ArrayList<String> curList=new ArrayList<>();\n            if(flag==1) {  // No string found with prefix\n               curList.add(\"0\");\n               res.add(curList);\n                continue;\n            }\n            if( cur.word[s.charAt(i)-'a']!=null && cur.word[s.charAt(i)-'a'] == true) {\n                curList.add(new String(sb.toString()));\n            }\n            findAllPrefixes(cur, sb, curList); \n            if(curList.size()>0)  // Adding all words which start with prefix 0-i of String s.\n                res.add(curList);\n            else {\n                curList.add(\"0\");\n                res.add(curList);\n            }\n                \n        }\n        return res;\n    }\n    public static int  findAllPrefixes(Trie cur, StringBuilder sb, ArrayList<String> curList) {   // Adding all words which start with the preficx from o-i of string s, storing in curList\n        int childVis = -1;\n        for(int i=0;i<26;i++) {\n            if(cur.child[i]!=null && childVis!=i) {\n                sb.append(\"\"+(char)(i+'a'));\n                if(cur.child[i].word[i]!=null && cur.child[i].word[i]==true) {\n                    curList.add(new String(sb.toString()));\n                }\n                childVis=findAllPrefixes(cur.child[i], sb, curList);\n                sb.deleteCharAt(sb.length()-1);\n            }\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "GFG/Primes sum/Primes sum.cpp",
    "content": "class Solution {\n    public:\n      bool checkPrime(int n)\n\n    {\n\n        if(n<2)\n\n        return false;\n\n        for(int i=2; i<=sqrt(n); i++)\n\n        {\n\n            if(n%i==0)\n\n            return false;\n\n        }\n\n        return true;\n\n    }\n    \n    string isSumOfTwo(int N){\n        // code here\n        \n          for(int i=2; i<N; i++)\n\n      {\n\n          bool flag=true;\n\n          if(!checkPrime(i))\n\n          {\n\n              flag=false;\n\n          }\n\n        if(flag==true)\n\n        {\n\n            if(checkPrime(N-i))\n\n            return \"Yes\";\n\n        }\n\n      }\n\n    return \"No\";\n    }\n\n};\n"
  },
  {
    "path": "GFG/Primes sum/Primes sum.java",
    "content": "class Solution {\n    static String isSumOfTwo(int N){\n        // code here\n        boolean[]primes=new boolean[N];\n        Arrays.fill(primes,true);\n        \n        for(int i=2;i*i<=N;i++){\n            if(primes[i]){\n                for(int j=i*i;j<N;j+=i){\n                    primes[j]=false;\n                }\n            }\n        }\n        \n        for(int i=2;i<=N/2;i++){\n            if(primes[i] && primes[N-i]){\n                return \"Yes\";\n            }\n        }\n        return \"No\";\n    }\n}\n"
  },
  {
    "path": "GFG/Primes sum/README.md",
    "content": "## Primes sum\n\nGiven a number **N**. Find if it can be expressed as sum of two prime numbers.\n\n**Example 1:**\n\n```\nInput: N = 34\n\nOutput: \"Yes\" \n\nExplanation: 34 can be expressed as \nsum of two prime numbers.\n```\n**Example 2:**\n```\nInput: N = 23\nOutput: \"No\"\nExplanation: 23 cannnot be expressed as\nsum of two prime numbers. \n```\n\n***\n**Your Task:**  \nYou dont need to read input or print anything. Complete the function *isSumOfTwo()* which takes N as input parameter and returns \"Yes\" if can be expressed as sum of two prime numbers. else return \"No\".\n\nExpected Time Complexity: O(N*sqrt(N))\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 <= N <= 105\n"
  },
  {
    "path": "GFG/Print Diagonally/Print Diagonally.cpp",
    "content": "class Solution{\n\t\n\tpublic:\n\tvector<int> downwardDigonal(int N, vector<vector<int>> A)\n\t{\n\t\t// Your code goes here\n\t\tvector<int>v;\n\t\tfor(int i=0;i<N;i++){\n\t\t    for(int j=0;j<N&&j<=i;j++){\n\t\t          v.push_back(A[j][i-j]);\n\t\t    }\n\t\t}\n\t\tint s=1;\n\t\tfor(int i=N;i<=2*(N-1);i++){\n\t\t    for(int j=s;j<N;j++){\n\t\t          v.push_back(A[j][i-j]);\n\t\t    }\n\t\t    s++;\n\t\t}\n\t\treturn v;\n\n\t}\n\n};\n"
  },
  {
    "path": "GFG/Print Diagonally/Print Diagonally.java",
    "content": "class Solution{\n    static ArrayList<Integer> downwardDigonal(int N, int A[][])\n    {\n        // code here \n        ArrayList<Integer> ans=new ArrayList<>();\n        int row=0;\n        int col=0;\n        while(col<N){\n            int r=row;\n            int c=col;\n            while(r<N && c>=0){\n                ans.add(A[r][c]);\n                r++;\n                c--;\n            }\n            col++;\n        }\n        col=N-1;\n        row=1;\n        while(row<N){\n            int r=row;\n            int c=col;\n            while(r<N && c>=0){\n                ans.add(A[r][c]);\n                r++;\n                c--;\n            }\n            row++;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Print Diagonally/README.md",
    "content": "## Print Diagonally\n\nGive a **N * N** square matrix **A**, return all the elements of its **anti-diagonals** from top to bottom.\n\n**Example 1:**\n```\nInput: \nN = 2\nA = [[1, 2],\n     [3, 4]]\nOutput:\n1 2 3 4\nExplanation: \n\n```\n\n![ScreenShot2022-10-17at9-1665980852](https://user-images.githubusercontent.com/76674591/196438008-83b2851a-b6b9-4a19-949b-06826956a58e.png)\n\n```\nHence, elements will be returned in the \norder {1, 2, 3, 4}.\n\n```\n**Example 2:**\n\n```\nInput: \nN = 3 \nA = [[1, 2, 3],\n     [4, 5, 6],\n     [7, 8, 9]]\nOutput: \n1 2 4 3 5 7 6 8 9\nExplanation: \n```\n\n![ScreenShot2022-10-17at9-1665980941](https://user-images.githubusercontent.com/76674591/196438089-a533157f-3d20-4be3-a631-dcb4fda61cff.png)\n\n```\nHence, elements will be returned in \nthe order {1, 2, 4, 3, 5, 7, 6, 8, 9}.\n```\n***\n\n**Your Task:**\n\nYou don't need to read input or print anything. Your task is to complete the function **downwardDigonal()** which takes an integer N and a 2D matrix A[ ][ ] as input parameters and returns the list of all elements of its anti-diagonals from top to bottom.\n\n**Expected Time Complexity:** O(N*N)\n**Expected Auxillary Space:** O(N*N)\n\nConstraints:\n1 ≤ N, M ≤ 103\n0 ≤ A[i][j] ≤ 106\n\n"
  },
  {
    "path": "GFG/Print leaf nodes from preorder traversal of BST/Print leaf nodes from preorder traversal of BST.cpp",
    "content": "class Solution {\n  public:\n    vector<int> leafNodes(int a[],int n) {\n        // code here\n        \n         stack<int> s;\n        vector<int> vec;\n        s.push(a[0]);\n        for(int i=1;i<n;i++){\n            if(s.top()<a[i]){\n                int pc = 0;\n                int ln = s.top();\n                while(!s.empty()&&s.top()<a[i]){\n                    s.pop();\n                    pc++;\n                }\n                if(pc>1){\n                    vec.push_back(ln);\n                }\n            }\n            s.push(a[i]);\n        }\n        if(!s.empty()){\n            vec.push_back(s.top());\n        }\n        return vec;\n    }\n};\n"
  },
  {
    "path": "GFG/Print leaf nodes from preorder traversal of BST/Print leaf nodes from preorder traversal of BST.java",
    "content": "class Solution\n{\n    public int[] leafNodes(int arr[], int N)\n    {\n        // code here\n        ArrayList<Integer> ans=new ArrayList<>();\n        Stack<Integer> st=new Stack<>();\n        st.push(arr[0]);\n        for(int i=1;i<N;i++){\n            if(arr[i]<st.peek()){\n                st.push(arr[i]);\n            }else{\n                int temp=st.peek();\n                int removed=0;\n                while(!st.isEmpty() && st.peek()<arr[i]){\n                    st.pop();\n                    removed++;\n                }\n                st.push(arr[i]);\n                if(removed>=2){\n                    ans.add(temp);\n                }\n            }\n        }\n        ans.add(st.peek());\n        int[] res=new int[ans.size()];\n        int idx=0;\n        for(int i:ans){\n            res[idx++]=i;\n        }\n        return res;\n    }\n}\n"
  },
  {
    "path": "GFG/Print leaf nodes from preorder traversal of BST/README.md",
    "content": "## Print leaf nodes from preorder traversal of BST\n\nGiven a preorder traversal of a BST, find the leaf nodes of the tree without building the tree.\n\n\n**Example 1:**\n```\nInput:\nN = 2\n\narr = {2,1}\n\nOutput: {1}\n\nExplaination: 1 is the only leaf node.\n```\n**Example 2:**\n```\nInput:\nN = 3\n\nArr = {3, 2, 4}\n\nOutput: {2, 4}\n\nExplaination: 2, 4 are the leaf nodes.\n```\n***\n\n**Your Task:**\nYou don't need to read input or print anything. Your task is to complete the function **leafNodes()** which takes the array arr[] and its size N as input parameters and returns the leaf nodes of the tree.\n\n\n**Expected Time Complexity:** O(N)\n**Expected Auxiliary Space:** O(N)\n\n\n**Constraints:**\n1 ≤ N ≤ 103\n1 ≤ arr[i] ≤ 103\n"
  },
  {
    "path": "GFG/Queries on a matrix/Queries on a matrix hard s25 gfg.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\n  public:\n    vector<vector<int>> solveQueries(int n, vector<vector<int>> Queries) {\n        // Code here\n        vector<vector<int>>mat(n, vector<int> (n,0));\n        \n        for(auto e: Queries){\n            int a,b,c,d;\n            a = e[0]; b=e[1]; c=e[2]; d=e[3];\n            \n            mat[a][b] +=1;\n            if(c <n-1) mat[c+1][b]-=1;\n            if(d<n-1) mat[a][d+1]-=1;\n            if(c<n-1 && d <n-1) mat[c+1][d+1]+=1;\n        }\n        \n        for(int i =1; i<n; i++){\n            for(int j =0; j<n; j++){\n                mat[i][j]+= mat[i-1][j];\n            }\n        }\n                for(int i =0; i<n; i++){\n            for(int j =1; j<n; j++){\n                mat[i][j]+= mat[i][j-1];\n            }\n        }\n        return mat;\n    }\n};\n\nint main() {\n    int tc;\n    cin >> tc;\n    while (tc--) {\n        int n, q;\n        cin >> n >> q;\n        vector<vector<int>> Queries;\n        for (int i = 0; i < q; i++) {\n            vector<int> cur(4);\n            for (int j = 0; j < 4; j++) cin >> cur[j];\n            Queries.push_back(cur);\n        }\n        Solution obj;\n        vector<vector<int>> ans = obj.solveQueries(n, Queries);\n        for (auto i : ans) {\n            for (auto j : i) cout << j << \" \";\n            cout << \"\\n\";\n        }\n    }\n    return 0;\n}\n// } Driver Code Ends"
  },
  {
    "path": "GFG/Rearrange Array Alternately/Rearrange Array Alternately.java",
    "content": "class Solution{\n    \n    // temp: input array\n    // n: size of array\n    //Function to rearrange  the array elements alternately.\n    public static void rearrange(long arr[], int n){\n        \n        // Your code here\n        int l=0;\n        int r=n-1;\n        long mod=1000001;\n        for(int i=0;i<n;i++){\n            if(i%2==0){\n                long newValue=arr[r]%mod;\n                arr[i]=newValue*mod+arr[i];\n                r--;\n            }else{\n                long newValue=arr[l]%mod;\n                arr[i]=newValue*mod+arr[i];\n                l++;\n            }\n        }\n        for(int i=0;i<n;i++){\n            arr[i]=arr[i]/mod;\n        }\n        \n    }\n    \n}\n"
  },
  {
    "path": "GFG/Reorder List/Reorder List.java",
    "content": "class Solution {\n    Node reorderlist(Node head) {\n        // Your code here\n        if(head.next==null)return head;\n        Node fast=head;\n        Node slow=head;\n        Node prev=null;\n        while(fast!=null && fast.next!=null){\n            prev=slow;\n            slow=slow.next;\n            fast=fast.next.next;\n        }\n        prev.next=null;\n        Node revHead=reverse(slow);\n        Node startHead=head;\n        while(startHead!=null){\n            Node startNext=startHead.next;\n            Node revNext=revHead.next;\n            startHead.next=revHead;\n            if(startNext!=null)revHead.next=startNext;\n            startHead=startNext;\n            revHead=revNext;\n        }\n        return head;\n    }\n    Node reverse(Node head){\n        Node prev=null;\n        while(head!=null){\n            Node next=head.next;\n            head.next=prev;\n            prev=head;\n            head=next;\n        }\n        return prev;\n    }\n}\n"
  },
  {
    "path": "GFG/Replace O's with X's/Replace O's with X's.cpp",
    "content": "class Solution{\npublic:\n int delrow[4]={-1,0,1,0};\n int delcol[4]={0,-1,0,1};\n    void dfs(int r,int c,vector<vector<int>> &vis,int n,int m,vector<vector<char>> &grid)\n    {\n        vis[r][c]=1;\n        for(int i=0;i<4;i++){\n            int nr=r+delrow[i];\n            int nc=c+delcol[i];\n            if(nr>=0 && nr<n && nc>=0 && nc<m && !vis[nr][nc] && grid[nr][nc]=='O'){\n                dfs(nr,nc,vis,n,m,grid);\n            }\n        }\n    }\n    vector<vector<char>> fill(int n, int m, vector<vector<char>> grid)\n    {\n        vector<vector<int>> vis(n,vector<int>(m,0));\n        for(int j=0;j<m;j++){\n            if(!vis[0][j] && grid[0][j]=='O'){\n                dfs(0,j,vis,n,m,grid);\n            }\n            if(!vis[n-1][j] && grid[n-1][j]=='O'){\n                  dfs(n-1,j,vis,n,m,grid);\n            }\n        }\n        \n        for(int i=0;i<n;i++){\n            if(!vis[i][0] && grid[i][0]=='O'){\n                dfs(i,0,vis,n,m,grid);\n            }\n            if(!vis[i][m-1] && grid[i][m-1]=='O'){\n                dfs(i,m-1,vis,n,m,grid);\n            }\n        }\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(!vis[i][j] && grid[i][j]=='O'){\n                    grid[i][j]='X';\n                }\n            }\n        }\n        \n        return grid;\n    }\n};\n"
  },
  {
    "path": "GFG/Replace every element with the least greater element on its right/README.md",
    "content": "## Replace every element with the least greater element on its right\n\n\nGiven an array arr[] of N integers and replace every element with the least greater element on its right side in the array. If there are no greater elements on the right side, replace it with -1. \n\n**Example 1:**\n\n```\nInput:\n\narr[] = {8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28}\n\nOutput: {18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1}\n\nExplanation: \nThe least next greater element of 8 is 18.\nThe least next greater element of 58 is 63 and so on.\n```\n**Example 2:**\n```\nInput:\narr[] = {2, 6, 9, 1, 3, 2}\n\nOutput: {3, 9, -1, 2, -1, -1}\n\nExplanation: \n\nThe least next greater element of 2 is 3. \nThe least next greater element of 6 is 9.\n\nleast next greater element for 9 does not\nexist and so on.\n```\n***\n\n**Your Task:** \nYou don't need to read input or print anything. Your task is to complete the function **findLeastGreater()** which takes an array arr[] of size N and returns a list as an output.\n\n**Expected Time Complexity:** O(N* log N)\n**Expected Auxiliary Space:** O(N)\n\n**Constraints:**\n1 <= N <= 105\n1 <= A[i] <= 105\n"
  },
  {
    "path": "GFG/Replace every element with the least greater element on its right/Replace every element with the least greater element on its right.cpp",
    "content": "class Solution{\n    public:\n    vector<int> findLeastGreater(vector<int>& arr, int n) {\n        \n        \n         vector<int> v; \n\n        set<int>s;\n\n        for(int i=n-1;i>=0;i--)\n\n        {\n\n            auto up=s.upper_bound(arr[i]);          //finds the nearest greater value\n\n            if(up==s.end())                         //if not find nearest  grater value\n\n            v.push_back(-1); \n\n            else\n\n            v.push_back(*up);\n\n            \n\n            s.insert(arr[i]);                       //insert ans in array\n\n        }\n\n        reverse(v.begin(),v.end());            //reverse it cause we itarate to last\n\n        return v;\n    }\n};\n"
  },
  {
    "path": "GFG/Replace every element with the least greater element on its right/Replace every element with the least greater element on its right.java",
    "content": "class Solution {\n    public static ArrayList<Integer> findLeastGreater(int n, int[] arr) {\n        // code here\n        TreeSet<Integer> set=new TreeSet<>();\n        ArrayList<Integer> ans =new ArrayList<>();\n        for(int i=n-1;i>=0;i--){\n            set.add(arr[i]);\n            if(set.higher(arr[i])==null)ans.add(-1);\n            else ans.add(set.higher(arr[i]));\n        }\n        Collections.reverse(ans);\n        return ans;\n    }\n}\n\n\n// second Method using Binary Search Tree\n\n\nclass Solution {\n    static class Node {\n        int val;\n        Node left;\n        Node right;\n        Node(int val) {\n            this.val=val;\n            this.left=null;\n            this.right=null;\n        }\n    }\n    public static ArrayList<Integer> findLeastGreater(int n, int[] arr) {\n        Node head = null;\n        ArrayList<Integer> res=new ArrayList<>();\n        for(int i=arr.length-1;i>=0;i--) {\n            if(head==null) {\n                head=new Node(arr[i]);\n            }\n            else {\n                Node prev=addNodeInBST(arr[i], head, head);\n                \n                if(prev.val>arr[i]) {\n                    prev.left=new Node(arr[i]);\n                }\n                else {\n                    prev.right=new Node(arr[i]);\n                }\n            }\n            \n            int max[]=new int[1];\n            max[0]=Integer.MAX_VALUE;\n            leastGreater(head, max, arr[i]);\n            if(max[0]==Integer.MAX_VALUE) {\n                arr[i]=-1;\n            }\n            else {\n                arr[i]= max[0];\n            }\n        }\n        \n        for(int i=0;i<arr.length;i++) res.add(arr[i]);\n        \n        return res;\n    }\n    public static Node addNodeInBST(int val, Node cur, Node prev) {\n        if(cur==null) return prev;\n        \n        if(cur.val>val) {\n            return addNodeInBST(val, cur.left, cur);\n        }\n        else {\n           return addNodeInBST(val, cur.right, cur);\n        }\n    }\n    \n    public static void leastGreater(Node head, int []max, int value) {\n        if(head==null) {\n            return ;\n        } \n        \n        \n        if(head.val>value) {\n            max[0]=Math.min(max[0], head.val);\n        }\n        \n        if(head.val>value) {\n            leastGreater(head.left, max, value);\n        }\n        else {\n            leastGreater(head.right, max, value);\n        }\n    }\n}\n        \n"
  },
  {
    "path": "GFG/Reverse Spiral Form of Matrix/Reverse Spiral Form of Matrix.cpp",
    "content": "class Solution {\n  public:\n    vector<int> reverseSpiral(int R, int C, vector<vector<int>>&a)  {\n        // code here\n        \n          vector<int>ans;\n\n       \n\n        int top=0,left=0,right=C-1,bottom=R-1;\n\n        while(top<=bottom and left<=right)\n\n        { // top row\n\n         if(top<=bottom)\n\n            {\n\n                for(int i=left;i<=right;i++)\n\n                 ans.push_back(a[top][i]);\n\n            \n\n                 top++;\n\n            }\n\n            // right column\n\n            if(left<=right){\n\n            for(int i=top;i<=bottom;i++)\n\n            {\n\n                ans.push_back(a[i][right]);\n\n            }\n\n            right--;\n\n            }\n\n          //bottom row (reverse order)\n\n          if(top<=bottom)\n\n          {\n\n              for(int i=right;i>=left;i--)\n\n              {\n\n                  ans.push_back(a[bottom][i]);\n\n              }\n\n              bottom--;\n\n          }\n\n          //left column (reverse order)\n\n           if(left<=right)\n\n          {\n\n              for(int i=bottom;i>=top;i--)\n\n              {\n\n                  ans.push_back(a[i][left]);\n\n              }\n\n              left++;\n\n          }\n\n        }\n\n        // reverse ans vector\n\n      reverse(ans.begin(),ans.end());\n\n        return ans;\n    }\n};\n"
  },
  {
    "path": "GFG/Reverse Spiral Form of Matrix/Reverse Spiral Form of Matrix.java",
    "content": "class Solution\n{\n    public int[] reverseSpiral(int R, int C, int[][] a)\n    {\n        // code here\n        int[] ans=new int[R*C];\n        int idx=R*C-1;\n        \n        int up=0;\n        int down=a.length-1;\n        int left=0;\n        int right=a[0].length-1;\n        \n        \n        \n        while(idx>=0){\n            //upper row\n            for(int i=left;i<=right && idx>=0;i++){\n                ans[idx--]=a[up][i];\n            }\n            up++;\n            \n            //last col\n            for(int i=up;i<=down && idx>=0;i++){\n                ans[idx--]=a[i][right];\n            }\n            right--;\n            \n            //lower row\n            for(int i=right;i>=left && idx>=0;i--){\n                ans[idx--]=a[down][i];\n            }\n            down--;\n            \n            for(int i=down;i>=up && idx>=0;i--){\n                ans[idx--]=a[i][left];\n            }\n            left++;\n        }\n        \n        return ans;\n        \n    }\n}\n"
  },
  {
    "path": "GFG/Satisfy the equation/Satisfy the equation.java",
    "content": "class Pair{\n    int x;\n    int y;\n    Pair(int a,int b){\n        x=a;\n        y=b;\n    }\n}\n\n\n// 1 2 4 5==curr\n// 0 3 4 5 ==ans\n\nclass Solution {\n    \n    static int[] satisfyEqn(int[] A, int N) {\n        // code here\n        int ans[]=new int[4];\n        Arrays.fill(ans,Integer.MAX_VALUE);\n        Map<Integer,Pair> map=new HashMap<>();//key-> sum, values-> indices\n        \n        for(int i=0;i<N-1;i++){\n            for(int j=i+1;j<N;j++){\n                int sum=A[i]+A[j];\n                if(!map.containsKey(sum)){\n                    map.put(sum,new Pair(i,j));\n                    continue;\n                }\n                \n                Pair p=map.get(sum);\n                if(p.x!=i && p.y!=j && p.x!=j && p.y!=i){\n                    int curr[]=new int[4];\n                    curr[0]=p.x;\n                    curr[1]=p.y;\n                    curr[2]=i;\n                    curr[3]=j;\n                    if(ans[0]==Integer.MAX_VALUE){\n                        for(int idx=0;idx<4;idx++){\n                            ans[idx]=curr[idx];\n                        }\n                    }else{\n                        boolean replace=false;\n                        for(int idx=0;idx<4;idx++){\n                            if(ans[idx]>curr[idx]){\n                                replace=true;\n                                break;\n                            }else if(ans[idx]<curr[idx]){\n                                break;\n                            }\n                        }\n                        if(replace){\n                            //replace it\n                            for(int idx=0;idx<4;idx++){\n                                ans[idx]=curr[idx];\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        if(ans[0]==Integer.MAX_VALUE){\n            Arrays.fill(ans,-1);\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "GFG/Save Your Life/README.md",
    "content": "## Save Your Life\n\nGiven a string w, integer array b,  character array x and an integer n. n is the size of array b and array x. Find a substring which has the sum of the ASCII values of its every character, as maximum. ASCII values of some characters are redefined.\nNote: Uppercase & lowercase both will be present in the string w. Array b and Array x contain corresponding redefined ASCII values. For each i, b[i] contain redefined ASCII value of character x[i].\n\nExample 1:\n\n```\nInput:\nW = abcde\nN = 1\nX[] = { 'c' }\nB[] = { -1000 }\n\nOutput:\nde\n\nExplanation:\n\nSubstring \"de\" has the\nmaximum sum of ascii value,\nincluding c decreases the sum value\n\n```\nExample 2:\n\n```\nInput:\nW = dbfbsdbf \nN = 2\nX[] = { 'b','s' }\nB[] = { -100, 45  }\n\nOutput:\ndbfbsdbf\n\nExplanation:\nSubstring \"dbfbsdbf\" has the maximum\nsum of ascii value.\n```\n**Your Task:**\nYou don't need to read input or print anything. Your task is to complete the function maxSum() which takes string W, character array X, integer array B, integer N as length of array X and B as input parameters and returns the substring with the maximum sum of ascii value.\n \n\nExpected Time Complexity: O(|W|)\nExpected Auxiliary Space: O(1)\n\n\nConstraints:\n\n1<=|W|<=100000\n1<=|X|<=52\n-1000<=Bi<=1000\n"
  },
  {
    "path": "GFG/Save Your Life/Save Your Life.cpp",
    "content": "class Solution{\npublic:\n      string maxSum(string w,char x[], int b[],int n){\n\n      }\n};\n"
  },
  {
    "path": "GFG/Save Your Life/Save Your Life.java",
    "content": "class Solution{\n    static String maxSum(String w,char x[],int b[], int n){\n        //code here\n        Map<Character,Integer> map=new HashMap<>();\n        for(int i=0;i<n;i++){\n            map.put(x[i],b[i]);\n        }\n        \n        StringBuilder ans=new StringBuilder();\n        StringBuilder temp=new StringBuilder();\n        \n        int max=Integer.MIN_VALUE;\n        int curr=0;\n        for(char c:w.toCharArray()){\n            curr+=map.containsKey(c)?map.get(c):c;\n            temp.append(c);\n            if(curr>max){\n                max=curr;\n                ans=new StringBuilder(temp);\n            }\n            \n            if(curr<0){\n                curr=0;\n                temp=new StringBuilder();\n            }\n        }\n        return ans.toString();\n    }\n}\n\n\n\n//Approach 2\nclass Solution{\n    static String maxSum(String w,char x[],int b[], int n){\n        int i= 0;\n        int j=0;\n        int max=Integer.MIN_VALUE;\n        int res[]=new int[52];\n        for(int k=0;k<52;k++) {\n            res[k]=2000;\n        }\n        for(int k=0;k<x.length;k++) {\n            if(x[k]>='a' && x[k]<='z')\n                res[x[k]-'a']=b[k];\n            else\n                res[x[k]-'A'+26]=b[k];\n        }\n        for(int k=0;k<26;k++) {\n            if(res[k]==2000) {\n                res[k]=97+k;\n            }\n        }\n        for(int k=26;k<52;k++) {\n            if(res[k]==2000) {\n                res[k]=65+k-26;\n            }\n        }\n        int count =0;\n        int maxI=0;\n        int maxJ=0;\n        while(j<w.length()) {\n            if(w.charAt(j)>='a' && w.charAt(j)<='z')\n                count+=res[w.charAt(j)-'a'];\n            else\n                count+=res[w.charAt(j)-'A'+26];\n            if(count>max) {\n                max=count;\n                maxI=i;\n                maxJ=j;\n            }\n            \n            if(count<0) {\n                count=0;\n                i=j+1;\n            }\n            j+=1;\n        }\n        return w.substring(maxI, maxJ+1);\n    }\n}\n"
  },
  {
    "path": "GFG/Search Pattern (KMP-Algorithm)/Search Pattern (KMP-Algorithm).java",
    "content": "class Solution\n{\n    \n    ArrayList<Integer> search(String pat, String txt)\n    {\n        int pn=pat.length(), tn=txt.length();\n        int lps[]=new int[pn];\n        fill(lps,pat,pn);\n        ArrayList<Integer> list=new ArrayList<>();\n        \n        int j=0;\n        for(int i=0;i<tn;){\n            \n            //character match check for next\n            if(pat.charAt(j)==txt.charAt(i)){\n                j++;\n                i++;\n            }\n            \n            //if j reached end\n            if(j==pn){\n                \n                //there's a substring\n                list.add(i-pn+1);\n                \n                // if there is a similar substring present in pattern then\n                // j will go to that position\n                // in other words\n                // j is at the end so just say j and i is not similar (as j exhausted)\n                // and j-1 prefix array is similar\n                // so j will go to that position where prefix is similar\n                // e.g. aabaab      lps[]={0,1,0,1,2,3}\n                j=lps[j-1];\n            }\n            else if(i<tn && pat.charAt(j)!=txt.charAt(i)){\n                \n                //this character is not same but prefix is same \n                //we go to the index where prefix is same \n                //only j char is not same but j-1 prefix is same\n                //we check for same prefix (j-1) index\n                if(j!=0)   j=lps[j-1];\n                \n                //if j is at initial postion so there is no similar string back in patter\n                //so we have no other option except for check next char in text string\n                else{\n                    i++;\n                }\n            }\n        }\n        \n        if(list.isEmpty())  list.add(-1);\n        return list;\n    }\n    void fill(int lps[],String s,int pn){\n        \n        //assume 1 based indexing we are filling \n        //bat (indexing 1,2,3)  we will fill according to this\n        \n        //aabaab    string index[]={0,1,2,3,4,5}\n        //lps will track longest prefix substring\n        //aabaab    lps[]={0,1,0,1,2,3}     as we are filling according to 1 based indexing\n        \n        int si=0;\n        for(int i=1;i<pn;){\n            if(s.charAt(si)==s.charAt(i)){\n                \n                //0 and 1 is equal\n                //means this value is similar to si index\n                //but we are filling according to 1 based indexing so just added 1 before that\n                //next step since index value same so check for next\n                si++;\n                lps[i]=si;\n                i++;\n                \n            }else{\n                \n                //si char not same\n                //if first character is not same then we can't do anthing just move i pointer\n                //and check for next char\n                if(si==0)  i++;\n                \n                //only si char is not same\n                //but till si-1 prefix substring is same\n                //in naive approach we go to start\n                //but in this case we know whether there is a similar substring present or not\n                //so we go to that position\n                else    si=lps[si-1];\n            }\n        }\n    }\n    \n}\n"
  },
  {
    "path": "GFG/Search Pattern (Rabin-Karp Algorithm)/Search Pattern (Rabin-Karp Algorithm).java",
    "content": "class Solution\n{\n    \n    ArrayList<Integer> search(String pat, String S)\n    {\n        int total=26, mod=101;\n        ArrayList<Integer> list=new ArrayList<>();\n        int p=0, s=0, sn=S.length(), pn=pat.length();\n        \n        // calculate most significant position\n        // (we will need this when we have to remove most signicant position value)\n        // The value of h would be \"pow(d, M-1)%q\"\n        int h = 1; \n        for (int i = 0; i < pn-1; i++)\n            h = (h*total)%mod;\n        \n        // System.out.println(h);\n\n        for(int i=0;i<pn;i++){\n            \n            // pattern string hash\n            p = ( p*total + pat.charAt(i) ) % mod;\n            \n            // first window hash\n            s = ( s*total + S.charAt(i) ) % mod;\n        }\n        \n        for(int i=0;i<=sn-pn;i++){\n        \n            // hash are equal\n            if(p==s && compare(pat,S,i))    list.add(i+1);\n            \n            // rolling hash\n            // remove a value from most significant position & \n            // add new value to the least significant position\n            if(i+pn<sn)     s=( (s-S.charAt(i)*h)*total + S.charAt(i+pn))%mod;\n            if(s<0)     s+=mod;\n        }\n        \n        if(list.isEmpty())  list.add(-1);\n        return list;\n    }\n    \n    boolean compare(String p,String s,int st){\n        for(int i=0;i<p.length();i++)\n            if(p.charAt(i)!=s.charAt(i+st)) return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "GFG/Sequence Fun/Sequence Fun.java",
    "content": "class Solution\n{\n    public int NthTerm(int n)\n    {\n        // code here\n        long prev=2L;\n        long mod=1000000007;\n        for(int i=2;i<=n;i++){\n            long curr=(prev%mod * i%mod)+1;\n            prev=curr;\n        }\n        return (int)prev;\n   \n"
  },
  {
    "path": "GFG/Shortest Distance in a Binary Maze/README.md",
    "content": "## Shortest Distance in a Binary Maze\n\nGiven a n * m matrix grid where each element can either be 0 or 1. You need to find the shortest distance between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1. \n\nIf the path is not possible between source cell and destination cell, then return -1.\n\n**Note:** You can move into an adjacent cell if that adjacent cell is filled with element 1. Two cells are adjacent if they share a side. In other words, you can move in one of the four directions, Up, Down, Left and Right.\n\n**Example 1:**\n\n```\nInput:\ngrid[][] = {{1, 1, 1, 1},\n            {1, 1, 0, 1},\n            {1, 1, 1, 1},\n            {1, 1, 0, 0},\n            {1, 0, 0, 1}}\n            \nsource = {0, 1}\n\ndestination = {2, 2}\n\nOutput:\n3\n\nExplanation:\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 0 0\n1 0 0 1\n\nThe highlighted part in the matrix denotes the \nshortest path from source to destination cell.\n\n```\n\n\n**Example 2:**\n\n```\nInput:\n\ngrid[][] = {{1, 1, 1, 1, 1},\n            {1, 1, 1, 1, 1},\n            {1, 1, 1, 1, 0},\n            {1, 0, 1, 0, 1}}\n            \nsource = {0, 0}\ndestination = {3, 4}\n\nOutput:\n-1\n\nExplanation:\nThe path is not possible between source and \ndestination, hence return -1.\n```\n\n**Your Task:**\n\nYou don't need to read or print anything. Your task is to complete the function **shortestPath()** which takes the a 2D integer array grid, source cell and destination cell as an input parameters and returns the shortest distance between source and destination cell.\n\n**Expected Time Complexity:** O(n * m)\n**Expected Space Complexity:** O(n * m)\n\n**Constraints:**\n\n1 ≤ n, m ≤ 500\ngrid[i][j] == 0 or grid[i][j] == 1\n\nThe source and destination cells are always inside the given matrix.\nThe source and destination cells always contain 1.\n"
  },
  {
    "path": "GFG/Shortest Distance in a Binary Maze/Shortest Distance in a Binary Maze.cpp",
    "content": "class Solution {\n  public:\n    bool isSafe(int i,int j,int n,int m){\n      if(i<0 || j<0 || i>=n || j>=m)\n      return false;\n      return true;\n  }\n\n    int shortestPath(vector<vector<int>> &grid, pair<int, int> source, pair<int, int> destination){\n        if(source==destination){\n            return 0;\n        }\n        int n=grid.size();\n        int m =grid[0].size();\n        queue<pair<pair<int,int>,int>>q;\n        q.push({source,0});\n        grid[source.first][source.second]=0;\n        while(!q.empty()){\n                int row = q.front().first.first;\n                int col = q.front().first.second;\n                int dis = q.front().second;\n                q.pop();\n                if(row==destination.first && col==destination.second){\n                    return dis;\n                }\n                if(isSafe(row+1,col,n,m) && grid[row+1][col]==1){\n                    q.push({{row+1,col},dis+1});\n                    grid[row+1][col]=0;\n                }\n                if(isSafe(row-1,col,n,m) && grid[row-1][col]==1){\n                    q.push({{row-1,col},dis+1});\n                    grid[row-1][col]=0;\n                }\n                if(isSafe(row,col+1,n,m) && grid[row][col+1]==1){\n                    q.push({{row,col+1},dis+1});\n                    grid[row][col+1]=0;\n                }\n                if(isSafe(row,col-1,n,m) && grid[row][col-1]==1){\n                    q.push({{row,col-1},dis+1});\n                    grid[row][col-1]=0;\n                }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "GFG/Shortest Distance in a Binary Maze/Shortest Distance in a Binary Maze.java",
    "content": "class Solution {\n\n    class Pair{\n        int x;\n        int y;\n        Pair(int i,int j){\n            x=i;\n            y=j;\n        }\n    }\n    int shortestPath(int[][] grid, int[] src, int[] des) {\n        Queue<Pair> q=new LinkedList<>();\n        q.add(new Pair(src[0],src[1]));\n        grid[src[0]][src[1]]=0;\n        int dis=0;\n        while(!q.isEmpty()){\n            int sz=q.size();\n            while(sz-->0){\n                Pair curr=q.remove();\n                int i=curr.x;\n                int j=curr.y;\n                if(i==des[0] && j==des[1])return dis;\n                if(i>0 && grid[i-1][j]==1){\n                    grid[i-1][j]=0;\n                    q.add(new Pair(i-1,j));\n                }\n                if(j>0 && grid[i][j-1]==1){\n                    grid[i][j-1]=0;\n                    q.add(new Pair(i,j-1));\n                }\n                if(i<grid.length-1 && grid[i+1][j]==1){\n                    grid[i+1][j]=0;\n                    q.add(new Pair(i+1,j));\n                }\n                if(j<grid[0].length-1 && grid[i][j+1]==1){\n                    grid[i][j+1]=0;\n                    q.add(new Pair(i,j+1));\n                }\n            }\n            dis++;\n        }\n        return -1;\n    }\n}\n\n\n//Approach 2\n\n\nclass Solution {\n    class Pair {\n        int i, j;\n        Pair(int i, int j) {\n            this.i=i;\n            this.j=j;\n        }\n    }\n    int shortestPath(int[][] grid, int[] source, int[] destination) {\n        int visited[][]=new int[grid.length][grid[0].length];\n        Queue<Pair> q=new LinkedList<>();\n        visited[source[0]][source[1]]=1;\n        if(grid[source[0]][source[1]] == 0) return -1;\n        q.add(new Pair(source[0], source[1]));\n        int ans=0;\n        while(!q.isEmpty()) {\n            int n=q.size();\n            while(n>0) {\n                Pair p=q.poll();\n                if(p.i==destination[0] && p.j==destination[1]) return ans;\n                \n                Pair up=getPair(p.i, p.j+1, grid, visited);\n                Pair down=getPair(p.i, p.j-1, grid, visited);\n                Pair left=getPair(p.i-1, p.j, grid, visited);\n                Pair right=getPair(p.i+1, p.j, grid, visited);\n                \n                if(up!=null) q.add(up);\n                if(down!=null) q.add(down);\n                if(left!=null) q.add(left);\n                if(right!=null) q.add(right);\n                n-=1;\n            }\n            ans+=1;\n        }\n        return -1;\n    }\n    public Pair getPair(int x, int y, int[][] grid, int [][]visited) {\n        if(x<0 || y<0 || x>=grid.length || y>=grid[0].length) return null;\n        if(grid[x][y]==0 || visited[x][y]==1) {\n            return null;\n        }\n        visited[x][y]=1;        \n        return new Pair(x, y);\n    }\n}\n"
  },
  {
    "path": "GFG/Shortest Path by Removing K walls/Shortest Path by Removing K walls.java",
    "content": "class Solution {\n    static int shotestPath(int[][] mat, int n, int m, int k) {\n        // code here\n        int[][]dirs={{1,0},{0,1},{0,-1},{-1,0}};\n        Queue<int[]> q=new LinkedList<>();\n        q.add(new int[]{0,0,k});\n        boolean[][][]vis=new boolean[n][m][k+1];\n        vis[0][0][k]=true;\n        int dis=0;\n        while(!q.isEmpty()){\n            int sz=q.size();\n            while(sz-->0){\n                int[]curr=q.remove();\n                if(curr[0]==n-1 && curr[1]==m-1)return dis;\n                for(int[]d:dirs){\n                    int i=curr[0]+d[0];\n                    int j=curr[1]+d[1];\n                    int obs=curr[2];\n                    if(i<n && j<m && i>=0 && j>=0){\n                        if(mat[i][j]==0 && !vis[i][j][obs]){\n                            q.add(new int[]{i,j,obs});\n                            vis[i][j][obs]=true;\n                        }else if(mat[i][j]==1 && obs>0 && !vis[i][j][obs-1]){\n                            q.add(new int[]{i,j,obs-1});\n                            vis[i][j][obs-1]=true;\n                        }\n                    }\n                }\n            }\n            dis++;\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "GFG/Shortest Prime Path/Shortest Prime Path.java",
    "content": "class Solution\n{\n    boolean[] prime;\n    Solution()\n    {\n        prime =new boolean[10000];\n        Arrays.fill(prime,true);\n        prime[0]=prime[1]=false;\n        for(int i=2;i<10000;i++){\n            if(!prime[i])continue;\n            for(int j=2;i*j<10000;j++)prime[i*j]=false;\n        }\n        // Every index of prime stores zero or one\n        // If prime[i] is zero means i is not a prime\n        // If prime[i] is one means i is a prime\n    }\n    \n    public int shortestPath(int Num1,int Num2){\n        // Complete this function using prime array\n        \n        boolean[]vis=new boolean[10000];\n        Queue<int[]> q=new LinkedList<>();\n        q.add(new int[]{Num1,0});\n        vis[Num1]=true;\n        while(!q.isEmpty()){\n            int[] curr=q.remove();\n            if(curr[0]==Num2)return curr[1];\n            \n            char[] arr= Integer.toString(curr[0]).toCharArray();\n            for(int i=0;i<4;i++){\n                for(char ch='0';ch<='9';ch++){\n                    char prevChar = arr[i];\n                    arr[i]=ch;\n                    int newNum = Integer.parseInt(new String(arr));\n                    if(!vis[newNum] && prime[newNum] && newNum>=1000){\n                        vis[newNum]=true;\n                        q.add(new int[]{newNum,curr[1]+1});\n                    }\n                    arr[i]=prevChar;\n                }\n            }\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "GFG/Shreyansh and his bits/Shreyansh and his bits.java",
    "content": "class Solution{\n    long[][]dp;\n    long count(long n)\n    {\n        dp=new long[64][64];\n        for(int i=0;i<64;i++){\n            Arrays.fill(dp[i],-1);\n        }\n        int ones=0;\n        int positions=0;\n        long ans=0;\n        while(n>0){\n            if((n&1)==1){\n                ones++;\n                ans+=nCr(positions,ones);\n            }\n            n=n>>1;\n            positions++;\n        }\n        return ans;\n    }\n    long nCr(int n,int r){\n        if(r>n){\n            return 0;\n        }\n        if(r==0 || r==n)return 1;\n        if(dp[n][r]!=-1)return dp[n][r];\n        return dp[n][r]=nCr(n-1,r-1)+nCr(n-1,r);\n    }\n}\n"
  },
  {
    "path": "GFG/Single valued subtree/Single valued subtree.java",
    "content": "class Solution\n{\n    int ans;\n    public int singlevalued(Node root)\n    {\n        //code here\n        ans=0;\n        dfs(root);\n        return ans;\n    }\n    Integer dfs(Node root){\n        if(root==null)return null;\n        Integer lefty=dfs(root.left);\n        Integer righty=dfs(root.right);\n        if(lefty!=null && righty!=null && lefty==righty && lefty==root.data){\n            ans++;\n            return righty;\n        }else if(root.left==null && root.right==null){\n            ans++;\n            return root.data;\n        }else if(root.left==null && righty!=null && righty==root.data){\n            ans++;\n            return root.data;\n        }else if(root.right==null && lefty!=null && lefty==root.data){\n            ans++;\n            return root.data;\n        }\n        return null;\n    }\n}\n"
  },
  {
    "path": "GFG/Sort an array of 0s, 1s and 2s/Sort an array of 0s, 1s and 2s.java",
    "content": "class Solution\n{\n    public static void sort012(int a[], int n)\n    {\n        // code here \n        int zero=0;\n        int one=0;\n        int two=0;\n        for(int i:a){\n            if(i==0){\n                zero++;\n            }else if(i==1){\n                one++;\n            }else{\n                two++;\n            }\n        }\n        \n        int idx=0;\n        while(zero>0){\n            zero--;\n            a[idx++]=0;\n        }\n        while(one-->0){\n            a[idx]=1;\n            idx++;\n        }\n        while(two-->0){\n            a[idx++]=2;\n        }\n    }\n}\n"
  },
  {
    "path": "GFG/Sort an array of 0s, 1s and 2s/Sort an array of 0s,1s and 2s s29.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nclass Solution\n{\n    public:\n    void sort012(int a[], int n)\n    {\n        // code here \n        int zero =0, one =0, two =n-1;\n        while(one<=two){\n            if(a[one]==0){\n                swap(a[one] ,a[zero]); zero++, one++;\n            }else if(a[one]==2){\n                swap(a[one], a[two]); two--;\n            }else one++;\n        }\n    }\n    \n};\nint main() {\n\n    int t;\n    cin >> t;\n\n    while(t--){\n        int n;\n        cin >>n;\n        int a[n];\n        for(int i=0;i<n;i++){\n            cin >> a[i];\n        }\n\n        Solution ob;\n        ob.sort012(a, n);\n\n        for(int i=0;i<n;i++){\n            cout << a[i]  << \" \";\n        }\n\n        cout << endl;\n        \n        \n    }\n    return 0;\n}"
  },
  {
    "path": "GFG/Spiral Matrix/Spiral Matrix.cpp",
    "content": "class Solution{\n\n\tpublic:\n\tint findK(vector<vector<int>> &matrix, int m, int n, int k)\n    {\n        // Your code goes here\n        vector<int> v;\n        int left = 0, right = n-1, top = 0, bottom = m-1;\n        int direction = 1;\n        while(left <= right and top <= bottom){\n            if(direction == 1){ // --->\n                for(int i=left;i<=right;i++) v.push_back(matrix[top][i]);\n                direction = 2;\n                top++;\n            }\n            else if(direction == 2){ // downwords\n                for(int i=top;i<=bottom;i++) v.push_back(matrix[i][right]);\n                direction = 3;\n                right--;\n            }\n            else if(direction == 3){ // <----\n                for(int i=right;i>=left;--i) v.push_back(matrix[bottom][i]);\n                direction = 4;\n                bottom--;\n            }else if(direction == 4){ // upwards\n                for(int i=bottom;i>=top;--i) v.push_back(matrix[i][left]);\n                direction = 1;\n                left++;\n            }\n        }\n        return v[k-1];\n    }\n\n};\n"
  },
  {
    "path": "GFG/Split Array Largest Sum/Split Array Largest Sum.java",
    "content": "class Solution {\n    static int splitArray(int[] arr , int N, int K) {\n        // code here\n        int l=0;\n        int h=0;\n        int ans=0;\n        for(int i:arr){\n            l=Math.max(l,i);\n            h+=i;\n        }\n        \n        while(l<=h){\n            int mid=l+(h-l)/2;\n            if(isPossible(mid,arr,K)){\n                ans=mid;\n                h=mid-1;\n            }else{\n                l=mid+1;\n            }\n        }\n        return ans;\n    }\n    static boolean isPossible(int maxSum,int[]arr,int k){\n        int cnt=0;\n        int currSum=0;\n        for(int i:arr){\n            if(currSum+i>maxSum){\n                cnt++;\n                currSum=i;\n            }else{\n                currSum+=i;\n            }\n        }\n        \n        if(currSum<=maxSum)cnt++;\n        return cnt<=k;\n    }\n};\n"
  },
  {
    "path": "GFG/Stepping Numbers/README.md",
    "content": "## Stepping Numbers\n\nA number is called a stepping number if all adjacent digits have an absolute difference of 1, e.g. '321' is a Stepping Number while 421 is not. Given two integers **n** and **m**, find the count of all the stepping numbers in the range [n, m].\n\n**Example 1:**\n```\nInput: n = 0, m = 21\n\nOutput: 13\n\nExplanation: Stepping no's are 0 1 2 3 4 5\n6 7 8 9 10 12 21\n\n```\n\n\n\n**Example 2:**\n\n```\nInput: n = 10, m = 15\n\nOutput: 2\n\nExplanation: Stepping no's are 10, 12\n\n```\n\n***\n\n**Your Task:**  \n\nYou don't need to read input or print anything. Your task is to complete the function **steppingNumbers()** which takes the integer n and integer m as input parameters and returns the number of stepping numbers in the range between n and m.\n\n**Expected Time Complexity:** O(log(M))\n\n**Expected Auxiliary Space:** O(SN) where SN is the number of stepping numbers in the range\n\n\n**Constraints:**\n0 ≤ N < M ≤ 10^7\n"
  },
  {
    "path": "GFG/Stepping Numbers/Stepping Numbers.cpp",
    "content": "class Solution{\npublic:\nunordered_map<int, int> mp;\n\npublic:\n    void dfs(int n, int m)\n    {\n        if (n > m)\n            return;\n\n        if (mp.find(n) != mp.end())\n            return;\n\n        mp[n] = 1;\n\n        if (n % 10 == 0)\n            dfs(n * 10 + 1, m);\n        else if (n % 10 == 9)\n            dfs(n * 10 + 8, m);\n        else\n        {\n            dfs(n * 10 + (n % 10) - 1, m);\n            dfs(n * 10 + (n % 10) + 1, m);\n        }\n    }\n    int steppingNumbers(int n, int m)\n    {\n        // Code Here\n        mp.clear();\n\n        for (int i = 0; i <= 9; i++)\n            dfs(i, m);\n\n        int ans = 0;\n\n        for (auto i : mp)\n            ans += (i.first >= n and i.second <= m);\n\n        return ans;\n    }\n\n};\n"
  },
  {
    "path": "GFG/Stepping Numbers/Stepping Numbers.java",
    "content": "class Solution{\n    int steppingNumbers(int n, int m){\n        // code here\n        int ans=0;\n        if(n==0)ans++;\n        Queue<Integer> q=new LinkedList<>();\n        for(int i=1;i<=9;i++){\n            q.add(i);\n        }\n        while(q.size()>0){\n            int sz=q.size();\n            while(sz-->0){\n                int ele=q.remove();\n                if(ele>=n && ele<=m)ans++;\n                int lastDigit=ele%10;\n                if(lastDigit==9){\n                    int next=ele*10+8;\n                    if(next<=m)q.add(next);\n                }else if(lastDigit==0){\n                    int next=ele*10+1;\n                    if(next<=m)q.add(next);\n                }else{\n                    int smaller=ele*10+(lastDigit-1);\n                    if(smaller<=m)q.add(smaller);\n                    int greater=ele*10+(lastDigit+1);\n                    if(greater<=m)q.add(greater);\n                }\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Substrings of length k with k-1 distinct elements/README.md",
    "content": "## Substrings of length k with k-1 distinct elements\n\nGiven a String **S** and an integer **K**. Find the count of all substrings of length **K** which have exactly **K-1** distinct characters.\n\n\n## Example 1:\n\n```\nInput:\n\nS = \"abcc\"\nK = 2\n\nOutput:\n\n1\n\nExplanation:\n\nPossible substrings of length K = 2 are\nab : 2 distinct characters\nbc : 2 distinct characters\ncc : 1 distinct character\nOnly one valid substring exists {\"cc\"}. \n```\n\n## Example 2:\n\n```\nInput:\n\nS = \"aabab\"\nK = 3\n\nOutput :\n\n3\n\nExplanation:\n\nPossible substrings of length K = 3 are\naab : 2 distinct characters\naba : 2 distinct characters\nbab : 2 distinct characters.\nAll of these Substrings are a possible answer,\nso the count is 3.\n```\n\n**Your Task:**  \nYou don't need to read input or print anything. Your task is to complete the function **countOfSubstrings()** which takes a String **S** and an integer **K** as input and returns the count of substrings of length **K** having **K-1** distinct characters.\n\n\n**Expected Time Complexity:** O(|S|)\n**Expected Auxiliary Space:** O(constant)\n\n\n**Constraints:**\n1 ≤ K ≤ |S| ≤ 105\n"
  },
  {
    "path": "GFG/Substrings of length k with k-1 distinct elements/Substrings of length k with k-1 distinct elements.cpp",
    "content": "\n};\n"
  },
  {
    "path": "GFG/Substrings of length k with k-1 distinct elements/Substrings of length k with k-1 distinct elements.java",
    "content": "class Solution {\n    static int countOfSubstrings(String s, int k) {\n        // code here\n        int ans=0;\n        int[]freq=new int[26];\n        for(int i=0;i<k;i++){\n            freq[s.charAt(i)-'a']++;\n        }\n        int cnt=0;\n        for(int x:freq){\n            if(x>0)cnt++;\n        }\n        int i=0;\n        int j=k;\n        while(j<=s.length()){\n            if(cnt==k-1){\n                ans++;\n            }\n            if(j==s.length())break;\n            freq[s.charAt(i)-'a']--;\n            if(freq[s.charAt(i)-'a']==0)cnt--;\n            freq[s.charAt(j)-'a']++;\n            if(freq[s.charAt(j)-'a']==1)cnt++;\n            i++;\n            j++;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "GFG/Sum of Beauty of All Substrings/Sum of Beauty of All Substrings.java",
    "content": "class Solution {\n    public static int beautySum(String s) {\n        // code here\n        int ans=0;\n        int n=s.length();\n        for(int size=3;size<=n;size++){\n            int i=0;\n            int j=size;\n            int[]freq=new int[26];\n            for(int k=i;k<j;k++){\n                freq[s.charAt(k)-'a']++;\n            }\n            ans+=beauty(freq);\n            while(j<n){\n                freq[s.charAt(j)-'a']++;\n                freq[s.charAt(i)-'a']--;\n                ans+=beauty(freq);\n                j++;\n                i++;\n            }\n        }\n        return ans;\n    }\n    static int beauty(int[]freq){\n        int min=Integer.MAX_VALUE;\n        int max=Integer.MIN_VALUE;\n        for(int i:freq){\n            if(i!=0){\n                min=Math.min(min,i);\n                max=Math.max(max,i);\n            }\n        }\n        return max-min;\n    }\n}\n"
  },
  {
    "path": "GFG/The Smurfs/The Smurfs.cpp",
    "content": "class Solution{\npublic:\n    int findMin(int n, char arr[]){\n        // code here\n        \n          unordered_map<char,int>mp;\n        for(int i = 0 ; i < n ; i++){\n            mp[arr[i]]++;\n        }\n        int cnt = 0;\n        for(auto x : mp){\n            cnt+=x.second;\n        }\n       if(mp['R']%2==0 and mp['B']%2==0 and mp['G']%2==0){\n           return 2;\n       }\n       else if(mp['R']%2==1 and mp['B']%2==1 and mp['G']%2==1){\n           return 2;\n       }\n       else{\n           return 1;\n       }\n    }\n};\n"
  },
  {
    "path": "GFG/The Smurfs/The Smurfs.java",
    "content": "\nclass Solution{\n    static int minFind(int n, String a[]){\n        // code here\n        int r=0;\n        int g=0;\n        int b=0;\n        for(int i=0;i<n;i++){\n            if(a[i].equals(\"R\")){\n                r++;\n            }else if(a[i].equals(\"G\")){\n                g++;\n            }else{\n                b++;\n            }\n        }\n        if(r==n || g==n || b==n)return n;\n        if((r%2==0 && b%2==0 && g%2==0) || (r%2!=0 && b%2!=0 && g%2!=0)){\n            return 2;\n        }\n        return 1;\n    }\n}\n"
  },
  {
    "path": "GFG/Tom and jerry/Tom and Jerry easy s26.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n  public:\n    int numsGame(int N) {\n        // code here\n        // as per example tom wins in every even number, \n        if(N%2==0) return 1;\n        else return 0;\n    }\n};\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int N;\n        \n        cin>>N;\n\n        Solution ob;\n        cout << ob.numsGame(N) << endl;\n    }\n    return 0;\n}"
  },
  {
    "path": "GFG/Tom and jerry/Tom and Jerry.java",
    "content": "class Solution {\n    static int numsGame(int N) {\n        // code here\n        if(N%2==0)return 1;\n        return 0;\n    }\n};\n"
  },
  {
    "path": "GFG/Tom and jerry/Tom and Jerry.py",
    "content": "class Solution:\n    def numsGame(self, N):\n        # code here\n        if(N%2==0):\n            return 1\n        else:\n            return 0\n"
  },
  {
    "path": "GFG/Transform to Sum Tree/Transform to Sum Tree.java",
    "content": "class Solution{\n    public void toSumTree(Node root){\n         //add code here.\n         dfs(root);\n    }\n    int dfs(Node root){\n        if(root==null)return 0;\n        int val = root.data;\n        int lefty=dfs(root.left);\n        int righty=dfs(root.right);\n        root.data=lefty+righty;\n        return val + lefty + righty;\n    }\n}\n"
  },
  {
    "path": "GFG/Two numbers with odd occurrences/README.md",
    "content": "## Two numbers with odd occurrences\n\n\nGiven an unsorted array, Arr[] of size N and that contains even number of occurrences for all numbers except two numbers. Find the two numbers in decreasing order which has odd occurrences.\n\n**Example 1:**\n\n```\nInput:\nN = 8\n\nArr = {4, 2, 4, 5, 2, 3, 3, 1}\n\nOutput: {5, 1} \n\nExplaination: 5 and 1 have odd occurrences.\n```\n**Example 2:**\n\n```\nInput:\nN = 8\n\nArr = {1 7 5 7 5 4 7 4}\n\nOutput: {7, 1}\n\nExplaination: 7 and 1 have odd occurrences.\n```\n\n***\n\n\n**Your Task:**\nYou don't need to read input or print anything. Your task is to complete the function **twoOddNum()** which takes the array Arr[] and its size N as input parameters and returns the two numbers in decreasing order which have odd occurrences.\n\n\n**Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n\n\nConstraints:\n2 ≤ N ≤ 106\n1 ≤ Arri ≤ 1012\n"
  },
  {
    "path": "GFG/Two numbers with odd occurrences/Two numbers with odd occurrences.cpp",
    "content": "class Solution{\n    public:\n    vector<long long int> twoOddNum(long long int Arr[], long long int N)  \n    {\n        // code here\n        vector< long long int> v;\n\nlong long int res=0,x=0,count=0,b=0;\n\n \n\nfor(long long int i=0;i<N;i++)\n\n{\n\n  res=res^Arr[i];\n\n}\n\nwhile(!(res&(1<<count))){\n\n ++count;\n\n}\n\nb=b|(1<<count);\n\n \n\nfor(long long int i=0;i<N;i++)\n\n{  \n\n if(Arr[i]&b)\n\n    x=x^res^Arr[i];\n\n}\n\n \n\nv.push_back(max(x,res^x));\n\nv.push_back(min(x,res^x));\n\n \n\nreturn v;\n    }\n};\n"
  },
  {
    "path": "GFG/Two numbers with odd occurrences/Two numbers with odd occurrences.java",
    "content": "class Solution\n{\n    public int[] twoOddNum(int arr[], int N)\n    {\n        // code here\n        int xor=0;\n        for(int i:arr){\n            xor^=i;\n        }\n        int setBit=0;\n        for(int i=0;i<32;i++){\n            int curr= 1<<i;\n            if((xor&curr)!=0){\n                setBit=curr;\n                break;\n            }\n        }\n        int first=0;\n        int second=0;\n        for(int i=0;i<N;i++){\n            if((arr[i]&setBit)!=0){\n                first^=arr[i];\n            }else{\n                second^=arr[i];\n            }\n        }\n        int[]ans=new int[2];\n        if(first<second){\n            ans[0]=second;\n            ans[1]=first;\n        }else{\n            ans[0]=first;\n            ans[1]=second;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/Unique partitions/Unique partitions.java",
    "content": "class Solution\n{\n    public ArrayList<ArrayList<Integer>> UniquePartitions(int n)\n    {\n        // Code here\n        ArrayList<ArrayList<Integer>> ans=new ArrayList<>();\n        ArrayList<Integer> curr=new ArrayList<>();\n        int idx=n-1;\n        \n        int[]arr=new int[n];\n        for(int i=0;i<n;i++){\n            arr[i]=i+1;\n        }\n        dfs(ans,curr,idx,n,arr);\n        return ans;\n    }\n    void dfs(ArrayList<ArrayList<Integer>> ans,ArrayList<Integer> curr,\n    int idx,int n,int[]arr){\n        if(idx<0 || n<0)return;\n        curr.add(arr[idx]);\n        if(n-arr[idx]==0){\n            ans.add(new ArrayList<>(curr));\n        }\n        dfs(ans,curr,idx,n-arr[idx],arr);\n        curr.remove(curr.size()-1);\n        dfs(ans,curr,idx-1,n,arr);\n        \n    }\n}\n"
  },
  {
    "path": "GFG/Wine Buying and Selling/Wine Buying and Selling.java",
    "content": "//{ Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\npublic class GFG {\n    public static void main(String[] args) throws Exception {\n        Scanner sc = new Scanner(System.in);\n        int T = sc.nextInt();\n        while(T>0)\n        {\n            int N = sc.nextInt();\n            int arr[] = new int[N];\n            for(int i=0; i<N; i++)\n                arr[i] = sc.nextInt();\n            \n            Solution g = new Solution();\n            long ans = g.wineSelling(arr,N);\n            \n            System.out.println(ans);\n            T--;\n        }\n    }\n}\n\n\n// } Driver Code Ends\n//User function Template for Java\n\n\nclass Solution {\n    long wineSelling(int arr[],int N){\n        // code here\n        Queue<int[]> q=new LinkedList<>();\n        for(int i=0;i<N;i++){\n            if(arr[i]>0)q.add(new int[]{i,arr[i]});\n        }\n        int i=0;\n        long ans=0l;\n        while(!q.isEmpty()){\n            while(i<N && arr[i]>0)i++;\n            int sell=Math.abs(arr[i]);\n            while(sell>0){\n                int buy=q.peek()[1];\n                int pos=q.peek()[0];\n                if(sell>=buy){\n                    ans+=(Math.abs(i-pos)*buy);\n                    sell-=buy;\n                    q.remove();\n                }else{\n                    ans+=(Math.abs(i-pos)*sell);\n                    q.peek()[1]=buy-sell;\n                    sell=0;\n                }\n            }\n            i++;\n        }\n    \n        return ans;\n        \n        \n        //Method 2\n        ArrayList<Integer> positive=new ArrayList<>();\n        ArrayList<Integer> negative=new ArrayList<>();\n        \n        for(int i=0;i<Arr.length;i++) {\n            if(Arr[i]>=0) {\n                positive.add(i);\n            }\n            else {\n                negative.add(i);\n            }\n        }\n        long ans=0;\n        int neg=0;\n        int i=0;\n        while(i<positive.size() && neg<negative.size()) {\n            if(Arr[positive.get(i)]>=Math.abs(Arr[negative.get(neg)])) {\n                long diff=Math.abs(positive.get(i)-negative.get(neg));\n                long sum=-1*Arr[negative.get(neg)];\n                Arr[positive.get(i)]= Arr[positive.get(i)]+Arr[negative.get(neg)];\n                ans+=sum*diff;\n                neg+=1;\n            }\n            else {\n                long diff=Math.abs(positive.get(i)-negative.get(neg));\n                long sum=Arr[positive.get(i)];\n                Arr[negative.get(neg)]= Arr[negative.get(neg)]+Arr[positive.get(i)];\n                ans+=sum*diff;\n                i+=1;\n            }\n        }\n        return ans;\n    }\n}\n\n//{ Driver Code Starts.\n// } Driver Code Ends\n\n\n//{ Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\npublic class GFG {\n    public static void main(String[] args) throws Exception {\n        Scanner sc = new Scanner(System.in);\n        int T = sc.nextInt();\n        while(T>0)\n        {\n            int N = sc.nextInt();\n            int arr[] = new int[N];\n            for(int i=0; i<N; i++)\n                arr[i] = sc.nextInt();\n            \n            Solution g = new Solution();\n            long ans = g.wineSelling(arr,N);\n            \n            System.out.println(ans);\n            T--;\n        }\n    }\n}\n\n\n// } Driver Code Ends\n//User function Template for Java\n\n\nclass Solution {\n    long wineSelling(int arr[],int N){\n        // code here\n        long sum=0l;\n        long ans=0l;\n        for(int i:arr){\n            sum+=i;\n            ans+=Math.abs(sum);\n        }\n        return ans;\n    }\n}\n\n//{ Driver Code Starts.\n// } Driver Code Ends\n"
  },
  {
    "path": "GFG/Zero Sum Subarrays/Zero Sum Subarrays.java",
    "content": "class Solution{\n    //Function to count subarrays with sum equal to 0.\n    public static long findSubarray(long[] arr ,int n) \n    {\n        //Your code here\n        Map<Long,Long> map=new HashMap<>();\n        map.put(0L,1L);\n        long sum=0;\n        long ans=0;\n        for(long i:arr){\n            sum+=i;\n            if(map.containsKey(sum)){\n                ans+=map.get(sum);\n            }\n            map.put(sum,map.getOrDefault(sum,0L)+1);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG/k-th smallest element in BST/k-th smallest element in BST.java",
    "content": "\nclass Solution {\n    // Return the Kth smallest element in the given BST\n    public int KthSmallestElement(Node root, int k) {\n        // Write your code here\n        Node curr=root;\n        int count=0;\n        int ans=-1;\n        while(curr!=null){\n            if(curr.left==null){\n                count++;\n                if(count==k)return curr.data;\n                curr=curr.right;\n            }else{\n                Node leftSubtree=curr.left;\n                while(leftSubtree.right!=null && leftSubtree.right!=curr){\n                    leftSubtree=leftSubtree.right;\n                }\n                \n                if(leftSubtree.right==null){\n                    leftSubtree.right=curr;\n                    curr=curr.left;\n                }else{\n                    leftSubtree.right=null;\n                    count++;\n                    if(count==k)return curr.data;\n                    curr=curr.right;\n                }\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "GFG_Find_all_distinct_subset_(or subsequence",
    "content": "class Solution{\n    public:\n    vector<int> DistinctSum(vector<int>nums){\n        // tabulation - bottom up approach - used , it is faster than memoization\n\t   vector<int>res;\n\t   int sum =0, m= nums.size();\n\t   for(auto n : nums) sum+=n;\n\t   \n\t   vector<vector<bool>>dp_tab(m+1, vector<bool>(sum+1));\n\t   for(int i=0; i<=m;i++){\n\t      for(int j =0; j<=sum; j++){\n\t          if(j==0) dp_tab[i][j] = true;\n\t          else if(i==0) dp_tab[i][j] = false;\n\t          else if(j>=nums[i-1])\n\t              dp_tab[i][j] = dp_tab[i-1][j-nums[i-1]] || dp_tab[i-1][j];\n\t          else dp_tab[i][j] = dp_tab[i-1][j];\n\t      }\n\t   }\n\t   for(int j =0; j<=sum; j++){\n\t      for(int i =0; i<=m; i++){\n\t          if(dp_tab[i][j]){\n\t              res.push_back(j);\n\t              break;\n\t          }\n\t      }\n\t   }\n\t   return res;\n\t//    TC: O(n*sum), SC: O(n*sum)\n    }\n\n};\n"
  },
  {
    "path": "Game with nos",
    "content": "int* game_with_number(int arr[], int n)\n{\n    \n    // Complete the function\n    for(int i=1;i<n;i++)\n    {\n        arr[i-1] = arr[i-1]^arr[i];\n    }\n    return arr;\n}\n"
  },
  {
    "path": "Game with nos.java",
    "content": "class Complete{\n    \n   \n    // Function for finding maximum and value pair\n    public static int[] game_with_number (int arr[], int n) {\n        // Complete the function\n        for(int i=0;i<n-1;i++){\n            arr[i]=arr[i]^arr[i+1];\n        }\n        return arr;\n    }\n    \n    \n}\n"
  },
  {
    "path": "Gas Station.java",
    "content": "class Solution {\n    public int canCompleteCircuit(int[] gas, int[] cost) {\n        int sum = 0, n = gas.length;\n        int gasInTank = 0, start = 0;\n        for(int i=0;i<n;i++) {\n            gasInTank += gas[i]-cost[i];\n            sum += gas[i]-cost[i];\n            // if we are not able to reach next station from i, \n            if(gasInTank < 0) {\n                start = i+1;\n                gasInTank = 0;\n            }\n        }\n        \n        return sum >= 0 ? start : -1;\n    }\n}\n"
  },
  {
    "path": "Geek and Number String s23 med.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std; \nclass Solution{\npublic:\n    int minLength(string s, int n) {\n        // code here\n        vector<string>v={\"12\",\"21\",\"34\",\"43\",\"56\",\"65\",\"78\",\"87\",\"09\",\"90\"};\n        int n1=n;\n        stack<char>st;\n        for(int i=0;i<s.size();i++)\n        {\n            st.push(s[i]);\n            if(st.size()>1)\n            {\n                string temp=\"\";\n                char a=st.top(); st.pop();\n                char b=st.top(); st.pop();\n                temp+=a;\n                temp+=b;\n                if(find(v.begin(),v.end(),temp)==v.end())\n                {\n                    st.push(b);\n                     st.push(a);\n                }\n            }\n        }\n        return st.size();\n    } \n};\nint32_t main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(NULL);\n    cout.tie(NULL);\n\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int n;\n        cin >> n;\n\n        string s;\n        cin >> s;\n\n        Solution obj;\n        cout << obj.minLength(s, n) << \"\\n\";\n    }\n    return 0;\n}"
  },
  {
    "path": "Geek and Number String.cpp",
    "content": "class Solution{\npublic:\n    int minLength(string s, int n) {\n        // code here\n        stack<char> S;\n        char arr[10] = {'9','2','1','4','3','6','5','8','7','0'};\n        \n        for(char it : s)\n        {\n            if(!S.empty() and arr[S.top()-'0'] == it)\n                S.pop();\n            else\n                S.push(it);\n        }\n        \n        return S.size();\n    } \n};\n"
  },
  {
    "path": "Geek and Number String.java",
    "content": "\n=======\n    public int minLength(String s, int n) { \n    \t// code here\n    \tStack<Integer>st=new Stack<>();\n    \tint pair[]=new int[]{9,2,1,4,3,6,5,8,7,0};\n    \tfor(char ch:s.toCharArray()){\n    \t    int key=ch-'0';\n    \t    if(st.size()==0){\n    \t        st.push(key);\n    \t    }else{\n    \t        if(st.peek()==pair[key]){\n    \t            st.pop();\n    \t        }else{\n    \t            st.push(key);\n    \t        }\n    \t    }\n    \t}\n    \treturn st.size();\n    }\n}\n\nApproach 2:\n\nclass Solution { \n\n    public int minLength(String s1, int n) { \n    \tStack<Character>stack=new Stack<Character>();\n    \t\n    \tfor(int i=0;i<s1.length();i++){\n    \t    if(stack.isEmpty()){\n    \t        stack.push((s1.charAt(i)));\n    \t    }\n    \t    else{\n    \t        String s=\"\";\n    \t        s+=(stack.peek());\n    \t        s+=(s1.charAt(i));\n    \t        if(s.equals(\"12\") || s.equals(\"21\") || s.equals(\"34\") || s.equals(\"43\")|| s.equals(\"56\") || s.equals(\"65\")|| s.equals(\"78\") || s.equals(\"87\") || s.equals(\"90\") || s.equals(\"09\")){\n    \t            \n    \t            stack.pop();\n    \t        }\n    \t        else{\n    \t            stack.push((s1.charAt(i)));\n    \t        }\n    \t    }\n    \t}\n    \treturn stack.size();\n    }\n}\n\n/*\nNote:\n\nTotal Time Taken:O(N)[Traversal of String and Comparing with the given strings.]\n\nGFG Time: 0.8\n\nAuxiliary Space:O(N)[Stack is used][In worst Case all characters will be there in the stack.]\n\nTotal Test Cases:210\n*/\n\n"
  },
  {
    "path": "Geek and knots.java",
    "content": "class Solution{\n    static long mod=1000000007;\n    static int knots(int M, int N, int K){\n        // code here\n        long [][]dp=new long[1001][1001];\n        long a=comb(M,K,dp);\n        long b=comb(N,K,dp);\n        return (int)((a%mod * b%mod )%mod);\n    }\n    static long comb(int n,int k,long[][]dp){\n        if(k==0 || k==n)return 1;\n        if(dp[n][k]!=0)return dp[n][k];\n        dp[n][k]=(comb(n-1,k,dp)%mod + comb(n-1,k-1,dp)%mod)%mod;\n        return dp[n][k];\n    }\n}\n"
  },
  {
    "path": "Generate IP Addresses.cpp",
    "content": "class Solution{\n  public:\n    bool isValid(string op)\n    {\n        string temp = \"\";\n        int count = 0;\n        for(int i=0; i<op.size(); i++)\n        {\n            if(op[i] == '.')\n            {\n                if(temp[0] == '0')\n                {\n                    for(int i=1; i<temp.size(); i++)\n                    {\n                        if(temp[i] == 0)\n                            continue;\n                        else\n                            return false;\n                    }\n                }\n                long long a = stoll(temp);\n                if(a > 255)\n                    return false;\n                temp.clear();\n                count++;\n            }\n            else\n                temp.push_back(op[i]);\n        }\n        \n        if(temp[0] == '0')\n        {\n            for(int i=1; i<temp.size(); i++)\n            {\n                if(temp[i] == 0)\n                    continue;\n                else\n                    return false;\n            }\n        }\n        \n        long long a = stoll(temp);\n        if(a <= 255 && count == 3)\n            return true;\n        else\n            return false;\n        \n    }\n    \n    void solve(string ip,string op,vector<string> &ans)\n    {\n        if(ip.size() == 0)\n        {\n             if(isValid(op))\n                ans.push_back(op);\n            \n            return;\n        }\n        \n        if(op.size() == 0)\n        {\n           op.push_back(ip[0]);\n           ip.erase(ip.begin()+0);\n        }\n        \n        if(op[op.size()-1] == '.')\n        {\n            string opt = op + ip[0];\n            ip.erase(ip.begin()+0);\n            solve(ip,opt,ans);\n        }\n        else\n        {\n            \n            string op1 = op + '.';\n            solve(ip,op1,ans);\n            string op2 = op + ip[0];\n            ip.erase(ip.begin()+0);\n            solve(ip,op2,ans);\n        }\n        \n           \n    }\n    \n    vector<string> genIp(string &s) {\n        vector<string> ans;\n        if(s.size() < 4)\n            ans.push_back(\"-1\");\n        else\n        {\n            string op = \"\";\n            solve(s,op,ans);\n            if(ans.size() == 0)\n                 ans.push_back(\"-1\");\n        }\n        \n        return ans;\n    }\n\n};\n\n// Another approach\n\n// class Solution{\n//   public:\n//   vector<string> ans;\n  \n//     bool isValidIp(string &s)\n//     {\n//         string temp = \"\";\n        \n//         for(int i=0; i<s.length(); i++)\n//         {\n//             if(s[i] != '.')\n//                 temp.push_back(s[i]);\n                \n//             else\n//             {\n//                 if(temp.empty() or (temp.length() > 1 and temp[0] == '0'))\n//                     return false;\n                \n//                 if(stoll(temp) > 255)\n//                     return false;\n                \n//                 temp = \"\";\n//             }\n//         }\n        \n//         if(temp.empty() or (temp.length() > 1 and temp[0] == '0'))\n//             return false;\n            \n//         if(stoll(temp) > 255)\n//             return false;\n            \n//         return true;\n//     }\n    \n//     void solve(string &s, int i, int cnt)\n//     {\n//         if(cnt == 3)\n//         {\n//             if(isValidIp(s))\n//             ans.push_back(s);\n            \n//             return;\n//         }\n        \n//         for(int p=i+1; p<s.length() and (p-i)<=4; p++)\n//         {\n//             s.insert(s.begin()+p, '.');\n            \n//             solve(s, p, cnt+1);\n            \n//             s.erase(s.begin()+p);\n//         }\n//     }\n    \n//     vector<string> genIp(string &s) {\n//         // Your code here\n//         ans.clear();\n        \n//         if(s.length() >= 4 and s.length() <= 12)\n//         solve(s, 0, 0);\n        \n//         if(ans.empty())\n//         ans.push_back({\"-1\"});\n        \n//         return ans;\n//     }\n\n// };\n"
  },
  {
    "path": "Generate IP Addresses.java",
    "content": "class Solution {\n    public ArrayList<String> genIp(String s) {\n        // code here\n        ArrayList<String> ans=new ArrayList<>();\n        int n=s.length();\n        if(n>12){\n            ans.add(\"-1\");\n            return ans;\n        }\n        for(int i=1;i<n-2;i++){//1,2,3\n            for(int j=i+1;j<n-1;j++){//2,3,4 / 3,4,5 / 4,5,6\n                for(int k=j+1;k<n;k++){\n                    String a=s.substring(0,i);\n                    String b=s.substring(i,j);\n                    String c=s.substring(j,k);\n                    String d=s.substring(k,n);\n                    if(validx(a) && validx(b)\n                    && validx(c) && validx(d)){\n                        ans.add(a+\".\"+b+\".\"+c+\".\"+d);\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n    boolean validx(String s){\n        int n=s.length();\n        if(n==0 || n>3 || (s.charAt(0)=='0' && n>1) || Integer.parseInt(s)>255)return false;\n        return true;\n        \n    }\n}\n"
  },
  {
    "path": "Generate IP Addresses.py",
    "content": "class Solution:\n    def genIp(self, s):\n        n = len(s)\n        arr = set()\n        if len(s)<4: return []\n        for i in range(1, n):\n            if int(s[:i]) > 256 or str(int(s[:i])) != s[:i]:\n                continue\n            for j in range(i+1, n):\n                if int(s[i:j]) > 256 or str(int(s[i:j])) != s[i:j]: continue\n                for k in range(j+1, n):\n                    if int(s[j:k]) > 256 or str(int(s[j:k])) != s[j:k]: continue\n                    if int(s[k:]) > 256 or str(int(s[k:])) != s[k:]: continue\n                        \n                    ipAdd = s[:i] + \".\" + s[i:j] + \".\" + s[j:k]+ \".\" + s[k:]\n                    arr.add(ipAdd)\n        return list(arr)\n"
  },
  {
    "path": "Generate all Parentheses II.java",
    "content": "public class Solution {\n    \n    private ArrayList<String> res;\n    \n\tpublic ArrayList<String> generateParenthesis(int A) {\n\t    res = new ArrayList<>();\n\t    StringBuilder str = new StringBuilder();\n\t    rec(0, 0, 0, str, A);\n\t    return res;\n\t}\n\t\n\tpublic void rec(int leftCount, int rightCount, int index, StringBuilder str, int n) {\n\t    if (leftCount > n || rightCount > n)return;    \n\t    if (rightCount > leftCount)return;\n\t    \n\t    if (index == 2 * n) {\n\t        res.add(str.toString());\n\t        return;\n\t    }\n\t    \n\t    str.append('(');\n\t    rec(leftCount + 1, rightCount, index + 1, str, n);\n\t    str.deleteCharAt(str.length() - 1);\n\t    \n\t    str.append(')');\n\t    rec(leftCount, rightCount + 1, index + 1, str, n);\n\t    str.deleteCharAt(str.length() - 1);\n\t    \n\t}\n\t\n\t\n}\n"
  },
  {
    "path": "Get min at pop.java",
    "content": "\nclass GetMin\n{\n    //Function to push all the elements into the stack.\n    public static Stack<Integer> _push(int arr[],int n)\n    {\n        // your code here\n        Stack<Integer> s=new Stack<>();\n        s.push(arr[0]);\n        \n        for(int i=1;i<n;i++){\n            int curr=arr[i];\n            int prevMin=s.peek();\n            int min=Math.min(prevMin,curr);\n            s.push(min);\n        }\n        \n        return s;\n        \n    }\n    \n    //Function to print minimum value in stack each time while popping.\n    static void _getMinAtPop(Stack<Integer>s)\n    {\n        // your code here\n        while(!s.isEmpty()){\n            System.out.print(s.pop()+\" \");\n        }\n    }\n}\n"
  },
  {
    "path": "Greater of Lesser.java",
    "content": "public class Solution {\n    public int solve(ArrayList<Integer> A, ArrayList<Integer> B, int C) {\n        int i=0;\n        int j=0;\n        for(int num:A){\n            if(num>C)i++;\n        }\n        for(int num:B){\n            if(num<C)j++;\n        }\n        return Math.max(i,j);\n    }\n}\n"
  },
  {
    "path": "Greater than All.java",
    "content": "public class Solution {\n    public int solve(int[] A) {\n        int max=A[0];\n        int ans=1;\n        for(int i=1;i<A.length;i++){\n            if(A[i]>max){\n                ans++;\n                max=A[i];\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Hamiltonian Path - GFG/README.md",
    "content": "# Hamiltonian Path\n## Medium\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">A <a href=\"https://en.wikipedia.org/wiki/Hamiltonian_path\">Hamiltonian path</a>,&nbsp;is a path&nbsp;in an <strong>undirected graph</strong> that visits each vertex exactly once. Given an <strong>undirected&nbsp;graph,</strong>&nbsp;the task is to&nbsp;check if a Hamiltonian path&nbsp;is present in it or not.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4, M = 4\nEdges[][]= { {1,2}, {2,3}, {3,4}, {2,4} }\n<strong>Output:</strong>\n1 \n<strong>Explanation: </strong>\nThere is a hamiltonian path: \n1 -&gt; 2 -&gt; 3 -&gt; 4 </span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4, M = 3 \nEdges[][] = { {1,2}, {2,3}, {2,4} } \n<strong>Output: </strong>\n0 \n<strong>Explanation:</strong> \nIt can be proved that there is no \nhamiltonian path in the given graph</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>check</strong>() which takes the <strong>N&nbsp;</strong>(the number of vertices), <strong>M</strong> (Number of edges) and the list of&nbsp;<strong>Edges</strong>[][] (where Edges[i] denotes the <strong>undirected</strong> Edge between vertices <strong>Edge[i][0] and Edges[i][1]</strong> )&nbsp;as input parameter&nbsp;and returns <strong>true (boolean value)</strong> if the graph contains Hamiltonian path,otherwise returns <strong>false</strong>.&nbsp;</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(N!)</span><span style=\"font-size:18px\">.</span><br>\n<strong><span style=\"font-size:18px\">Expected Auxiliary Space:</span>&nbsp;</strong><span style=\"font-size:18px\">O(N+M).</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 ≤ N ≤ 10</span><br>\n<span style=\"font-size:18px\">1 ≤ M ≤ 15</span><br>\n<span style=\"font-size:18px\">Size of Edges[i] is&nbsp;2</span><br>\n<span style=\"font-size:18px\">1 ≤ Edges[i][0],Edges[i][1] ≤ N</span></p>\n</div>"
  },
  {
    "path": "Hamiltonian Path - GFG/hamiltonian-path.java",
    "content": "//{ Driver Code Starts\n//Initial Template for Java\nimport java.io.*;\nimport java.util.*; \nclass GFG{\n    public static void main(String args[]) throws IOException { \n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        \n        while(t-- > 0){\n            String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n            int N = Integer.parseInt(input_line[0]);\n            int M = Integer.parseInt(input_line[1]);\n            \n            input_line = read.readLine().trim().split(\"\\\\s+\");\n            ArrayList<ArrayList<Integer>> Edges = new ArrayList<ArrayList<Integer>>(); \n            for(int i = 0; i < M; i++){\n                ArrayList<Integer> e = new ArrayList<Integer>();\n                e.add(Integer.parseInt(input_line[2*i]));\n                e.add(Integer.parseInt(input_line[2*i+1]));\n                Edges.add(e);\n            }\n            Solution ob = new Solution();\n            if(ob.check(N, M, Edges)){\n                System.out.println(1);\n            }\n            else{\n                System.out.println(0);\n            }\n        }\n    } \n} \n// } Driver Code Ends\n\n\n//User function Template for Java\nclass Solution \n{ \n    int n;\n    boolean check(int N, int M, ArrayList<ArrayList<Integer>> Edges) \n    { \n        // code here\n        n=N;\n        Map<Integer,ArrayList<Integer>> map=new HashMap<>();\n        for(ArrayList<Integer> edge:Edges){\n            int src=edge.get(0);\n            int des=edge.get(1);\n            map.putIfAbsent(src,new ArrayList<>());\n            map.putIfAbsent(des,new ArrayList<>());\n            map.get(src).add(des);\n            map.get(des).add(src);\n        }\n        \n        Set<Integer> set=new HashSet<>();\n        for(int node=1;node<=N;node++){\n            if(dfs(node,set,map)){\n                return true;\n            }\n        }\n        return false;\n    }\n    boolean dfs(int curr,Set<Integer> set,Map<Integer,ArrayList<Integer>> map){\n        set.add(curr);\n        if(set.size()==n){\n            return true;\n        }\n        \n        for(int neb:map.get(curr)){\n            if(!set.contains(neb) && dfs(neb,set,map)){\n                return true;\n            }\n        }\n        \n        set.remove(curr);//back..\n        return false;\n    }\n} "
  },
  {
    "path": "Height Using Parent Array.java",
    "content": "class Solution{\n    static int findHeight(int N, int arr[]){\n        int h=1;\n        int k=arr[N-1];\n        while(arr[k]!=-1){\n            k=arr[k];\n            h++;\n        }\n        return h+1;\n    }\n}\n"
  },
  {
    "path": "Highest Product.java",
    "content": "public class Solution {\n    public int maxp3(int[] A) {\n        int n=A.length;\n        Arrays.sort(A);\n        int ans=Math.max(A[0]*A[1]*A[n-1],A[n-3]*A[n-1]*A[n-2]);\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Highest Score.java",
    "content": "public class Solution {\n    public int highestScore(String[][] A) {\n        HashMap<String,Long> totalMarks=new HashMap<>();\n        HashMap<String,Long> freqMarks=new HashMap<>();\n        for(String x[]:A){\n            long marks=Long.parseLong(x[1]);\n            if(totalMarks.containsKey(x[0])){\n                Long val=totalMarks.get(x[0]);\n                long freq=freqMarks.get(x[0]);\n                totalMarks.put(x[0],(Long)val+marks);\n                freqMarks.put(x[0],++freq);\n            }else{\n                totalMarks.put(x[0],marks);\n                freqMarks.put(x[0],1L);\n            }\n        }\n        long max=Integer.MIN_VALUE;\n        for(String x[]:A){\n            long sum=totalMarks.get(x[0]);\n            long freq=freqMarks.get(x[0]);\n            max=Math.max(max,(sum/freq));\n        }\n        return (int)max;\n    }\n}\n\n"
  },
  {
    "path": "Hit most Balloons.java",
    "content": "class Solution {\n    public int mostBalloons(int N, int arr[][]) {\n        int ans=0;\n        for(int i=0;i<N;i++){\n            int x1=arr[i][0],y1=arr[i][1];\n            HashMap<Double,Integer> hm=new HashMap<>();\n            int count=0;\n            for(int j=0;j<N;j++){\n                int x2=arr[j][0],y2=arr[j][1];\n                if(x1==x2 && y1==y2){\n                    count++;\n                    continue;\n                }\n                double tan_theta=(y2-y1)/(1.0*(x2-x1));\n                hm.putIfAbsent(tan_theta,0);\n                hm.put(tan_theta,hm.get(tan_theta)+1);\n            }\n            for(double z:hm.keySet())\n                ans=Math.max(ans,count+hm.get(z));\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "INVERSIONS.java",
    "content": "public class Solution {\n    public int countInversions(ArrayList<Integer> A) {\n        ArrayList<Integer>l=new ArrayList<>();\n        l.add(A.get(0));\n        int ans=0;\n    \n        for(int i=1;i<A.size();i++){\n            int el=A.get(i);\n            int index=Collections.binarySearch(l,el);\n            if(index<0){\n                index=index*-1-1;\n                ans+=(l.size()-index);\n                l.add(index,el);// if element is not in list then calculation of upperbound in java\n            }else{// if present then we will add it to most left corner upperbound\n                int j=index;\n                while(j<l.size()&&l.get(j)==el){\n                    j++;\n                }\n                ans+=(l.size()-(j));\n                l.add((j-1),el);\n            }\n        }\n        return ans;\n        //*** I THINK THIS IS SUFFICIENT TO IMPLEMENT !!\n    }\n}\n"
  },
  {
    "path": "IPL 2021 - Match Day 2 by AMAN SAINI",
    "content": "EASY TO UNDERSTAND SOLUTION USING PRIORITY QUEUE OF PAIR OF INT, INT\n\n\nclass Solution{\npublic:\n    vector<int> max_of_subarrays(vector<int> arr, int n, int k) {\n        // your code here\n        vector<int> ans;\n        priority_queue<pair<int, int>> pq;\n        for(int i=0; i<k; i++){\n            pq.push(make_pair(arr[i], i));\n        }\n        ans.push_back(pq.top().first);\n        for(int i=k; i<n; i++){\n            pq.push(make_pair(arr[i], i));\n            while(pq.top().second <= i-k){\n                pq.pop();\n            }\n            ans.push_back(pq.top().first);\n        }\n        return ans;\n    }\n    };\n"
  },
  {
    "path": "IPL 2021 - Match Day 2.cpp",
    "content": "class Solution {\n  public:\n    vector<int> max_of_subarrays(vector<int> arr, int n, int k) {\n        // your code here\n        vector<int> ans;\n        deque<int> dq;\n        \n        for(int i=0; i<k; i++)\n        {\n            while(!dq.empty() and arr[dq.back()] <= arr[i])\n                dq.pop_back();\n            \n            dq.push_back(i);\n        }\n        \n        ans.push_back(arr[dq.front()]);\n        \n        for(int i=k; i<n; i++)\n        {\n            if(dq.front() <= (i-k))\n                dq.pop_front();\n                \n            while(!dq.empty() and arr[dq.back()] <= arr[i])\n                dq.pop_back();\n                \n            dq.push_back(i);\n            \n            ans.push_back(arr[dq.front()]);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "IPL 2021 - Match Day 2.java",
    "content": "class Solution {\n    static ArrayList<Integer> max_of_subarrays(int arr[], int n, int k) {\n        // Your code here\n        ArrayList<Integer>ans=new ArrayList<>();\n        Deque<Integer>q=new LinkedList<>();\n        for(int i=0;i<n;i++){\n            while(q.size()>0 && i-q.peek()>=k){\n                q.removeFirst();\n            }\n            \n            while(q.size()>0 && arr[q.getLast()]<=arr[i]){\n                q.removeLast();\n            }\n            q.addLast(i);\n            if(i>=k-1)ans.add(arr[q.peek()]);\n        }\n        \n        return ans;\n    }\n}\n"
  },
  {
    "path": "IPL 2021 - Match Day 2.py",
    "content": "#User function Template for python3\n\nclass Solution:\n    def max_of_subarrays(self,arr,n,k):\n        '''\n        you can use collections module here.\n        :param a: given array\n        :param n: size of array\n        :param k: value of k\n        :return: A list of required values \n        '''\n        #code here\n        def arr_max_ind(array, start, end):\n            m_ind, m_ele = start, array[start]\n            for i in range(start, end):\n                if array[i]>=m_ele:\n                    m_ele = array[i]\n                    m_ind = i\n            return [m_ele, m_ind]\n        \n        strategy = []\n        max_ele, max_ind = arr_max_ind(arr, 0, k)\n        for i in range(k, n+1):\n            start, end = i-k, k\n            if max_ind<i and max_ind>=i-k:\n                if arr[i-1]>max_ele:\n                    max_ele = arr[i-1]\n                    max_ind = i-1\n            else:\n                max_ele, max_ind = arr_max_ind(arr, i-k, i)\n                \n            strategy.append(max_ele)\n                \n        return strategy\n"
  },
  {
    "path": "Identical Binary Trees.java",
    "content": "public class Solution {\n    public int isSameTree(TreeNode A, TreeNode B) {\n        if(equal(A,B)){\n            return 1;\n        }else{\n            return 0;\n        }\n    }\n    public boolean equal(TreeNode a,TreeNode b){\n        if(a==null && b==null)return true;\n        if((a==null && b!=null) || (a!=null && b==null))return false;\n        if(a.val!=b.val)return false;\n        return equal(a.left,b.left) && equal(a.right,b.right);\n    }\n}\n"
  },
  {
    "path": "Immediate Smaller Element.java",
    "content": "class Solution {\n    void immediateSmaller(int arr[], int n) {\n        // code here\n        for(int i=0;i<n-1;i++){\n            if(arr[i]>arr[i+1]){\n                arr[i]=arr[i+1];\n            }else{\n                arr[i]=-1;\n            }\n        }\n        arr[n-1]=-1;\n    }\n}\n"
  },
  {
    "path": "Immediate Smaller Element.js",
    "content": "class Solution {\n    immediateSmaller(arr,n){\n       //code here\n    //    loop iterates to last numbers\n       \t    for(let i=0; i<n-1; i++){\n\t        if(arr[i+1]<arr[i]) arr[i]= arr[i+1];\n\t        else arr[i] = -1;\n\t    }\n\t    arr[n-1] = -1;\n    }\n}"
  },
  {
    "path": "Immediate Smaller Element.py",
    "content": "\n#Question Link:-https://practice.geeksforgeeks.org/problems/immediate-smaller-element1142/1\nclass Solution:\n\n\tdef immediateSmaller(self,arr,n):\n\t\t# code here\n\t\tfor i in range(1,n):\n\t\t    if arr[i]<arr[i-1]:\n\t\t        arr[i-1]=arr[i]\n\t\t    else:\n\t\t        arr[i-1]=-1\n\t\tarr[n-1]=-1\n\t\treturn arr\n  \n  #EXPLANATION:- We iterate through the array and check if the current element is smaller than the prev element, if it is, we swap the element else we assign -1 to that element. Lastly, we initialize -1 to the last element as there is no element after it to check from\n  \n"
  },
  {
    "path": "Implement Power Function(IB)",
    "content": "public class Solution {\n\tpublic int pow(int a, int y, int d) {\n                \n        if(a==0)return 0;       // if base is 0\n        long res=1,x=a;         // x=a bcz of integer overflow\n        while(y>0){\n                if((y&1)!=0)res=(res*x)%d;  //if y is odd then result will be mul by \"a\"\n                y=y>>1;         // y=y/2\n                x=(x*x)%d;      // x=x^2 : eg. x^8 = (x^2)^4\n        }\n        return (int)((d+res)%d);// for -ve testcases d is added in res\n\t}\n}\n"
  },
  {
    "path": "Implement StrStr.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public int strStr(final String A, final String B) {\n        for(int i=0;i<=A.length()-B.length();i++){\n            if(A.charAt(i)==B.charAt(0)){\n                if(B.equals(A.substring(i,i+B.length()))){\n                    return i;\n                }\n            }\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "Implementing Dijkstra Algorithm.java",
    "content": "class Solution\n{\n    //Function to find the shortest distance of all the vertices\n    //from the source vertex S.\n    static int[] dijkstra(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int S)\n    {\n        // distance of all numbers from source\n        int[] distance=new int[V];\n        //currently we don't know so filling maximum distance\n        for(int i=0;i<V;i++){\n            distance[i]=Integer.MAX_VALUE;\n        }\n        //ditance to source will be 0\n        distance[S]=0;\n        \n        //boolean array to check if already a number is selected or not and also to reduce time\n        boolean[] selected=new boolean[V];\n        \n        //priority queue to always give smallest distance from one number\n        Queue<ArrayList<Integer>> pq=new PriorityQueue<>(\n            new Comparator<ArrayList<Integer>>(){\n                @Override\n                public int compare(ArrayList<Integer> a1,ArrayList<Integer> a2){\n                    return a1.get(0)-a2.get(0);\n                }\n            }\n        );\n        //adding first pair into our priority queue\n        ArrayList<Integer> a=new ArrayList<>();\n        a.add(0);\n        a.add(S);\n        pq.add(a);\n        while(!pq.isEmpty()){\n            //getting the smallest distance in pq\n            ArrayList<Integer> arr=pq.remove();\n            int currDistance=arr.get(0);\n            int number=arr.get(1);\n            //if that number was not already traversed then do it\n            if(!selected[number]){\n                //get all connected pairs for that particular number\n                ArrayList<ArrayList<Integer>> connecteds=adj.get(number);\n                for(int i=0;i<connecteds.size();i++){\n                    int connectedNumber=connecteds.get(i).get(0);\n                    int newDistance=connecteds.get(i).get(1)+currDistance;\n                    //if new distance to some number is smaller than the stored one\n                    if(newDistance<distance[connectedNumber]){\n                        distance[connectedNumber]=newDistance;\n                        ArrayList<Integer> newList=new ArrayList<>();\n                        newList.add(newDistance);\n                        newList.add(connectedNumber);\n                        pq.add(newList);\n                    }\n                }\n                //mark the number as selected\n                selected[number]=true;\n            }\n        }\n        return distance;\n    }\n}\n\n\n\n\n=======================================================================================================================================\n    \n//without using arraylist and comparator ::\n    \nclass Solution\n{\n    //Function to find the shortest distance of all the vertices\n    //from the source vertex S.\n    static int[] dijkstra(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int S)\n    {\n        // distance of all numbers from source\n        int[] distance=new int[V];\n        //currently we don't know so filling maximum distance\n        Arrays.fill(distance,Integer.MAX_VALUE);\n        \n        //ditance to source will be 0\n        distance[S]=0;\n        \n        //boolean array to check if already a number is selected or not and also to reduce time\n        // boolean[] selected=new boolean[V];\n        \n        //priority queue to always give smallest distance from one number\n        PriorityQueue<Integer> pq=new PriorityQueue<>();\n        pq.add(S);\n        \n        while(!pq.isEmpty()){\n            //getting the element from pq\n            int number=pq.remove();\n            int currDistance=distance[number];\n            //get all connected pairs for that particular number\n            ArrayList<ArrayList<Integer>> connecteds=adj.get(number);\n            for(int i=0;i<connecteds.size();i++){\n                int connectedNumber=connecteds.get(i).get(0);\n                int newDistance=connecteds.get(i).get(1)+currDistance;\n                //if new distance to some number is smaller than the stored one\n                if(newDistance<distance[connectedNumber]){\n                    distance[connectedNumber]=newDistance;\n                    pq.add(connectedNumber);\n                }\n            }\n        }\n        return distance;\n    }\n}\n"
  },
  {
    "path": "Inorder Traversal of Cartesian Tree.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    public TreeNode buildTree(int[] A) {\n        return dfs(A,0,A.length-1);\n    }\n    TreeNode dfs(int[]a,int i,int j){\n        if(i>j)return null;\n        int temp=i;\n        int max=Integer.MIN_VALUE;\n        int idx=0;\n        while(temp<=j){\n            if(a[temp]>max){\n                max=a[temp];\n                idx=temp;\n            }\n            temp++;\n        }\n        TreeNode node=new TreeNode(a[idx]);\n        node.left=dfs(a,i,idx-1);\n        node.right=dfs(a,idx+1,j);\n        return node;\n    }\n}\n"
  },
  {
    "path": "Inorder linear Traversal.java",
    "content": "public class Solution {\n    public ArrayList<Integer> inorderTraversal(TreeNode A) {\n        ArrayList<Integer> list=new ArrayList<>();\n        Map<TreeNode,Boolean> map=new HashMap<>();\n        Deque<TreeNode> stack=new ArrayDeque<>();\n        stack.push(A);\n        map.put(A,false);\n        while(!stack.isEmpty()){\n            TreeNode node=stack.pop();\n            if(map.get(node)==false){\n                if(node.right!=null){\n                    stack.push(node.right);\n                    map.put(node.right,false);\n                }\n                stack.push(node);\n                if(node.left!=null){\n                    stack.push(node.left);\n                    map.put(node.left,false);\n                }\n                map.put(node,true);\n            }else{\n                list.add(node.val);\n            }    \n        }\n        return list;\n    }\n}\n"
  },
  {
    "path": "Insert into a Binary Search Tree",
    "content": "class Solution {\n    public TreeNode insertIntoBST(TreeNode root, int val) {\n        if(root==null)return new TreeNode(val);\n        return addNode(root,root,val);\n    }\n    public TreeNode addNode(TreeNode head,TreeNode root,int val){\n        if(root.val>val){\n            if(root.left==null){\n                root.left=new TreeNode(val);\n                return head;\n            }else{\n                return addNode(head,root.left,val);\n            }\n        }else if(root.val<val){\n            if(root.right==null){\n                root.right=new TreeNode(val);\n                return head;\n            }else{\n                return addNode(head,root.right,val);\n            }\n        }\n        return head;\n    }\n}\n"
  },
  {
    "path": "Insertion Sort List.java",
    "content": "public class Solution {\n    public ListNode insertionSortList(ListNode A) {\n        ListNode prev = null, cur = A, head = new ListNode(Integer.MIN_VALUE), next = null;\n        prev = head;\n        ListNode temp = head;\n        //so we’ve declared head pointer with the least min val, -inf, and it will serve the purpose of prev pointer\n        //basically, everything will be added after that!!\n        while (cur != null) {\n            //for each item, do\n            //take the cur pointer and set next pointer to cur.next,\n            //i.e. hold the next pointer so we don’t loose it\n            temp = head;\n            next = cur.next;\n            //call a function, insert\n            iinsert(head, cur);\n            //after inserting, update our pointer\n            cur = next;\n        }\n        //return everthing other than -inf\n        return head.next;\n    }\n    //insert funct\n    public static void iinsert(ListNode head, ListNode in ) {\n        ListNode temp = head, prev = null;\n        //for all values starting from -inf, check whether, cur val is lesser than the\n        //end of the sorted list [-inf…end]\n        while (temp != null) {\n\n            if (temp.val > in.val) {\n                //if there is some faulty node, 'en insert it b/w prev and temp\n                prev.next = in ; in.next = temp;\n                return;\n            }\n            prev = temp;\n            temp = temp.next;\n        }\n        prev.next = in;\n        //make sure to cut off some extra nodes\n        in.next = null;\n        return;\n    }\n}\n"
  },
  {
    "path": "Insertion Sort for Singly Linked List.java",
    "content": "class Solution\n{\n    public static Node insertionSort(Node head){\n        Node newHead=new Node(-1);\n        Node temp=head;\n        while(temp!=null){\n            Node newtemp=newHead;\n            Node toAdd=temp;\n            temp=temp.next;\n            toAdd.next=null;\n            if(newtemp.next==null){\n                newtemp.next=toAdd;\n            }else{\n                while(newtemp!=null){\n                    if(newtemp.next==null){\n                        break;\n                    }\n                    if(newtemp.next.data<toAdd.data){\n                        newtemp=newtemp.next;\n                    }else{\n                        break;\n                    }\n                }\n                Node nexxt=newtemp.next;\n                newtemp.next=toAdd;\n                toAdd.next=nexxt;\n            }\n        }\n        return newHead.next;\n    }\n}\n"
  },
  {
    "path": "Integer To Roman.java",
    "content": "public class Solution {\n    public String intToRoman(int A) {\n        StringBuilder sb=new StringBuilder();\n        while(A!=0){\n            String str=Integer.toString(A);\n            String num=\"\";\n            for(int i=str.length()-1;i>=0;i--){\n                if(str.charAt(i)!='0'){\n                    num=str.substring(i);\n                    break;\n                }\n            }\n            String roman=getRoman(Integer.parseInt(num));\n            sb.insert(0,roman);\n            A-=Integer.parseInt(num);\n        }\n        return sb.toString();\n    }\n    public String getRoman(int a){\n        switch(a){\n            case 1:\n                return \"I\";\n            case 2:\n                return \"II\";\n            case 3:\n                return \"III\";\n            case 4:\n                return \"IV\";\n            case 5:\n                return \"V\";\n            case 6:\n                return \"VI\";\n            case 7:\n                return \"VII\";\n            case 8:\n                return \"VIII\";\n            case 9:\n                return \"IX\";\n            case 10:\n                return \"X\";\n            case 20:\n                return \"XX\";\n            case 30:\n                return \"XXX\";\n            case 40:\n                return \"XL\";\n            case 50:\n                return \"L\";\n            case 60:\n                return \"LX\";\n            case 70:\n                return \"LXX\";\n            case 80:\n                return \"LXXX\";\n            case 90:\n                return \"XC\";\n            case 100:\n                return \"C\";\n            case 200:\n                return \"CC\";\n            case 300:\n                return \"CCC\";\n            case 400:\n                return \"CD\";\n            case 500:\n                return \"D\";\n            case 600:\n                return \"DC\";\n            case 700:\n                return \"DCC\";\n            case 800:\n                return \"DCCC\";\n            case 900:\n                return \"CM\";\n            case 1000:\n                return \"M\";\n            case 2000:\n                return \"MM\";\n            case 3000:\n                return \"MMM\";\n        }\n        return \"\";\n    }\n}\n"
  },
  {
    "path": "Integers in Strings.java",
    "content": "public class Solution {\n    public ArrayList<Integer> solve(String A) {\n        ArrayList<Integer> arr=new ArrayList<>();\n        String[] ar=A.split(\",\");\n        for(int i=0;i<ar.length;i++){\n            arr.add(Integer.parseInt(ar[i]));\n        }\n        return arr;\n    }\n}\n"
  },
  {
    "path": "Intersection Of Sorted Arrays.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE LIST. IT IS READ ONLY\n    public ArrayList<Integer> intersect(final List<Integer> a, final List<Integer> b) {\n        ArrayList<Integer> ans=new ArrayList<>();\n        int i=0;\n        int j=0;\n        while(i<a.size() && j<b.size()){\n            int x=a.get(i);\n            int y=b.get(j);\n            if(x==y){\n                ans.add(a.get(i));\n                i++;\n                j++;\n            }else if(x<y){\n                i++;\n            }else{\n                j++;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Intersection of Linked Lists.java",
    "content": "public class Solution {\n\tpublic ListNode getIntersectionNode(ListNode a, ListNode b) {\n        //size of list a\n        int sizeA=0;\n        ListNode tempA=a;\n        while(tempA!=null){\n            sizeA++;\n            tempA=tempA.next;\n        }\n\n        //size of list b\n        int sizeB=0;\n        ListNode tempB=b;\n        while(tempB!=null){\n            sizeB++;\n            tempB=tempB.next;\n        }\n\n        tempA=a;\n        tempB=b;\n\n        if(sizeB>sizeA){\n            //move b diff times\n            int diff=sizeB-sizeA;\n            while(diff--!=0){\n                tempB=tempB.next;\n            }\n        }else if(sizeA>sizeB){\n            //move a diff times\n            int diff=sizeA-sizeB;\n            while(diff--!=0){\n                tempA=tempA.next;\n            }\n        }\n\n        //move untill they meet or they become null\n        while(tempA!=tempB && tempA!=null && tempB!=null){\n            tempA=tempA.next;\n            tempB=tempB.next;\n        }\n        \n        if(tempA==null || tempB==null)return null;\n        return tempB;\n\t}\n}\n"
  },
  {
    "path": "Interviewbit/Colorful Number/Colorful Number.java",
    "content": "public class Solution {\n    public int colorful(int num) {\n        Set<Integer> set=new HashSet<>();\n        String s=Integer.toString(num);\n        for(int i=0;i<s.length();i++){\n            for(int j=i;j<s.length();j++){\n                if(set.contains(product(s,i,j))){\n                    return 0;\n                }else{\n                    set.add(product(s,i,j));\n                }\n            }\n        }\n        return 1;\n    }\n    public int product(String s,int i,int j){\n        int product=1;\n        int index=i;\n        while(index<=j){\n            product*=Integer.parseInt(s.charAt(index)+\"\");\n            index++;\n        }\n        return product;\n    }\n\n}\n"
  },
  {
    "path": "Interviewbit/Colorful Number/Colorful Number.py",
    "content": "class Solution:\n# @param A : integer\n# @return an integer\n    def colorful(self, A):\n        A=str(A)\n        if A=='0' or A=='1':\n            return 1\n        if len(A)>8:\n            return 0\n        digitset={ch for ch in A}\n        if len(digitset)!=len(A):\n            return 0\n        if ('1' in digitset) or ('0' in digitset):\n            return 0\n        if '2' not in digitset:\n            return 1\n\n        bigrams={A[i:i+2] for i in range(len(A)-1)}\n        if ('23'in bigrams or '32' in bigrams) and '6' in digitset:\n            return 0\n        if ('24'in bigrams or '42' in bigrams) and '8' in digitset:\n            return 0\n        if ('26'in bigrams or '62' in bigrams) and ('43' in bigrams or '34' in bigrams):\n            return 0\n        \n        return 1\n"
  },
  {
    "path": "Interviewbit/Copy List/Copy List.java",
    "content": "/**\n * Definition for singly-linked list with a random pointer.\n * class RandomListNode {\n *     int label;\n *     RandomListNode next, random;\n *     RandomListNode(int x) { this.label = x; }\n * };\n */\npublic class Solution {\n    public RandomListNode copyRandomList(RandomListNode head) {\n        Map<RandomListNode,RandomListNode> map=new HashMap<>();\n        RandomListNode temp=head;\n        while(temp!=null){\n            map.put(temp,new RandomListNode(temp.label));\n            temp=temp.next;\n        }\n        temp=head;\n        RandomListNode newHead=map.get(head);\n        while(temp!=null){\n            if(temp.next!=null){\n                map.get(temp).next=map.get(temp.next);\n            }\n            map.get(temp).random=map.get(temp.random);\n            temp=temp.next;\n        }\n        return newHead;\n    }\n}\n"
  },
  {
    "path": "Interviewbit/Valid Sudoku/Valid Sudoku.cpp",
    "content": "int Solution::isValidSudoku(const vector<string> &A) {\n    vector<unordered_set<int>> row(9);\n    vector<unordered_set<int>> col(9);\n    vector<unordered_set<int>> box(9);\n   \n    for(int i=0;i<9;i++){\n        for(int j=0;j<9;j++){\n       \n            if(A[i][j] != '.'){\n                char curr = A[i][j];\n               \n                if(row[i].find(curr) != row[i].end())\n                return 0;\n                else row[i].insert(curr);\n               \n               \n                if(col[j].find(curr) != col[j].end())\n                return 0;\n                else col[j].insert(curr);\n             \n                int index = i - i%3 + j/3;\n                if(box[index].find(curr) != box[index].end())\n                return 0;\n                else box[index].insert(curr);\n               \n            }\n        }\n    }\n   \n    return 1;\n}\n"
  },
  {
    "path": "Interviewbit/Valid Sudoku/Valid Sudoku.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public int isValidSudoku(final String[] A) {\n        char[][] board=new char[9][9];\n        for(int i=0;i<9;i++){\n            for(int j=0;j<9;j++){\n                board[i][j]=A[i].charAt(j);\n            }\n        }\n          for(int i=0;i<9;i++){\n            Set<Character> row=new HashSet<>();\n            Set<Character> col=new HashSet<>();\n            Set<Character> cube=new HashSet<>();\n            int rowindex=(i/3)*3,colindex=(i%3)*3;\n            for(int j=0;j<9;j++){\n                if(board[i][j]!='.'&&!(row.add(board[i][j])))\n                    return 0;\n                 if(board[j][i]!='.'&&!(col.add(board[j][i])))\n                    return 0;\n                if(board[rowindex+j/3][colindex+j%3]!='.'&&!(cube.add(board[rowindex+j/3][colindex+j%3])))\n                    return 0;\n            }\n            \n        }\n        return 1;\n    }\n}\n\n"
  },
  {
    "path": "Invert the Binary Tree.java",
    "content": "public class Solution {\n    public TreeNode invertTree(TreeNode A) {\n        if(A==null)return null;\n        TreeNode le=null;\n        if(A.left!=null){\n            le=invertTree(A.left);\n        }\n        TreeNode ri=null;\n        if(A.right!=null){\n            ri=invertTree(A.right);\n        }\n        A.left=ri;\n        A.right=le;\n        return A;\n    }\n}\n"
  },
  {
    "path": "Is Subsequence.java",
    "content": "class Solution {\n    public boolean isSubsequence(String s, String t) {\n        int i = 0;\n        for(int j = 0;j<t.length() && i<s.length();j++)\n            if(t.charAt(j) == s.charAt(i)) i++;\n        return i == s.length();  \n    }\n}\n"
  },
  {
    "path": "IsRectangle.java",
    "content": "public class Solution {\n    public int solve(int a, int b, int c, int d) {\n        if(a==b && c==d)return 1;\n        if(a==c && b==d)return 1;\n        if(a==d && b==c)return 1;\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Jump Game Array.java",
    "content": "class Solution {\n    static int canReach(int A[], int N) {\n        int step=0;\n        for(int i=N-2;i>=0;i--)\n        {\n            step++;\n            if(A[i]>=step)step=0;\n        }\n        if(step==0)return 1;\n        return 0;\n    } \n}\n"
  },
  {
    "path": "Jump Game IV",
    "content": "class Solution {\n    public int minJumps(int[] arr) {\n        if (arr.length == 1) return 0;\n        if (arr[0] == arr[arr.length - 1] || arr.length == 2) return 1;\n        if (arr[0] == arr[arr.length - 2]) return 2;\n        \n        Queue<Integer> q = new LinkedList<>();\n        \n        HashMap<Integer, List<Integer>> ind = new HashMap<>();\n        \n        \n        for (int i = 0; i < arr.length; i++) {\n            if (!ind.containsKey(arr[i])) {\n                ind.put(arr[i], new ArrayList<>());\n            }\n            ind.get(arr[i]).add(i);\n        }\n        \n        \n        \n        q.add(arr.length - 1);\n        boolean[] seen = new boolean[arr.length];\n        int level = 0;\n        while (!q.isEmpty()) {\n            \n            int sz = q.size();\n            for (int s = 0; s < sz; s++) {\n                int state = q.poll();\n\n                if (state == 0) return level;\n\n                if (state + 1 < arr.length && !seen[state + 1]) {\n                    seen[state + 1] = true;\n                    if (state + 1 == 0) return level + 1;\n                    \n                    q.add(state + 1);\n                }\n                \n                if (state - 1 >= 0 && !seen[state - 1]) {\n                    seen[state - 1] = true;\n                    if (state - 1 == 0) return level + 1;\n                    q.add(state - 1);\n                }\n\n\n                List<Integer> same = ind.get(arr[state]);     \n                for (int i : same) {\n                    if (i == state || seen[i]) continue;\n                    seen[i] = true;\n                    if (i == 0) return level + 1;\n                    q.add(i);\n                }\n            }\n            level++;\n        }\n        \n        \n        return -1;\n    }\n}\n"
  },
  {
    "path": "K Largest Elements.java",
    "content": "public class Solution {\n    public ArrayList<Integer> solve(ArrayList<Integer> A, int B) {\n        Collections.sort(A);\n        ArrayList<Integer> ans=new ArrayList<>();\n        for(int i=A.size()-1;i>=A.size()-B;i--){\n            ans.add(A.get(i));\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "K-diff Pairs in an Array.java",
    "content": "class Solution {\n    public int findPairs(int[] nums, int k) {\n        Arrays.sort(nums);\n        \n        int i = 0;\n        int n = nums.length;\n        int j = 0;\n        int count = 0;\n        \n        while(j < n) {\n            j = i + 1;\n            \n            while(j < n && nums[j] - nums[i] < k) {\n                j++;\n            }\n            \n            if (j < n && nums[j] - nums[i] == k) {\n                count++;\n            }\n            \n            while(i + 1 < n && nums[i+1] == nums[i]) {\n                i++;\n            }\n            i++;\n        }\n        return count;\n    }\n}\n\n================================================================================\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}\n"
  },
  {
    "path": "Kill Captain America - GFG/README.md",
    "content": "# Kill Captain America\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Captain America is hiding from Thanos in a maze full of N rooms connected by M gates.<br>\nThe maze is designed in such a way that each room leads to another room via gates. All connecting gates are unidirectional.&nbsp;Captain America is hiding only in those rooms which are accessible directly/indirectly through every other room in the maze.<br>\nHelp Thanos find the number of rooms in which Captain America can hide.&nbsp;</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>:\nN = 5 and M = 5\nV = [[1, 2], [2, 3], [3, 4], [4, 3], [5, 4]]\n<strong>Output:</strong>&nbsp;2\n<strong>Explanation</strong>:\n<img alt=\"\" src=\"https://media.geeksforgeeks.org/img-practice/ScreenShot2022-05-06at10-1651814266.png\" class=\"img-responsive\">\nWe can look closesly after forming graph \nthan captain america only can hide in a \nroom 3 and 4 because they are the only room \nwhich have gates through them. So,\nanswer is 2.\n\n</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 2, M = 1\nV = [[1, 2]]\n<strong>Output: </strong>1\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>captainAmerica()</strong>&nbsp;which takes the integer N, an integer M and 2-d array V&nbsp;as input parameters and returns the Total no of rooms.<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(</span><span style=\"font-size:18px\">N+M</span><span style=\"font-size:18px\">)<br>\n<strong>Expected Auxiliary Space:</strong> O(N+M)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ n ≤ 30000<br>\n1 ≤ m ≤ 200000<br>\n1 ≤ p,q ≤ n</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Kill Captain America - GFG/kill-captain-america.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        \n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n            int  N = Integer.parseInt(input_line[0]);\n            int  M = Integer.parseInt(input_line[1]);\n            int V[][] = new int[M+1][2];\n            for(int i=0;i<M;i++){\n                String input_line1[] = read.readLine().trim().split(\"\\\\s+\");\n                V[i][0] = Integer.parseInt(input_line1[0]);\n                V[i][1] = Integer.parseInt(input_line1[1]);\n            }\n            Solution ob = new Solution();\n            int ans = ob.captainAmerica(N, M, V);\n            System.out.println(ans);\n        }\n    }\n}\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass UnionFind\n{\n    int N;\n    int parent[];\n    \n    UnionFind(int N)\n    {\n        this.N = N;\n        parent = new int[N+1];\n        for(int i=1; i<=N; i++)\n        {\n            parent[i] = i;\n        }\n    }\n    \n    private int findParent(int x)\n    {\n        if(parent[x]==x) return x;\n        return parent[x] = findParent(parent[x]);\n    }\n    \n    public void union (int x, int y)\n    {\n        int px = findParent(x);\n        int py = findParent(y);\n        \n        parent[y] = px;\n    }\n    \n    public int getMain()\n    {\n        int count[] = new int[N+1];\n        for(int i=1; i<=N; i++)\n        {\n            findParent(i);\n            count[parent[i]]++;\n        }\n        \n        int total_count = 0;\n        \n        for(int i=1; i<=N; i++)\n        {\n            if(count[i]==N) return i;\n        }\n        \n        return 0;\n    }\n    \n}\n\n\nclass Solution\n{\n    \n    int captainAmerica(int N, int M, int V[][])\n    {\n        UnionFind uf = new UnionFind(N);\n        \n        for(int i=0; i<M; i++)\n        {\n            uf.union(V[i][1], V[i][0]);\n        }\n        \n        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n        \n        for(int i=0; i<=N; i++)\n        {\n            adj.add(new ArrayList<>());\n        }\n        \n        for(int i=0; i<M; i++)\n        {\n            adj.get(V[i][0]).add(V[i][1]);\n        }\n        \n        int mainNd = uf.getMain();\n        \n        if(mainNd == 0) return 0;\n        \n        Queue<Integer> q = new ArrayDeque<>();\n        boolean visited[] = new boolean[N+1];\n        \n        visited[mainNd] = true;\n        \n        q.add(mainNd);\n        \n        int count = 1;\n        \n        while(!q.isEmpty())\n        {\n            int nd = q.poll();\n            \n            for(int nei : adj.get(nd))\n            {\n                if(visited[nei]==false)\n                {\n                    count++;\n                    visited[nei]=true;\n                    q.add(nei);\n                }\n            }\n            \n        }\n        \n        \n        return count;\n    }\n    \n}"
  },
  {
    "path": "Killing Spree - GFG/README.md",
    "content": "# Killing Spree\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">There are Infinite People Standing in a row, indexed from 1.<br>\nA person having index 'i' has&nbsp;strength of (i*i).<br>\nYou have Strength 'P'. You need to tell what is the maximum number of People You can Kill With your Strength P.<br>\nYou can only Kill a person with strength 'X' if P &gt;= 'X' &nbsp;and after killing him, Your Strength decreases by 'X'.&nbsp;</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>:\nN = 14\n<strong>Output:</strong>&nbsp;3\n<strong>Explanation</strong>:</span>\n<span style=\"font-size:18px\">The strengths of people is 1, 4, 9, 16, .... \nand so on. WE can kill the first 3 person , \nafter which our Power becomes 0 and we cant \nkill anyone else. So answer is 3</span><span style=\"font-size:18px\">\n</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 10\n<strong>Output: </strong>2\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>killinSpree()</strong>&nbsp;which takes the integer N as input parameters and returns the maximum Number of People You can kill.<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(log(n))<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ T ≤ 10<sup>3</sup><br>\n1 ≤ N ≤ 10<sup>12</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Killing Spree - GFG/killing-spree.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        \n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n            long N = Long.parseLong(input_line[0]);\n            Solution ob = new Solution();\n            long ans = ob.killinSpree(N);\n            System.out.println(ans);\n        }\n    }\n}\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    \n    long killinSpree(long n)\n    {\n        long low=1;\n        long high=(long)Math.sqrt(n);\n        long ans=0;\n        while(low<=high){\n            long mid=low+(high-low)/2;\n            long sum=(mid*(mid+1)*(2*mid + 1))/6;\n            if(sum==n)return mid;\n            else if(sum<n){\n                low=mid+1;\n                ans=mid;\n            }else{\n                high=mid-1;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Koko Eating Bananas.java",
    "content": "class Solution {\n    public int minEatingSpeed(int[] piles, int h) {\n        int low=1;\n        int high=max(piles);\n        int speed=1;\n        while(speed<max(piles)){\n            int total=0;\n            speed=(low+high)/2;\n            for(int i:piles){\n                total+= Math.ceil((double) i / speed);\n            }\n            if(total<=h){\n                high=speed;\n            }else{\n                low=speed+1;\n            }\n            if(low==high)return low;\n        }\n        return speed;\n    }\n    public int max(int[]a){\n        Arrays.sort(a);\n        return a[a.length-1];\n    }\n}\n"
  },
  {
    "path": "Kth Permutation Sequence.java",
    "content": "public class Solution {\n    public String getPermutation(int A, int B) {\n        B--;\n        \n        int[] fact = new int[A];\n        fact[0] = 1;\n        for (int i = 1; i < A; i++) {\n            fact[i] = i * fact[i - 1];\n            if (fact[i] > B) {\n                Arrays.fill(fact, i, A, B + 1);\n                break;\n            }\n        }\n\n        List<Integer> dig = new ArrayList<>();\n        for (int i = 1; i <= A; i++)\n            dig.add(i);\n\n        StringBuilder res = new StringBuilder();\n        \n        for (; A > 0; A--) {\n            int pos = (B / fact[A - 1]);\n            res.append(dig.get(pos));\n            dig.remove(pos);\n            B = (B % fact[A - 1]);\n        }\n\n        return res.toString();\n    }\n}\n\n"
  },
  {
    "path": "Kth Row of Pascal's Triangle.java",
    "content": "public class Solution {\n    public int[] getRow(int a) {\n        int[] res = new int[a+1];\n\t    res[0]=1;\n\t    res[a]=1;\n        for(int i=1; i<a; i++){\n\t        int num = (a+1-i)*res[i-1]/i;\n\t        res[i]=num;\n\t    }\n\t    return res;\n    }\n}\n"
  },
  {
    "path": "Kth Smallest Absolute Difference.java",
    "content": "class Compute {\n    \n    public long kthDiff(long arr[], long n, long k)\n    {\n        Arrays.sort(arr);\n        int diff= (int) (arr[(int)n-1]-arr[0]);\n        int l=0;\n        int h=diff;\n        while(l<h){\n            int m=(l+h)/2;\n            if(ok(m,arr,(int)n,(int)k))\n                h=m;\n            else\n                l=m+1;\n        }\n        return l;\n    }\n    public static boolean ok(int m,long[] arr,int n,int k){\n        int j=1;\n        int total=0;\n        for(int i=0;i<n;i++){\n            while(j<n && arr[j]-arr[i]<=m) j++;\n            j--;\n            int x=(j-i);\n            total+=x;\n        }\n        return (total>=k);\n    }\n}\n"
  },
  {
    "path": "Kth Smallest Element In Tree.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    static int count, result;\n    public int kthsmallest(TreeNode root, int B) {\n        count = 0;\n        result = Integer.MIN_VALUE;\n        inorder(root,B);\n        return result;\n    }\n    public static void inorder(TreeNode root,int k){\n        if(root == null){\n            return;\n        }\n        inorder(root.left,k);\n        count++;\n        if(count == k){\n            result = root.val;\n            return;\n        }\n        inorder(root.right,k);\n    }\n}\n\n"
  },
  {
    "path": "Kth smallest element.cpp",
    "content": "class Solution{\n    public:\n    // arr : given array\n    // l : starting index of the array i.e 0\n    // r : ending index of the array i.e size-1\n    // k : find kth smallest element and return using this function\n    int kthSmallest(int arr[], int l, int r, int k) {\n        //code here\n        int n=r+1;\n       sort(arr,arr+n);\n       return arr[k-1];\n    }\n};\n"
  },
  {
    "path": "LC 1000. Minimum Cost to Merge Stones.cpp",
    "content": "class Solution {\npublic:\n\n\n// This problem comes under the category of partition dp.\n\n    int mergeStones(vector<int> &stones, int k)\n{\n    int n = stones.size();\n    \n    // Condition to check if it's possible to merge all piles of stones into a single pile\n    if ((n - 1) % (k - 1) != 0)\n        return -1;\n    vector<int> prefixSum(n + 1);\n    prefixSum[0] = 0;\n    prefixSum[1] = stones[0];\n    for (int i = 2; i <= n; i++)\n    {\n        prefixSum[i] = prefixSum[i - 1] + stones[i - 1];\n    }\n    vector<vector<int>> dp(n, vector<int>(n, 0));\n    for (int i = n - 1; i >= 0; i--)\n    {\n        for (int j = i+1; j <= n - 1; j++)\n        {\n            int mini = 1e9;\n            for (int idx = i; idx < j; idx = idx + k - 1)\n            {\n                int cost =  dp[i][idx] + dp[idx + 1][j];\n                mini = min(cost, mini);\n            }\n                 if((j-i)%(k-1) == 0){\n                    mini += prefixSum[j+1] - prefixSum[i];\n                }\n             dp[i][j] = mini;\n        }\n    }\n    return dp[0][n - 1];\n}\n\n};\n"
  },
  {
    "path": "LCP - GFG/README.md",
    "content": "# LCP\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\"><strong>Note: This&nbsp;<a href=\"http://practice.geeksforgeeks.org/problem-of-the-day\" target=\"_blank\">POTD</a>&nbsp;is a part of&nbsp;<a href=\"https://practice.geeksforgeeks.org/summer-carnival-2022?utm_source=potd&amp;utm_medium=problempage&amp;utm_campaign=gsc22\" target=\"_blank\">Geek Summer Carnival</a>. Solve all POTD consecutively from 5th to 10th April and get a chance to win exclusive discount vouchers on our GfG courses.</strong></span></p>\n\n<hr>\n<p><span style=\"font-size:18px\">Geek is at the geek summer carnival. He is given an array of N strings. To unlock exclusive course discounts he needs to find the longest common prefix among all strings present in the array. Can you help him ?</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\">Input:\nN = 4\nar[] = {geeksforgeeks, geeks, geek, geezer}</span>\n\n<span style=\"font-size:18px\">Output:\ngee</span>\n\n<span style=\"font-size:18px\">Explanation: \nLongest common prefix in all the given string is gee. </span></pre>\n\n<p>&nbsp;</p>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\">Input:\nN = 3\nar[] = {apple, ape, april}</span>\n\n<span style=\"font-size:18px\">Output:\nap</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Complete the function LCP() that takes integer n and ar[] as input parameters and return the LCP.&nbsp;</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected time complexity: </strong>O(NlogN)<br>\n<strong>Expected space complexity:</strong> O(string length)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N &lt;= 10^3<br>\n1 &lt;= String Length &lt;= 100</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "LCP - GFG/lcp.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.math.*;\n\nclass GFG\n{\n    public static void main(String args[])\n    {\n        Scanner sc = new Scanner(System.in);\n        int t = Integer.parseInt(sc.next());\n        \n        while(t-- > 0)\n        {\n            int n = Integer.parseInt(sc.next());\n            \n            String s[] = new String[n];\n            for(int i=0;i<n;i++)\n            {\n                s[i] = sc.next();\n            }\n            Solution T = new Solution();\n            System.out.println(T.lcp(s,n));\n        }\n        \n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n    public String lcp(String s[],int n){\n        Arrays.sort(s,(a,b)->a.length()-b.length());\n        String ans=s[0];\n        for(int i=1;i<s.length;i++){\n            StringBuilder curr=new StringBuilder();\n            for(int j=0;j<ans.length();j++){\n                if(ans.charAt(j)==s[i].charAt(j)){\n                    curr.append(ans.charAt(j));\n                }\n            }\n            ans=curr.toString();\n        }\n        if(ans.length()==0)ans=\"-1\";\n        return ans;\n    }\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "Attribution 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n     wiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More considerations\n     for the public:\n     wiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution 4.0 International Public License (\"Public License\"). To the\nextent this Public License may be interpreted as a contract, You are\ngranted the Licensed Rights in consideration of Your acceptance of\nthese terms and conditions, and the Licensor grants You such rights in\nconsideration of benefits the Licensor receives from making the\nLicensed Material available under these terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n\n  d. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  e. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  f. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  g. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  h. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  i. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  j. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  k. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part; and\n\n            b. produce, reproduce, and Share Adapted Material.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n       4. If You Share Adapted Material You produce, the Adapter's\n          License You apply must not prevent recipients of the Adapted\n          Material from complying with this Public License.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n\n=======================================================================\n\nCreative Commons is not a party to its public licenses.\nNotwithstanding, Creative Commons may elect to apply one of its public\nlicenses to material it publishes and in those instances will be\nconsidered the “Licensor.” The text of the Creative Commons public\nlicenses is dedicated to the public domain under the CC0 Public Domain\nDedication. Except for the limited purpose of indicating that material\nis shared under a Creative Commons public license or as otherwise\npermitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the public\nlicenses.\n\nCreative Commons may be contacted at creativecommons.org.\n"
  },
  {
    "path": "Largest BST - GFG/README.md",
    "content": "# Largest BST\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.<br>\n<strong>Note: </strong>Here Size is equal to the number of nodes in the subtree.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\n&nbsp;       1\n&nbsp;     /   \\\n&nbsp;    4     4\n&nbsp;  /   \\\n&nbsp; 6     8<strong>\nOutput: </strong>1<strong>\nExplanation: </strong>There's no sub-tree with size\ngreater than 1 which forms a BST. All the\nleaf Nodes are the BSTs with size equal\nto 1.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>6 6 3 N 2 9 3 N 8 8 2\n&nbsp;           6\n&nbsp;       /       \\\n&nbsp;      6         3\n&nbsp;       \\      /   \\\n&nbsp;        2    9     3\n&nbsp;         \\  /  \\\n&nbsp;         8 8    2 <strong>\nOutput: </strong>2<strong>\nExplanation: </strong>The following sub-tree is a\nBST of size 2:&nbsp;\n&nbsp; &nbsp; &nbsp;  2\n&nbsp; &nbsp; /&nbsp; &nbsp; \\&nbsp;\n&nbsp;  N&nbsp; &nbsp; &nbsp; 8</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function</span><span style=\"font-size:18px\"><strong> largestBst()&nbsp;</strong>that takes the root node of the Binary Tree<strong>&nbsp;</strong>as its input&nbsp;and returns the size&nbsp;of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(N).<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(Height of the BST).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ Number of nodes ≤ 10<sup>5</sup><br>\n1 ≤ Data of a node ≤ 10<sup>6</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Largest BST - GFG/largest-bst.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\nimport java.math.*;\n\nclass Node  \n{ \n    int data; \n    Node left, right; \n   \n    public Node(int d)  \n    { \n        data = d; \n        left = right = null; \n    } \n}\n\nclass GFG\n{\n    static Node buildTree(String str)\n    {\n        // Corner Case\n        if(str.length() == 0 || str.equals('N'))\n            return null;\n        String[] s = str.split(\" \");\n        \n        Node root = new Node(Integer.parseInt(s[0]));\n        Queue <Node> q = new LinkedList<Node>();\n        q.add(root);\n        \n        // Starting from the second element\n        int i = 1;\n        while(!q.isEmpty() && i < s.length)\n        {\n              // Get and remove the front of the queue\n              Node currNode = q.remove();\n        \n              // Get the curr node's value from the string\n              String currVal = s[i];\n        \n              // If the left child is not null\n              if(!currVal.equals(\"N\")) \n              {\n        \n                  // Create the left child for the curr node\n                  currNode.left = new Node(Integer.parseInt(currVal));\n        \n                  // Push it to the queue\n                  q.add(currNode.left);\n              }\n        \n              // For the right child\n              i++;\n              if(i >= s.length)\n                  break;\n              currVal = s[i];\n        \n              // If the right child is not null\n              if(!currVal.equals(\"N\")) \n              {\n        \n                  // Create the right child for the curr node\n                  currNode.right = new Node(Integer.parseInt(currVal));\n        \n                  // Push it to the queue\n                  q.add(currNode.right);\n              }\n              \n              i++;\n        }\n    \n        return root;\n    }\n    \n    public static void main(String args[]) throws IOException {\n    \n       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(br.readLine().trim());\n        while(t>0)\n        {\n            String s = br.readLine();\n            Node root = buildTree(s);\n            \n            Solution T = new Solution();\n            System.out.println(T.largestBst(root));\n            \n            t--;\n        }\n    }\n}\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n// class Node  \n// { \n//     int data; \n//     Node left, right; \n   \n//     public Node(int d)  \n//     { \n//         data = d; \n//         left = right = null; \n//     } \n// }\n\n\nclass Solution{\n    static int ans;\n    // Return the size of the largest sub-tree which is also a BST\n    static int largestBst(Node root){\n        if(root==null)return 0;\n        ans=0;\n        checkBST(root);\n        return ans;\n    }\n    static boolean checkBST(Node root){\n        if(root==null)return true;\n        boolean isLeftBST=checkBST(root.left);\n        boolean isRightBST=checkBST(root.right);\n        boolean isLeftSmaller=true;\n        boolean isRightLarger=true;\n        if(root.left!=null && isLeftBST){\n            if(getMAX(root.left)>=root.data)isLeftSmaller=false;\n        }\n        if(root.right!=null && isRightBST){\n            if(getMIN(root.right)<=root.data)isRightLarger=false;\n        }\n        boolean isBST=isLeftSmaller && isRightLarger && isLeftBST && isRightBST;\n        if(isBST){\n            ans=Math.max(ans,count(root));\n        }\n        return isBST;\n    }\n    static int count(Node root){\n        if(root==null)return 0;\n        return 1+count(root.left)+count(root.right);\n    }\n    static int getMIN(Node root){\n        if(root.left==null)return root.data;\n        return getMIN(root.left);\n    }\n    static int getMAX(Node root){\n        if(root.right==null)return root.data;\n        return getMAX(root.right);\n    }\n    \n}"
  },
  {
    "path": "Largest Number.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public String largestNumber(final List<Integer> A) {\n        Collections.sort(A,(a,b)->{\n            String s1=Integer.toString(a);\n            String s2=Integer.toString(b);\n            return (s1+s2).compareTo(s2+s1)>0?-1:1;\n        });\n        StringBuilder sb=new StringBuilder();\n        for(int i=0;i<A.size();i++){\n            if(i==0 && A.get(i)==0)return \"0\";\n            sb.append(A.get(i));\n        }\n        return sb.toString();\n    }\n}\n"
  },
  {
    "path": "Largest Permutation.java",
    "content": "public class Solution {\n    public int[] solve(int[] A, int B) {\n        int len = A.length;\n        int position[] = new int[len+1];\n        for (int i=0; i<len; i++){\n            position[A[i]] = i;\n        }\n        for (int i=0; i<len && B>0; i++){\n            if (A[i]!=len-i){\n                A[position[len-i]] = A[i];\n                int temp = position[A[i]];\n                position[A[i]] = position[len-i];\n                A[i] = len-i;\n                B--;\n            }\n        }\n        return A;\n    }\n}\n"
  },
  {
    "path": "Largest Rectangle in Histogram.java",
    "content": "class Solution {\n    public int largestRectangleArea(int[] a) {\n        int max=0;\n        int ps[]=prevSmallest(a);\n        int ns[]=nextSmallest(a);\n        for(int i=0;i<a.length;i++){\n            int cur=(ns[i]-ps[i]-1)*a[i];\n            max=Math.max(max,cur);\n        }\n        return max;\n        \n    }\n    public int[] prevSmallest(int[]a){\n        int ps[]=new int[a.length];\n        Deque<Integer> s=new ArrayDeque<>();\n        for(int i=0;i<a.length;i++){\n            while(!s.isEmpty() && a[s.peek()]>=a[i]){\n                s.pop();\n            }\n            if(s.isEmpty()){\n                ps[i]=-1;\n            }else{\n                ps[i]=s.peek();\n            }\n            s.push(i);\n        }\n        return ps;\n    }\n    public int[] nextSmallest(int[]a){\n        int ns[]=new int[a.length];\n        Deque<Integer> s=new ArrayDeque<>();\n        for(int i=a.length-1;i>=0;i--){\n            while(!s.isEmpty() && a[s.peek()]>=a[i]){\n                s.pop();\n            }\n            if(s.isEmpty()){\n                ns[i]=a.length;\n            }else{\n                ns[i]=s.peek();\n            }\n            s.push(i);\n        }\n        return ns;\n    }\n}\n"
  },
  {
    "path": "Largest number with given sum - GFG/README.md",
    "content": "# Largest number with given sum\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Geek lost the password of his super locker.&nbsp;He remembers the number of digits <strong>N</strong> as well as the sum <strong>S</strong> of all the digits&nbsp;of his password.&nbsp;He know that his&nbsp;password is the largest number of <strong>N</strong> digits that can be made with given sum <strong>S</strong>. As he&nbsp;is busy doing his homework, help him&nbsp;retrieving his password.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:\n</span></strong><span style=\"font-size:18px\">N = 5, S = 12\n<strong>Output:\n</strong>93000<strong>\nExplanation:\n</strong>Sum of elements is 12. Largest possible \n5 digit number is 93000 with sum 12.</span>\n</pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:\n</span></strong><span style=\"font-size:18px\">N = 3, S = 29\n<strong>Output:\n</strong>-1<strong>\nExplanation:\n</strong>There is no such three digit number \nwhose sum is 29.</span></pre>\n\n<p dir=\"ltr\"><strong><span style=\"font-size:18px\">Your Task :&nbsp;</span></strong><br>\n<span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function l<strong>argestNumber()</strong> which takes 2 integers <strong>N</strong>&nbsp;and <strong>S</strong> as input parameters and returns the password in the form of&nbsp;string, else return \"-1\" in the form of string.</span></p>\n\n<p dir=\"ltr\"><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤&nbsp;10<sup>4</sup><br>\n0 ≤&nbsp;S ≤ 9*10<sup>4</sup></span></p>\n\n<p dir=\"ltr\"><span style=\"font-size:18px\"><strong>Expected Time Complexity</strong> : O(N)<br>\n<strong>Expected Auxilliary Space </strong>: O(1)</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Largest number with given sum - GFG/largest-number-with-given-sum.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass Driverclass\n{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        \n        //testcases\n\t\tint t = Integer.parseInt(br.readLine().trim());\n\t\t\n\t    while(t-- >0)\n\t    {\n\t        String inputLine[] = br.readLine().trim().split(\" \");\n\t        \n\t        //taking n and sum\n            int n = Integer.parseInt(inputLine[0]);\n            int sum = Integer.parseInt(inputLine[1]);\n            \n            //calling largestNumber() function\n            System.out.println(new Solution().largestNumber(n, sum));\n\t    }\n    }\n}// } Driver Code Ends\n\n\n\nclass Solution\n{\n    //Function to return the largest possible number of n digits\n    //with sum equal to given sum.\n    static String largestNumber(int n, int sum){\n        StringBuilder sb=new StringBuilder();\n        while(n-->0){\n            if(sum!=0){\n                int num=9;\n                while(sum<num && num>0){\n                    num--;\n                }\n                sum-=num;\n                sb.append(num);\n            }else{\n                sb.append(0);\n            }\n        }\n        if(sum!=0)return \"-1\";\n        return sb.toString();\n    }\n}\n\n\n"
  },
  {
    "path": "Largest prime factor.cpp",
    "content": "class Solution{\npublic: \nbool isPrime(int N){\n    for(int i=2;i<=sqrt(N); i++){\n        if(N % i==0) return false;\n    }\n    return true;\n}\n    long long int largestPrimeFactor(int N){\n        if(isPrime(N)) return N;\n        long long int ans = 0;\n        \n        for(long long int i=N-1;i>=2;i--){\n            if(N%i==0 && isPrime(i)) return i;\n            // else cout<<i<<\" \";\n        }\n        \n    }\n};\n"
  },
  {
    "path": "Largest value in each level.java",
    "content": "class Solution\n{\n    public ArrayList<Integer> largestValues(Node root)\n    {\n        //code here\n        Map<Integer,Integer> map=new HashMap<>();\n        dfs(root,1,map);\n        ArrayList<Integer> ans=new ArrayList<>();\n        int level=1;\n        while(map.containsKey(level)){\n            ans.add(map.get(level));\n            level++;\n        }\n        return ans;\n    }\n    public void dfs(Node root,int level,Map<Integer,Integer> map){\n        if(root==null)return;\n        if(!map.containsKey(level)){\n            map.put(level,root.data);\n        }else{\n            int cur=root.data;\n            int init=map.get(level);\n            map.put(level,Math.max(cur,init));\n        }\n        dfs(root.right,level+1,map);\n        dfs(root.left,level+1,map);\n    }\n}\n"
  },
  {
    "path": "Last Node in a Complete Binary Tree.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    public int lastNode(TreeNode A) {\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(A);\n        int val=-1;\n        while(q.size()>0){\n            int sz=q.size();\n            while(sz-->0){\n                TreeNode node=q.remove();\n                if(node.left!=null)q.add(node.left);\n                if(node.right!=null)q.add(node.right);\n                val=node.val;\n            }\n        }\n        return val;\n    }\n}\n"
  },
  {
    "path": "Last digit K count.java",
    "content": "public class Solution {\n    public int solve(int A, int B, int C) {\n        while((A%10)!=C && A<B){\n            A++;\n        }\n        while((B%10)!=C && B>A){\n            B--;\n        }\n        if(A==B && A%10!=C)return 0;\n        return (B-A)/10+1;\n    }\n\n}\n"
  },
  {
    "path": "Leaders in an array.java",
    "content": "public class Solution {\n    public ArrayList<Integer> solve(ArrayList<Integer> A) {\n        int high=-1;\n        ArrayList<Integer> ans=new ArrayList<>();\n        for(int i=A.size()-1;i>=0;i--){\n            if(A.get(i)>high){\n                high=A.get(i);\n                ans.add(high);\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Leaves to DLL.java",
    "content": "class Tree{\n    // return the head of the DLL and remove those node from the tree as well.\n    public Node convertToDLL(Node root)\n   {\n       // Code here\n          if(root==null)\n            return null;\n       ArrayList<Node> al=new ArrayList<>();\n       solve(root,al);\n       Node head=al.get(0);\n       Node prev=al.get(0);\n       for(int i=1;i<al.size();i++)\n       {\n           Node curr=al.get(i);\n           prev.right=curr;\n           curr.left=prev;\n           prev=curr;\n       }\n       prev.right=null;\n       head.left=null;\n       return head;\n   }\n    static Node solve(Node root,ArrayList<Node> al)\n   {\n       if(root==null)\n       return null;\n       \n       if(root.right==null && root.left==null)\n       {\n           al.add(root);\n           return null;\n       }\n       root.left=solve(root.left,al);\n       root.right=solve(root.right,al);\n       return root;\n   }\n   \n    \n}\n"
  },
  {
    "path": "Leetcode/104 maximum depth of binary tree/104 maximum depth of binary tree.cpp",
    "content": "/**\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    int maxDepth(TreeNode* root) {\n    if(root==NULL){\n        return 0;\n    }\n    int h1=maxDepth(root->left);\n    int h2=maxDepth(root->right);\n    return 1+max(h1,h2);\n    }\n};\n"
  },
  {
    "path": "Leetcode/104 maximum depth of binary tree/104. Maximum Depth of Binary Tree.java",
    "content": "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}\n"
  },
  {
    "path": "Leetcode/104 maximum depth of binary tree/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/maximum-depth-of-binary-tree/\">104. Maximum Depth of Binary Tree</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p>\n\n<p>A binary tree's <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg\" style=\"width: 400px; height: 277px;\">\n<pre><strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><strong>Input:</strong> root = [1,null,2]\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n</div>\n"
  },
  {
    "path": "Leetcode/112 Path Sum/112 Path Sum oc4.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nstruct 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 };\nclass Solution {\npublic:\n    bool hasPathSum(TreeNode* root, int targetSum) {\n        if(!root) return false;\n        if(!root->left && !root->right && root->val == targetSum) return true;\n        return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);\n    }\n};"
  },
  {
    "path": "Leetcode/112 Path Sum/Path Sum.java",
    "content": "Solution 1:\nUsing ArrayList\n\nclass Solution {\n    public static void fun(TreeNode root, int sum , int val, ArrayList<Integer>aa){\n        if(root==null){\n            return ;\n        }\n        else if(root.left==null && root.right==null){\n            val=val+root.val;\n            aa.add(val);\n            return ;\n        }\n        else{\n            fun(root.left,sum,val+root.val,aa);\n            fun(root.right,sum,val+root.val,aa);\n        }\n    }\n    public boolean hasPathSum(TreeNode root, int sum) {\n        if(root==null){\n            return false;\n        }\n        else{\n            ArrayList<Integer>aa=new ArrayList<Integer>();\n            fun(root,sum,0,aa);\n           // System.out.println(aa);\n            if(aa.contains(sum)){\n                return true;\n            }\n            return false;\n        }\n    }\n}\n\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\nSolution 2:\nWithout Using ArrayList\n\nclass Solution {\n    boolean status=false;\n    public void fun(TreeNode root, int sum,int s, boolean status){\n        if(root==null){\n            return;\n        }\n        else if(root.left==null && root.right==null){\n           s=s+root.val;\n            if(s==sum){\n                this.status=true;\n            }\n        }\n        else{\n            fun(root.left,sum,s+root.val,status);\n            fun(root.right,sum,s+root.val,status);\n        }\n    }\n   \n    public boolean hasPathSum(TreeNode root, int sum) {\n        if(root==null){\n            return false;\n        }\n        else{\n            \n            fun(root,sum,0,status);\n            if(status==true){\n                return true;\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "Leetcode/1155. Number of Dice Rolls With Target Sum/1155 Number of Dice Rolls With Target Sum.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define MOD 1000000007\nclass Solution {\npublic:\n    long long solve(int dice, int faces, int target, vector<vector<long long>> &dp){\n        //         top down appr\n        if(target <0) return 0;\n        if(dice ==0 and target != 0 || target==0 and dice !=0) return 0;\n        if(target ==0 and dice ==0) return 1;\n        if(dp[dice][target] != -1)\n            return dp[dice][target];\n        long long res =0;\n        for(int i =1; i<= faces; i++){\n            res = (res + solve(dice - 1, faces, target - i, dp))%MOD;\n        }\n        return dp[dice][target] = res;\n    }\n    int numRollsToTarget(int n, int k, int target) {\n        vector<vector<long long>> dp(n + 1, vector<long long>(target + 1, -1));\n        return solve(n, k, target, dp);\n    }\n};"
  },
  {
    "path": "Leetcode/1155. Number of Dice Rolls With Target Sum/1155. Number of Dice Rolls With Target Sum.java",
    "content": "class Solution {\n    static int MOD = (int)1e9 + 7;\n    int helper(int n,int t,int k,int dp[][]){\n        if(n < 0 || t < 0) return 0;\n        if(n == 0 && t == 0) return 1;\n        if(dp[n][t] != -1) return dp[n][t];\n        int c_ans = 0;\n        for(int i = 1;i <= k;i++){\n            c_ans = (c_ans + helper(n - 1,t - i,k,dp)) % MOD;\n        }\n        return dp[n][t] = c_ans;\n    }\n    public int numRollsToTarget(int n, int k, int target) {\n        int dp[][] =  new int[n + 1][target + 1];\n        for(var a:dp) Arrays.fill(a,-1);\n        return helper(n,target,k,dp);\n    }\n}"
  },
  {
    "path": "Leetcode/1155. Number of Dice Rolls With Target Sum/1155. Number of Dice Rolls With Target Sum.py",
    "content": "class Solution:\n    def numRollsToTarget(self, n: int, k: int, target: int) -> int:\n        dicti={}\n        m=(10**9)+7\n        def rec(i,res):\n            if i in dicti:\n                if res in dicti[i]:\n                    return dicti[i][res]\n            if res>=target or res+n-i>target or res+(n-i)*k<target:\n                return 0\n            if i==n-1 and res+k>=target:\n                return 1\n            temp=0\n            for j in range(1,k+1):\n                temp+=rec(i+1,res+j)\n            if i not in dicti:\n                dicti[i]={}\n            dicti[i][res]=temp\n            return temp%m\n        return rec(0,0)\n"
  },
  {
    "path": "Leetcode/1217. Minimum Cost to Move Chips to The Same Position/1217. Minimum Cost to Move Chips to The Same Position.java",
    "content": "class Solution {\n\npublic int minCostToMoveChips(int[] position) {\n    int even = 0;\n    int odd = 0;\n    for(int i=0; i<position.length; i++) {\n        if(position[i] % 2 == 0){ \n            odd++;\n        } else { \n            even++;\n     }\n    }\n    return Math.min(odd, even);\n}\n}\n"
  },
  {
    "path": "Leetcode/1217. Minimum Cost to Move Chips to The Same Position/Notes.md",
    "content": "\n"
  },
  {
    "path": "Leetcode/1217. Minimum Cost to Move Chips to The Same Position/README.md",
    "content": "# [1217. Minimum Cost to Move Chips to The Same Position](https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/)\n\n## Easy\n\n\nWe have n chips, where the position of the ith chip is position[i].\n\nWe need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:\n\nposition[i] + 2 or position[i] - 2 with cost = 0.\nposition[i] + 1 or position[i] - 1 with cost = 1.\nReturn the minimum cost needed to move all the chips to the same position.\n\n \n\n### Example 1:\n![image](https://user-images.githubusercontent.com/78613699/193616422-20bfea65-c8a4-4f16-9611-359f03a4c25a.png)\n\n\n\nInput: position = [1,2,3]\n\nOutput: 1\n\nExplanation: First step: Move the chip at position 3 to position 1 with cost = 0.\nSecond step: Move the chip at position 2 to position 1 with cost = 1.\nTotal cost is 1.\n### Example 2:\n![image](https://user-images.githubusercontent.com/78613699/193616478-5840c53b-0f81-42c9-9439-efb16bb7e1f8.png)\n\n\nInput: position = [2,2,2,3,3]\n\nOutput: 2\n\nExplanation: We can move the two chips at position  3 to position 2. Each move has cost = 1. The total cost = 2.\n"
  },
  {
    "path": "Leetcode/1252. Cells with Odd Values in a Matrix/1252. Cells with Odd Values in a Matrix.java",
    "content": "class Solution {\n    public int oddCells(int m, int n, int[][] indices) {\n        int arr[][] = new int[m][n];\n        int count=0;\n        for(int i=0 ; i<indices.length ; i++){\n            for(int j=0 ; j<indices[i].length ; j++){\n                int a = indices[i][j];\n                if(j==0){\n                    increment1(a,arr); \n                    }\n                else{\n                    increment2(a,arr);\n                }\n            }\n            \n        }\n        // for(int i=0 ; i< arr.length ; i++){\n        //     for(int j=0; j<arr[0].length ; j++){\n        //         System.out.print(arr[i][j]);\n        //     }\n        //     System.out.println();\n        // }\n        count =cunt(arr,m,n);\n        return count;\n    }\n    \n    static void increment1(int b , int[][] arr){\n            // #this is to increase the value of the row\n            for(int i=0; i<arr[b].length; i++){\n                arr[b][i]+=1;\n            }\n        }\n    \n    static void  increment2(int c,int[][]arr){\n            \n            // #this is to increase the value of the column\n            for(int i=0; i<arr.length; i++){\n                arr[i][c]+=1;\n            }  \n        }\n    \n    static int cunt(int[][] brr, int m , int n)\n        {\n            int add=0;\n            for(int i=0; i<m; i++){\n                for(int j=0; j<n ; j++){\n                    if(brr[i][j] %2 != 0){\n                        add+=1;\n                    }\n                }\n            }\n        System.out.println(add);\n        return add;\n        }\n        \n    }\n"
  },
  {
    "path": "Leetcode/1252. Cells with Odd Values in a Matrix/Notes.md",
    "content": "\n"
  },
  {
    "path": "Leetcode/1252. Cells with Odd Values in a Matrix/README.md",
    "content": "[1252\\. Cells with Odd Values in a Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/)\n============================================================================================================\n\n**Easy**\n\n* * *\n\nThere is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each  \nindices\\[i\\] = \\[ri, ci\\] represents a `0-indexed location` to perform some increment operations on  \nthe matrix.\n\nFor each location indices\\[i\\], do both of the following:\n\n1.  Increment all the cells on row ri.\n2.  Increment all the cells on column ci.\n\nGiven m, n, and indices, return the number of odd-valued cells in the matrix after applying the  \nincrement to all locations in indices.\n\n**Example 1:**\n--------------\n\n![](https://assets.leetcode.com/uploads/2019/10/30/e1.png)\n\n**Input:** m = 2, n = 3, indices = \\[\\[0,1\\],\\[1,1\\]\\]\n\n**Output:** 6\n\n**Explanation :** 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**Example 2:**\n--------------\n\n![](https://assets.leetcode.com/uploads/2019/10/30/e2.png)\n\n**Input :** m = 2, n = 2, indices = \\[\\[1,1\\],\\[0,0\\]\\]\n\n**Output :** 0\n\n**Explanation :** Final matrix = \\[\\[2,2\\],\\[2,2\\]\\]. There are no odd numbers in the final  \nmatrix.\n\n**Constraints :**\n-----------------\n\n*   1 <= m, n <= 50 \n*   1 <= indices.length <= 100 \n*   0 <= ri < m \n*   0 <= ci < n   `\n\n### **Follow up :**\n\nCould you solve this in O(n + m + indices.length) time with only O(n + m) extra space?\n"
  },
  {
    "path": "Leetcode/1304.Find N Unique Integers Sum up to Zero/1304.Find N Unique Integers Sum up to Zero.java",
    "content": "class Solution {\n    public int[] sumZero(int n) {\n        int arr[] = new int[n];\n        int len=n/2;\n        if(n%2 != 0){\n            for(int i=0 ; i<len ; i++){\n                arr[i]= i+1;\n                arr[i+len] = -(i+1);\n            }\n            arr[n-1] = 0;\n        }\n        else{\n            for(int i=0 ; i<len ; i++){\n                arr[i]= i+1;\n                arr[i+len] = -(i+1);\n            }\n        }\n        return arr;\n    }\n}\n"
  },
  {
    "path": "Leetcode/1304.Find N Unique Integers Sum up to Zero/Notes.md",
    "content": "\n"
  },
  {
    "path": "Leetcode/1304.Find N Unique Integers Sum up to Zero/README.md",
    "content": "**[1304\\. Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/)**\n------------------------------------------------------------------------------------------------------------------------\n\nEasy\n----\n\n* * *\n\nGiven an integer n, return any array containing n unique integers such that they add up to 0.\n\n  \n  \n\nExample 1:\n==========\n\n**Input:** n = 5 \n\n**Output:** [-7,-1,1,3,4]\n  \n**Explanation:** These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].   `\n\nExample 2:\n==========\n\n **Input:** n = 3  \n\n  **Output:** [-1,0,1]   `\n\nExample 3:\n==========\n\n **Input:** n = 1  \n\n **Output:** [0]   `\n\nConstraints\n===========\n\n`1 <= n <= 1000`\n"
  },
  {
    "path": "Leetcode/15. 3Sum/3sum.java",
    "content": "// solution of 3sum problem in leetcode\n\npublic class Solution {\n    public List<List<Integer>> threeSum(int[] num) {\n        List<List<Integer>> result = new ArrayList<List<Integer>>();\n        if (num.length < 3) {\n            return result;\n        }\n        Arrays.sort(num);\n        for (int i = 0; i < num.length - 2; i++) {\n            if (i > 0 && num[i] == num[i - 1]) {\n                continue;\n            }\n            int j = i + 1;\n            int k = num.length - 1;\n            while (j < k) {\n                if (num[i] + num[j] + num[k] == 0) {\n                    List<Integer> list = new ArrayList<Integer>();\n                    list.add(num[i]);\n                    list.add(num[j]);\n                    list.add(num[k]);\n                    result.add(list);\n                    j++;\n                    k--;\n                    while (j < k && num[j] == num[j - 1]) {\n                        j++;\n                    }\n                    while (j < k && num[k] == num[k + 1]) {\n                        k--;\n                    }\n                } else if (num[i] + num[j] + num[k] < 0) {\n                    j++;\n                } else {\n                    k--;\n                }\n            }\n        }\n        return result;\n    }\n}\n"
  },
  {
    "path": "Leetcode/15. 3Sum/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/3sum/description/\">15. 3Sum</a></h2>\n<h3>Medium</h3>\n<hr>\n<div>\n  <p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>. Notice that the solution set must not contain duplicate triplets.</p>\n  <p>Notice that the solution set must not contain duplicate triplets.</p>\n  \n  <p>&nbsp;</p>\n  <p><strong>Example 1:</strong></p>\n  <pre>\n  <strong>Input:</strong> nums = [0,1,1]\n  <strong>Output:</strong> []\n  <strong>Explanation:</strong> The only possible triplet does not sum up to 0.\n  </pre>\n  <p><strong>Example 2:</strong></p>\n  <pre>\n  <strong>Input:</strong> nums = [-1,0,1,2,-1,-4]\n  <strong>Output:</strong> [[-1,-1,2],[-1,0,1]]\n  <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\n  nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\n  nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\n  The distinct triplets are [-1,0,1] and [-1,-1,2].\n  Notice that the order of the output and the order of the triplets does not matter.\n  </pre>\n</div>\n"
  },
  {
    "path": "Leetcode/151.Reverse Words in a String/Reverse Words in a String.java",
    "content": "class Solution {\n    public String reverseWords(String s) {\n      \n        String s1=s.trim();\n        StringBuilder sb=new StringBuilder();\n        ArrayList<String>aa=new ArrayList<String>();\n        int i=0;\n        while(i<s.length()){\n            if(s.charAt(i)==' '){\n                if(sb.length()!=0){\n                    aa.add(sb.toString());\n                    sb.setLength(0);\n                }\n                i++;\n            }\n            else{\n                sb.append(s.charAt(i));\n                i++;\n            }\n        }\n        if(sb.length()!=0){\n            aa.add(sb.toString());\n        }\n        sb.setLength(0);\n        for(int i1=aa.size()-1;i1>-1;i1--){\n            sb.append(aa.get(i1));\n            sb.append(\" \");\n        }\n        sb.setLength(sb.length()-1);\n        return sb.toString();\n    }\n}\n"
  },
  {
    "path": "Leetcode/1531. String Compression II/1531. String Compression II.cpp",
    "content": "class Solution {\npublic:\n\n int helper(int currIdx,int prevchar,int curFreq,int k, vector<vector<vector<vector<int>>>> &dp, string &s)\n    {\n        if(k < 0) return 100000000;\n        if(currIdx >= s.size()) return 0;\n        \n    // if curCharFreqCount, consider it as 10, because, until 10 .. 99, string length will be 2, \n        if(curFreq >= 10) curFreq = 10;\n        if(dp[currIdx][prevchar][curFreq][k] != -1) return dp[currIdx][prevchar][curFreq][k];\n        \n//         // exclude\n           int res = 100000000;\n   \n         /*\n        3 cases:\n        case 1: We will delete our current character if K is available, so our string length will be minimum.\n        case 2: If cur char is not same as prev, our res will be increased by 1 and curCharFreqCount will be 1\n        case 3: If cur char is same as prev char, we need to merge it and increase our count\n                case 3.1: If curCharFreqCount is either 1 or more than 9, our res will be increased by 1\n                case 3.2: Else, we just need to increase curCharFreqCount.\n        */\n           res = min(res, helper(currIdx + 1, prevchar, curFreq, k - 1, dp, s));\n   \n//         // include\n        if(s[currIdx] - 'a' != prevchar)\n        {\n            res = min(res, 1 + helper(currIdx + 1, s[currIdx] - 'a', 1, k, dp, s));\n        }\n        else\n        {\n            if(curFreq == 1 || curFreq == 9)\n            {\n                res = min(res, 1 + helper(currIdx + 1, prevchar, curFreq + 1, k, dp, s));\n            }\n            else res = min(res, helper(currIdx + 1, prevchar, curFreq + 1, k, dp, s));\n        }\n        \n        return dp[currIdx][prevchar][curFreq][k] = res;\n    }\n    int getLengthOfOptimalCompression(string s, int k) {\n        int n = s.size();\n        vector<vector<vector<vector<int>>>> dp(n+1, vector<vector<vector<int>>>(28, vector<vector<int>>(11, vector<int>(n+1, -1))));\n        string p = s;\n        if(n == 100)\n        {\n            bool isSame = true;\n            sort(s.begin(), s.end());\n            for(int i = 1; i < s.size(); i++)\n            {\n                if(s[i] != s[i-1])\n                {\n                    isSame = false;\n                    break;\n                }\n            }\n            if(isSame) return 4;\n        }\n        s = p;\n        \n        return helper(0, 27, 0, k, dp, s);\n    }\n\n};\n"
  },
  {
    "path": "Leetcode/1578 Minimum Time to Make Rope Colorful/1578 Minimum Time to Make Rope Colorful.cpp",
    "content": "//There are two approch for this Problem both approch are optimal also both uses O(n) Time Complexity\n\n#include<bits/stdc++.h>\nusing namespace std;\n\n\n//===========================Approch 1======================\n\n\nclass Solution {\npublic:\n    int minCost(string s, vector<int>& time) {\n        int ans = 0;\n        int n = s.length();\n        for(int i = 1; i < n; i++)\n        {\n            if(s[i] == s[i - 1])\n            {\n                ans += min(time[i], time[i - 1]); \n                time[i] = max(time[i], time[i - 1]); \n            }     \n        }\n        \n        return ans;\n    }\n};\n\n\n//===========================Approch 2 =========================\n\n\n\n\nclass Solution {\npublic:\n    int minCost(string colors, vector<int>& neededTime) {\n//         initializing 2 pointers\n        int totalTime =0, i =0, j =0;\n        while(i<neededTime.size() && j < neededTime.size()){\n            int currTotal =0, currMax =0;\n//             find all balloons having the same color as the balloon indexed[i], record the total removal time & maxi removal time\n            while(j < neededTime.size() && colors[i]== colors[j]){\n                currTotal+= neededTime[j];\n                currMax = max(currMax, neededTime[j]);\n                j++;\n            }\n//             once we reach the end of the curr group, add the cost of this group to total_time, & reset 2 pointers\n            totalTime+=currTotal-currMax;\n            i=j;\n        }\n        return totalTime;\n//         TC: O(n), SC: O(1)\n    }\n};\n"
  },
  {
    "path": "Leetcode/1578. Minimum Time to Make Rope Colorful/1578. Minimum Time to Make Rope Colorful.py",
    "content": "class Solution:\n    def minCost(self, colors: str, neededTime: List[int]) -> int:\n        lenC = len(colors)\n        temp = []\n        count = 0\n        ans = 0\n        for x in range(0,lenC):\n            if x == lenC-1:\n                if colors[x] == colors[x-1]:\n                    temp.append(neededTime[x])\n                    count+=1\n                    temp = sorted(temp)\n                    if len(temp) > 1:\n                        for i in range(0,count-1):\n                            ans+=temp.pop(0)\n                        temp = []\n                        count = 0\n                    else:\n                        temp = []\n                        count = 0\n                        \n            elif colors[x] == colors[x+1]:\n                temp.append(neededTime[x])\n                count += 1\n            else:\n                temp.append(neededTime[x])\n                count+=1\n                temp = sorted(temp)\n                if len(temp) > 1:\n                    for i in range(0,count-1):\n                        ans+=temp.pop(0)\n                    temp = []\n                    count=0\n                else:\n                    temp = []\n                    count=0\n        return ans\n"
  },
  {
    "path": "Leetcode/1662. Check If Two String Arrays are Equivalent/Check If Two String Arrays are Equivalent.java",
    "content": "Using StringBuilder Objects:\n\nclass Solution {\n    public boolean arrayStringsAreEqual(String[] word1, String[] word2) {\n        StringBuilder sb1=new StringBuilder();\n         StringBuilder sb2=new StringBuilder();\n        \n        for(String a:word1){\n            sb1.append(a);\n        }\n        \n        \n        for(String a:word2){\n            sb2.append(a);\n        }\n        \n        if(sb1.toString().equals(sb2.toString())){\n            return true;\n        }\n        return false;\n        \n        \n        \n    }\n}\n\n=======================================================================================================================================================================\n  \nWithout Using StringBuilder objects:\n\nclass Solution {\n    public boolean arrayStringsAreEqual(String[] word1, String[] word2) {\n        String sum=null;\n        String sum2=null;\n        \n        for(int i=0;i<word1.length;i++)\n        {\n            sum=sum+word1[i];\n        }\n        for(int i=0;i<word2.length;i++)\n        {\n            sum2=sum2+word2[i];\n        }\n        if(sum.equals(sum2))\n            return true;\n        else\n            return false;\n    }\n}\n\n"
  },
  {
    "path": "Leetcode/19 Remove Nth Node From End of List/19 Remove Nth Node From End of List.cpp",
    "content": "//Here are two Approach both one are optimal first Approch use O(n) time complexity and second Approch use O(n^2) time complexity\n\n//===================================== Approch 1 ==========================================\n\nclass Solution {\npublic:\n    ListNode* removeNthFromEnd(ListNode* head, int n) {\n        int count =0;\n        ListNode* p = head;\n        while(p!=NULL){\n            count++;\n            p=p->next;\n        }\n        \n        if(count==1){\n            return NULL;\n        }\n        \n        int x = count-n;\n        if(x==0){\n            return head->next;\n        }\n        p = head;\n        for(int i =0;i<x-1;i++){\n            p=p->next;\n        }\n        p->next = p->next->next;\n        return head;\n    }\n};\n\n\n\n\n//=============================Approch 2 ========================================================\n\n\n\n#include<bits/stdc++.h>\nusing namespace std;\n\n/**\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* removeNthFromEnd(ListNode* head, int n) {\n        ListNode *prev = head, *NextNode = head;\n        \n        for(int i =0; i<n; i++)\n            prev = prev->next;\n            if(!prev) return head->next;\n            \n            while(prev->next){\n                NextNode = NextNode->next;\n                prev = prev->next;\n            }\n            NextNode->next = NextNode->next->next;\n        return head;\n    }\n};\n"
  },
  {
    "path": "Leetcode/19 Remove Nth Node From End of List/Remove Nth Node from End Of List.java",
    "content": "Solution 1:\n\nUsing ArrayList as additional Space\nTime: 2ms \nSpace: 42.3Mb\n\n\nArrayList<Integer>aa=new ArrayList<Integer>();\n        ListNode temp=head;\n        while(temp!=null){\n            aa.add(temp.val);\n            temp=temp.next;\n        }\n        aa.remove(aa.size()-n);\n        ListNode temp2=new ListNode(-1);\n        ListNode temp3=temp2;\n        for(int i=0;i<aa.size();i++){\n            temp2.next=new ListNode(aa.get(i));\n            temp2=temp2.next;\n        }\n        ListNode temp4=temp3.next;\n        return temp4; \n\n\nSolution 2:\n\nWithout Using additonal space\nTime: 0ms \nSpace: 42.5Mb\n\nclass Solution {\n    public ListNode removeNthFromEnd(ListNode head, int n) {\n    \n        if(head.next==null){\n            return null;\n        }\n        ListNode temp=head;\n        int count=0;\n        while(temp!=null){\n            count++;\n            temp=temp.next;\n        }\n        int val=count-n;\n        if(count==n){\n            ListNode temp2=head;\n            return temp2.next;\n        }\n        count=0;\n        \n        ListNode temp1=head;\n        ListNode temp2=null;\n        while(count!=val){\n            count++;\n            temp2=temp1;\n            temp1=temp1.next;\n        }\n        ListNode newnext=temp1.next;\n        temp2.next=newnext;\n        ListNode temp5=head;\n        return temp5;\n    \n    \n    }\n    \n}\n"
  },
  {
    "path": "Leetcode/1996. The Number of Weak Characters in the Game/The Number of Weak Characters in the Game.cpp",
    "content": "class Solution {\npublic:\n    \n    static bool comp(vector<int> &a,vector<int> &b){\n        if(a[0]!=b[0])\n            return a[0]>b[0];\n        return a[1]<b[1];\n    }\n    \n    int numberOfWeakCharacters(vector<vector<int>>& p) {\n       sort(p.begin(),p.end(),comp);\n        int max = INT_MIN;\n        int ans=0;\n        for(auto it:p){\n            if(max>it[1]){\n                ans++;\n            }\n            else{\n                max = it[1];\n            }\n        }\n        return ans;\n    }\n};\n\n\n///===============Approch 1=========================\n\n\n// int n = properties.size();\n//         int weakp=0;\n//         for(int i =0;i<n-1;i++){\n//             for(int j =0;j<properties[0].size()-1;j++){\n//                 if(properties[i][j]<properties[i+1][j+1]){\n//                     weakp++;\n//                 }    \n//             }\n//         }\n//         return weakp;\n\n\n\n\n//==================Approch 2======================\n // vector<pair<int,int>> v;\n //        int n = properties.size();\n //        for(int i =0;i<n;i++){\n //            v.push_back({properties[i][0],properties[i][1]});\n //        }\n //        sort(v.begin(),v.end());\n //        int ans=0;\n //        vector<int> m(v.size(),0);\n //        int i =0;\n //        for(auto it:v){\n //            int x = it.first;\n //            int y = it.second;\n //            for(auto it1:v){\n //                if(x<it1.first&&y<it1.second&&m[i]==0){\n //                    m[i]=1;\n //                    ans++;\n //                }\n //            }\n //            i++;\n //        }\n //        return ans;\n"
  },
  {
    "path": "Leetcode/2095. Delete the Middle Node of a Linked List/2095 Delete the Middle Node of a Linked List.java",
    "content": "/**\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 deleteMiddle(ListNode head) {\n        if(head == null || head.next == null){\n            return null;\n        }\n        else{\n            ListNode slow = head;\n            ListNode fast = head.next.next;\n            while(fast != null && fast.next != null ){\n                slow= slow.next;\n                fast = fast.next.next;\n            }\n            slow.next = slow.next.next;\n        }\n        return head;\n        \n    }\n}\n"
  },
  {
    "path": "Leetcode/2095. Delete the Middle Node of a Linked List/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/\">2095. Delete the Middle Node of a Linked List</a></h2><h3>Medium</h3><hr><div><p>You are given the <code>head</code> of the Linked List. Delete the middle node and return the <code>head</code>of the modified linked list. The middle node of the list of size <code>n</code> is the <code>[n/2]th</code>node from the start using 0-based indexing, where <code>[x]</code>denotes the largest integer less than or equal to <code>x</code>\n \n <p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png\" style=\"height: 150px; width: 650px;\">\n<pre><strong>Input:</strong> tops = [2,1,2,4,2,2]\n<strong>Output:</strong> [1,3,4,1,2,6]\n<strong>Explanation:</strong> \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</pre>\n\n \n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>The number of nodes in the list is in the range [1, 10]<sup>5</sup></code></li>\n <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n</div>\n"
  },
  {
    "path": "Leetcode/2124. Check if All A's Appears Before All B's/2124. Check if All A's Appears Before All B's.java",
    "content": "Code :\nclass Solution {\n    public boolean checkString(String s) {\n       int indexb=s.indexOf(\"b\");\n       int indexa=s.lastIndexOf(\"a\");\n       if(indexa!=-1 && indexb!=-1 && indexa>indexb){\n           return false;\n       }\n       else if(indexa==-1 || indexb==-1){\n           return true;\n       }\n        return true;\n    }\n}\n\nTime Complexity:O(String Length)[As indexOf() method will found out the index of a particular character after thraversing the whole string]\nSpace Complexity:O(1)\nAuxiliary Space:O(1)\n  \nLeetcode Time:1ms beats 86.26%\nLeetcode Space:42.2Mb beats 42.38%\n  \n  \n"
  },
  {
    "path": "Leetcode/218 The Skyline Problem/218 The Skyline Problem s30.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {\n       vector<vector<int>> res;\n        multiset<int> pq{0};\n        \n        vector<pair<int, int>> points;\n        \n        for(auto b: buildings){\n            points.push_back({b[0], -b[2]});\n            points.push_back({b[1], b[2]});\n        }\n        \n        sort(points.begin(), points.end());\n        \n        int ongoingHeight = 0;\n        \n        for(int i = 0; i < points.size(); i++){\n            int currentPoint = points[i].first; // x coordinate\n            int heightAtCurrentPoint = points[i].second; // ht\n            \n            if(heightAtCurrentPoint < 0){\n                pq.insert(-heightAtCurrentPoint);\n            } else {\n                pq.erase(pq.find(heightAtCurrentPoint));\n            }\n            \n            auto pqTop = *pq.rbegin();\n            if(ongoingHeight != pqTop){\n                ongoingHeight = pqTop;\n                res.push_back({currentPoint, ongoingHeight});\n            }\n        }\n        \n        return res; \n    }\n};"
  },
  {
    "path": "Leetcode/221. Maximal Square/221. Maximal Square.java",
    "content": "class Solution {\n    public int maximalSquare(char[][] matrix) {\n        int rows = matrix.length;\n        int cols = matrix[0].length;\n        int maxSquare = 0;\n        int[][] maxSideLength = new int[rows+1][cols+1];\n\n        for(int i=rows-1;i>=0;i--){\n            for(int j=cols-1;j>=0;j--){\n                if(matrix[i][j] == '1'){\n                    // maximum sideLength of square is minimum of length covered by either of row, column, diagonal\n                    maxSideLength[i][j] = Math.min(maxSideLength[i+1][j],Math.min(maxSideLength[i][j+1],maxSideLength[i+1][j+1]))+1;\n                    maxSquare = Math.max(maxSquare, maxSideLength[i][j]);\n                }else{\n                    maxSideLength[i][j] = 0;\n                }\n            }\n        }\n        return maxSquare*maxSquare;\n    }\n}\n   "
  },
  {
    "path": "Leetcode/222. Count Complete Tree Nodes/Count Complete Tree Nodes.java",
    "content": "class Solution {\n    int count = 0;\n    public int countNodes(TreeNode root) {\n        if(root==null) return 0;\n        countNodes(root.left);\n        count++;\n        System.out.print(root.val+\" \");\n        countNodes(root.right);\n        return count;\n    }\n}\n"
  },
  {
    "path": "Leetcode/2368. Reachable Nodes With Restrictions/Reachable Nodes With Restrictions.cpp",
    "content": "class Solution {\npublic:\n    \n    void dfs(vector<int> adj[],vector<int>&vis,int node,int &no){\n        vis[node]=1;\n        no++;\n        for(auto it:adj[node]){\n            if(vis[it]==0){\n                dfs(adj,vis,it,no);\n            }\n        }\n    }\n    \n    int reachableNodes(int n, vector<vector<int>>& edges, vector<int>& res) {\n        vector<int> adj[n];\n        vector<int> v(n,0);\n        for(int i =0;i<edges.size();i++){\n            adj[edges[i][0]].push_back(edges[i][1]);\n            adj[edges[i][1]].push_back(edges[i][0]);\n        }\n        \n        for(auto a:res){\n            v[a]=1;\n        }\n        int no=0;\n        dfs(adj,v,0,no);\n        return no;\n    }\n};\n"
  },
  {
    "path": "Leetcode/237. Delete Node in a Linked List/Delete Node in a Linked List.cpp",
    "content": "/**\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        // swap(node,node->next);\n        // ListNode* temp = node;\n        int temp = node->next->val;\n        node->next->val = node->val;\n        node->val = temp;\n        node->next = node->next->next;\n        // ListNode *t = node->next;\n        // free(node);\n        // node = t;\n        // free(t);\n        // cout<<node->val<<endl;\n    }\n};\n"
  },
  {
    "path": "Leetcode/237. Delete Node in a Linked List/Delete Node in a Linked List.java",
    "content": "class Solution {\n    public void deleteNode(ListNode node) {\n     \n        ListNode newnode=node.next;\n        node.val=newnode.val;\n        node.next=newnode.next;\n        \n    }\n}\n"
  },
  {
    "path": "Leetcode/2424. Longest Uploaded Prefix/2424. Longest Uploaded Prefix.java",
    "content": "/*\n You are given a stream of n videos, each represented by a distinct number from 1 to n that you need to \"upload\" to a server. You need to implement a data structure that calculates the length of the longest uploaded prefix at various points in the upload process.\n\nWe consider i to be an uploaded prefix if all videos in the range 1 to i (inclusive) have been uploaded to the server. The longest uploaded prefix is the maximum value of i that satisfies this definition.\n\nImplement the LUPrefix class:\n\nLUPrefix(int n) Initializes the object for a stream of n videos.\nvoid upload(int video) Uploads video to the server.\nint longest() Returns the length of the longest uploaded prefix defined above.\n \n\nExample 1:\n\nInput\n[\"LUPrefix\", \"upload\", \"longest\", \"upload\", \"longest\", \"upload\", \"longest\"]\n[[4], [3], [], [1], [], [2], []]\nOutput\n[null, null, 0, null, 1, null, 3]\n\nExplanation\nLUPrefix server = new LUPrefix(4);   // Initialize a stream of 4 videos.\nserver.upload(3);                    // Upload video 3.\nserver.longest();                    // Since video 1 has not been uploaded yet, there is no prefix.\n                                     // So, we return 0.\nserver.upload(1);                    // Upload video 1.\nserver.longest();                    // The prefix [1] is the longest uploaded prefix, so we return 1.\nserver.upload(2);                    // Upload video 2.\nserver.longest();                    // The prefix [1,2,3] is the longest uploaded prefix, so we return 3.\n \n\nConstraints:\n\n1 <= n <= 105\n1 <= video <= 105\nAll values of video are distinct.\nAt most 2 * 105 calls in total will be made to upload and longest.\nAt least one call will be made to longest.\n */\n\n // SOLUTION\nclass LUPrefix {\n    int count=0;\n            boolean [] arr;    \n        public LUPrefix(int n) {\n    arr=new boolean[n];\n            \n        }\n        \n        public void upload(int video) {\n            \n            \n            arr[video-1]=true;\n            while(count<arr.length && arr[count]){\n                count++;\n            }\n                \n        }\n        \n        public int longest() {\n            return count;\n            \n            \n        }\n    }\n    \n    /**\n     * Your LUPrefix object will be instantiated and called as such:\n     * LUPrefix obj = new LUPrefix(n);\n     * obj.upload(video);\n     * int param_2 = obj.longest();\n     */"
  },
  {
    "path": "Leetcode/2427. Number of Common Factors/2427. Number of Common Factors.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std ; \n\nclass Solution {\npublic:\n    int commonFactors(int a, int b) {\n        \n        int count = 1 ; \n        \n        for(int i = 2 ; i <= b ; i++ )\n        {\n            if(a % i == 0 && b % i == 0)\n            {\n                count ++ ; \n            }\n        }\n        return count ; \n    }\n};\n"
  },
  {
    "path": "Leetcode/2428. Maximum Sum of an Hour Glass/2428. Maximum Sum of an Hour Glass.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std ; \n\nclass Solution {\npublic:\n    int maxSum(vector<vector<int>>& grid) {\n        int m = grid.size() ; \n        // Gives the no. of rows in a matrix. \n        int n = grid[0].size() ; \n        // Gives the no. of columns in a matrix. \n\n        int sum = 0 ; \n        // Initialised a variable for calculating the sum. \n        int maxi = 0 ; \n        // Initialized a variable for comparing and finding the maximum sum. \n        for(int i = 1 ; i < m - 1 ; i++) \n        {\n            for(int j = 1 ; j < n - 1 ; j++)\n            {\n                // Carefully, Access all the grid indices in the form of hour glass by sticking to one point. \n                // Avoid accessing the wrong indices and indices out of bound. \n                sum += grid[i][j] + grid[i + 1][j] + grid[i + 1][j  - 1] + grid[i + 1][j + 1] + grid[i - 1][j] + grid[i - 1][j + 1] + grid[i - 1][j - 1] ; \n                maxi = max(sum , maxi) ; \n                // Used the inbuilt max function of C++ to comapare the previous and curreent values. \n\n                sum = 0 ; \n                // Again, initialised the sum to be zero so that for next iteration it will again start from zero. \n\n            }\n\n        }\n        return maxi ; \n        // Return the maximum sum after completing all the iterations. \n// Generalised, Time Complexity of the solution is - O(N^2) -  As the nested loop is involved. \n    }\n};\n"
  },
  {
    "path": "Leetcode/263. Ugly Number/263. Ugly Number.cpp",
    "content": "class Solution {\npublic:\n    bool isUgly(int n) {\n        if(n == 0) return false;\n        if(n == 1) return true;\n        \n        while(n%2==0)\n        {\n            n = n/2;\n        }\n        while(n%3==0)\n        {\n            n = n/3;\n        }\n        while(n%5==0)\n        {\n            n = n/5;\n        }\n        \n       return n == 1 ? true:false;\n    }\n};\n"
  },
  {
    "path": "Leetcode/279. Perfect Squares/279. Perfect Squares.cpp",
    "content": "class Solution {\n    int solve(int ind, vector<int> &nums, int tar, vector<vector<int>> &dp)\n    {\n        if(tar == 0) \n            return 0;\n        \n        if(ind == 0)\n             return tar; \n        \n        \n        if(dp[ind][tar] != -1) return dp[ind][tar];\n        \n        int excl = solve(ind-1, nums, tar, dp);\n        int incl = 1e9;\n        if(nums[ind] <= tar)\n            incl = 1 + solve(ind, nums, tar-nums[ind], dp);\n        \n        return dp[ind][tar] = min(excl, incl);\n    }\npublic:\n    int numSquares(int n) {\n        \n        if(n <= 3) return n;\n        \n        vector<int> nums;\n        \n        for(int i = 1; i*i <= n; i++)\n        {\n            nums.push_back(i*i);\n            \n        }\n        int m = nums.size();\n        \n        vector<vector<int>> dp(m+1, vector<int>(n+1, -1));  //n is target\n        \n        return solve(m-1, nums, n , dp);\n    }\n};\n"
  },
  {
    "path": "Leetcode/336. Palindrome Pairs/336. Palindrome Pairs.java",
    "content": "class Solution {\n    static int palindromepair(int N, String arr[]) {\n        for(int i = 0; i< N;i++){\n            for(int j =0; j< N;j++){\n                if(i!=j){\n                    String newStr = arr[i]+arr[j];\n                    if(isPalindrome(newStr)) return 1;\n                }\n            }\n        }\n        return 0;\n    }\n    \n    \n    static boolean isPalindrome(String input){\n        int i = 0;\n        int j = input.length() - 1;\n \n        while (i < j) {\n            if (input.charAt(i) != input.charAt(j)) {\n                return false;\n            }\n            i++;\n            j--;\n        }\n \n        return true;\n    }\n};\n"
  },
  {
    "path": "Leetcode/336. Palindrome Pairs/336. Palindrome pairs.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n\nstruct TrieNode {\n    TrieNode *next[26] = {};\n    int index = -1;\n    vector<int> palindromeIndexes;\n};\n\nclass Solution {\n    TrieNode root; // Suffix trie\n    void add(string &s, int i) {\n        auto node = &root;\n        for (int j = s.size() - 1; j >= 0; --j) {\n            if (isPalindrome(s, 0, j)) node->palindromeIndexes.push_back(i); // A[i]'s prefix forms a palindrome\n            int c = s[j] - 'a';\n            if (!node->next[c]) node->next[c] = new TrieNode();\n            node = node->next[c];\n        }\n        node->index = i;\n        node->palindromeIndexes.push_back(i); // A[i]'s prefix is empty string here, which is a palindrome.\n    }\n    \n    bool isPalindrome(string &s, int i, int j) {\n        while (i < j && s[i] == s[j]) ++i, --j;\n        return i >= j;\n    }\npublic:\n    vector<vector<int>> palindromePairs(vector<string>& words) {\n        int N = words.size();\n        for (int i = 0; i < N; ++i) add(words[i], i);\n        vector<vector<int>> ans;\n        for (int i = 0; i < N; ++i) {\n            auto s = words[i];\n            auto node = &root;\n            for (int j = 0; j < s.size() && node; ++j) {\n                if (node->index != -1 && node->index != i && isPalindrome(s, j, s.size() - 1)) ans.push_back({ i, node->index }); \n                // A[i]'s prefix matches this word and A[i]'s suffix forms a palindrome\n                node = node->next[s[j] - 'a'];\n            }\n            if (!node) continue;\n            for (int j : node->palindromeIndexes) { \n                // A[i] is exhausted in the matching above. \n                // If a word whose prefix is palindrome after matching its suffix with A[i], \n                // then this is also a valid pair\n                if (i != j) ans.push_back({ i, j });\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Leetcode/4. Median of Two Sorted Arrays/4. Median of Two Sorted Arrays.java",
    "content": "// as median we have to divide values in array\n// left side (some of nums1 and some of nums2)\n// right side (some of nums1 and some of nums2)\n\nclass Solution {\n    public double findMedianSortedArrays(int[] arr1, int[] arr2) {\n        //taking nums2 bigger always (bcz we taking values from nums2)\n        //so to not get index out of bound\n        if(arr2.length<arr1.length)   return findMedianSortedArrays(arr2,arr1);\n        \n        int n=arr1.length, m=arr2.length;\n        int l=0, r=n, k = (n+m+1)/2;\n        // int l = Math.max(0,k-n), r = Math.min(k,m);\n        \n        // for(int i:arr1) System.out.print(i+\" \");\n        // System.out.println();\n        // for(int i:arr2) System.out.print(i+\" \");\n        // System.out.println();\n        \n        \n        while(l<=r){\n            \n            int cut1=l+(r-l)/2;\n            int cut2=k-cut1;\n            \n            int l1=cut1==0?Integer.MIN_VALUE:arr1[cut1-1];\n            int l2=cut2==0?Integer.MIN_VALUE:arr2[cut2-1];\n            int r1=cut1==n?Integer.MAX_VALUE:arr1[cut1];\n            int r2=cut2==m?Integer.MAX_VALUE:arr2[cut2];\n            \n            \n            // System.out.println(\"l & r=> \"+l+\" \"+r+\"\\n\"+\n            // \"cut1 & cut2 => \"+cut1+\" \"+cut2+\"\\n\"+\n            // \"left half=> \"+Math.min(l1,l2)+\" \"+Math.max(l1,l2)+\"\\n\"+\n            // \"right half=> \"+Math.min(r1,r2)+\" \"+Math.max(r1,r2));\n            \n            if(l1<=r2 && l2<=r1){\n                // System.out.print(l1+\" \")\n                if((n+m)%2==0){\n                    // System.out.println(l1+\" \"+l2+\" \"+r1+\" \"+r2);\n                    return ( Math.max(l1,l2) + Math.min(r1,r2) )/2.0;\n                }else{\n                    //odd length\n                    return Math.max(l1,l2);\n                }\n            }\n            \n            else if(l1>r2){\n                r=cut1-1;\n            }\n            \n            else if(l2>r1){\n                l=cut1+1;\n            }\n            \n        }\n        return 1L;\n        \n    }\n}\n"
  },
  {
    "path": "Leetcode/4. Median of Two Sorted Arrays/Median of Two Sorted Arrays.cpp",
    "content": "class Solution {\npublic:\n    double findMedianSortedArrays(vector<int>& v1, vector<int>& v2) {\n        for(int i =0;i<v2.size();i++){\n            v1.push_back(v2[i]);\n        }\n        sort(v1.begin(),v1.end());\n        double ans=0;\n        if(v1.size()%2==0){\n            int x = v1[v1.size()/2];\n            int y = v1[v1.size()/2 -1];\n            ans = (x+y)/(double)2;\n        }\n        else{\n            ans = v1[v1.size()/2];\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Leetcode/401 binary watch/401-binary-watch.java",
    "content": "class Solution {\n    public List<String> readBinaryWatch(int turnedOn) {\n        \n        List<String> ans=new ArrayList<>();\n        \n        if(turnedOn>8){\n            return ans;\n        }\n        for(int h=0;h<12;h++){\n            for(int m=0;m<60;m++){\n                \n                //bit count will count total set bit(1) in a numbmer\n                if(Integer.bitCount(h*64+m)==turnedOn){\n                    ans.add(String.format(\"%d:%02d\",h,m));\n                }\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "Leetcode/401 binary watch/NOTES.md",
    "content": "​"
  },
  {
    "path": "Leetcode/401 binary watch/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-watch/\">401. Binary Watch</a></h2><h3>Easy</h3><hr><div><p>A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent&nbsp;the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.</p>\n\n<ul>\n\t<li>For example, the below binary watch reads <code>\"4:51\"</code>.</li>\n</ul>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/08/binarywatch.jpg\" style=\"width: 500px; height: 500px;\"></p>\n\n<p>Given an integer <code>turnedOn</code> which represents the number of LEDs that are currently on (ignoring the PM), return <em>all possible times the watch could represent</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>The hour must not contain a leading zero.</p>\n\n<ul>\n\t<li>For example, <code>\"01:00\"</code> is not valid. It should be <code>\"1:00\"</code>.</li>\n</ul>\n\n<p>The minute must be consist of two digits and may contain a leading zero.</p>\n\n<ul>\n\t<li>For example, <code>\"10:2\"</code> is not valid. It should be <code>\"10:02\"</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n<pre><strong>Input:</strong> turnedOn = 1\n<strong>Output:</strong> [\"0:01\",\"0:02\",\"0:04\",\"0:08\",\"0:16\",\"0:32\",\"1:00\",\"2:00\",\"4:00\",\"8:00\"]\n</pre><p><strong>Example 2:</strong></p>\n<pre><strong>Input:</strong> turnedOn = 9\n<strong>Output:</strong> []\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= turnedOn &lt;= 10</code></li>\n</ul>\n</div>\n"
  },
  {
    "path": "Leetcode/437 Path Sum III/pathSum.cpp",
    "content": "class Solution {\npublic:\n    int cnt=0;\n    void dfs(TreeNode* root,long long target)\n    {\n        if(!root)\n            return;\n        if(root->val==target)\n            cnt++;\n        dfs(root->left,target-root->val);\n        dfs(root->right,target-root->val);\n    }\n    /////////\n    int pathSum(TreeNode* root, int targetSum) \n    {\n        if(root)\n        {\n            dfs(root,targetSum);\n            pathSum(root->left,targetSum);\n            pathSum(root->right,targetSum);\n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "Leetcode/450 Delete Node in a BST/deleteNode.java",
    "content": "```java\nclass Solution {\n    public TreeNode deleteNode(TreeNode root, int key) {\n        // if current node is null, return null\n        // this can happen only if the tree is empty or if the key does not exist in the tree\n        if (root == null) return null;\n        \n        // if current node's value is equal to key, then simply delete it\n        if (root.val == key) {\n            // straightforward case where node is leaf node, then just delete it\n            if (root.left == null && root.right == null) {\n                return null;\n            } else if (root.left != null) {\n                // if the left child exists, then the node to attach is the left child's rightmost descendant\n                // and we should return the current node's left child as the new root for its parent to attach to\n                TreeNode newRoot = root.left;\n                TreeNode attach = newRoot;\n                while (attach.right != null) {\n                    attach = attach.right;\n                }\n                // attach the deleted nodes' right child to the right of the node to attach\n                attach.right = root.right;\n                return newRoot;\n            } else {\n                // if the right child exists, then the node to attach is the right child's leftmost descendant\n                // and we should return the current node's right child as the new root for its parent to attach to\n                TreeNode newRoot = root.right;\n                TreeNode attach = newRoot;\n                while (attach.left != null) {\n                    attach = attach.left;\n                }\n                // attach the deleted nodes' left child to the left of the node to attach\n                attach.left = root.left;\n                return newRoot;\n            }\n        }\n        \n        // if the key is not equal to the current node's value, keep searching for the key using BST property\n        // attach the current node to the result of the deletion (which will either return the original child or a new child if the child is deleted)\n        if (key > root.val) {\n            root.right = deleteNode(root.right, key);\n        } else {\n            root.left = deleteNode(root.left, key);\n        }\n        \n        // return current node\n        return root;\n    }\n}\n```\n"
  },
  {
    "path": "Leetcode/4Sum II/4Sum II.java",
    "content": "class Solution {\n    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {\n        Map<Integer, Integer> map = new HashMap<>();\n        for(int k : nums3)\n            for(int l : nums4)\n                map.put(k + l, map.getOrDefault(k + l, 0) + 1);\n        int count = 0;\n        for(int i : nums1)\n            for(int j : nums2)\n                        count += map.getOrDefault(-(i + j), 0);\n        return count;\n    }\n}\n"
  },
  {
    "path": "Leetcode/622 Design Circular Queue/622 Design Circular Queue med s25.cpp",
    "content": "#include<bits.stdc++.h>\nusing namespace std;\n\nclass MyCircularQueue {\npublic:\n    MyCircularQueue(int k) {\n//        queue holding the elems for circular queue\n        q.resize(k);\n//         no. of elems in the circular queue\n        count =0;\n        size =k; // queue size\n        headIndex =0; // index of head element\n    }\n    \n    bool enQueue(int value) {\n//         handle full case\n        if(isFull()) return false;\n        q[(headIndex+count)% size] = value;\n        count+=1;\n        return true;\n    }\n    \n    bool deQueue() {\n//         handle empty case\n        if(isEmpty()) return false;\n//         update head idx\n        headIndex= (headIndex+1)% size;\n        count-=1;\n        return true;\n    }\n    \n    int Front() {\n//         handle empty queue case\n        if(isEmpty()) return -1;\n        return q[headIndex]; // return head elem\n    }\n    \n    int Rear() {\n//         handle empty queue case\n        if(isEmpty()) return -1;\n        return q[(headIndex+count-1) %size];\n    }\n    \n    bool isEmpty() {\n//        no elem in queue\n        return count == 0;\n    }\n    \n    bool isFull() {\n//         return true if the count is equal to the queue size\n        return count==size;\n//         else return false\n    }\n    private:\n    int count, size, headIndex;\n    vector<int> q;\n};\n"
  },
  {
    "path": "Leetcode/623 Add One Row To Tree/Add one row to tree.java",
    "content": "class Solution {\n    public TreeNode addOneRow(TreeNode root, int val, int depth) {\n        if(depth==1) { // if depth is 1 we have to add for root\n            TreeNode newH=new TreeNode(val);\n            newH.left=root;\n            return newH;\n        }\n        addRow(root, val, 1, depth-1); //starting with root starting from 1 to depth-1\n        return root;\n    }\n    public void addRow(TreeNode root, int val, int height, int expHeight) {\n        if(root==null) {\n            return ;\n        }\n        if(expHeight==height) {\n            TreeNode left=new TreeNode(val, root.left, null);\n            TreeNode right=new TreeNode(val, null, root.right);\n            root.left=left;\n            root.right=right;\n            return ;\n        }\n        \n        addRow(root.left, val, height+1, expHeight);\n        addRow(root.right, val, height+1, expHeight);\n\n    }\n}\n"
  },
  {
    "path": "Leetcode/623 Add One Row To Tree/ReadMe.md",
    "content": "# 623. Add One Row to Tree\nGiven 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\nGiven 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.\ncur's original left subtree should be the left subtree of the new left subtree root.\ncur's original right subtree should be the right subtree of the new right subtree root.\nIf 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### Example 1:\n\n![addrow-tree](https://user-images.githubusercontent.com/75923481/193965191-3f95d1b4-9bf0-499d-ae01-5daee00b9110.jpg)\n\n\nInput: root = [4,2,6,3,1,5], val = 1, depth = 2 <br>\nOutput: [4,1,1,2,null,null,6,3,1,5]  <br>\n\n## Example 2:\n\n![add2-tree](https://user-images.githubusercontent.com/75923481/193965239-82dc673e-015a-46c3-8e0d-9d04907c0c32.jpg)\n\nInput: root = [4,2,null,3,1], val = 1, depth = 3 <br>\nOutput: [4,2,null,1,1,3,null,null,1] <br>\n \n\nConstraints:\n\nThe number of nodes in the tree is in the range [1, 104]. <br>\nThe depth of the tree is in the range [1, 104]. <br>\n-100 <= Node.val <= 100 <br>\n-105 <= val <= 105 <br>\n1 <= depth <= the depth of tree + 1 <br>\n"
  },
  {
    "path": "Leetcode/623 Add One Row to Tree/623 Add One Row to Tree.java",
    "content": "class Solution {\n    \n    public TreeNode add(TreeNode root, int val, int depth, int currdepth){\n        if(root==null) return root;\n        \n        if(depth==1){\n            TreeNode temp = new TreeNode(val);\n            // if(side=='l')\n            temp.left = root;\n            \n            \n            return temp;\n        }\n        else if(currdepth==depth-1){\n            TreeNode temp1 = new TreeNode(val);\n            TreeNode temp2 = new TreeNode(val);\n            \n            \n            temp1.right = root.right;\n            temp2.left = root.left;\n            \n            \n            root.left = temp2;\n            root.right = temp1;\n            return root;\n        }else{\n            root.left = add(root.left,val,depth,currdepth+1);\n            root.right = add(root.right,val,depth,currdepth+1); \n            return root;\n        }\n        \n        \n        \n        \n    }\n    public TreeNode addOneRow(TreeNode root, int val, int depth) {\n        \n        if(depth==1){\n            TreeNode temp = new TreeNode(val);\n            temp.left = root;\n            \n            return temp;\n        }\n        return add(root,val,depth,1);\n        \n    }\n}\n"
  },
  {
    "path": "Leetcode/658 Find K Closest Elements/658 Find K Closest Elements s29.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n        int L =0, R = arr.size()-1;\n        while(R-L >= k)\n            if(x- arr[L] <=  arr[R]-x) R--;\n            else L++;\n        return vector<int>(arr.begin() + L, arr.begin() + R+1);\n    }\n};"
  },
  {
    "path": "Leetcode/658 Find K Closest Elements/Find k Closest Elements.java",
    "content": "Approach 1:\nclass Solution {\n    public List<Integer> findClosestElements(int[] arr, int k, int x) {\n        TreeMap<Integer,LinkedList<Integer>>map=new TreeMap<Integer,LinkedList<Integer>>();\n        \n        for(int i=0;i<arr.length;i++){\n            int a=(int)Math.abs(arr[i]-x);\n            if(map.containsKey(a)){\n                LinkedList<Integer>set=map.get(a);\n                set.add(arr[i]);\n                map.put(a,set);\n            }\n            else{\n                LinkedList<Integer>set=new LinkedList<Integer>();\n                set.add(arr[i]);\n                map.put(a,set);\n            }\n        }\n        //System.out.println(map);\n        List<Integer>list=new ArrayList<Integer>();\n        boolean flag=false;\n        for(int a:map.keySet()){\n            LinkedList<Integer>set=map.get(a);\n            for(int b:set){\n                list.add(b);\n                if(list.size()==k){\n                    flag=true;\n                    break;\n                }\n            }\n            if(flag==true){\n                break;\n            }\n        }\n        Collections.sort(list);\n        return list;\n    }\n}\nTime Taken:130ms  \n\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nApproach 2:\nclass Solution {\n    public static class Pair implements Comparable<Pair>{\n        \n    int ele;\n    int diff;\n    \n    public Pair(int a, int b){\n        ele=a;\n        diff=b;\n    } \n    \n     public int compareTo(Pair p){\n         if((p.diff)==(this.diff)){\n             return this.ele-p.ele;\n         }\n         return this.diff-p.diff;\n     }\n     \n}\n    \n    public List<Integer> findClosestElements(int[] arr, int k, int x) {\n       Pair obj[]=new Pair[arr.length];\n       for(int i=0;i<arr.length;i++){\n           int a=(int)(Math.abs(arr[i]-x));\n           \n           obj[i]=new Pair(arr[i],a);\n           \n       }\n        \n       Arrays.sort(obj);\n       \n       List<Integer>aa=new ArrayList<Integer>();\n       for(int i=0;i<k;i++){\n           aa.add(obj[i].ele);\n       } \n        Collections.sort(aa);\n        return aa;\n        \n    }\n}\n\nTime Taken:53ms\n"
  },
  {
    "path": "Leetcode/704 binary search/704-Binary-Search.py",
    "content": "# Binary search logic in python \n\ndef binary_search(arr, x):\n    low = 0\n    high = len(arr) - 1\n    mid = 0\n \n    while low <= high:\n \n        mid = (high + low) // 2\n \n        # If x is greater, ignore left half\n        if arr[mid] < x:\n            low = mid + 1\n \n        # If x is smaller, ignore right half\n        elif arr[mid] > x:\n            high = mid - 1\n \n        # means x is present at mid\n        else:\n            return mid\n \n    # If we reach here, then the element was not present\n    return -1\n"
  },
  {
    "path": "Leetcode/704 binary search/NOTES.md",
    "content": "\r\n"
  },
  {
    "path": "Leetcode/704 binary search/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/binary-search/\">704. Binary Search</a></h2><h3>Easy</h3><hr><div><p>Given an array of integers <code>nums</code> which is sorted in ascending order, and an integer <code>target</code>, write a function to search <code>target</code> in <code>nums</code>. If <code>target</code> exists, then return its index. Otherwise, return <code>-1</code>.</p>\r\n\r\n<p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p>\r\n\r\n<p>&nbsp;</p>\r\n<p><strong>Example 1:</strong></p>\r\n\r\n<pre><strong>Input:</strong> nums = [-1,0,3,5,9,12], target = 9\r\n<strong>Output:</strong> 4\r\n<strong>Explanation:</strong> 9 exists in nums and its index is 4\r\n</pre>\r\n\r\n<p><strong>Example 2:</strong></p>\r\n\r\n<pre><strong>Input:</strong> nums = [-1,0,3,5,9,12], target = 2\r\n<strong>Output:</strong> -1\r\n<strong>Explanation:</strong> 2 does not exist in nums so return -1\r\n</pre>\r\n\r\n<p>&nbsp;</p>\r\n<p><strong>Constraints:</strong></p>\r\n\r\n<ul>\r\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\r\n\t<li><code>-10<sup>4</sup> &lt; nums[i], target &lt; 10<sup>4</sup></code></li>\r\n\t<li>All the integers in <code>nums</code> are <strong>unique</strong>.</li>\r\n\t<li><code>nums</code> is sorted in ascending order.</li>\r\n</ul>\r\n</div>\r\n"
  },
  {
    "path": "Leetcode/72 Edit distance/minDistance.cpp",
    "content": "/*This code is contributed by mr-optimizer (https://github.com/mr-optimizer) */\nclass Solution {\npublic:\n    int memo[501][501];\n    int dp(string word1, string word2, int i, int j) {\n        if (i == 0)return j;\n        if (j == 0)return i;\n        if (memo[i][j] != -1)return memo[i][j];\n        if (word1[i - 1] == word2[j - 1]) {\n            return memo[i][j] = dp(word1, word2, i - 1, j - 1);\n        } else {\n            return memo[i][j] = 1 + min(dp(word1, word2, i - 1, j), min(dp(word1, word2, i, j - 1), dp(word1, word2, i - 1, j - 1)));\n        }\n    }\n    int minDistance(string word1, string word2) {\n        memset(memo, -1, sizeof(memo));\n        return dp(word1, word2, word1.size(), word2.size());\n    }\n};\n"
  },
  {
    "path": "Leetcode/72 Edit distance/minDistance.java",
    "content": "public class Solution {\n    public int minDistance(String A, String B) {\n        int[][]list=new int[A.length()][B.length()];\n        return editDist(A,B,0,0,list);\n    }\n    int editDist(String A,String B,int x,int y,int[][]memory){\n        if(y==B.length())return A.length()-x;\n        if(x==A.length())return B.length()-y;\n        int ans=memory[x][y];\n        if(ans!=0)return ans;\n        if(A.charAt(x)==B.charAt(y)){\n            ans=editDist(A,B,x+1,y+1,memory);\n        }else{\n            ans=1+Math.min(editDist(A,B,x+1,y,memory),Math.min(editDist(A,B,x,y+1,memory),editDist(A,B,x+1,y+1,memory)));\n        }\n        memory[x][y]=ans;\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Leetcode/75.Sort colors/75.Sort-colors.java",
    "content": "class Solution {\n    public void sortColors(int[] nums) {\n        int count0 = 0;\n        int count1=0;\n        for(int i=0 ; i<nums.length ; i++){\n            if(nums[i] == 0 ){\n                count0++;\n                continue;\n            }\n            if(nums[i] ==1){\n                count1++;\n                \n            }\n        }\n        \n        for(int i=0 ; i<nums.length ; i++){\n            if(count0-- > 0){\n                nums[i] = 0 ;\n                \n            }\n            else if(count1-- > 0){\n                nums[i]=1;\n            }\n            else{\n                nums[i]=2;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Leetcode/75.Sort colors/Notes.md",
    "content": "\n"
  },
  {
    "path": "Leetcode/75.Sort colors/README.md",
    "content": "# [75. Sort Colors](https://leetcode.com/problems/sort-colors/)\n\n## Medium\nGiven 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## Example 1:\n\n#### Input: nums = [2 , 0 , 2 , 1 , 1 , 0]\n#### Output: [0 , 0 , 1 , 1 , 2 , 2 ]\n\n## Example 2:\n#### Input: nums = [2 , 0 , 1]\n\n#### Output: [0 , 1 , 2]\n\n## Constraints:\n ### n == nums.length\n\n ### 1 <= n <= 300\n\n ### nums[i] is either 0, 1, or 2.\n"
  },
  {
    "path": "Leetcode/75.Sort colors/Sort colors.cpp",
    "content": "class Solution {\npublic:\n    void sortColors(vector<int>& v) {\n        int n =v.size();\n        for(int i =0;i<n-1;i++){\n            for(int j =0;j<(n-1)-i;j++){\n                if(v[j]>v[j+1]){\n                    swap(v[j],v[j+1]);\n                }\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "Leetcode/766.Toeplitz Matrix/Toeplitz Matrix.java",
    "content": "Solution 1:\n\nBackward Comparison: Comparison with previous diagonal cee\n\nTime Complexity:O(N*M)\nSpace Complexity:O(N*M)\nAuxiliary Space:O(1)\n  \nLeetCode Time: 1 ms faster than 93.83%\nLeetCode Memory: 45.2MB less than 80.01%\n  \n\n  boolean flag=false;\n        int n=arr.length;\n        int m=arr[0].length;\n       for(int i=01;i<n;i++){\n           for(int j=01;j<m;j++){\n               int a=arr[i][j];\n               int b=arr[i-1][j-1];\n               if(a==b){\n                   flag=true;\n                                   \n               }\n               else{\n                   return false;\n               }\n               \n           }\n       }\n        return true;\n\n\n========================================================================================================================================================================\n  \nSolution 2:\n\nForward Comparison: Comparison with next diagonal cee\n\nTime Complexity:O(N*M)\nSpace Complexity:O(N*M)\nAuxiliary Space:O(1)\n  \nLeetCode Time: 0 ms faster than 100.00%\nLeetCode Memory: 42MB less than 96.94%\n  \n   int n=arr.length;\n   int m=arr[0].length;\n for(int i=0;i<n-1;i++){\n           for(int j=0;j<m-1;j++){\n               int a=arr[i][j];\n               int b=arr[i+1][j+1];\n               if(a!=b){\n                  return false;\n                                   \n               }\n             \n           }\n       }\n        return true;\n\n\n\n\n\n\n  \n\n"
  },
  {
    "path": "Leetcode/79.Word Search/79. Word Search.cpp",
    "content": "class Solution {\npublic:\n    bool exist(vector<vector<char>>& board, string word) {\n        if (word.empty()) return true;\n        if (board.empty() || board[0].empty()) return false;\n\n        m = board.size();\n        n = board[0].size();\n        for (int i = 0; i < m; ++i)\n            for (int j = 0; j < n; ++j)\n                // traverse the board to find the first char\n                if (dfsSearch(board, word, 0, i, j)) return true;\n        return false;\n    }\nprivate:\n    int m;\n    int n;\n    bool dfsSearch(vector<vector<char>>& board, string& word, int k, int i, int j) {\n        if (i < 0 || i >= m || j < 0 || j >= n || word[k] != board[i][j]) return false;\n        if (k == word.length() - 1) return true;  // found the last char\n\n        char cur = board[i][j];\n        board[i][j] = '*';  // used\n        bool search_next = dfsSearch(board, word, k+1, i-1 ,j)\n                        || dfsSearch(board, word, k+1, i+1, j)\n                        || dfsSearch(board, word, k+1, i, j-1)\n                        || dfsSearch(board, word, k+1, i, j+1);\n        board[i][j] = cur;  // reset\n        return search_next;\n    }\n};\n"
  },
  {
    "path": "Leetcode/79.Word Search/NOTES.md",
    "content": ""
  },
  {
    "path": "Leetcode/79.Word Search/README.md",
    "content": "<h2><a href=\"https://leetcode.com/problems/word-search/\">79. Word Search</a></h2><h3>Medium</h3><hr><div><p>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.</p>\n<br>\n<p><strong>Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/word2.jpg\" style=\"width: 310px; height: 280px;\">\n<pre><strong>Input:</strong> board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"\n<strong>Output:</strong> true\n</pre>\n<br>\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg\" style=\"width: 310px; height: 280px;\">\n<pre><strong>Input:</strong> board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"\n<strong>Output:</strong> true\n</pre>\n<br>\n<p><strong>Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/15/word3.jpg\" style=\"width: 310px; height: 280px;\">\n<pre><strong>Input:</strong> board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"\n<strong>Output:</strong> false\n"
  },
  {
    "path": "Leetcode/838 Push Dominoes/838 Push Dominoes lc med s27.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n// using 2-pointer\n    string pushDominoes(string dominoes) {\n        int l = 0, n = dominoes.size();\n        for (int r = 0; r < n; r++) {\n            if (dominoes[r] == '.') {\n                continue;\n            } else if ((dominoes[r] == dominoes[l]) || (dominoes[l] == '.' && dominoes[r] == 'L')) {\n                for (int k = l; k < r; k++) dominoes[k] = dominoes[r];\n            } else if (dominoes[l] == 'L' && dominoes[r] == 'R') {\n\n            }  else if (dominoes[l] == 'R' && dominoes[r] == 'L') {\n\n                int m = (r - l - 1) / 2;\n                for (int k = 1; k <= m; k++) dominoes[r - k] = 'L', dominoes[l + k] = 'R';\n            }\n            l = r;\n            dominoes[l] = dominoes[r];\n        }\n        if (dominoes[l] == 'R') for (int k = l; k < n; k++) dominoes[k] = 'R';\n        return dominoes;\n    }\n};"
  },
  {
    "path": "Leetcode/91 Decode Ways/91 Decode Ways oc1.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    int numDecodings(string s) {\n//         check for empty string or leading zero\n        if(!s.size() || s.front() == '0') return 0;\n        int d1=1, d2 =1;   \n        for(int i =1; i<s.size(); i++){\n            if(s[i] == '0') d1 =0;\n            if(s[i-1] == '1' || s[i-1] == '2' && s[i] <= '6'){\n                d1= d2 + d1;\n                d2 = d1-d2;\n            }else\n                d2 = d1;\n        }\n        return d1;\n    }\n};"
  },
  {
    "path": "Leetcode/92 Reverse Linked List II/Reverse Linked List II.cpp",
    "content": "/**\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* reverseBetween(ListNode* head, int left, int right) {\n       int count=0;\n        ListNode* p = head;\n        while(p!=NULL){\n            count++;\n            p=p->next;\n        }\n        p = head;\n        vector<int> v;\n        while(p!=NULL){\n           v.push_back(p->val);\n           p=p->next; \n        }\n        reverse(v.begin()+left-1,v.begin()+right);\n        p = head;\n        int i=0;\n        while(p!=NULL){\n            p->val = v[i];\n            p=p->next;\n            i++;\n        }\n        return head;\n    }\n};\n\n\n // ListNode* p = head;\n //        int count =0;\n //        while(p!=NULL){\n //            count++;\n //            p=p->next;\n //        }\n //        p = head;\n //        int a[count];\n //        int i =0;\n //        while(p!=NULL){\n //            a[i]=p->val;\n //            p=p->next;\n //            i++;\n //        }\n //        p = head;\n //        reverse(a+(left-1),a+right);\n //        int j =0;\n //        while(p!=NULL){\n //            p->val = a[j];\n //            p=p->next;\n //            j++;\n //        }\n //        return head;\n"
  },
  {
    "path": "Leetcode/92 Reverse Linked List II/Reverse Linked List II.java",
    "content": "public class Solution {\n    public ListNode reverseBetween(ListNode A, int B, int C) {\n\n        ListNode temp = A;\n        ListNode prevtemp = null;\n\n        int count = 1;\n        while(count<B) {\n            count++;\n            prevtemp= temp;\n            temp= temp.next;\n        }\n\n        ListNode curr= temp;\n        ListNode next = null;\n        ListNode prev = null;\n\n        count--;\n        while(count<C) {\n            count++;\n            next = curr.next;\n            curr.next= prev;\n            prev = curr;\n            curr = next;\n        }\n\n        if(prevtemp==null) {\n            A = prev;\n        } else {\n            prevtemp.next = prev;\n        }\n        temp.next = curr;\n\n\n        return A;\n    }\n}\n"
  },
  {
    "path": "Leetcode/990 Satisfiability of Equality Equations/990 Satisfiability of Equality Equations med s26.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    int alphabet_size[26];\n    int find(int x){\n        return alphabet_size[x] == x ? x: find(alphabet_size[x]);\n    }\n    bool equationsPossible(vector<string>& equations) {\n        int n = (int) equations.size();\n        \n        for(int i =0; i<26; i++) alphabet_size[i]=i;\n        \n        for(auto x : equations){\n            if(x[1]== '='){\n                alphabet_size[find(x[0]-'a')] = find(x[3]-'a');\n            }\n        }\n//         handle != case\n        for(auto x : equations){\n            if(x[1]== '!' && find(x[0]-'a') == find(x[3]-'a')){\n                return false;\n            }\n        }\n            return true;\n    }\n};"
  },
  {
    "path": "Leetcode/Break A Palindrome/Break A Palindrome.java",
    "content": "class Solution{\n  public String breakPalindrome(String s) {\n          if(s.length()<=1){\n              return \"\";\n          }\n          else{\n              int len=0;\n              len=s.length()/2;\n              int i=0;\n              StringBuilder sb=new StringBuilder(s);\n              while(i<len){\n                  if(s.charAt(i)!='a'){\n                      sb.setCharAt(i,'a');\n                      return sb.toString();\n                  }\n\n                  i++;\n              }\n              sb.setCharAt(s.length()-1,'b');\n              return sb.toString();\n\n          }\n      }\n}\n\nTime Complexity:O(S.length()/2);\nSpace Complexity:O(1)\nAuxiliary Space:O(1)\n  \nLeetCode Time:0ms faster than 100%\nLeetCode Memory:40Mb less than 96.69%\n"
  },
  {
    "path": "Leetcode/K diff pairs/K diff pairs.cpp",
    "content": "class Solution {\npublic:\n    int findPairs(vector<int>& nums, int k) {\n        unordered_map<int, int> mp;\n            for(auto i: nums) {\n                    mp[i]++;\n            }\n            int ans = 0;\n            for(auto x: mp) {\n                    if(k == 0) {\n                            if(x.second > 1) {\n                                    ans++;\n                            }\n                    }else if(mp.find(x.first+k) != mp.end()) {\n                            ans++;\n                    }\n            }\n            return ans;\n    }\n};"
  },
  {
    "path": "Leetcode/Merge Overlapping Intervals/Merge Overlapping Intervals.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> merge(vector<vector<int>>& intervals) {\n        vector<vector<int>> ans;\n            sort(intervals.begin(), intervals.end());\n            \n         vector<int> temp = intervals[0];\n            for(int i= 1; i<intervals.size(); i++) {\n                    if(intervals[i][0] <= temp[1]) {\n                            temp[1] = max(intervals[i][1], temp[1]);\n                    }else {\n                            ans.push_back(temp);\n                            temp = intervals[i];\n                    }\n            }\n            ans.push_back(temp);\n            return ans;\n    }\n};"
  },
  {
    "path": "Leetcode/Minimum time to Make Rope Colorful/Minimum Time to Make Rope Colorful.cpp",
    "content": "class Solution {\npublic:\n    int minCost(string colors, vector<int>& neededTime) {\n        if(colors.length() != neededTime.size()) return -1;\n                int time = 0; int maxTime;\n            for(int i=0; i<colors.length(); i++) {\n                   if(i>0 && colors[i]!=colors[i-1])\n                           maxTime =0;\n                 \n                  time += min(maxTime, neededTime[i]);\n                  maxTime = max(maxTime, neededTime[i]);  \n            }\n            \n            return time;\n    }\n};"
  },
  {
    "path": "Leetcode/Number of Dice rolls with target sum/Number of dice rolls.cpp",
    "content": "vector<int> dp(target + 1);\n  dp[0] = 1;\n  for (int i = 1; i <= d; ++i) {\n    vector<int> dp1(target + 1);\n    for (int j = 1; j <= f; ++j)\n      for (auto k = j; k <= target; ++k)\n        dp1[k] = (dp1[k] + dp[k - j]) % 1000000007;\n    swap(dp, dp1);\n  }\n  return dp[target];"
  },
  {
    "path": "Leetcode/Remove Letter To Equalize Frequency/Remove Letter To Equalize Frequency.cpp",
    "content": "class Solution {\npublic:\n    bool equalFrequency(string word) {\n        vector<int> v;\n        unordered_map<char, int> mp;\n        for(char ch : word) mp[ch]++;\n        for(auto x : mp){\n            v.push_back(x.second);\n        }\n        sort(v.begin(), v.end());\n        if(v.size() == 1) return 1;\n        \n        else if(v.size() == 2){\n            if(v[0] == 1 and v[1] == 1) return 1;\n            else if(v[1] - v[0] == 1) return 1;\n            return 0;\n        }\n        \n        else{\n            if(v[0] == 1 and count(v.begin(), v.end(), v[0]) == v.size()) return 1;\n            else if(v[0] == 1 and count(v.begin(), v.end(), v[0]) != v.size()){\n                if(v.size() == 3 and v[v.size() - 1] == 2) return 1;\n            }\n            \n            int sum = 0;\n            for(int x : v) sum += x;\n            \n            if(sum == (v[0] * v.size() + 1)) return 1;\n            else return 0;\n        }\n        return 0;\n    }\n};\n"
  },
  {
    "path": "Leetcode/Sort Colors/Sort Colors.cpp",
    "content": "class Solution {\npublic:\n    void sortColors(vector<int>& nums) {\n        if(nums.size() == 0) return;\n            int i=0, j=0, k = nums.size()-1;\n            while(j<=k) {\n                    if(nums[j] == 2) {\n                            swap(nums[j], nums[k]);  k--;\n                    }\n                    if(nums[j] == 0) {\n                            swap(nums[j], nums[i]);  i++; j++;\n                    }else if(nums[j] == 1) {\n                            j++;\n                    }\n            }\n    }\n};"
  },
  {
    "path": "Leetcode/Top K Frequent Words/Top K Frequent Words.cpp",
    "content": "class Solution {\npublic:\n    #define ps pair<int, string>\n   class comp {\n  public:\n    bool operator() (const ps &p1, const ps &p2) {\n      if(p1.first == p2.first) return p1.second < p2.second;\n      \n      return p1.first > p2.first;\n    }\n   }; \n    vector<string> topKFrequent(vector<string>& words, int k) {\n        int n=words.size();\n        \n        unordered_map<string,int>map;\n        for(auto x:words){\n            map[x]++;\n        }\n        \n        priority_queue<ps,vector<ps >,comp>pq;\n        \n        for(auto x:map){\n            pq.push({x.second,x.first});\n            if(pq.size()>k) pq.pop();\n        }\n        vector<string>ans(k);\n        while(k--){\n            ans[k]=pq.top().second;\n            pq.pop();\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Leetcode/Two Sum IV-Input is BST/Two Sum IV-Input is a BST.java",
    "content": "Solution 1:\nWithout using set:\n\nApproach:\n1.Doing Inorder Traversal \n2.Storing data values in an arraylist\n3.Applying two pointer algorithm and if target is found return true else return false\n  \nCode:\n\nclass Solution {\n    \n    public void fun(TreeNode root,ArrayList<Integer>aa){\n        if(root==null){\n            return ;\n        }\n        else{\n            fun(root.left,aa);\n            aa.add(root.val);\n            fun(root.right,aa);\n        }\n    }\n    public boolean findTarget(TreeNode root, int target) {\n        ArrayList<Integer>aa=new ArrayList<Integer>();\n        fun(root,aa);\n        int start=0;\n        int end=aa.size()-1;\n        while(start<end){\n            if(aa.get(start)+aa.get(end)==target){\n                return true;\n            }\n            else if(aa.get(start)+aa.get(end)>target){\n                end--;\n            }\n            else{\n                start++;\n            }\n        }\n        return false;\n    }\n    \n  \n  \n  \nSolution 2:\nUsing Set:\n  \n  \n  Approach:\n1.Doing Inorder Traversal \n2.While traversal if we get (target-root.val) in set we made flag as true else add the root.val in set.\n3.return flag. If flag==true it means target is found else target sum is not present in the BST.\n  \n  class Solution {\n   \n    HashSet<Integer>set=new HashSet<Integer>();//global set\n    boolean flag=false;//global variable\n    \n    \n    public void fun(TreeNode root,int target){\n        if(root==null){\n            return;\n        }\n        if(set.contains(target-root.val)){\n            flag=true;\n        }\n        else{\n            set.add(root.val);\n        }\n        fun(root.left,target);\n        fun(root.right,target);\n    }\n     public boolean findTarget(TreeNode root, int target) {\n         fun(root,target);\n         return flag;\n     }\n}\n\n"
  },
  {
    "path": "Length of Last Word.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE LIST. IT IS READ ONLY\n    public int lengthOfLastWord(final String s) {\n        int ans=0;\n        boolean started=false;\n        for(int i=s.length()-1;i>=0;i--){\n            if(s.charAt(i)==' '){\n                if(started){\n                    return ans;\n                }\n            }else{\n                started=true;\n                ans++;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Length of longest palindrome in Linked List.java",
    "content": "class GfG\n{\n        public static int fun(LinkedList<Integer>list,int start, int end){\n            //System.out.println(\"Hi\");\n            \n            while(start<end){\n                if(list.get(start)!=list.get(end)){\n                    return -1;\n                }\n                else{\n                    start++;\n                    end--;\n                }\n            }\n           //System.out.println((end-start+1));\n            return end-start+1;\n        }\n        public static int maxPalindrome(Node head)\n        {\n          LinkedList<Integer>list=new LinkedList<Integer>();\n          Node temp=head;\n          while(temp!=null){\n              list.add(temp.data);\n              temp=temp.next;\n          }\n          int max=01;\n          int end=list.size()-1;\n          int start=0;\n          \n         for(int i=0;i<list.size();i++){\n             for(int j=list.size()-1;j>i;j--){\n                 if(list.get(i)==list.get(j)){\n                     //System.out.println(\"hi\"+list.get(i));\n                     int a=fun(list,i,j);\n                     if(a!=-1){\n                         max=Integer.max(max,j-i+1);\n                         break;\n                     }\n                 }\n                 \n                 \n                 \n                \n             }\n         }\n          \n          return max;\n          \n        }\n}\n"
  },
  {
    "path": "Length of longest palindrome in linked list.java",
    "content": "class GfG\n{\n   \n        public static int maxPalindrome(Node head)\n        {\n          //add code here.\n          ArrayList<Integer> al = new ArrayList<>();\n          while(head != null){\n              al.add(head.data);\n              head = head.next;\n          }\n          int[] arr = new int[2];\n          int center = 0;\n          while(center < al.size()){\n              center = binary(al,center,arr);\n              center++;\n          }\n          return(arr[1]-arr[0]-1);\n        }\n        public static int binary(ArrayList<Integer> al , int i, int[] arr){\n            int n = al.size();\n            int new_center = i;\n            int t = i;\n            while(new_center < n-1 && al.get(new_center) == al.get(new_center+1) ){\n                new_center++;\n            }\n            int center = new_center;\n            while(t >= 0 && new_center < n && al.get(t) == al.get(new_center) ){\n                t--;\n                new_center++;\n            }\n            if(arr[1]-arr[0]-1 < new_center-t-1){\n                arr[0] = t;\n                arr[1] = new_center;\n            }\n            return center;\n        }\n}\n"
  },
  {
    "path": "Letter Phone.java",
    "content": "public class Solution {\n    String[] map = {\"0\", \"1\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n    public ArrayList<String> letterCombinations(String digits) {\n        ArrayList<String> res = new ArrayList<>();\n        if(digits == null || digits.length() == 0){\n            return res;\n        }\n        dfs(digits, 0, new StringBuilder(), res);\n        return res;\n    }\n    \n    public void dfs(String digits, int index, StringBuilder sb, ArrayList<String> res){\n        if(index == digits.length()){\n            res.add(sb.toString());\n            return;\n        }\n        \n        String str = map[digits.charAt(index) - '0'];\n        for(int i = 0; i < str.length(); i++){\n            sb.append(str.charAt(i));\n            dfs(digits, index + 1, sb, res);\n            sb.deleteCharAt(sb.length() - 1);\n        }\n    }\n}\n"
  },
  {
    "path": "Level Order.java",
    "content": "public class Solution {\n    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode A) {\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(A);\n        ArrayList<ArrayList<Integer>> ans=new ArrayList<>();\n\n        while(!q.isEmpty()){\n            int size=q.size();\n            ArrayList<Integer> arr=new ArrayList<>();\n            for(int i=0;i<size;i++){\n                TreeNode n=q.remove();\n                arr.add(n.val);\n                if(n.left!=null){\n                    q.add(n.left);\n                }\n                if(n.right!=null){\n                    q.add(n.right);\n                }\n            }\n            ans.add(arr);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Levels Of Game.java",
    "content": "// Dynamic Programming approach\nclass Solution {\n    public static int maxLevel(int h,int m) {\n        // code here\n        int[][]dp=new int[2000][2000];\n        for(int i=0;i<2000;i++){\n            Arrays.fill(dp[i],-1);\n        }\n        \n        return dfs(h,m,dp)-1;\n    }\n    static int dfs(int h,int m,int[][]dp){\n        if(h<=0 || m<=0)return 0;\n        \n        if(dp[h][m]!=-1)return dp[h][m];\n        \n        int a=dfs(h+3-5,m+2-10,dp)+2;\n        int b=dfs(h+3-20,m+2+5,dp)+2;\n        return dp[h][m]=Math.max(a,b);\n    }\n}\n\n//===============================================================\n\n//Iterative brute force approach\nclass Solution {\n    public static int maxLevel(int h,int m) {\n        // code here\n        int level=0;\n        boolean selectOne=true;\n        while(h>0 && m>0){\n            if(selectOne){\n                h+=3;\n                m+=2;\n                level++;\n                selectOne=false;\n            }else{\n                selectOne=true;\n                level++;\n                if(h>5 && m>10){\n                    h-=5;\n                    m-=10;\n                }else{\n                    h-=20;\n                    m+=5;\n                }\n            }\n        }\n        return level-1;\n    }\n}\n"
  },
  {
    "path": "Licence Key Formatting.java",
    "content": "class Solution{\n    static String ReFormatString(String s, int k){\n        StringBuilder sb=new StringBuilder(s);\n        StringBuilder sb2=new StringBuilder();\n        for(int i=0;i<sb.length();i++){\n            if(sb.charAt(i)!='-'){\n                sb.setCharAt(i,Character.toUpperCase(sb.charAt(i)));\n                sb2.append(Character.toUpperCase(s.charAt(i)));\n            }\n                \n        }\n        if(sb.length()<k){\n            \n            return sb2.toString();\n        }\n        StringBuilder sb1=new StringBuilder();\n        int count=0;\n        \n        for(int i=s.length()-1;i>=0;i--){\n           if(s.charAt(i)!='-'){\n               if(count==k){\n                   count=01;\n                   sb1.append(\"-\");\n                   sb1.append(sb.charAt(i));\n               }\n               else{\n                   count++;\n                   sb1.append(sb.charAt(i));\n               }\n           }\n           \n        }\n        sb1.reverse();\n        return sb1.toString();\n        \n        \n    }\n}\n"
  },
  {
    "path": "License Key Formatting GFG/Licence.cpp",
    "content": "string ReFormatString(string S, int K){\n    \t  int len=0;\n        string temp=\"\";\n        for(int i=0;i<S.size();i++){\n            if(isdigit(S[i]) || isalpha(S[i])){\n                temp+=toupper(S[i]);\n                len++;\n            }\n        }\n        \n        if(len<K){\n            return temp;\n        }\n    \tstring str=\"\";\n    \tint Size=len%K;\n    \tint index=0;\n    \tfor(int i=0;i<Size;i++){\n    \t    str+=toupper(temp[i]);\n    \t}\n    \tif(str.size()!=0)\n    \tstr+='-';\n    \tint j=0;\n    \tfor(int i=Size;i<temp.size();i++){\n    \t      if(j==K){\n    \t          str+='-';\n    \t          j=0;\n    \t      }\n    \t        str+=toupper(temp[i]);\n    \t        j++;\n    \t        \n    \t    }\n    \t    \n    \t\n    \tif(str[0]=='-'){\n    \t    str=str.substr(1);\n    \t}\n    \tif(str[str.size()-1]=='-'){\n    \t    str.pop_back();\n    \t}\n    \treturn str;\n    }\n\n// Approach 2 : \nclass Solution\n{\n   public:\n    string ReFormatString(string S, int K){\n    \tstring str = \"\", tmp = \"\";\n\n    \tfor(int i=S.length()-1; i>=0; i--){\n    \t    if(tmp.length()==K){\n    \t        if(str.length()==0) str = tmp;\n    \t        else str = tmp + \"-\" + str ;\n    \t        tmp = \"\";\n    \t    }\n    \t    if(S[i]!='-'){  \n    \t        char ch;\n    \t        if(islower(S[i])) ch = toupper(int(S[i]));\n    \t        else ch = S[i];\n    \t        tmp = ch + tmp;\n    \t    }\n    \t}\n\n    \tif(tmp.length()>0){\n        \tif(str.length()==0) str = tmp;\n        \telse str = tmp + \"-\" + str;\n    \t}\n\n    \treturn str;\n    }\n};\n"
  },
  {
    "path": "License Key Formatting med s21.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nclass Solution\n{\n   public:\n    string ReFormatString(string S, int K){\n    \tint n = S.size()-1,size =0;\n    \tstring res=\"\", temp=\"\";\n    \t\n    \twhile(n>=0){\n    \t    while(size<K && n>=0){\n    \t        if(S[n]!='-'){\n    \t           // to check alphabets\n    \t           int check = isalpha(S[n]);\n    \t           if(check){\n    \t               S[n] = toupper(S[n]);\n    \t           }\n    \t           temp+=S[n];\n    \t           size++;\n    \t        }\n    \t        n--;\n    \t    }\n    \t    size=0;\n    \t    res+=temp;\n    \t    temp.clear();\n    \t    if(n>=0) res+='-';\n    \t}\n    \treverse(res.begin(), res.end());\n    \tif(res[0]=='-') return res.substr(1);\n    \treturn res;\n    \t\n    }\n};\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t    string S;\n\t    cin>>S;\n\t    int K;\n\t    cin >> K;\n\t    Solution ob;  \n\t    string ans=ob.ReFormatString(S, K);\n\t    cout<<ans;\n\t    cout<<\"\\n\";\n\t}\n\treturn 0;\n}"
  },
  {
    "path": "License Key Formatting(explanation in comments).cpp",
    "content": "//{ Driver Code Starts\n/* Driver program to test above function */\n\n#include<bits/stdc++.h>\nusing namespace std;\n\n// } Driver Code Ends\n//Back-end complete function Template for C++\nclass Solution\n{\n   public:\n    string ReFormatString(string S, int K){\n    \t\n    \tint n = S.size();\n    \tstring ans, temp;\n    \t\n    \t/*we start fro the end of the string , \n    \tbecause only the first group can have contain characters less than K*/\n    \tfor(int i=n-1;i>=0;i--){           \n    \t    char ch = S[i];\n    \t    \n    \t    //if we encounter a dash, ignore and continue\n    \t    if(ch=='-')\n    \t        continue;\n    \t    else{\n    \t        \n    \t        //change to uppercase\n    \t        temp+=toupper(ch);\n    \t        \n    \t        //check temp size\n    \t        if(temp.size() == K){\n    \t            \n    \t            //add temp to ans\n    \t            ans+=temp;      \n    \t            \n    \t            //add dash b/w them\n    \t            ans+='-';\n    \t            \n    \t            //empty the temp to search for next K elements\n    \t            temp=\"\";\n    \t        }\n    \t    }\n    \t}\n    \t\n    \t/*Adding the leftover elements(Since the size of temp never reached K, \n    \ttemp won't enter the if case nested inside the else ABOVE)*/\n    \tans+=temp;\n    \t\n    \t//Since we stored the elements in temp in reverse order, we'll reverse\n    \treverse(ans.begin(), ans.end());\n    \t\n    \t//Incase the first element is a dash, we would remove it\n    \tif(ans[0] == '-')\n    \t    ans.erase(ans.begin());\n    \t    \n    \treturn ans;\n    }\n};\n\n//{ Driver Code Starts.\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t    string S;\n\t    cin>>S;\n\t    int K;\n\t    cin >> K;\n\t    Solution ob;  \n\t    string ans=ob.ReFormatString(S, K);\n\t    cout<<ans;\n\t    cout<<\"\\n\";\n\t}\n\treturn 0;\n}\n\n// } Driver Code Ends\n"
  },
  {
    "path": "License Key Formatting.cpp",
    "content": "class Solution\n{\n   public:\n    string ReFormatString(string s, int k){\n    \tint n = s.size();\n    \tint cnt=0;\n    \tstring ans=\"\";\n    \tfor(int i=n-1;i>=0;i--){\n    \t   if(s[i] == '-'){\n    \t       if(cnt== k){\n    \t           cnt=0;\n    \t           ans+= '-';\n    \t       }\n    \t   }else{\n    \t       if(cnt == k){\n    \t           ans+= '-';\n    \t           cnt=0;\n    \t       }\n    \t       cnt++;\n    \t       if(s[i] <= 'z' && s[i] >= 'a'){\n    \t           ans += char('A' + (s[i]-'a'));\n    \t       }else{\n    \t           ans+= s[i];\n    \t       }\n    \t   }\n    \t}\n    \tif(ans.back() == '-'){\n    \t    ans.pop_back();\n    \t}\n    \treverse(ans.begin(), ans.end());\n    \treturn ans;\n    }\n};\n"
  },
  {
    "path": "License Key Formatting.java",
    "content": "class Solution{\n    static String ReFormatString(String S, int K){\n        StringBuilder ans = new StringBuilder();\n        int cnt = 0;\n        for(int i = S.length() - 1; i >= 0; i--) {\n                char ch = S.charAt(i);\n                if(ch != '-' && cnt < K){\n                    ans.append(Character.toUpperCase(ch));\n                    cnt++;\n                }\n                if(cnt==K){\n                    cnt = 0;\n                    ans.append('-');\n                }\n        }\n        ans.reverse();\n        if(ans.length() > 0 && ans.charAt(0)=='-') ans.deleteCharAt(0);\n        return ans.toString();\n        \n    }\n}\n"
  },
  {
    "path": "Linked List Cycle II.java",
    "content": "public class Solution {\n    public ListNode detectCycle(ListNode head) {\n        ListNode meet=detect(head);\n        if(meet==null)return meet;\n        ListNode temp=head;\n        while(temp!=meet){\n            temp=temp.next;\n            meet=meet.next;\n        }\n        return temp;\n    }\n    public ListNode detect(ListNode node){\n        ListNode slow=node;\n        ListNode fast=node;\n        while(fast!=null && fast.next!=null){\n            slow=slow.next;\n            fast=fast.next.next;\n            if(slow==fast)return fast;\n        }\n        return null;\n    }\n}\n"
  },
  {
    "path": "Linked List Cycle.java",
    "content": "public class Solution {\n    public boolean hasCycle(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            if(slow==fast)return true;\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "Longest Bitonic subsequence.cpp",
    "content": "class Solution{\n\tpublic:\n\tint LongestBitonicSequence(vector<int>nums)\n\t{\n\t    vector<int> Incre(nums.size(), 0 ), Dec(nums.size(), 0);\n\t    \n\t    Incre[0] = 1;\n\t    for(int i=1; i<nums.size(); i++){\n\t        int mx = 0;\n\t        for(int j=0;j<i;j++){\n\t            if(nums[j]<nums[i])\n\t                mx = max(mx, Incre[j]);\n\t        }\n\t        Incre[i] = mx + 1;\n\t    }\n\t    \n\t    Dec[nums.size()-1] = 1;\n\t    for(int i=nums.size()-2; i>=0; i--){\n\t        int mx = 0;\n\t        for(int j=i+1;j<nums.size();j++){\n\t            if(nums[j]<nums[i])\n\t                mx = max(mx, Dec[j]);\n\t        }\n\t        Dec[i] = mx + 1;\n\t    }\n\t    \n\t    int ans = 0;\n\t    \n\t    for(int i=0; i<nums.size(); i++){\n\t        ans = max(ans, Incre[i] + Dec[i] - 1);\n\t    }\n\t    \n\t    return ans;\n\t}\n};\n"
  },
  {
    "path": "Longest Common Prefix.java",
    "content": "public class Solution {\n    public String longestCommonPrefix(ArrayList<String> a) {\n        String ans=a.get(0);\n        int index=0;\n        String s=\"\";\n        for(int i=1;i<a.size();i++){\n            s=a.get(i);\n            index=0;\n            while(index<ans.length() && index<s.length()){\n                if(ans.charAt(index)!=s.charAt(index)){\n                    break;\n                }\n                index++;\n            }\n            ans=ans.substring(0,index);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Longest Common Subsequence.java",
    "content": "public class Solution {\n    public int solve(String A, String B) {\n        int n=A.length();\n        int m=B.length();\n        int[][]dp=new int[n+1][m+1];\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]=0;\n                }else if(A.charAt(i-1)==B.charAt(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        }\n        return dp[n][m];\n    }\n}\n"
  },
  {
    "path": "Longest Palindrome by Concatenating Two Letter Words",
    "content": "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']++;//increase the index for every word\n    int left = 0;\n    boolean odd = false;\n    for (int i = 0; i != 26; i++) {\n      odd |= (freq[i][i] & 1) == 1;\n      left += freq[i][i] / 2;\n      for (int j = i + 1; j != 26; j++)\n        left += Math.min(freq[i][j], freq[j][i]);//taking min times from both present \n    }\n    int res = left * 2 * 2;\n    if (odd){\n        res+=2;// middle element\n    } \n    return res;\n  }\n}\n"
  },
  {
    "path": "Longest Palindromic Subsequence.java",
    "content": "public class Solution {\n    public int solve(String A) {\n        int n=A.length();\n        int[][]dp=new int[n+1][n+1];\n        for(int i=0;i<A.length();i++){\n            dp[i][i]=1;\n        }\n        for(int i=0;i<A.length()-1;i++){\n            if(A.charAt(i)==A.charAt(i+1)){\n                dp[i][i+1]=2;\n            }else{\n                dp[i][i+1]=1;\n            }\n        }\n        for(int gap=3;gap<=A.length();gap++){\n            for(int i=0,j=i+gap-1;j<A.length();i++,j++){\n                if(A.charAt(i)==A.charAt(j)){\n                    dp[i][j]=2+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        return dp[0][A.length()-1];\n    }\n}\n"
  },
  {
    "path": "Longest Palindromic Substring.java",
    "content": "public class Solution {\n    public String longestPalindrome(String s) {\n        int n=s.length();\n        int sz=0;\n        int asnI=0;\n        int ansJ=0;\n        boolean[][]dp=new boolean[n][n];\n        for(int diff=0;diff<n;diff++){\n            for(int i=0,j=i+diff;j<n;i++,j++){\n                if(i==j){\n                    dp[i][j]=true;\n                }else if(diff==1){\n                    dp[i][j]=(s.charAt(i)==s.charAt(j))?true:false;    \n                }else{\n                    if(s.charAt(i)==s.charAt(j) && dp[i+1][j-1]){\n                        dp[i][j]=true;\n                    }\n                }\n                if(dp[i][j] && j-i+1>sz){\n                    sz=j-i+1;\n                    asnI=i;\n                    ansJ=j+1;\n                }\n            }\n        }\n        return s.substring(asnI,ansJ);\n    }\n}\n"
  },
  {
    "path": "Longest Path in a matrix - GFG/README.md",
    "content": "# Longest Path in a matrix\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a n*m&nbsp;matrix, find the maximum length path (starting from any cell) such that all cells along the path are in strictly increasing order.</span></p>\n\n<p><span style=\"font-size:18px\">We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1) or (i-1, j) or (i, j-1).</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>matrix = {{1,2,9},{5,3,8},{4,6,7}}\n<strong>Output: </strong>7\n<strong>Explanation: </strong>The longest increasing path is\n{1,2,3,6,7,8,9}.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>matrix = {{3,4,5},{3,2,6},{2,2,1}}\n<strong>Output: </strong>4\n<strong>Explanation: </strong>The longest increasing path is\n{3,4,5,6}.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anyhting. Your task is to complete the function&nbsp;<strong>longestIncreasingPath()&nbsp;</strong>which takes matrix as input parameter and returns the length of the lonest increasing path.<br>\n<br>\n<strong>Expected Time Complexity:&nbsp;</strong>O(n*m)<br>\n<strong>Expected Space Comeplxity:&nbsp;</strong>O(n*m)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n, m &lt;= 100<br>\n1 &lt;= matrix[i][j] &lt;= 10<sup>4</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Longest Path in a matrix - GFG/longest-path-in-a-matrix.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String[] S1 = br.readLine().trim().split(\" \");\n            int n  = Integer.parseInt(S1[0]);\n            int m = Integer.parseInt(S1[1]);\n            int[][] matrix = new int[n][m];\n            for(int i = 0; i < n; i++){\n                String[] S2 = br.readLine().trim().split(\" \");\n                for(int j = 0; j < m; j++){\n                    matrix[i][j] = Integer.parseInt(S2[j]);\n                }\n            }\n            Solution obj = new Solution();\n            int ans = obj.longestIncreasingPath(matrix);\n            System.out.println(ans);\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    int[][]dp;\n    int [][]arr;\n    public int longestIncreasingPath(int[][] matrix){\n        int n=matrix.length;\n        int m=matrix[0].length;\n        dp=new int[n][m];\n        arr=matrix;\n        int ans=Integer.MIN_VALUE;\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                ans=Math.max(ans,dfs(i,j));\n            }\n        }\n        return ans;\n    }\n    public int dfs(int i,int j){\n        if(valid(i,j)){\n            if(dp[i][j]!=0){\n                return dp[i][j];\n            }\n            int ans=0;        \n            if(valid(i+1,j) && arr[i+1][j]>arr[i][j]){\n                int curr=dfs(i+1,j);\n                ans=Math.max(ans,curr);\n            }\n            if(valid(i-1,j) && arr[i-1][j]>arr[i][j]){\n                int curr=dfs(i-1,j);\n                ans=Math.max(ans,curr);\n            }\n            if(valid(i,j+1) && arr[i][j+1]>arr[i][j]){\n                int curr=dfs(i,j+1);\n                ans=Math.max(ans,curr);\n            }\n            if(valid(i,j-1) && arr[i][j-1]>arr[i][j]){\n                int curr=dfs(i,j-1);\n                ans=Math.max(ans,curr);\n            }\n            dp[i][j]=ans+1;\n            return dp[i][j];\n        }else{\n            return 0;\n        }\n    }\n    public boolean valid(int i,int j){\n        int n=arr.length;\n        int m=arr[0].length;\n        if(i<0 || j<0 || i==n || j==m)return false;\n        return true;\n    }\n}"
  },
  {
    "path": "Longest Possible Route in a Matrix with Hurdles - GFG/README.md",
    "content": "# Longest Possible Route in a Matrix with Hurdles\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an N&nbsp;x M&nbsp;matrix, with a few hurdles(denoted by 0) arbitrarily placed, calculate the length of the longest possible route possible from source<strong>(xs,ys)</strong> to a destination<strong>(xd,yd)</strong> within the matrix. We are allowed to move to only adjacent cells which are not hurdles. The route cannot contain any diagonal moves and a location once visited in a particular path cannot be visited again.If it is impossible to reach the destination from the source return <strong>-1</strong>.</span></p>\n\n<p>&nbsp;</p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:</span></strong>\n<span style=\"font-size:18px\">{xs,ys} = {0,0}</span>\n<span style=\"font-size:18px\">{xd,yd} = {1,8}</span>\n<span style=\"font-size:18px\">matrix = 1 1 1 1 1 1 1 1 1 1</span>\n<span style=\"font-size:18px\">         1 1 0 1 1 0 1 1 0 1</span>\n<span style=\"font-size:18px\">         1 1 1 1 1 1 1 1 1 1</span>\n<strong><span style=\"font-size:18px\">Output: </span></strong><span style=\"font-size:18px\">24</span>\n<strong><span style=\"font-size:18px\">Explanation:</span></strong>\n<strong><span style=\"font-size:18px\"><img alt=\"\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/matrix_highlight.png\" style=\"height:175px; width:500px\" class=\"img-responsive\"></span></strong></pre>\n\n<p>&nbsp;</p>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input: </span></strong>\n<span style=\"font-size:18px\">{xs,ys} = {0,3}</span>\n<span style=\"font-size:18px\">{xd,yd} = {2,2}</span>\n<span style=\"font-size:18px\">matrix =<strong><span style=\"font-size:18px\"> </span></strong>1 0 0 1 0</span>\n<span style=\"font-size:18px\">         0 0 0 1 0</span>\n<span style=\"font-size:18px\">         0 1 1 0 0</span>\n<strong><span style=\"font-size:18px\">Output: </span></strong><span style=\"font-size:18px\">-1</span>\n<strong><span style=\"font-size:18px\">Explanation:</span></strong>\n<span style=\"font-size:18px\">We can see that it is impossible to</span>\n<span style=\"font-size:18px\">reach the cell (2,2) from (0,3).</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>longestPath()&nbsp;</strong>which takes matrix ,source and destination as&nbsp;input parameters and returns an integer denoting the longest path.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(2^(N*M))<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(N*M)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N,M &lt;= 10</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Longest Possible Route in a Matrix with Hurdles - GFG/longest-possible-route-in-a-matrix-with-hurdles.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\n\nclass IntArray\n{\n    public static int[] input(BufferedReader br, int n) throws IOException\n    {\n        String[] s = br.readLine().trim().split(\" \");\n        int[] a = new int[n];\n        for(int i = 0; i < n; i++)\n            a[i] = Integer.parseInt(s[i]);\n        \n        return a;\n    }\n    \n    public static void print(int[] a)\n    {\n        for(int e : a)\n            System.out.print(e + \" \");\n        System.out.println();\n    }\n    \n    public static void print(ArrayList<Integer> a)\n    {\n        for(int e : a)\n            System.out.print(e + \" \");\n        System.out.println();\n    }\n}\n\n\nclass IntMatrix\n{\n    public static int[][] input(BufferedReader br, int n, int m) throws IOException\n    {\n        int[][] mat = new int[n][];\n        \n        for(int i = 0; i < n; i++)\n        {\n            String[] s = br.readLine().trim().split(\" \");\n            mat[i] = new int[s.length];\n            for(int j = 0; j < s.length; j++)\n                mat[i][j] = Integer.parseInt(s[j]);\n        }\n        \n        return mat;\n    }\n    \n    public static void print(int[][] m)\n    {\n        for(var a : m)\n        {\n            for(int e : a)\n                System.out.print(e + \" \");\n            System.out.println();\n        }\n    }\n    \n    public static void print(ArrayList<ArrayList<Integer>> m)\n    {\n        for(var a : m)\n        {\n            for(int e : a)\n                System.out.print(e + \" \");\n            System.out.println();\n        }\n    }\n}\n\nclass GFG {\n    public static void main(String[] args) throws IOException {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int t;\n        t = Integer.parseInt(br.readLine());\n        while(t-- > 0){\n            \n            int[] a = IntArray.input(br, 2);\n            \n            \n            int[] b = IntArray.input(br, 4);\n            \n            \n            int[][] mat = IntMatrix.input(br, a[0], a[1]);\n            \n            Solution obj = new Solution();\n            int res = obj.longestPath(mat,a[0],a[1],b[0],b[1],b[2],b[3]);\n            \n            System.out.println(res);\n            \n        }\n    }\n}\n// } Driver Code Ends\n\n\nclass Solution {\n    static int xd;\n    static int yd;\n    public static int longestPath(int[][] mat,int n,int m,int xs,int ys,int x,int y) {\n        xd=x;\n        yd=y;\n        boolean[][]vis=new boolean[n][m];\n        int ans=dfs(mat,xs,ys,vis);\n        return ans<0?-1:ans;\n    }\n    public static int dfs(int[][]mat,int x,int y,boolean[][]vis){\n        if(!valid(mat,x,y,vis))return Integer.MIN_VALUE;\n        if(x==xd && y==yd)return 0;\n        \n        vis[x][y]=true;\n        \n        int ans=Integer.MIN_VALUE;\n        \n        if(valid(mat,x+1,y,vis))\n            ans=Math.max(ans,1+dfs(mat,x+1,y,vis));\n        if(valid(mat,x,y+1,vis))\n            ans=Math.max(ans,1+dfs(mat,x,y+1,vis));\n        if(valid(mat,x-1,y,vis))\n            ans=Math.max(ans,1+dfs(mat,x-1,y,vis));\n        if(valid(mat,x,y-1,vis))\n            ans=Math.max(ans,1+dfs(mat,x,y-1,vis));\n            \n        vis[x][y]=false;\n        return ans;\n    }\n    \n    public static boolean valid(int[][]mat,int x,int y,boolean[][]vis){\n        if(x<0 || y<0 || x==mat.length || y==mat[0].length)return false;\n        if(mat[x][y]==0 || vis[x][y])return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "Longest Sub-Array with Sum K.cpp",
    "content": "class Solution{\n    public:\n    int lenOfLongSubarr(int A[],  int N, int K) \n    { \n        // Complete the function\n        map<int,int> mp;\n        mp.insert({0,-1});\n      \n        int ans = 0, sum = 0;\n        \n        for(int i=0; i<N; i++)\n        {\n            sum += A[i];\n            \n            if(mp.find(sum-K) != mp.end())\n            ans = max(ans, (i-mp[sum-K]));\n            \n            if(mp.find(sum) == mp.end())\n            mp[sum] = i;\n        }\n        \n        return ans;\n    } \n  \n};\n"
  },
  {
    "path": "Longest Sub-Array with Sum K.java",
    "content": "class Solution{\n    \n   \n    // Function for finding maximum and value pair\n    public static int lenOfLongSubarr (int A[], int N, int K) {\n        //Complete the function\n        Map<Integer,Integer> map=new HashMap<>();\n        int sum=0;\n        int length=0;\n        for(int i=0;i<N;i++){\n            sum+=A[i];\n            if(sum==K){\n                length=i+1;\n            }else if(map.containsKey(sum-K)){\n                length=Math.max(length,i-map.get(sum-K));\n            }\n            \n            if(!map.containsKey(sum)){\n                map.put(sum,i);\n            }\n        }\n        return length;\n    }\n    \n    \n}\n"
  },
  {
    "path": "Longest subarray with sum divisible by K - GFG/README.md",
    "content": "# Longest subarray with sum divisible by K\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array containing <strong>N</strong> integers and a positive integer <strong>K</strong>, find the length of the longest sub array with sum of the elements divisible by the given value <strong>K</strong>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>A[] = {2, 7, 6, 1, 4, 5}\nK = 3\n<strong>Output:</strong> 4\n<strong>Explanation:</strong>The subarray is {7, 6, 1, 4}\nwith sum 18, which is divisible by 3.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>A[] = {-2, 2, -5, 12, -11, -1, 7}\nK = 3\n<strong>Output:</strong> 5\n<strong>Explanation:\n</strong>The subarray is {2,-5,12,-11,-1} with\nsum -3, which is divisible by 3.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThe input is already taken care of by the driver code. You only need to complete the function <strong>longSubarrWthSumDivByK()</strong> that takes an array <strong>(arr)</strong>, sizeOfArray <strong>(n)</strong>, positive integer <strong>K</strong>, and return the length of the longest subarray which has sum divisible by <strong>K</strong>. The driver code takes care of the printing.<br>\n<br>\n<strong>Expected Time Complexity:</strong>&nbsp;O(N).<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(N).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1&lt;=N,K&lt;=10<sup>6</sup><br>\n-10<sup>5</sup>&lt;=A[i]&lt;=10<sup>5</sup></span><br>\n&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Longest subarray with sum divisible by K - GFG/longest-subarray-with-sum-divisible-by-k.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\n\n // } Driver Code Ends\n//User function Template for Java\n\nclass Solution{\n    int longSubarrWthSumDivByK(int a[], int n, int k){\n        int prefixSum = 0;\n        int maxResult = 0;\n        HashMap<Integer,Integer> map = new HashMap<>();\n        for (int i = 0; i < a.length; i++) {\n            prefixSum += a[i];\n            int rem = ((prefixSum%k) + k) % k;\n            if(rem == 0)maxResult = i + 1;\n            if(map.containsKey(rem))\n                maxResult = Math.max(maxResult,i-map.get(rem));\n            else\n                map.put(rem,i);\n        }\n        return  maxResult;\n    }\n}\n// { Driver Code Starts.\n\n// Driver class\nclass GFG {\n    \n    // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t    \n\t\t    String line1 = br.readLine();\n\t\t    String[] element = line1.trim().split(\"\\\\s+\");\n\t\t    int sizeOfArray = Integer.parseInt(element[0]);\n\t\t    int K = Integer.parseInt(element[1]);\n\t\t    \n\t\t    int arr [] = new int[sizeOfArray];\n\t\t    \n\t\t    String line = br.readLine();\n\t\t    String[] elements = line.trim().split(\"\\\\s+\");\n\t\t    \n\t\t    for(int i = 0;i<sizeOfArray;i++){\n\t\t        arr[i] = Integer.parseInt(elements[i]);\n\t\t    }\n\t\t    \n\t\t    Solution obj = new Solution();\n\t\t   \n\t\t    int res = obj.longSubarrWthSumDivByK(arr, sizeOfArray, K);\n\t\t    \n\t\t    System.out.println(res);\n\t\t    \n\t\t    \n\t\t}\n\t}\n}\n\n\n  // } Driver Code Ends"
  },
  {
    "path": "Longest substring to form a Palindrome - GFG/README.md",
    "content": "# Longest substring to form a Palindrome\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string <strong>S </strong>which only contains lowercase alphabets. Find the length of the longest substring of <strong>S</strong> such that the characters in it can be rearranged to form a <a href=\"https://www.geeksforgeeks.org/c-program-check-given-string-palindrome/\" target=\"_blank\">palindrome</a>. </span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>S = \"aabe\"\n<strong>Output:\n</strong>3\n<strong>Explanation:</strong>\nThe substring \"aab\" can be rearranged to\n\"aba\" which is the longest palindrome\npossible for this String.</span>\n</pre>\n\n<div><span style=\"font-size:18px\"><strong>Example 2:</strong></span></div>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>S = \"adbabd\"\n<strong>Output:</strong>\n6</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\nThe whole string “adbabd” can be\nrearranged to form a palindromic substring.\nOne possible arrangement is \"abddba\".\nThus, output length of the string is 6. </span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>longestSubstring()</strong>&nbsp;which takes a String S as input and returns the length of largest possible Palindrome.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(|S|*26)<br>\n<strong>Expected Auxiliary Space:</strong> O(|S|*26)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ |S| ≤ 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Longest substring to form a Palindrome - GFG/longest-substring-to-form-a-palindrome.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            String S = read.readLine();\n            \n            Solution ob = new Solution();\n            System.out.println(ob.longestSubstring(S));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    static int longestSubstring(String S) {\n        \n        int n = S.length();\n        Map<Integer, Integer> index = new HashMap<>();\n      \n        // Initialize answer with 0 \n        int answer = 0;\n      \n        int mask = 0;\n        index.put(mask, -1);\n        \n        for(int i = 0; i < n; i++){\n            int temp = (int)S.charAt(i) - 97;\n            // Turn the temp-th bit on if \n            // character occurs odd number \n            // of times and turn off the temp-th \n            // bit off if the character occurs \n            // ever number of times \n            mask ^= (1 << temp);\n            // If a mask is present in the index \n            // Therefore a palindrome is \n            // found from index[mask] to i \n            if (index.containsKey(mask)){ \n                answer = Math.max(answer, i - index.get(mask)); \n            }\n            // If x is not found then add its \n            // position in the index dict. \n            else\n                index.put(mask,i); \n            \n            // Check for the palindrome of \n            // odd length \n            for (int j = 0;j < 26; j++){\n                // We cancel the occurrence \n                // of a character if it occurs \n                // odd number times \n                int mask2 = mask ^ (1 << j);\n                if (index.containsKey(mask2))\n                { \n                    answer = Math.max(answer, \n                        i - index.get(mask2)); \n                }\n            }\n        }\n        return answer;\n    }\n};"
  },
  {
    "path": "Longest valid Parentheses.java",
    "content": "public class Solution {\n    public int longestValidParentheses(String s) {\n        int ans=0;\n        int n=s.length();\n        int open=0;\n        int close=0;\n        for(int i=0;i<n;i++){\n            if(s.charAt(i)==')'){\n                close++;\n            }else{\n                open++;\n            }\n            if(close>open){\n                open=close=0;\n            }else if(open==close)\n                ans=Math.max(ans,open*2);\n        }\n        open=close=0;\n        for(int i=n-1;i>=0;i--){\n            if(s.charAt(i)==')')\n                close++;\n            else\n                open++;\n            \n            if(close<open)\n                open=close=0;\n            else if(open==close)\n                ans=Math.max(ans,open*2);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "M-Coloring Problem.java",
    "content": "class solve {\n    // Function to determine if graph can be coloured with at most M colours\n    // such\n    // that no two adjacent vertices of graph are coloured with same colour.\n    public boolean graphColoring(boolean graph[][], int m, int n) {\n        // Your code here\n        Map<Integer,ArrayList<Integer>> map=new HashMap<>();\n        for(int i=0;i<n;i++){\n            map.put(i,new ArrayList<>());\n            for(int j=0;j<n;j++){\n                if(graph[i][j]){\n                    map.get(i).add(j);\n                }\n            }\n        }\n        int[]col=new int[n];//index===node, value==color nummber\n        return dfs(map,0,col,n,m);\n    }\n    boolean dfs(Map<Integer,ArrayList<Integer>> map,int currNode,int[]col,int n,int m){\n        if(currNode==n)return true;\n        for(int currColor=1;currColor<=m;currColor++){\n            if(safe(currNode,currColor,map,col)){\n                col[currNode]=currColor;\n                if(dfs(map,currNode+1,col,n,m))return true;\n                col[currNode]=0;//backtracking\n            }\n        }\n        return false;\n    }\n    \n    boolean safe(int currNode,int currColor,Map<Integer,ArrayList<Integer>> map,int[]col){\n        ArrayList<Integer> arr=map.get(currNode);\n        for(int neb:arr){\n            if(col[neb]==currColor)return false;\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "MInimum time to fulfil all orders.cpp",
    "content": "class Solution{\n    public:\n  \n    // Function to return number of donuts prepared by R rank in T time\n    int countDonut(int R, int T)\n    {\n        int cnt = 1;\n        \n        while(T-R*cnt >= 0)\n        {\n            T -= R*cnt;\n            cnt++;\n        }\n        \n        return cnt-1;\n    }\n    \n    int findMinTime(int N, vector<int>&A, int L){\n        //write your code here\n        int ans = INT_MAX;\n        int low = 0, high = INT_MAX;\n        \n        while(low <= high)\n        {\n            int mid = low + (high-low)/2;\n            int cnt = 0;\n            \n            for(auto it : A)\n            cnt += countDonut(it, mid);\n            \n            if(cnt >= N)\n            {\n                ans = mid;\n                high = mid-1;\n            }\n            else\n                low = mid+1;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "Magician and Chocolates.java",
    "content": "public class Solution {\n    public int nchoc(int A, ArrayList<Integer> B) {\n        Queue<Integer> pq=new PriorityQueue<>((a,b)->b-a);\n        pq.addAll(B);\n        int ans=0;\n        int mod=1000000007;\n        while(A-->0){\n            int ele=pq.remove();\n            ans=(ans%mod +ele%mod)%mod;\n            pq.add(ele/2);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Magnet Array Problem - GFG/README.md",
    "content": "# Magnet Array Problem\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given <strong>N</strong> Magnets which are placed linearly, with each magnet to be considered as of point object. Each magnet suffers force from its left sided magnets such that they repel it to the right and vice versa. <strong>All forces are repulsive</strong>. The force being equal to the distance (1/d ,&nbsp;d being the distance). Now given the positions of the magnets, the task to find&nbsp;all the points along the linear line where net force is <strong>ZERO</strong>.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\">More Formally, Magnets are placed on X axis, the coordinates of which are given, you are asked to find out the X-co-ordinates of all the equilibrium points (i.e. the point where net force is zero). You notice the point each magnet repels each other, it means the polarity of the magnet is such that exerts +ve force in its right side and -ve force in left side, (here +ve is considered in +ve direction of x-axis). And that forces are inversely proportional to the distance, thus there lies an equilibrium point between every two magnetic points. Thus there will be total of <strong>N-1</strong> equllibrium points. You have to find those N-1 points.<br>\n<strong>Note:</strong> Array <strong>M[]</strong> is <strong>sorted</strong> and distance have to be calculated with precision of <strong>2 decimal places</strong>.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 2\nM[] = {1, 2}\n<strong>Output:</strong>\n1.50\n<strong>Explanation:\n</strong>The mid point of two points will have \nnet force zero, thus answer = 1.50\n</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4\nM[] = {0, 10, 20, 30}\n<strong>Output:</strong>\n3.82, 15.00, 26.18</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>nullPoints()</strong>&nbsp;which takes the array <strong>M[]</strong>, its size <strong>N </strong>as inputs and an answer array<strong> getAnswer[] </strong>to <strong>store</strong> the points having <strong>net force zero</strong> till precised two decimal places.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N<sup>2</sup>&nbsp;* Log(N))<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n2 ≤ N ≤ 10<sup>5</sup><br>\n0 ≤ &nbsp;M[1] &lt; ....M[i] &lt; M[i+1] &lt; ....M[N] ≤ 10<sup>6</sup></span><br>\n&nbsp;</p>\n\n<p>&nbsp;</p>\n\n<p>&nbsp;</p>\n\n<p>&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Magnet Array Problem - GFG/magnet-array-problem.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\n\nclass GFG {\n\tpublic static void main(String[] args) throws IOException\n\t{\n\t        BufferedReader br =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t =\n            Integer.parseInt(br.readLine().trim()); // Inputting the testcases\n        while(t-->0)\n        {\n            int n = Integer.parseInt(br.readLine().trim());\n            double a[] = new double[(int)(n)];\n            double getAnswer[] = new double[(int)(n)];\n            String inputLine[] = br.readLine().trim().split(\" \");\n            for (int i = 0; i < n; i++) {\n                a[i] = Double.parseDouble(inputLine[i]);\n            }\n            \n            Solution obj = new Solution();\n            obj.nullPoints(n, a, getAnswer); \n            \n            StringBuilder output = new StringBuilder();\n            for(int i=0;i<n-1;i++)\n                output.append(String.format(\"%.2f\", getAnswer[i])+\" \");\n                \n            System.out.println(output);\n            \n        }\n\t}\n}\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    \n    public void nullPoints(int n, double magnets[], double getAnswer[])\n    {\n        for(int i=0;i<n-1;i++){\n            getAnswer[i]=solve(n,magnets,magnets[i],magnets[i+1]);\n        }\n    }\n    public double solve(int n,double arr[],double low,double high){\n        while(low<high){\n            double mid=(low+high)/2.0;\n            double frc=force(arr,n,mid);\n            if(Math.abs(frc)<0.0000001){\n                return mid;\n            }else if(frc<0){\n                high=mid;\n            }else{\n                low=mid;\n            }\n        }\n        return low;\n    }\n    public double force(double arr[],int n,double mid){\n        double frc=0.00;\n        for(int i=0;i<n;i++){\n            frc+=1/(mid-arr[i]);\n        }\n        return frc;\n    }\n}\n\n\n"
  },
  {
    "path": "Majority Element.java",
    "content": "//Boyer-Moore Voting Algorithm\n\nclass Solution {\n    public int majorityElement(int[] nums) {\n        int count = 0;\n        Integer candidate = null;\n\n        for (int num : nums) {\n            if (count == 0) {\n                candidate = num;\n            }\n            count += (num == candidate) ? 1 : -1;\n        }\n\n        return candidate;\n    }\n}\n\n//=================================================================\n\n//recursive\nclass Solution {\n\npublic int majorityElement(int[] nums) {\n        return recurse(nums, 0);\n    }\n    \n    public int recurse(int[] nums, int start){\n        int n = nums.length;\n        int tracker= 1;\n        for(int i=start+1;i<n;i++){\n            if(nums[start]==nums[i]){\n                tracker++;\n            }else{\n                tracker--;\n            }\n            if(tracker==0){\n                return recurse(nums, i+1);\n            }\n        }\n        return nums[start];\n    }\n}\n\n//=====================================================================\n//Naive approach using map\n    class Solution {\n    public int majorityElement(int[] nums) {\n        Map<Integer,Integer> map=new  HashMap<>();\n        for(int i=0;i<nums.length;i++){\n            if(!map.containsKey(nums[i])){\n                map.put(nums[i],1);\n            }else{\n                int count = map.get(nums[i]);\n                map.put(nums[i], count + 1);\n            }\n        }\n        return Collections.max(map.entrySet(),Comparator.comparingInt(Map.Entry::getValue))\n            .getKey();\n    }\n}\n"
  },
  {
    "path": "Make equal elements Array.java",
    "content": "public class Solution {\n    public int solve(int[] A, int B) {\n        Set<Integer> set=new HashSet<>();\n        set.add(A[0]+B);\n        set.add(A[0]-B);\n        for(int i=1;i<A.length;i++){\n            if(!set.contains(A[i]+B) && !set.contains(A[i]-B) && !set.contains(A[i])){\n                return 0;\n            }\n        }\n        return 1;\n    }\n}\n"
  },
  {
    "path": "Matrix Chain Multiplication.cpp",
    "content": "class Solution{\npublic:\n    int solve(vector<vector<int>> &dp, int arr[] , int i , int j)\n    {\n        if(i == j)\n            return dp[i][j] = 0;\n        if(dp[i][j] != -1)\n            return dp[i][j];\n         \n        int mn = INT_MAX;   \n        for(int k = i;k<j;k++)\n        {\n            mn = min(mn , solve(dp ,arr, i , k) + solve(dp ,arr, k+1 , j) + arr[i]*arr[k+1]*arr[j+1]);\n        }\n        \n        return dp[i][j] = mn;   \n    }\n    int matrixMultiplication(int N, int arr[])\n    {\n        vector<vector<int>> dp(N-1 , vector<int>(N-1 , -1));\n        solve(dp , arr , 0 , N-2);\n        return dp[0][N-2];\n        // code here\n    }\n};\n"
  },
  {
    "path": "Matrix Exponentiation - GFG/README.md",
    "content": "# Matrix Exponentiation\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an equation of the form f(n) = f(n-1) + f(n-2) where f(0) = 1, F(1) = 1&nbsp;, the task is to find the n<sup>th</sup>&nbsp;term of this sequence.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>n = 3\n<strong>Output: </strong>3\n<strong>Explanation: </strong>f(3) = f(2) + f(1) = 3\n</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>n = 2\n<strong>Output: </strong>2\n<strong>Explanation: </strong>f(2) = f(1) + f(0) = 2</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Yout Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>FindNthTerm()&nbsp;</strong>which takes n as input parameter and returns n<sup>th</sup>&nbsp;term mod 10^9+7&nbsp;.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Compelxity:&nbsp;</strong>O(log(n))<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(K) where K is constant.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n &lt;= 10<sup>9</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Matrix Exponentiation - GFG/matrix-exponentiation.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            int n = Integer.parseInt(br.readLine().trim());\n            Solution ob = new Solution();\n            int ans = ob.FindNthTerm(n);\n            System.out.println(ans);\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n    static long mod = 1000000007;\n    \n    long[][] multiply(long [][]m1, long[][]m2)\n    {\n        long ans[][] =new long[2][2];\n        for(int i=0;i<2;i++)\n            for(int j=0;j<2;j++)\n                for(int k=0;k<2;k++)\n                    ans[i][j] += (m1[i][k]*m2[k][j])%mod;\n        return ans;\n    }\n    \n    \n    long[][] matPow(long [][]mat,long n){\n        if(n == 1)return mat;\n        long[][] ans = matPow(mat,n/2);\n        ans = multiply(ans,ans);\n        if((n&1) == 1)ans = multiply(ans,mat);\n        return ans;\n    }\n    \n    public int FindNthTerm(int N){\n       long n = N;\n       if(n==1 || n==0)return 1;\n       long mat[][] = {{1,1},{1,0}};\n       mat = matPow(mat,n);\n       return (int) (mat[0][0]%mod);\n    }\n}"
  },
  {
    "path": "Matrix Operations.java",
    "content": "class Solution{\n    static int[]UP=new int[]{-1,0};\n    static int[]RIGHT=new int[]{0,1};\n    static int[]DOWN=new int[]{1,0};\n    static int[]LEFT=new int[]{0,-1};\n    static int [] endPoints(int [][]arr, int m, int n){\n        char dir='R';\n        int row=0;\n        int col=0;\n        while(true){\n            if(arr[row][col]==1){\n                arr[row][col]=0;\n                dir=changeDir(dir);\n            }\n            int[]move=getDir(dir);\n            if(outOfBounds(arr,row+move[0],col+move[1])){\n                return new int[]{row,col};\n            }else{\n                row+=move[0];\n                col+=move[1];\n            }\n        }\n    }\n    static boolean outOfBounds(int[][] arr,int row,int col){\n        int a=arr.length;\n        int b=arr[0].length;\n        if(row>=a)return true;\n        if(col>=b)return true;\n        if(row<0 || col<0)return true;\n        return false;\n    }\n    static int[] getDir(char c){\n        if(c=='U'){\n            return UP;\n        }else if(c=='D'){\n            return DOWN;\n        }else if(c=='R'){\n            return RIGHT;\n        }else{\n            return LEFT;\n        }\n    }\n    static char changeDir(char c){\n        if(c=='R'){\n            return 'D';\n        }else if(c=='D'){\n            return 'L';\n        }else if(c=='L'){\n            return 'U';\n        }else{\n            return 'R';\n        }\n    }\n}\n"
  },
  {
    "path": "Matrix Search.java",
    "content": "public class Solution {\n    public int searchMatrix(ArrayList<ArrayList<Integer>> A, int B) {\n        return dfs(A,B,0,A.size()-1);\n    }\n    public int dfs(ArrayList<ArrayList<Integer>> A, int B,int l,int h){\n        if(l<=h){\n            int mid=l+(h-l)/2;\n            if(A.get(mid).get(0)>B){\n                return dfs(A,B,l,mid-1);\n            }else if(A.get(mid).get(A.get(mid).size()-1)<B){\n                return dfs(A,B,mid+1,h);\n            }else{\n                if(A.get(mid).contains(B))return 1;\n            }\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Max Depth of Binary Tree.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    public int maxDepth(TreeNode A) {\n        if(A==null)\n            return 0;\n        return 1 + Math.max(maxDepth(A.left),maxDepth(A.right));\n    }\n}\n"
  },
  {
    "path": "Max Distance.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public int maximumGap(final int[] arr) {\n        int n=arr.length;\n        int lmin[]=new int[n];\n        int rmax[]=new int[n];\n        int ans=-1;\n        lmin[0]=arr[0];\n        rmax[n-1]=arr[n-1];\n        for(int i=1;i<n;i++)\n            lmin[i]=Math.min(lmin[i-1],arr[i]);\n        for(int i=n-2;i>=0;i--)\n            rmax[i]=Math.max(rmax[i+1],arr[i]);\n        int i=0,j=0;\n        while(i<n && j<n){\n            if(lmin[i]<=rmax[j]){\n                ans=Math.max(ans,j-i);\n                j++;\n            }\n            else\n                i++;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Max Non Negative SubArray.java",
    "content": "public class Solution {\n    public ArrayList<Integer> maxset(ArrayList<Integer> a) {\n        long max=0;\n        ArrayList<Integer> ans=new ArrayList<>();\n        int i=0;\n        while(i<a.size()){\n            long curr=0;\n            ArrayList<Integer> maybe=new ArrayList<>();\n            while(i<a.size()){\n                if(a.get(i)<0)break;\n                maybe.add(a.get(i));\n                curr+=a.get(i);\n                i++;\n            }\n            if(curr>max){\n                max=curr;\n                ans.clear();\n                ans=maybe;\n            }else if(curr==max){\n                if(maybe.size()>ans.size()){\n                    ans.clear();\n                    ans=maybe;\n                }\n            }\n            i++;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Max Product Subarray.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public int maxProduct(final int[] nums) {\n        int length = nums.length;\n        int result = nums[0];;\n        int curr_max = nums[0];\n        int curr_min = nums[0];\n        for(int i =1; i < length; i++){\n            int curr_max_prev= curr_max;\n            curr_max = Math.max(nums[i], Math.max(curr_max*nums[i], curr_min*nums[i]));\n            curr_min = Math.min(nums[i], Math.min(curr_max_prev*nums[i], curr_min*nums[i]));\n            result = Math.max(result,curr_max);     \n        }        \n        return result;   \n    }\n}\n"
  },
  {
    "path": "Max Rectangle in Binary Matrix.java",
    "content": "public class Solution {\n    public int maximalRectangle(int[][] a) {\n        int max=Integer.MIN_VALUE;\n        for(int i=0;i<a.length;i++){\n            if(i==0){\n                max=Math.max(max,largestRectangleArea(a[i]));\n            }else{\n                for(int j=0;j<a[i].length;j++){\n                    if(a[i][j]!=0){\n                        a[i][j]+=a[i-1][j];\n                    }\n                }\n                max=Math.max(max,largestRectangleArea(a[i]));\n            }\n        }\n        return max;\n    }\n    public int largestRectangleArea(int[] a) {\n        int max=0;\n        int ps[]=prevSmallest(a);\n        int ns[]=nextSmallest(a);\n        for(int i=0;i<a.length;i++){\n            int cur=(ns[i]-ps[i]-1)*a[i];\n            max=Math.max(max,cur);\n        }\n        return max;\n        \n    }\n    public int[] prevSmallest(int[]a){\n        int ps[]=new int[a.length];\n        Deque<Integer> s=new ArrayDeque<>();\n        for(int i=0;i<a.length;i++){\n            while(!s.isEmpty() && a[s.peek()]>=a[i]){\n                s.pop();\n            }\n            if(s.isEmpty()){\n                ps[i]=-1;\n            }else{\n                ps[i]=s.peek();\n            }\n            s.push(i);\n        }\n        return ps;\n    }\n    public int[] nextSmallest(int[]a){\n        int ns[]=new int[a.length];\n        Deque<Integer> s=new ArrayDeque<>();\n        for(int i=a.length-1;i>=0;i--){\n            while(!s.isEmpty() && a[s.peek()]>=a[i]){\n                s.pop();\n            }\n            if(s.isEmpty()){\n                ns[i]=a.length;\n            }else{\n                ns[i]=s.peek();\n            }\n            s.push(i);\n        }\n        return ns;\n    }\n}\n"
  },
  {
    "path": "Max Sum Path in Binary Tree.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    Map<TreeNode,Integer> map;\n    public int maxPathSum(TreeNode A) {\n        if(A==null)return 0;\n        map=new HashMap<>();\n        return dfs(A);\n    }\n    int dfs(TreeNode A){\n        if(A==null)\n            return Integer.MIN_VALUE;\n        int s=A.val;\n        if(A.left!=null && sum(A.left)>0)\n            s=s+sum(A.left);\n        if(A.right!=null && sum(A.right)>0)\n            s=s+sum(A.right);\n        return max(s,dfs(A.left),dfs(A.right));\n    }\n    int max(int a,int b,int c){\n        return (a>b&&a>c?a:(b>c?b:c));\n    }\n    int sum(TreeNode A){\n        if(A==null)\n            return 0;\n        if(map.containsKey(A))return map.get(A);\n        int ans=A.val+Math.max(sum(A.left),sum(A.right));\n        map.put(A,ans);\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Max length chain.cpp",
    "content": "class Solution{\npublic:\n    /*You are required to complete this method*/\n    int maxChainLen(struct val p[],int n){\n        //Your code here\n        vector<pair<int,int>>ans;\n        for(int i=0;i<n;i++)\n        {\n            ans.push_back({p[i].second,p[i].first});\n        }\n        sort(ans.begin(),ans.end());\n        int count=1;\n        int x = ans[0].first;\n        for(int i=0;i<n-1;i++)\n        {\n            if(ans[i+1].second>x)\n            {\n                x = ans[i+1].first;\n                count++;\n            }\n        }\n        return count;\n    }\n};\n"
  },
  {
    "path": "Max length chain.java",
    "content": "class GfG\n{\n    int maxChainLength(Pair arr[], int n)\n    {\n        Arrays.sort(arr,(a,b)->a.y-b.y);\n        int ans=1;\n        int prev=arr[0].y;\n        for(int i=1;i<n;i++){\n            if(arr[i].x>prev){\n                prev=arr[i].y;\n                ans++;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Maximize Distance to Closest Person",
    "content": "class Solution {\n    public int maxDistToClosest(int[] seats) {\n        int max=Integer.MIN_VALUE;\n        for(int i=0;i<seats.length;i++){\n            if(seats[i]==0){\n                max=Math.max(max,closestPerson(seats,i));\n            }\n        }\n        return max;\n    }\n    public int closestPerson(int[]a,int i){\n        int leftClosest=0;\n        int x=i-1;\n        while(x>=0){\n            leftClosest++;\n            if(a[x]==1)break;\n            x--;\n        }\n        int y=i+1;\n        int rightClosest=0;\n        while(y<a.length){\n            rightClosest++;\n            if(a[y]==1)break;\n            y++;\n        }\n        if(y==a.length){\n            return rightClosest+leftClosest;\n        }\n        if(leftClosest==0){\n            return rightClosest;\n        }\n        return Math.min(leftClosest,rightClosest);\n    }\n}\n"
  },
  {
    "path": "Maximize The Array - GFG/README.md",
    "content": "# Maximize The Array\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two integer arrays Arr1 and Arr2 of size N. Use the greatest elements from the given arrays to create a new array of size N such that it consists of only unique elements and the sum of all its elements is maximum.<br>\nThe created elements should contain the elements of Arr2 followed by elements of Arr1 in order of their appearance.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 5\nArr1 = {7, 4, 8, 0, 1}\nArr2 = {9, 7, 2, 3, 6}\n<strong>Output: </strong>9 7 6 4 8\n<strong>Explanation:</strong> 9, 7, 6 are from 2nd array\nand 4, 8 from 1st array.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>N = 4\nArr1 = {6, 7, 5, 3}\nArr2 = {5, 6, 2, 9} \n<strong>Output:</strong> 5 6 9 7 \n<strong>Explanation:</strong> 5, 6, 9 are from 2nd array\nand 7 from 1st array.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task: </strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>maximizeArray()</strong> which takes the array arr1[], arr2[] and n as input parameters and returns the desired array of integers.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(NlogN)<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N &lt;= 10<sup>5</sup><br>\n0 &lt;=| Arr1[i] |&lt;= 10<sup>9</sup><br>\n0 &lt;= |Arr2[i] |&lt;= 10<sup>9</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Maximize The Array - GFG/maximize-the-array.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*;\n\npublic class GFG {\n\n    public static void main(String[] args) throws Exception {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int tc = Integer.parseInt(br.readLine().trim());\n        while (tc-- > 0) {\n            String[] inputLine;\n            int n = Integer.parseInt(br.readLine().trim());\n            int[] arr1 = new int[n], arr2 = new int[n];\n            inputLine = br.readLine().trim().split(\" \");\n            for (int i = 0; i < n; i++) {\n                arr1[i] = Integer.parseInt(inputLine[i]);\n            }\n            inputLine = br.readLine().trim().split(\" \");\n            for (int i = 0; i < n; i++) {\n                arr2[i] = Integer.parseInt(inputLine[i]);\n            }\n\n            ArrayList<Integer> ans = new Solution().maximizeArray(arr1, arr2, n);\n            for (Integer x : ans) {\n                System.out.print(x + \" \");\n            }\n            System.out.println();\n        }\n    }\n}\n// } Driver Code Ends\n\nclass Solution {\n    ArrayList<Integer> maximizeArray(int[] arr1, int[] arr2, int n) {\n        ArrayList<Integer> ans=new ArrayList<>();\n        PriorityQueue<Integer> pq=new PriorityQueue<>((a,b)->b-a);\n        for(int i:arr1)pq.add(i);\n        for(int i:arr2)pq.add(i);\n        Set<Integer> set=new HashSet<Integer>();\n        while(set.size()!=n && pq.size()>0){\n            set.add(pq.remove());\n        }\n        for(int i:arr2){\n            if(set.contains(i)){\n                ans.add(i);\n                set.remove(i);\n            }\n        }\n        for(int i:arr1){\n            if(set.contains(i)){\n                ans.add(i);\n                set.remove(i);\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "Maximize the sum of selected numbers from an array to make it empty - GFG/README.md",
    "content": "# Maximize the sum of selected numbers from an array to make it empty\n## Medium\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Given a array of<strong> N</strong> numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number A<sub>i</sub>, delete one occurrence of&nbsp;<strong>A<sub>i</sub>-1 (if exists), and A<sub>i</sub></strong>&nbsp;each from the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of the selected numbers.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[ ] = {1, 2, 2, 2, 3, 4}\n<strong>Output :</strong> 10\n<strong>Explanation:</strong>\nWe select 4, so 4 and 3 are deleted leaving us with {1,2,2,2}.\nThen we select 2, so 2 &amp; 1 are deleted. We are left with{2,2}.\nWe select 2 in next two steps, thus the sum is 4+2+2+2=10.\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[ ] = {1, 2, 3} <strong>\nOutput :</strong>  4\n<strong>Explanation:</strong> We select 3, so 3 and 2 are deleted leaving us with {1}. Then we select 1, 0 doesn't exist so we delete 1. thus the sum is 3+1=4.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function <strong>maximizeSum()</strong> that takes an array <strong>(arr)</strong>, sizeOfArray <strong>(n),</strong>&nbsp;and return the maximum sum of the selected numbers. The driver code takes care of the printing.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(N).</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n1 ≤ A[i] ≤ 10<sup>5</sup><br>\n<strong>Note:</strong> Numbers need to be selected from maximum to minimum.</span></p>\n</div>"
  },
  {
    "path": "Maximize the sum of selected numbers from an array to make it empty - GFG/maximize-the-sum-of-selected-numbers-from-an-array-to-make-it-empty.java",
    "content": "//{ Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\n\nclass Array {\n    \n    // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t    String line = br.readLine();\n\t\t    String[] element = line.trim().split(\"\\\\s+\");\n\t\t    int sizeOfArray = Integer.parseInt(element[0]);\n\t\t     \n\t\t    int arr [] = new int[sizeOfArray];\n\t\t    \n\t\t    line = br.readLine();\n\t\t    String[] elements = line.trim().split(\"\\\\s+\");\n\t\t    for(int i = 0;i<sizeOfArray;i++){\n\t\t        arr[i] = Integer.parseInt(elements[i]);\n\t\t    }\n\t\t    Arrays.sort(arr);\n\t\t    Complete obj = new Complete();\n\t\t    int ans = obj.maximizeSum(arr, sizeOfArray);\n\t\t    System.out.println(ans);\n\t\t}\n\t}\n}\n\n\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n\n\nclass Complete{\n    \n   \n    // Function for finding maximum and value pair\n    public static int maximizeSum (int arr[], int n) {\n        //Complete the function\n        int[] map=new int[100001];\n        for(int x:arr){\n            map[x]++;\n        }\n        int sum=0;\n        for(int i=n-1;i>=0;i--){\n            int curr=arr[i];\n            if(map[curr]!=0){\n                sum+=curr;\n                map[curr]--;\n                if(map[curr-1]!=0){\n                    map[curr-1]--;\n                }\n            }\n            \n        }\n        return sum;\n    }\n    \n    \n}\n\n\n"
  },
  {
    "path": "Maximum Depth of Binary Tree.java",
    "content": "class Solution {\n    public int maxDepth(TreeNode root) {\n        if(root==null){\n            return 0;\n        }\n        return Math.max(maxDepth(root.right),maxDepth(root.left))+1;\n    }\n}\n"
  },
  {
    "path": "Maximum GCD of siblings of a binary tree - GFG/README.md",
    "content": "# Maximum GCD of siblings of a binary tree\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a 2d list that represents the nodes of a <a href=\"https://www.geeksforgeeks.org/binary-tree-data-structure/\" target=\"_blank\">Binary tree</a> with <strong>N</strong> nodes, the task is to find the maximum <a href=\"https://www.geeksforgeeks.org/c-program-find-gcd-hcf-two-numbers/\" target=\"_blank\">GCD</a> of the siblings of this tree without actually constructing it.<br>\n<strong>Note: </strong>If there are no pairs of siblings in the given tree, print 0. Also, if given that there's an edge between a and b in the form of {a,b} in the list, then a is the parent node.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 7\narr = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}}\n<strong>Output:\n</strong>6\n<strong>Explanation:</strong>\n</span><img alt=\"\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAb0AAAGYCAIAAABZLauWAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAhdEVYdENyZWF0aW9uIFRpbWUAMjAyMTowMjowMSAxMzoyMjoxNpkacP0AAFLrSURBVHhe7d0JXFNX2j/wAwEJgUgIIBBFlKLIIkvYRJCl4MKI1qUyqLV1aludtr5Wp07HTl+rra31Py1Tq7V2Wlurg1KtFVdcQBRFxLIIIkiNCKLBEAgBJEZD4H+aHH3dwATuDbnwfIdPmudcdISc/HLOXc416ejoQAAAAHRmSv4LAABAN5CbAACgH8hNAADQD+QmAADoB3ITAAD0A7kJAAD6gdwEAAD9QG4CAIB+4Lx38AeVSlVZWSmTyZqamuQa9fX1+PGe6p4JMmGz2Vwu18bGxs3NTSAQuLq68vl88icB6H8gN/u1lpaWkpKS/Pz8kosllgLLdof2e7x7Cp5CbiO/aX+zllerMFfgbzNTmjm3ODvUOzjdcLKusW670sbj8cYIx/j6+np6erJYLO3fBkA/AbnZH+Fx5fnz5wsLC0WVIrYXuzK08ozvmVZuK9msA3uRvXux+/Ci4Ww5e2LMxPEx42EECvoPyM3+BQ8w09LSTp05ZRpkelF48Tff39TmarKtW2xqbDwzPYfnDh/mMWzhzIV4Ck82ANB3QW72FyqV6hCWfkgZodw7ba9eo8tnYqlY7pnuvgd93X3cl0xf4ujoSDYA0BdBbvZ9arU6JydnR+qOe573DiQeqHesJxuohtPTc7+n1zGvsfFj357yNuz3BH0V5GYfJ5fL/9/n/6+OXZcxJ6ParZq00okj4wRtCRpSP+RvC/8mdBOSVgD6EMjNvkwkEn3+5edXJ17NmJJBmgzF5bxL6JbQ8Onh70x6hzQB0FdAbvZZeG6+ZduW84vOXwq4RJoMy0pqFbE+QuAg+GrhV9Zsa9IKAPNBbvZNu3fvTj+bnrY8rVHQSJp6g4naJPiH4GGVw5LfSx7MG0xaAWA4yM2+Rq1Wb9i4oaClYPeS3Xe5d0lrr/JO8x51atTK5St9Bb6kCQAmg+vT+5qdP+88qzybsiLFSEITuzTt0oUXLnz06Ucl4hLSBACTQW72KdnZ2ccLj+9bvK+DZVzTiKvRVwtmF3yy5pMaWQ1pAoCxIDf7DpFI9EPKD2nL0u5x7pEmY1IVXlU8tXjZp8vq5XSdQAqAYUBu9hFyuXzdl+sy38psFjSTJuNTManictjldze+q1b36OJOAHoX5GZfoFKpPvn8k+KJxTd8b5AmY1U6s/SaxbWPtn9EagAYCHKzLzieebzCpuK3Kb+R2ridXXz2QumFAzkHSA0A00BuMp5Codi1d9epuadIbfTa2G2nF5/euW2nTCYjTQAwCuQm4+07tK86oNqYd2s+qdG18eKEi+u2rCM1AIwCuclscrn80NFD55LOkZo5Lk279Lvs95ycHFIDwByQm8y2bfc2UZxIyVOSmjk6WB1n55396Zef4Ng6YBzITQaTSCR5+XlFU4tIzTR1XnW1gtrjx4+TGgCGgNxksCPZR8riyozzLHcd5STm7N6/W6VSkRoAJoDcZLCc/JybvjdJwUyNro1KV2V+fj6pAWACyE2mwpP0ltYWqYeU1Ix1Lu7cwfSDpACACSA3mepc0blqP0Pc94Ju1/yv1cpqa2pgvQ/AGJCbTHUi/0RVaBUpmKyD1aEKVRUUFJAaAKMHuclILS0t0ippnWcdqSmXgtBwhJaTim4FAQXFxcWkAMDoQW4yUnl5ucRLojan58xHPIpdpHk01Hpvlz0vX6u+plAoSA2AcYPcZCSRVNToRM+Ng9oQmofQbVIZBp6q27jbiEQiUgNg3CA3GelW0607NndIQa0vEDqDEI9UBtPu0g6HhgBTQG4yklQupeXaygsIfYCQP0JvkwaDaXBpgNwETAG5yUhNsiaFLdV7A3EOz0bIDKHtmkfDahjUUF8P988AzAC5yUitDa137Kiepy9H6DJCaxDyIQ2GJLWStra2kgIA4wa5yUhtTW0U7988hNBGhKIR+htpMDAFRwHH0wFTQG4yUoeyo43dRoqew/Pj1zTHgvAMvZd0sDpgQTnAFJCbzGSOWCoWed5zryN0SzPeHEIaDI+lZLHZbFIAYNwgNxmJxWOx5RSlzBaE0hB6EaG5pKFXuMhc+Hw+KQAwbpCbjMRx4FhJrUjRQ59pHqsQinnoa6um8cj9kn4OMgfITcAUkJuMxLXhspsoGm9qd5PmI3TyoS/tgiF48q4t6Wcts7azsyMFAMYNcpOR7Hh2lk2WpOih0whde+LrHc0mPHnXlvSzkFnAeBMwBeQmIznznCnbvzkEoWFPfGmvs7S+X9LPpMGExzP41Z0AdAvkJiO52rtyJVxS9AnqerWtrS0pADBukJuM5OfhN7hssInahNQM5yhxbGtpc3NzIzUAxg1yk5H4fL61o7VDhQOpKfcKQlkIvUcqusXkxwgDhKQAwOhBbjJVmDBsSAFt56kP01xzOYpUdLPLtwsLCyMFAEYPcpOpJgROGFZokEM2NLOV2d4T3/P09CQ1AEYPcpOpXFxcrJG1bTXjj6VEnI8IDgpmsai7bBQAmkFuMtho4WhBkYAUjDUkbwhM0gGzQG4y2KzIWZ4ZnlQu8GFww0TDkBR5eHiQGgAmgNxkMFdX1xEjRngcYXDoPL/t+bmz55qbm5MaACaA3GS2JUlLRh8cPUAxgNSMIswROiPn8PBwUgPAEJCbzObo6CgMFY5OG01q5mCpWH47/ebNnUdqAJgDcpPx3pjxxsgTIzkyDqkZIuZQjL+HP+zZBEwEucl4PB5vfPx4/13+pGYCnPIu6S6zk2aTGgBGgdzsC/4c/2ePCo9hOcw4Dd5MaTbty2nTE6Y7ONB2nSgAdILc7As4HM6a5WvGbhvLr2TAEpYJ3yaEC8KnTJlCagCYBnKzjxAIBEsXLY1LjqNsXU56RKdGe8m9Fr6+kNQAMBDkZt8RFBA0PW76hOQJRnsmvNdJr9H5o/+x7B9wVSVgNMjNPiVpWlKYU1jElghSGxNBqWDMrjE4NLncPrXiMuiHIDf7FJVK5T7I3et3r+c3PW9Uo073bPfYL2JD/ELgZhigD2CtWrWKPAUMl52dnZycbGFhsXDBQkWFgnOYUxVQ1cbW3q+y15ioTcaljBubPXbJX5dcv35969atcrnc1dWVzTbq/bAAdMGko6ODPAWMVVZWtmPHDlNT05dfftnd3V3buCttV9qxtKPvHpW5ybQthmfRYjFpw6RA88Dli5drgxKH5oEDB06dOhUaGjp16lRHR0ftdwLAIJCbzCaRSFJSUqqrq5OSkp5cja2goGD9lvVn5p25FmaQm/k+yrbaNj45PiEiIXFG4mMHglpaWo5p+Pj44PTEw0+yAQAmgNxkKoVCsWfPnjNnziQkJEyaNKmzJYVqamo+/vzjq55XzyWeU/AVpJVmAxQD/A/5e2R4vL3g7ZCQENL6BKVSefLkyf379w8fPnzy5MleXl5kAwDGDXKTedRq9fHjx/fu3YunurNmzXrm4WmcsAfSDxxMP3gl7krR1KJ7nHtkAw1YKpb3Ee/RB0eHBoXOmzVPl6NAKpUqJydn3759dnZ28fHxgYGBZAMAxgpyk2HOnz+/c+dOgUAwd+5c/EhadSCXy1N2p5zLP3dh+oXy2HK1uZpsoIiJ2mTEyRFBe4JGe47+S+Jf9N1xiT8MCgoK8IcBfo5H0GPGjIFzPIHRgtxkjMrKyh07drS2tuLE9PHxIa16EovFW1O3ltWUlUWVVQVUNbo2kg09YFNjM7RgqNcprxFOI15Leq2HOyuLiooOHTrU0NCA0zMyMhKWNAZGCHKTAWQyWWpqamlpaVJSUnh4eM8HYiKR6HTu6bzCvNvodo2wpjykvN69voOlR0/Ao8tB5YPcityGFQ6zQlZhwrDIsMgHh/J7rqKiAqcn/ndOnjw5JiaGw2HYKnmgb4PcNGoKhQLHx9GjR+Pj43GCUH7OY3V1NR7fZednS6XSJp+mRodGKU96x+aO0kbZ6tCq5CnxdN5MaWbZZGnZYMlp5LDlbH4Tnyfl8S7yBrkMGuc3Ljgw2MXFhfx1VMP/PPzjFxcXT5gwITY2Fs6ZB0YCctNIqdXq06dP79q1y9fXFw8z6Y4MPKQtLy/Hj3K5XCwXy5pkjdJGhVzRrmpnsVmWNpY8O549317AE9ja2PL5fE9PT4OlmEQiSU9PP3PmTFRU1KRJk2D1OdDrIDeNEZ6Sb9++ncvlzps3D85t1MKBfvjw4VOnTgUEBEydOlWvY2IAUAty07jU1NTs2LHj1q1bL730EpyR8ySFQqE9Yd7d3X3atGlubm5kAwAGBLlpLPB46tdff83Ly5s5c2ZsbCychdMFlUqVmZmJJ+94zj5jxgw4YR4YGORm78MpcOjQITyGioiIwGMoOHasI7VanZOTg391pqamL774IgzPgcFAbvYy/M7ftWsXnm8mJSXBIhfdoz1hvrW1dfr06ZScpwVA1yA3e01FRcX27dvxWGnu3LlwO9yeKysrS0tLE4vFCQkJsbGxcMI8oA/kZi+QSCSpqamVlZWJiYl4fERaARWqq6v37NmDP5MmTJgQHx8POz0AHSA3DUqhUOAx0alTp7TnscOYiCb4kwnP3IuKiiIiIqZMmQInzANqQW4aiFqtzszMxEOh0NDQGTNmwDvZAGCNZEATyE1DKCgo+O9//+vk5DRnzhz6rkoETwVrJAPKQW7Sq7q6evv27fitO2/evG4vYgR6DtZIBhSC3KSLTCbbtWtXSUlJYmLiuHHj4OQYYwBrJANKQG5SDw9tDh06lJ6ePnHixClTpsCNG40NrJEMeghyk0oPFjHCU/KkpCQ+n082AKMEaySD7oHcpExpaWlKSoqVldWcOXNgvQkGgTWSgb4gNykgFotxYuLH2bNnd3H7RmDMYI1koDvIzR5paWnZvXt3Xl7e9OnTx48fD7vJmA7WSAa6gNzsJpVKdeTIkYMHD0ZERMycORMmd30JrJEMuga52R25ubmpqamwiFHfBmskg85AbuqnoqIiJSWlvb19zpw5cO50fwBrJIMnQW7qSiKR7Nq1C+fm7NmzYRGj/gbWSAYPg9x8Njxf279/f1ZWFixiBGCNZIBBbnZFu4hRWlpaQEDArFmz4NwUoAVrJPdzkJudKioqSklJ4fP58+bNg0WMwJNgjeR+C3LzKR4sYjR37lxfX1/SCsDTwBrJ/RDk5iPkcnlqamppaen06dOjo6Nh7xXQEayR3K9AbhIqlWr//v3aRYwmT54Mcy7QDbBGcj8BuUlOMcHDTNzXZ82aBZfWgR6CNZL7vP6em2VlZdu3b2ez2XPnznV3dyetAPQYrJHch/Xf3JRIJNu2bYNFjACtYI3kPqk/5mZLS8uePXtyc3OnTp06YcIEOPkOGACskdyX9K/cxFOnY8eO7d+/PywsLDExEQ7+AAODNZL7hn6Um3iAuWvXLhcXl7lz58JpIqAXwRrJTNcvchN/vKekpCiVynnz5sHBTWAkYI1k5urjuSmVSlNTU8vLy5OSkiIjI0krAEYD1khmoj6bmw8WMcJTIdwdYTc8MGawRjKz9MHcVKvVJ0+e3Lt3r/ZmvLDzCDAFrJHMFH0tN0tKSrZt28bn8+fOnQtXuQEmgjWSjV/fyc3q6uqUlBSZTIYTMyAggLQCwFiwRrLR6gu5KZfLd+/eXVRUNHPmTFjECPQxsEayEWJSbiqVyixRVrWsulZWK2uRtchb7jbdbWtoM20xxVtNOCZtdm0DOAPsnOwGOw72FHhOdJ/IZrO1fxYABmlUNGaKMmvltXWyOm1Xvye5h26idrP2Dk6HKTJt57dbciztneyHOA7xFfhGuEdAVzckBuRmjbhmT9EePJxUViob3Bpu29++Y3fnLvfuHZs7Shslft5u2q79To6MY3HbwvqWNVfCHSgeaFdpZyIwEXgIJgZMnOgzUfs9ABit4uritKK0y8WX22racFdX8BU6dnX7SnszgZmLh8uMgBnBPsHa7wH0Md7cvFBx4efcn6uKq5Ttypt+N28E3ajzrFObq8lmHbBULNtqW8dSR5c8l4EtAweHDn418lUfVx+yGQDjcKToyOH8w5JiiYKtuCm8KfYV13vUd6+ru+a54q7uEerxcuTLbq5wMhNdjDE3L5Rd2Pzr5tqGWtHzopv+N5tcmsiGHsAfy0Nzh47IGGEjsHk54eXnfZ8nGwDoPRkFGT/+8qOULa0Kq7rld6vFsYVs6AFtVx+VMcpeYP9awmtBvkFkA6COceVmZXXl+l3rr4uvF08vrgqv6mBR/G8zUZu4nnP1POhpx7JbPG9xiAcsHwd6R3ZB9pZfttRa1RbPKK7zqiOt1NF29dEHRzuznJfMW+LlAaeCUslYcrOmpuar3V9Vi6qLZhZdjb5KeWI+Bn8gB6YEunq5rkhaMYg/iLQCQL+8orxvd31bh+qKEovEAWLSShvc1UNSQry9vP8n6X/4fD5pBT1jFLmZmZP5fcr3RVOLRLEivXbr9ARLxfJO8/bM8HxpwUsJIQmkFQDaKJXKf2/99/lr5/MT828E3iCt9NN29dEZo99a8FZYSBhpBT3Qy7mpVqs3bt+YXZyduSyTkv2Y+uJX8iM2RPiN9nt/zvtwJgegj0QiWZW8qnR46bn559rYbaTVgHBXj9kQEz46/K9z/gpdvYd6MzflcvnHGz8utig+tfhUr/QkLTOlWeDWQC+xV/KyZLiYHdDh/PnzG7ZsyJ2dezX6KmnqDbirj9k6JlAcuGrZKujqPdFruVlZWbk6efWFmAslM0tIU6/y3e07Om/02mVrXQQupAmAHsMzqp92/HSs8Nixd441ujaS1l7lv9s/JC/kw2Ufwpp13cZatWoVeWpAODQ//PzDzNcyRc+LSFNvk3hL7rDuXPruUqh/qA3XhrQC0DP/3vDv9Kb0Q/841OrQSpp62y3vW02spivfXQnxD+FyuaQV6KMXchNPz1d8siLr1aybwpukyTjI3GSt1q0V31XEhsXCDiDQcz9t/ymrNmvfe/vUFgY62qkjbVev+q4qMiwSuno3GDo3lUrlPz75R05sztWo3tzR0xm5q/yeyb2SrSVxYXEWFhakFQD9HTlyJC037ZeVv7QPIBdHGhWZq+yOyZ2rW6/i6ISurq8/VsQwGLVavXbD2gtuF8oml5Em41MxqeKS36V/bvonqQHQ3/nz51P3p+75YE8vHvB8pvJJ5Rf8Lnyx6QtSA50ZNDe3/ry1QFVw9tWzpDZWRXOKflf+/v2B70kNgD4qKio2/WfT/g/2K3lK0mSszs05V6ws3ndgH6mBbgyXmyUlJcd+O3Z02VG6rwXqOfwvPL349LH0Y2Ui4x0XA+OkUCiS1yefXna6UWAUR8+7hrv6scXHfkn/RSQyliO0jGCg3MQz9G9Svjnz8hljnrY8TMFX5M3L+3zL5/hfTpoA0EFaWpoiSFHpVUlqo4e7es68nA1bNkBX152BcjM7J/sG94YBrsal0PWw69e5138+/jOpAXgWsViceSpz96zdpGaIa2HXcFc/fvw4qcGzGCI3VSrVT6k/nZ1j7Ls1n/Tb/N8O7j+IZ16kBqBL27dvl06X3uXeJTVznJh/4uf9P0NX15EhcnPX/l3VPtUyNxmpmaNZ0FzpW/lj+o+kBqBzRUVFVdKqg+MPkppRcFe/6XvzUPohUoMu0Z6bcrk8/Vj6b7N+IzXTlE0vO3PsjFJp7AdGQe/6Y1K17aei+UXGf9izM+emnzt07BB0dV3QnpuHTx6+EnbFeC4y01eLY8t1n+t7sveQGoCnKSkpabdrz/PJIzUD4a4u8ZFkZ2eTGnSO9tw8W3y2OqiaFMx0NeZqRnYGKQB4mry8PEmEhBSMVRRTlJ6dTgrQOXpzUyaTNYgb6jypvw2AIeF/f7O8WSJh/LsC0ARP0gsKCzICGf/hiru6VC6Frv5M9Obm+aLzN/1uMnePjxb+91eFVu3I3UFqAB6FJ+kD3QbKuMw78vkYbVfPyc0hNegEvbl5NO/otdBrpGCyWr/ai6UXSQHAo/AkXT5WTgqGq/SrPFvKvFMGDYzG3FQqlXWiulrfWlL3XBVCqzv5ukC+hSbSkVJFpQJPx0gNwH24VxQWFh4NPEpqqhxC6C8IxWi+piO0Bb+jyBZa4a5+q/IWdPWu0ZibRSVFdZ51VN5nDfekVZ18FZNvoUkbu002RFZSaRRL0wOjUlpaautmW8ulbnxwG6F4hBIQ2orQSc1XGkKvIRSM0C3yLfTBXV05RFlZyZjrRHsFjbkpkooaBjeQghKXNY+4Pz0WmvjLT7OJTvJh8rM3YP4CHieTydqcKF11YSlCRxByQuggHs0i1IFQLkKjcEIjNIV8C61qh9XeuGG4220yEY25KW4S37G5QwpKnNM8voPQh098+Ws20emPEzkl10kBwH04N+/yqbuwEucVHmZiBxCajJCZ5vkYhI4jZI1QPkKZmhY6yRxlIgksj9QVGnNTJpdRvP6gdrwZqHk0uNtOt+tv1ZMCgPsaGhpu8/HUmiJ5eKqsGV0GkQZiCELRmifa0QOdcFevulVFCvA0NOZmk6xJYUvdMgF4koI7pztCvXT70rvWd1tbmHrVE6BPfX29xJ66Ex6jEMpC6EtSPUI7CNGOQOmEu3pzSzMpwNPQmJuKBsUdO+rm6RWaRx+EvkVoHELDNV+zEDqjaaefgq8wkZmQAoD75HK5mEfdAon2mnHlRFL9n1v3u/pj41Aa4K5+W0bdCLovojE31U1qKvdvaqcnBxFapHmOX1Y8k/hFk6HrNZvo147/B8CjZDJZDb+GFPT5q2a86Y9QLGkAvYjG3OxQdlC5urt25yb+NMZZidNYihDuqy9pGt9BiOqT557UweroUDP7widAB6VS2cRuIgVNlmpORWIj9B1poBXu6rD2e9fozE3zDpaKRYqem4/QBwilIzTz/i6eIQhtR2iS5vkazSOdzJRmHWzITfA4c3NzKvv5Y/DAA4fml5o+/19DTNIx3NVZbNp+oj6Bxtw05Zmy5dTd0h7H5cdPO9/oXc3jGc3MnU74Z8E/ESkAuI/P5zvJnEhBLdylZ2lC0xqhVM1bwCBwV+fwOKQAT0NjELAd2FZSK1LQ5znyX0TzOUJW9VYW9nB7fvA4Ozu7IQ147kO1W5p993h6bn9/mmUouKvb2tuSAjwNjblpZWPFbqJovIlnK1Wak36f9GAPKv5MppNlk+VA3kBSAHAfHm86NDqQgiqXEQrQrLowSnOxUARpNgzc1e15OK1Bp2jMTT6Pj18AUvRQqeaso2BNej5Gu8A2/ryn+YXGkxf8E5ECgPtwbtrKKB2d4U4eoxlv4rjEoelOmg0Gd3UnHj17HvoKGnPTgedA2f5Nf00yYo+dcnT7/hGh1zSPdMI/i6ONIykAuA/nplUDdfuj8Pxp9v3QxNPz3rjKA3f14TZ4nAI6RWNuuti7cCVcUvTcZ5rHLxH63/u7Ms8hNF4zo8Fzmb9pWuiEfxYXBxdSAHAfj8czlVL3Pkq5f6qyNUKLNUvJPfa1T7OVTnwJ38GB6j0PfQuNuRnhEeFU5mSipugam7madY/MNANM/JrivzVM08PwUDSL9p2bFi0W3FvcWFc45xg8ztfXt7W81UxJ0fWPqeS/fyyJtPVpXzQvNYu7uvUta1dXV1KDp6Fz/yafz3HkOFRQ98H1IULlCP1Dc85mtOakd9zJftOsuEUzQZHA1M+Ua07d8Bn0FWw2e6T7SJ8SH1L3EO7bDy+Q+ORXFPlGmuCuPthvsLm5OanB05h0dNB4LvcXaV/saNlROK+Q1Iw1LnlcQmjC38P/TmoAHnLy5MltZdt+fPNHUjNZZHLkitAVk8K115OAp6NxvInNDJzpUsj4fYIsFWtQ2aB5AfNIDcCjAgMD2wvbabxqyFDwj+Bc5hwZEElq0Al6c3OYyzArZGVbzexzaJ1LnJEbcuY4kxqAR3G53BFuIzxKPEjNWI6ljrZuthwOXCz0DPTmJjZCOEJQJCAFMwkKBV5CL1IA8DThY8MD83ppSW3qDMkfEiWkeQdqn0B7bs6NnDsyYyRzpzBsOdsl3+WlMdqVlwB4On9/f1YxyxAXFtPmj9M284dPGgN7Np+N/vGm6wjBCIHHEaZOYUb/OtohymEkbySpAXgaHo/3QvwL41PHk5qBcFcPjArEPwipQedoz03s/aT3vQ96D1AMIDVzcCXcoXlDV05bSWoAOjd58mQnkROVJ94ZEO7q7nnub017i9SgS4bITYGjYGToSO80b1Izh1+qn3uCOxwRArowNzd/KfGlCdsnkJpR/FP9JyRMgCNCOjJEbmLvznh35ImRHBmTXhV+Jd+pwunDSR+SGoBnCQ8PH2w6eETOCFIzBO7qQyuGzp00l9TgWQyUmzweLzQ+dPSu0aRmgoAdAWFJYZbmFC3pBPqH119+PXRnKGWXXRpE8I7g2Umz4Roh3RkoN7GF8Qufq3huWM4wUhs37zRv23u2S8KXkBoA3bi7u48Vjo3bFEfZygw0w13d9Z4rXCCkF8PlJofD+Wz5Z6HbQvGkgDQZK0GRYFTGqC+XfcliwV1WgN7eeOUNoVIY/HMwqY0Y7up+GX7rlq2Drq4Xw+Um5iJweWPRGzHJMZSty0kDmxqbsO/CFi9bPJg3mDQBoA+cQf9855/CQuHITKM+fQ139XHfjVu1bBWce6Qvg+Ym9nzA8+PjxkcnRxvnmfAWLRaRyZGT5k6KcoOrJkD34dnVquWrwvaG/XGRrlHCXT02OXbB3AUj3Bh2FMsYGDo3sYXTFgqdhCFbQkhtNEzUJmM3jB09dvRr4fQvHw/6OkdHxxWLV8R8HYOHdaTJaOCuHrkhcvzY8ePDGXyifi9irVq1ijw1oPDR4YVHCy3KLMT+4g6WUdyUfIBiQOQXkSOsRnz+yuempr3wcQL6Hnt7+wGmA+5uutswvOG2I803qtYZ7uoxX8R4tngumr3IyorBF4b2ot4JCDabvfH9jTEoZsLHE4xhX+dA8cAJKyeEu4VvensT7CAHVJHL5RnHMhKnJcb9J87rgFEsDYO7+uSVk6e5TYsdE7tp0ya1Wk02AH30zngTw/H0fPDziiaF2X/MbnneumN7h2wwOOcS5+c/e35a4rSlk5fCSBNQBUdScnKyUCicOWNmzNiYyj2V7HK2eLS43aydfIfB4a4+/rPxCxIXzJk8Z9SoUb/99tu1a9f8/PzIZqCzXstNrcBRgQInQcPXDc385iaXJtJqQB5HPEJ2hixdujQhMIE0AUCFbdu23b179/XXX8fP8QRrQsSEugt1nH2cG343VFYq7fcYEu7qETsj/rn0n2GBYdqWgICA7du329nZDR4Mp47op5dzExsqGBrkG1T1nypONUfmJlNZGqhL4QlL6OZQr8teX37w5SiXUaQVACpkZ2efPn16xYoVZmbkwiE8wRoXNM683Vz9tbrNtK1xeKPB9uzjrh6xOUJ4Wfj5B58PdRlKWjUX1Ht5eX311VchISHW1jTf2rBv6f3cxHg2vIlRE1li1oBvBrAUrEa3RrU5jbtd2HK2cLsweGfwjKgZKxesHGg9kGwAgAoikejrr79+//33bW0fv9OB13Ne40LGybJlgv8KlFZKuYuc1kMMuKsHbw8es3PMvKh5SxcsfTIceTwel8vFo85x48Y9iHjwTPTel01fcrn8m93fFOcXX5h+QRQrojw9BygGjEwf6ZXuFRgX+PbUt2H1F0A53Ic/+OCDN954w9fXlzQ9TWV15b9T/n1TerMgseB62HXSSh3c1Uelj/JO9x4XN+6Vqa903dU3b96MHxctWqQtwTMZV25qicXiDakbrtRcuRx1WRwgbnRtJBt6wKHCwbnEecSpESN8RixPXM7nG/u1noCJ1Gr16tWrhULhtGnTSFOXLpRd2JS6qVZVeyXqCu7qLY4tZEMPaLu61ymv0T6jFyUu0qWrK5VK/M+Oi4uLjY0lTaBLxpibWniysz93f0lhSStqrRRW1oTU1LvX67VLiKVi2VfYu+a6Di0eamVl5R/kP3PMTBcXxt9fExgtPHC7e/fukiX6LQdTWFp4IPfAleIrt61uXwu6VutbK/WQkm260Xb14bnDcVcfaDVwTNCYCWMm6NXVJRLJypUr33vvPTc3N9IEOme8uflAdXX1qaJTZ/PPNkmbbvrcbHZoVvKUd2zuKG2UrQ6t+DmezpspzSybLC0bLDmNHLacjZ9bS60FFwU2LjYRQRETgiY4OjqSvw4Aehw7diwrK+vDDz9ks7t5SjIeKxwpOlJQWKBoUtzwvKHt3s/s6jwpz+mik52LXUxQTHhQeLe7ekFBwbZt29auXQv7r56JAbn5gEwmKy8vvya7dkt+q0He0NzUfFt6WyVXIRUyYZuY2ZhZ2VnZ8G3sefaDbAa58919fHy4XC75wwDQqaysbOPGjXi26+BAwX0ypFJp+e/lVbKqWnkt7uotTS0KqeJBVze3Mbe2s8YTcNzVnWycXPguVHX1HTt21NTU4FEnqUEnmJSbABgnHHM4MRctWoTzizQxk1qtXrNmjZ+fn477Z/stuDwGgB5RKpXJyckJCQlMD02MxWItWbIkIyOjtLSUNIGngdwEoEd++OEHV1fXSZP6yHrpPB4PD5w3b94sk8lIE3gC5CYA3XfgwAGxWLxgwQJS9wl44Dxx4sQNGzbAqh+dgdwEoJtKSkqOHj26bNmyvndHsylTpnA4nB07dpAaPApyE4DukEgkX3/99TvvvNNXr6F466238vPzz58/T2rwEMhNAPSmPRY0e/Zsd3d30tTn4PEmHkpv2bIFf0KQJnAf5CYAetuwYQNOzOjoaFL3Ua6urvizAX9C4M8J0gQ0IDcB0M+ePXvu3r376quvkrpPw58Nw4cP37p1K6mBBuQmAHooKirKysp6++23+8/9VObPn19dXZ2ZmUlqALkJgO5qamo2b968bNmyfnXDcTab/c477+zatauyspI09XuQmwDoRKFQJCcnz507tx+uGOTo6LhgwYL169fjXwJp6t8gNwF4NrVavWHDhuDg4MjISNLUz4SEhAQFBeFfAqn7N8hNAJ5t9+7dODr//Oc/k7pfmjNnjlKpTEtLI3U/BrkJwDPk5OTk5uYuXry4n99bH//4+JcAq35gkJsAdKW6ujolJeXdd9+FtVwxPp8Pq35gkJsAdEoulycnJ8+fPx9ur/KAj49PXFxcP1/1A3ITgKfDubBx48aIiIiQkBDSBDSmTZvGZrP786ofkJsAPN327dstLCxmzJhBavCQxYsX9+dVPyA3AXiK7Ozs0tJSOBbUGQ6Hs2TJkn676gfkJgCPE4lE27ZtW7ZsWbfvTNkfuLm5JSYmfvnll/1w1Q/ITQAeIZfLcRa89dZbAoGANIFOxMbGurq69sNVPyA3Afg/arU6OTk5Li4uICCANIEuzZ8//9q1aydPniR1/wC5CcD/+e677+zs7OAuuLpjs9nLli3buXNndXU1aeoHIDcBII4dO4aHTgsXLiQ10I121Q88Tu8/q35AbgLwh7KysrS0tHfffReOBXWDdtWPr7/+mtR9HeQmAEgqlW7atOnNN990cHAgTUBPc+bMwePNAwcOkLpPg9wE/Z32Jmvx8fE+Pj6kCehPu+rH0aNH+8OqH5CboL/74YcfXF1dJ0+eTGrQXQ9W/ZDL5aSpj4LcBP0anleKxeIFCxaQGvSMdtWP9evX9+1VPyA3Qf9VUlKC55XLli0zNzcnTaDHtKt+/Pzzz6Tui0w6OjrIUwB6g0qlqqyslMlkTU1NeH6H3ay/2ShvxO14qwkyseXbcjlcFycXR0dHgUDg7u5OySFviUSycuVKHJoeHh6kCVBEoVCsWLHi5ZdfDgwMJE098GQPEdeLZXKZtodgfD6fjh7SBchN0DtaWlrwcO9c/rmSiyXtgnalg7KV1yrnyW/Z3Gq1b1XylGpzMtHjyDgWty2cbzk7SZxsxbYdlR2OAkdfD9+AgIBuH8lRKpUffvhhfHx8dHQ0aQKUwkm3bt26jz76CGcZadKTtofk5ecVXyzuEHTccbjTdQ9xvOXoLHHmiXkmlSY97yFdg9wEBoVHDefPn88tzL1Wee2O153i0OLrvtfvcu+SzTpgqVi21bajSke55bmxW9gRoRGRkZGurq5ks26Sk5O5XO7rr79OakCDzMzMjIwM/Pmk1+hP20PyCvOuVl6963W3KLSo2z1keN5w3EPGhY7rRg/pGuQmMBA8fPgl7ZesM1kNQQ0lwpJa39oH44Vu40q4gbmBrhmu7gL3qQlTfX19yYYu7dmzp7S09IMPPoA14ui2efNm/Lho0SJt2TXcQ35N+xX3kMagxkJhIVU9JCA3YFjGsOcEz01LmKZjD3kmyE1AO5VKdeDQgf3p+2sianKm5eg1dtCFidrE55xP4MFAJ5bT/Hnzu95fWVRUtGXLljVr1vB4PNIEaKPj/hDcQw4dOrQvfd/1iOs09RDPc55BB4NwD3l13qs936MNuQlopFarc3Jyfkr9SeIpyU7MbnFsIRvo4Z3rHZwSHOQVNDtpNp/PJ60PEYvFq1evfu+999zc3EgToJn2+Nv777//1JmytodsS92Ge8ipxFN09xDPXE/cQ0K8QjrrITqC3AR0kcvlqz9fXcOuyZqTJXMz0O0PWSpWXFrc4IzBCxcsfOy+QAqF4p///Of06dMjIyNJEzCI8+fPp6SkrF27lsPhkCYN3EM++fyTKnbViTknDNlDItMi8cx90YJF3b5zFGvVqlXkKQDUEYlEH3z6wbmoc1mvZ92xvUNa6dfB6rjqffWG942mLU0ysczT09PMzAy343HNl19+icuEhATtdwKDGTx4cH19fVZWVnh4OGnS9JCVn67Mico58foJA/eQKu+qm943G7c0NogbvDy9tD1EL5CbgHrZOdlffPNFxhsZV6KukCbDUtgqSqNLTQtMyw6XBQYEstnsPXv24LfuwoULTU3hWo9e4OPjk5mZ2dLSot23iOfmuIeceOPE71G/a7/BwHAPuRR9CRWgS4cvBQUE6Xu+J+QmoNj23dtTjqYcfv9w/ch60tQb2s3ay4PKzerNyneWt91rO3ny5IoVK+g+HRp0Bn9c+fr6fv/990OHDj1+6vh/j/734PsHpSOlZHNvwD2kIqgC95CynWV+Pn5cLpds0AHs3wSUwXPhtRvXnm85f2zJMcoPiXZbcGaw9w7vt998m5JrV0BPlJSUbN2xtdK68siSI8bTQ4SZwsC9gaveX6X7HaVgvAkosyV1y1HZ0fT30tvYbaTJCIjdxKY2ptLd0vAx4TDe7F2HMw+fuXfm4HsHjaqH1LrVKjnKmh9qdO8hsK8HUONY9rGjhUezFmd1sIxuBlMYXXjx+Ysfr/24H96x1nhkZWelF6YfX3zcCHtIWXRZwfMFq9au0rGHQG4CCohEoq0pW48vO36Pc480GZnTU05fcr/0zXffkBoYFu4h36d8f3TZUaPtIXlT8nAP2fjdRlJ3CXIT9JRcLv/oy49OvnWyWdBMmoxSxvyMfHF+dnY2qYGh4B6y5ss1WW9lGXkPyZqf9Zv4N116COQm6BGVSrXi8xUFEwtqfWtJk7FSm6sPvXnox9QfpdLePIzb3+AesvLzlUzpIUffPLoldcszewjkJuiRvZl7L9tcLptSRmrj1uTSVDS5aNPWTaQG9DuYebDcprx0CjNuOoR7SP7k/A1bN5C6E5CboPsUCsW+vfsK5xaSmglKJpWUi8tLSkpIDeiEe8ievXvOzz1PaiYon1T+zB4CuQm6b+uhrdcCrhn5TqvHdLA6Tr98etO2TX37BjhGYuehnUzsIWdfPvvVtq+66CGQm6Cb5HL56aOni5KKSM0c4gDxTe7NggsFpAb0wD0k82hmYRKTpiNauIfUcmvPX+h0mAy5Cbrpq91flceVK3mMPCPyQsKFn/b9RApAj827N5fFlTG0h5QklPy470dSPAFyE3SHRCK5lH+pfGo5qZnmpv9NSYtEJBKRGlAN95AL+RcY3UPqW+orRBWkfhTkJuiOlOyUy3GXjfYc5mfqYHVciruUkpVCakC1tOw0PB1hdA/B//6tWVtJ/SjITdAdeChh/Kfjde162PWK/Ao4OkSTvPy8PtBDqvKrntpDIDeB3vAUTNGqkHow++xxBV8hE8gKy5l31ML44R5yu/V2H+ghDYKGc+XnSP0QyE2gt4NFB2v8akjBZNVB1fuL9pMCUCerKKvar5oUTFYTVLO3aC8pHgK5CfR2Lv9cTSjVuXkboXz8VyMkJw0GUO9RX1VWRQpAnVP5p6jvIQ+UInSBPKUb7iE3ym6Q4iGQm0A/LS0tzVXNdZ51pO45HJSvI+SAUDBCYZon0xEySJo1DG9QiVWwuBy1cA9prGqksoc8TKTpJEtJRTfcQ5D4j7sZk/o+yE2gn9zy3FqvWrU5RYdT8DBzHELfI8RD6B2E/oGQD0JpmvcG/ecIdbA66kfU54pySQ2oUFReRGUPedgthKZo+oyhaHvIUdFRUt8HuQn087v099tO1PXcLzTTrlEIXUTo3witReg3hKZp3iF/Jd9CK/kQeYkYrlWn0jXptRYnGm6DjvsJ/oi9TCqDwT2kXPz4WaiQm0A/9U31d2you2vrZs3jZwjZa55gZpr0xDIMMbLAnwHVkr5wBMN43Gq6RWUPwfAsebVmNw6egjiRNoN5ag+B3AT6aZQ3UnblXBtCGxH6AKFY0kA8eG/Qf4yo1aG14VYDKQAV6uX1FF9buRgh7V3QPtd8xBoW7iGNtxpJcR/kJtDPbdltha2CFD2Eh5YzEfoYIWvSQBzSPA7RfNHsrvXduwpjubFi39Asa6ashzwwX7Mn52+kMiTcQ9oUj99FDnIT6EfZoLxjR+ks7GF4gPkFQos0z/Hggn4KvqJDBrfCppKiQUFxD/kGoR8RcieVgeEeYiIzIcV9kJtAP+1N7RTvvXqAi5AtQu9q5u+pCP2ZNANmUTepKe4heF7Sq9rx/x4FuQn0Y6I0oeXm13ikGYTQS5pj60rNvOxbsoVWHawOuESdYkpkVLdH7yHcQ0zUMN4EPdNh3sFSsUhBIR5CWQhtR6hcczonjk48W99DNtLHTGlmyoZ3AaXMES09pJfgHoLY5PkD0GOAfkx5pmz5E/2IWgs0403sS80jnfDPMoA3gBSACmY8M9p7iAHhnwX3eVLcB7kJ9MN2YFtJrUhBn2maR/ovQ7aqt7K0tyQFoIKlg6Uheoih4B4ywP7xT1bITaAfKxsrdhNFo4kqzZXps0j1FPQfELBssrTl2ZICUIFrw6WshxgB3EN4PB4p7oPcBPrBKYN7Eil6CL+5vkfoF81KSI85onkM0jzSCc/C7Hh2pABUwL9PynqIEcA9xJ734Go2AnIT6Af3Icr2XjkhFKd5svjRSyr3aPIUe0fzSCf8swyyGUQKQAVnnjNlPcQIPLWHQG4C/XjYe3AlXFL03Dea9DyHUABCnyD0NUKzEUrSnMKJQ3My+S764J/Fy8GLFIAKbvZuAyUDScF8uIe4Ozx+zj3kJtBPkEeQoEzw5Blt3YQ75GmEojVLNnyA0NuaM97xrGizZnkkmlm0WNjcshG6CkkNqODj4UNlD+lVuIcMvDUwxjWG1PdBbgL98Pl8a0drhwoHUvccjs4shK5plt38r2YduRqEFpKNtBIUCfh+fHNzc1IDKuAeYuNoQ2UPedgrCHVoOoxB4B5i7Wf9ZA+B3AR6CxGGDCmgesmNYQi9gNBczbEgQ11XNyR/yDjhOFIA6oQLw6nvIb0B95CxwrGkeAjkJtDbnwL/5FroSgrGYqlYTmVO0wK0Z4oCKsUExrgVupGCsXAPcSxzTAxIJPVDIDeB3lxcXKyRtW01s097dCx1tHKz4nA4pAbUwT3EClnZ1NiQmplwD2G7sQdynnKMC3ITdIe30FtQJCAFM+EpWLAwmBSAaoHCQKZP1XEP8RX6kuJRkJugO5Iik7wyvJi7fANbzh6WP2zOmDmkBlSbGjnVO8Ob0T3ENd/1L2P+QupHQW6C7nB1dR05YqTHEQ9SM83oX0cLo4RPXj8HqIJ7iNcIL88jnqRmGtxDvKK8nrxSSAtyE3TT4qTFvgd9ByiYt5gQV8J9Lu+5xdMWkxrQY1HSIub2ELc8t79P+zupnwC5CbrJ0dExODR4dNpoUjOHf6r/+ITxcESIbriHhIWG+aX5kZo5/FL9whPCu+ghkJug+16d8arHCQ+OjEkBxK/ku1S4zJs0j9SATi/NeGnkiZFM7CGLJmnvcvV0kJug+3g83oT4CcJdTLpOMWhHUFJSElwjZBi4h8THx4fsCiE1Ewh3CKcnTe+6h0Bugh6ZFT9rVMWoYTnDSG3cvNO83e+5/yn8T6QG9JseP92jwuO5nOdIbdxwD3G75zYjfAapOwG5CXqEw+GsXr46YlsEnt2QJmMlKBIIM4SfLPuExeo7d78xfriHrFy+MnxbOCN6iH+G/7pl657ZQ1irVq0iTwHoFi6XO3zIcMkmiWisyGhvZGhTYzN+/fiP/vaRs7MzaQKGgnvIsCHD6jbVXRl7xZh7SNz6uNV/Wz3YeTBp6hzkJqAADqOOex3KX5VXIq50sDpIq9GwaLGI/zT+r0l/DfALIE3AsHAPMblnovpVVRFRYZw9ZOKnExcmLQzy0+keAzBPB9R4cdqL4U7hUVuiSG00TNQmMRti/jT2T9Hh0aQJ9IYZ02ZEOEXEbokltdHAPSRqQ9SEsRNiw3X9t0FuAsq8NPMlr9+9Jm6aaDxX1w1QDJi8brJXi9fsKbNJE+g9b7z6RpAkKGFTglH1kPh18WOtxr424zXSpAOYpwPKpKenO9g5DFUNtT5sfTXgaq/vyRooHjjl0ynTvKe1K9stLCxcXFzIBtBLzMzMIsMjGwsbbQ7biAJ6f2847iGTP538gvcLi/+yWK+jhZCbgBoqlWrjxo2vv/56bEyseZO56X9Mb3jeuGN7h2w2OOcS50mfTVqUuGjq5KkDBgw4fPhwTMzjdzsAhofjKTQ4lNXEYv2HJfYUK2wVZIPB4R4y8bOJCxMXTp883dRUv5k35CagxunTp3F0jh8/Hj8fNWrUUKehzV83K/iKBpcG7TcYku8R36idUe8vfT8wMBCXTk5Oe/fuHT16tI0Ns1eE7DO0PaTl6xYlX1nvUk9aDcjziCfuIf9c+s+gwO7cbBpyE1Djm2++mTFjxqBB5I6pAoFA6Cu88Z8bg6sH17jVqCxV2na64ZnXnzb/yf+y/ycffPJgYo5HE3fu3Ll8+bK/v7+2BfQ63EMCfANwDxlePbzKrcqQPWTS5knCy8JPP/i027tuIDcBBUo15sx5ZDlLPLh7Pup5jphj9o2Zo8IRp6faXE220YAtZ4/fPj5kZ8jLUS8vXLDQ2tqabNDAQ86tW7dOmjQJTno3HriHxETFWIgtcA8ZqhiK05PuHvL89udxD5kfNX/RgkWP9RC9mHR0GN25VIBx/vWvfwUHB0dHP/1EH7lcvnv37pz8HNF00bnYc5S/NwYoBoxJHzMsfVh8XPzUqVM7W8YG/yOFQmFsrNGdBwO0PeRs/tnr06+fij1FRw8JSg96Lv25SXGTpk2d1vOlsCA3QU9JJJLVq1evX7++66UQxGLxztSdZTVlt6Ju5QbkNro2kg094FDhEFIS4nDKIdgnOCkxic/v6kq+kpKSXbt2rVmzhtTAyGh7SHlNuSRKci7gXL0rBfs9cQ8RlgidTjnhHjI7cXbXPUR3kJugp/D818rKatasWaTukkgkys3N/a3wt1bU2iJsyQvJq3Gv0esCEpaKJagQjMkdY1VsZWdlFxoUOmbMGB13VC3RcHNj/K0W+7AHPUSBFAqhIickp3s9JDg3eGDxQFsr27CgMN17iI4gN0GPKBSKpUuXrlu3Tt97TlRXVxcVFZ3PP18rre3w6VA6KJt5zXU2dWIbcbNDs5KnxJM1M6WZZZOldYP1kMYh9nL7gU0DLaWW7Rfbh7kMCwkKCQoKcnR0JH+dbg4cOCCVSl999VVSAyP2oIfckt5q92nvoodYNli6Nrry5XxtD0EXkauLK/5A7UYP0RHkJuiRQ4cO4f795ptvklp/MpmsvLwcP8o1mpqa8PukWd7cpmobwB4w0GbgILtBeHqFc9nGxgY/8fHx4XK55A/rCf/9y5Yt27hxY8/3cAGDMWQP0RHkJug+tVqNYwhzdXUlTUZvw4YNHh4eEyZMIDUA+oPr00H3FRQU4I93BoUmFhsbm5mZSQoAugVyE3Rfenp6QkICKRjCy8sLD5NFIhGpAdAf5CbopsrKSplMxsQrcGJiYnDikwIA/UFugm46cuRIfHw8Ey+/wblZXFzc0tJCagD0BLkJukMulxcWFkZGRpKaUTgcTlBQUHZ2NqkB0BPkJuiO48ePR0VFMfdsnri4uKysLFIAoCfITaA3lUqVkZHB6FN53N3dWSxWSUkJqQHQB+Qm0FtOTo6HhwdNV2IYDM59GHKC7oHcBHpLT0/vA+eNh4eHX7x4US6XkxoAnUFuAv2Ulpaampr6+PiQmrHYbPbYsWNPnz5NagB0BrkJ9IMHmxMnTiQFw0VHRx89elStpnGtXNAnQW4CPUgkkmvXruEZLqkZzs3Njc/nw9EhoC/ITaAHPNiMiYnpen1iZomLi8vIyCAFALqB3AS6UigUubm52jtW9hlhYWEikUgmk5EaAB1AbgJdZWVl+fn56bs+sZHDY2ccnceOHSM1ADqA3AQ6UavVOFwmT55M6j5kwoQJ2dnZcHQI6A5yE+iEiUtt6kiggX9AUgPwLJCbQCdMXGpTd7GxsXDtENAd5CZ4NuYutamjoKAg/DOKxWJSA9AlyE3wbMxdalNH5ubmMTExJ0+eJDUAXYLcBM/A6KU2dYen6qdOnVKpVKQGoHOQm+AZmL7Upo4cHBzc3Nzy8/NJDUDnIDdBV/rAUpu6g/sOAR1BboKu9I2lNnUUGBgok8lqampIDUAnIDdBV/rGUps6YrFYeMgJd1cHzwS5CTrVZ5ba1B3OzdzcXDg6BLoGuQk61ZeW2tQRn893d3eHW12CrkFugqfrY0tt6g5/VMC1Q6BrkJvg6freUps68vX1bWlpqaysJDUAT4DcBE/RJ5fa1F1cXBxcOwS6ALkJnqJPLrWpu3Hjxp05cwZ/eJAagEdBboLH9eGlNnWEPzACAgJwdJIagEdBboLH9eGlNnUXGxsLJ3KCzkBugsf17aU2deTl5YXH3SKRiNQAPARyEzyizy+1qTu4XB10BnITPKLPL7WpO5ybxcXFLS0tpAbgPshN8H/6yVKbOuJwOEFBQXDtEHgS5Cb4P/1kqU3dxcXFwbVD4EmQm4DoV0tt6sjd3Z3FYpWUlJAaAA3ITUD0q6U2dYc/SGDICR4DuQmIfrXUpu7Cw8MvXrwol8tJDQDkJtDqh0tt6ojNZo8dO/b06dOkBgAhk46ODvIUGBOVSqU9lbKpqQkPdrC6+roGeUObqg1vNUWm9nx7Dofj5OSEZ9YCgcDd3R2/w7V/thv+9a9/BQcHR0dHkxo8BL8QycnJ69ev7/bpWU++mvX19fjVvKe6p/0G/Gpac6ypejUB3SA3jQt+R124cOFc4bmy0jLTIaZtDm0tvJYmXlO9Tb3UXqrkKdXmau13cmScYbeHDb412E5ixxazb1feHiIY4uHhERAQoO+wUSKRrF69GudCP1w1TkcrV66cPn06/t2SWjctLS0lJSX5+fnFF4vNBGb41cSvIH5BJTaSWvvaZl7zw68m9zZ36K2hjhJHK7GVqlI1WDDYy8OrG68mMADITaOAkys3NzevOO9GzY0WYUupX2l1YHUb+4+hpY5YKpZXtZewVDgwb2B7S3toaGhkZKSO15hv3brVyspq1qxZpAZPyM7OzsvLW758Oam7hMeV58+fLyws/L3ydzMvs/LQ8gLfgrvcu2SzDvCraVtt61/qPyRviEWLRXhouO6vJjAAyM1ehhNz265tF8sv1obVXgy4WOdZ18Hq6SsyQjIiLjeuI6PDReCSkJDg6+tLNjyNQqFYunTpunXr+u2qcbrAE+2333577dq1fD6fND0NHmCmpaWdPHNSFaQqEBZU+FY8GFF2G1fCDcsNc85wdhe4T02Y2vWrCQwDcrPX4Cl5yu6U3PzciwkXL0261PM32GMs1ZZ/Pvdn24O2HBZn3rx5eApPNjzq0KFD1dXVb775JqlBJ/ConM1mJyUlkfpROFjxb/Jg+sHmiOb90/brNbrUhYnaxPecr/Cg0JHlOH/e/M5eTWAYkJu9AA/xfkn75fiJ479P/P3C5Av3OOTgAB3MkNlrua+ZpJj4ePng9/xjwyW1Wr1MA+aAzyQWi9esWbNhw4bHjg7h32FOTs6O1B0KT8WBxANyR3rPWPLM9QxNCQ3yCpqdNLvrwS+gD2vVqlXkKTCIoqKilZ+szBRkZvxPRnVgNeXDzMe0o/Z8l/zr46971Hjs/26/o6Pj4MGDyTaE8vPzb968+cILL5AadI7L5eLXjsPhPPwLxJOGNZ+uOXPzzMGFB89OOqu0VpINtKl3qb84/uK9mnt53+U5Ozo//I8BBgO5aVA79+z88dcfDy8/XBFToddhnx5qZbVme2e7ebtd23KtVlzr6elpZmaG27///vuEhASBQKD9NtA1c3PzU6dORUREaEuRSPTRpx8VRxXvfX3vbdvb2kYD6GB1VHpX3vC+Id8irxfXe3l6aV9NYDBw3ruBKJXKNclrfi7/ee+avTI3GWk1rN1uuw+uPXjz3s1PP/0UD5RgqU19BQUF4V8anrDj53hu/um/Pj214FTWlN65ClPqJk1Zm3L43uHVn67GryZpBQYB+zcNQSKRfJz8cal7afar2T0/XN5D1sj677v/3pTX5Ozs7O3tPWnSJLIB6CA1NbW9vR0PPA+fPbx/2X6ZS+98BD4senf06LzR/1j2D5g3GAzM02lXUVGx8tOVp6afKpxZaAzj+3vo3mnv03GsuKsnrk6fPt3W1pZsADqwt7f/Ne3X/Jb8XSt23XYw3Ny8C1XeVW2storvKoL8g7hcLmkFdIJ5Or3wnO7T5E+PLDlyJfoKaTICbahtdexq53nOGzZsgCmeXk6cOFHDr9mxYgflZxr1RGFsYU5izkfrPoJX0zAgN2mEO/Hqf60+O/dsnVcdaTIm66LXDXp+0Nq1a5VK2o8C9w3Z2dlHC4/uXby313e2PKk8srwwvnDlmpVwYw8DgNyki0ql+mz9Z4VjC0WRRnpPRDzqXDllJdud/d1335Em0DmRSPRDyg9py9JoPd+2J36b9NsFvwv/3vRvUgPaQG7SZeN3G4v4Rfmz8kltlHB0bp6/uVpcDXfR6RqeOqz7cl3mW5nNgmbSZJTOzDlzUXVx957dpAb0gNykBe64Z6RnMhdlktqI1ZnXFb5ZmJqaKpVKSRN4FJ46fPL5JxcnXrzhe4M0GasOVsfBtw8eyDpQVlZGmgANIDepJxaL9x/bf3jJYbqvBaJKlkuWxWSLrVu3kho8KjMz84rNlbwpeaQ2bkqe8uSCk+u/XY/jnjQBqkFuUu+77d8VzizE3ZfUTPDtpG/xbB1uQPYkhUKRujc1ay6TbjFUE1BT41EDs3X6QG5SDEfP77d+L48tJzVD3GHduf7y9W3btqnVzBgjG8yBQwfEAWIj3635pBPzThzJOlJTU0NqQCnITSrh0NmSsuX0y6eN8DyVZzoQcKCN23bhwgVSA83hoINHD55OYt7Nhe5y716cfnHH7h2kBpSC3KTSyZMnb9rcxLMkUjNNRULFvn37SAEQStmdciXuCrN2uTxwMfbiJdGl6upqUgPqQG5SRqFQ7NyzM2NeBqkZ6Kj/0bqWOpHISE84NbA/bl6Sn1s0tYjUTKM2V1+cejF1TyqpAXUgNylTVFTU6N7Y5NJEagbqYHVI46RZWUw6BkKfE9knKuIqjPYsd13gIWdZRRmcYUY5yE3K5OTlFIcWk4KxMsIyzuefh6NDWHZ+drUvsye5eMgpjZJmZjLgPGJmgdykhlKpLC374yaUpGasZn6zqcC0vJxh5wNQDk/Sm1ubpR6MH6nlROfggTN8EFILcpMaBQUF97zuGXIJd/rUBNUUFTF1px5VCooKbvgZ+9VBumgWNLc5tsEHIbUgN6lxNu8sXZN0OUJV5KlhFHoU4rEzKfqrE/knroRSt/TfLYTqydOnwx+4+FXu+nu6q9avFq5ooBbkJgVUKtXF0ovXfK+RmhL4jbQeoeEI2WoeuQj9BSGDDIDqhteJxeL+vLhcS0tLbVVtnSdFq//hV80ToeWketxRhMYhZKl5lR0QckZoBUKULohc4FuQX2jU68swDuQmBUpLS03cTahcyBaH5hSE3tGMU6YhlPTH/XzRVoSCDRGdHawO1ghWfz4bCc9qZV4yapYXwAmIX8rOVhPGH42TEDqDkDtCL2me4+/8TPNCU7cAsdRN2qRoksl6/5YefQbkJgWkUqlcQOk62/+L0BGERuF3MEJ7EdqJEB7LBmliFG+iX9OQJu3dx/on/IJKnCSk6Ak89Q5DqLMrsC4j9K7myWbNC70doXTNE/y6401LNZsoYj7cHE6ApxDkJgWampqaedRdv4wT+EvNABPH5TDShngIaZejTdWMRmlW61ArkVARHMx0o+nGHZs7pOge/Bp9i1AAnoz8cSe8p9ui+TY8n1hIGv6AX/GNmif4haZuT4lisKI/fxBSDnKTAg0NDVI+dSes7NO8YfCU7bEb9EZoBqHHSUWrm043b9zqC0eTu0cil/T02srFCC3STNLxiPId0vY47S/4yduJhmse8f8/nl5QpHZIbWVlJSlAj0FuUkBSL5HaU5ebZzSPT70770RNeuKhKM3uWt9tVjBsBSAKyWQyha2CFN2DUy8Ood8Q+lfnrxeeT3QgtIBU/wdP0rXwJIMidfZ1eFZECtBjkJsUaJA3ULn0g/Zto93JNU9zjNUEoREIrab4MGsXFHxFfz6M0NzQfMeuZ/P0f2tmBo/NGJ7qyVTFE3wMf0BSl5tSrhTu10YhyE0KNMmacNCQoue007dSzUHV/yLERsgeIRFCqzQnrBjFLbv7uHtN93q6f7PbkbdPc5gI+0DzSJFmdjPctZRCkJsUUClV1F8phN82QxAqQqgGjxYQykDISXNk9nWynVYdrI52dTsp+p92ZXvvXPp1RnM2EvYPzT4Z6uAXFC61pBDkJgVY5iyWikUKquDp28MTvVjN2BNLNcQpnGZKswHsAaTof0zMTah/QZ9pD0IxmvlEEkIfkzaqWCmt2Gw8cwHUgNykwED+QI6MQwqqTNOMNx+Go1N7WhL99wdjy9m2PFtS9D8DeAPwb4AUhrEOoRc1pyW9ozleRPWhPxeZC5/PJwXoMchNCjjYOVg2WJKi5/B8HHtw5ubDtI307+K0qrcaYv9YbPcjAx0GWkmtSEE3nJV/0UzMcVZuvH+WLtUcZY6QmxSC3KTAIP4gm0YbUvScj+bxqUs8aBOT/pHQoKZBPB51R3OZxsbGht1kkPEmDs3ZmitorRFKQ+gt0kw5voxvZ2dHCtBjkJsUwJ/kg2SDSNFz2jM3D2reVA+Taw6yY4GaRzrx5Dg2+29uOvIcLZuom0B0AY80f9HMMLIQmkza6GAps4TxJoUgNymAI8augboPc/z+wVPkKs0+r4ct15xNHa1ZA4Jm1nJrPOYiRf8zhDfEEPs3U+6fZ3ZAs/gAncwazCA3KQS5SQHcI6ncHYbfSN9r9nZ9oFlKZw9CPyMUr2nEs7kN5LtoZSmxdHBwIEX/M8h+kIOE/h//wRmaszSLyD35ReGJE/V/7Hwgz0GPQW5SwNfX16zczExJ3UHQiZpL0fG4Es/WX9ScmKItj9/f+0knixYL01umrq6upO5/PDw8HMocTNQmpKbD5fvLUeM5BH7y1C+KTiHlSXgdLR1ubm6kBj0GuUkBNpv9nPtzQ0ooPQAdq1lSLEszzNyseYLLMWQjrVyLXAP8AszNzUnd/+AJhJ2jnUMFRUPOJZplAP9FKmKYprHrL4o61Lj8cYEB9O8U708gN6kRNTZKmC8kBVXw+DVas+7DQs0Tqs/p64x/vn+wMJgU/VWUMGpYwVPPBdMfT5OS9qQi2JrGrr8oesUF+YKwsDBSACpAblIjMDCQU8jphYtMqIZ/BIsyi4CAAFL3V6GBocMLh5OCyTgyjlqs9vT0JDWgAuQmNbhcrpubm3OJM6kZa0jJkOfcnuNwqL78iWlcXFyskbVNDeOPpYw7Py4kKITFYvwnulGB3KRMzNiYgDzGD9OEhcJQYSgp+rcQYcjQgqGkYKwheUNgkk45yE3K+Pv72xbbGu76PBqw5eyB+QPHjDHI4SejNzFyok+GD6P3vQhEAnOpuYeHB6kBRSA3KcPj8V6IfyEyNZLUDBT3a9yEqAn9+Uqhh7m6unqP8PY+4k1qBpqwbcJLs1/qz6dG0ARyk0pTJk8ZIhpC2fkrhsWVcB3yHKZNm0ZqgNBrSa+NPjh6gIKRS+qNzhntjJzDw7W3KwJUgtykEv5gfyXxlajtUaRmlPjU+OkJ0+GI0MMcHR3DQ8OFaVSfYUY/lool3Cl8Ze4rpAaUgtykGP54H2o6dFjOMFIzhEOlA6+CN2nSU+8G16/NnjHb/YQ79eur0iz8ULjQQwh7NmkCuUm9v77817E7x1J52SX94nfEz02aCzvCnsTj8RLiE8J3MWm2i1PeLd1tdtJsUgOqQW5Sz93dPUwYFrsplt4LnKkTnRY95N4Q2BHWmSnxU56reO65nOdIbdzwB/YLX74wI2FGf16ZhW6Qm7T46yt/FSqFwT8z4GrFUUWjPDI8li9bDqdGd4bD4fzv8v+N2BbBr2TAUmwJ3yaEC8KnTJlCakADyE1a4Az64J0PhIXCkZkjSZNR4tfww78L//uyv8O5R10TCARLFi35U/KfDH3fIT1FpkZ6yb0Wvb6I1IAerFWrVpGngFLm5ubBfsGXv71cN6TutqMx3vXcosUi8dPEV5Ne9fPzI02gc87Ozugeavu17XLE5Q5WB2k1Jl4nvcacHPPhig/h1pV0g9ykkbW1tedznte/un7d//pdm7uk1TiYqE3mJc+L94+HY+i68xzlWVte23GhQxQkIk1GQ1AqiN4avfK9lfb2j628BKgHuUkv3IkFjgL5enm9a73xjDoHKAbM/WKuv5X//Ffmm5rCvho9+I32+/3o7zZlNlf9rxrPqHNk9sio76P+sfQfw4f3hTWcjB/kJu1cBrv4efrd/PqmWq2u86gjrb3HVmyb9GnSRO+Jf/nLX+BYkL7MzMwiwyMbCxttDtuIAkRtbIrWZO8uPG+ITIkMyw5btWIVhKbBQG4aAp/Pjx4bXb2n2rLc8sboG+1m7WSDwXmVeD3/2fPzE+dPnjwZRprdgz9sQoNDWU0s1n9YYk+xwlZBNhicRYtFQnJCxJ0IHJq2trakFdAPctNA2Gx2XESc7ILMcp9ljV+NykpFNhhQ3JG4gJ0By5cuDwyEuyb01KhRo4Y6DW3+ulnJV9a7PPVu9/SyrbZ94ZMXZgbMXPjqwgEDGHkFPXOZdHQY45HBPuzAsQOpe1IvTL1QMaFCba4mrTTDc/NpKdMcZA7vLX8P7gdLoZqamrWfr8WjzuOJxxV8Aw08BygGBB0Kcs9wf2vBWyEhIaQVGBDkZi+QSCTfp35/qeLS+cTzleMqaT28wJazX9z9okW+xYvTX4yNjYUrKSmnUCjS09MPpB+ojas9OfXkPc49soEGLBXL/4i/50HPMUFj5s6aC2fd9hbIzV5TXV39Tco3ldLKvMS862HXSSt18KgkIT1hYPrAiXETp06dCgsd0Uoul+/evTsnP0c0XXQu9hzlMwkTtcmIkyNC9oT4evq+nPiyo6Mj2QB6A+RmLysrK/s29dtaVW1pVOmNgBstji1kQw8MrhgcUhJid8ou0CcwMTERJuYGIxaLd6buvFRzqTqquiigqNG1kWzoAZsaG/cCd49THu5O7q8mvdqf72tvPCA3jUJpaemp3FMFxQVKK+WVoCvVvtVSDynZphs8gxtWMSw0N9Si2MLOyi4kKGTMmDEuLi5kMzAgkUiUm5ubV5jXilrlQvm5kHMSd4lee2Pw6HJQ+SDvIm9BocAKWYUJw8LDwt3d3clm0NsgN40LfssVFBWcLjwtb5K3erbKHeQynkxuI1faKFsdWpU8JZ4AminNLJssLRss7Rvt7eX2vCaevdRefVE9zGVYcFBwUFAQTOKMRHV1dVFRUV5+Xq20VuWjanJowq/mLZtbrTatT76anEaOg9yB38TnSrkWFy0GuwwO8wsLDAyEDz8jBLlppKRS6e+//y6TyeRyeb28vr6pvl5a3ypvbVe1m7PNuTbcQXaD7Pn2PB7PxsYGz8R9fHy4XC75w8DI4NexvLxc+2r+8YI21ddJ627Lb6tVajO2mZWNlZ2dnYAvePBqenp6wjEfYwa5CQAA+oErRgAAQB8I/X+dzz6uOSfNXgAAAABJRU5ErkJggg==\" style=\"height:367px; width:400px\" class=\"img-responsive\">\n<span style=\"font-size:18px\">For the above tree, the maximum GCD\nfor the sibilings is 6, formed for the\nnodes 6 and 12 for the children of node 3.</span>\n</pre>\n\n<div><span style=\"font-size:18px\"><strong>Example 2:</strong></span></div>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 3\narr[] = {{1,2}, {1,4}} \n<strong>Output :</strong>\n2</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\n</span><img alt=\"\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAP4AAADfCAIAAABZBPmVAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAhdEVYdENyZWF0aW9uIFRpbWUAMjAyMTowMjowMSAxMzoxNzoyNCxHyPAAACFlSURBVHhe7d0JQFNH/gfwoeEIQUy4DEYjilgMUjDIIYIHleJR8U/xKIpHC/VEq6vrrnbdXXd7r9S11R7WxXW1VMRq0cqiLRZB8IAICAhSMApIBEJCAAnBgPzHMEstCkJ4Od5789m3mN/EdZPMl5eZvJd5Jp2dnQDD6OcF9CeG0QyOPkZTOPoYTeHoYzSFo4/RFI4+RlM4+hhN4ehjNIWjj9EUjj5GUzj6GE3h6GM0haOP0RSOPkZTOPoYTeHz9fVHrVaLxWK5XN7Y2KjQqK+vhz9hO7yXyWRaW1uz2WxnZ2cej+fk5GRra9v1P8R0AUdf55qbmwsKCkQiUUFhwRDeEIYDo43T1sppbWI3yexltZzaSrNKC2DBVXHNms2G1w/n3uMyq5iqMpUNx8bXy9fDw0MgEDAYDPTPYQTB0dcVuHfPzs7Ozc29Lb5t7WZ9z+9emkea3FqO7u4H+3J79xvuI/NGMhXMkKCQmUEz8fsAgXD0iQd380lJSRmZGRbeFr94/fKzx88dZh3oPq2wq9geFzxGXRk11nVs1IIoOBZCd2CDgKNPJDhqT05O/m/Kf0EgOB52vMm6Cd1BBIaa4XLBRXhW6Oruuu61dVwuF92BaQVHnxgdHR1ZWVnHEo4BAfhh8Q/V3Gp0B9HgL4DgjGDCjxOC5gS9FfoWngNoDUefAAqFYnfs7gZmQ+rS1DLnMtSqSyw5yyfOZ1T9qK1rtno6e6JWbCBw9AervLz8k72f3Jt172zoWdSkL/xs/uS4yS+/9vLa2WtRE9ZvOPqDAgc5h44cEq0VFQgLUJN+WUmtpn46dYzDmD1r9jCZTNSK9QOOvvZOnDhx/vL55G3JNbwa1GQIJh0mPod8nMXO+/64z55jj1qx58HR1wac1O7bv6+wuTB+U3ybdRtqNagJSRME6YIPt33ownNBTVif8Dk82jh+/HiOKuffO/5tJLmHbobdzPu/vB0f7CiXlKMmrE84+gOWkZHxU+5P3238rpNhXG+Yt2fcFi0R7XxvZ5W8CjVhvcPRH5jy8vJD8YdObTn1kPUQNRmTuwF38+fn/+GDP9Qr6lET1gsc/QFQKBT/2PuPSzGXmnhEHqYlVuns0iL/ou37t8MJCWrCngVHv7/UavWHsR8WzCoQe4hRk7EqWlBUblH+4dEPUY09C45+f124cKGUXXot9BqqjVvWxixRkehc1jlUY0/B0e8XpVKZ8H1CWmQaqo1eO7M9Y2PG0SNH5fIBnCZNKzj6/XI6+bREKDHmIf7TGpwaCkIKYuNiUY39Fo7+88HZ7X/P//dSxCVUk8fNsJu35LeysrJQjT0BR//54k/ElwWXqTgqVJNHJ6Mza3nWf777D/6052k4+s9RW1t7RXQlb34eqsmmzq1OypP+9NNPqMb+B0f/OVIzUkuCS4zzAFY/pS9O/+7Md13rPmDdcPSfI0OUUeVB7vMC4Hy3zalNJBKhGtPA0e8LHO00tTRJXaWoJq2rwVeTU5JRgWng6PclOy+7ypMKp4LdnnhbIpdUVeHT2n6Fo9+XC6ILYj9jP22hPzoZnWo/9fXr11GN4ej3obm5ue5uXZ2gDtXEUgEwFYAlqNKDQmHhjRs3UIHh6PehpKSkzq1ukKtH9WojAJkA6PGLjQWCgjsVd5RKJappD0e/V+XScrmjDk6AaQfgTQD+hSq9gWMejgunvBx/hwvB0e9VTWNNK7sVFUQRAeADwGFU6VknvxPPdLvh6PdKppARfPLCJwD4A5APwGQA3kNt+iTjy3D0u+Ho90ohVyhtCB0ZFwFgD8BXAFwCYCRq0yfpMGl9Pf7iIoKj36sHsgetdoQOeGIAuAPAGgBMUYOeSa2kLS0tqKA9HP1etTe2EzzW9wbAoOujKVlK/AlPNxz9XnWqOtuZ7aighE5GJz57uRuOfu/MHq/ojW5TAkPFwOtydsPR7xWDw2AqKBUUvpyPL0nUDUe/V5YOllZSK1RQgq0cJh9HH8HR79UQ9hBmI6X2+tZyazs7O1TQHo5+rxw4DpaNlqigBEu5Jd7rd8PR7xWXw6XYWN9EZsLhcFBBezj6vRpjP8a61hoVlNBR32FjY4MK2sPR75WnqyevmGfSYYJqkrOvtW9vbnd2dkY17eHo9woOi4dwhziUOqCaWAGa8ze3o0oPZohmeAm9UIHh6PfN18t35HXdnGjmAsBKAGahSg+4Iq6/vz8qMBz9vs2dNNcplwpX5R8qH9omaRMIBKjGcPT7xufzh4AhNhWknxpOz57u6+2LL63+JBz955jgNYGXx0MFafGu8fBopwcc/eeImBYxPnU8qc9j45XzTKQmrq6uqMY0cPSfw8nJaey4sa7nSJybkCMhy5YsMzMzQzWmgaP/fFsitrx09iVzpTmqScUzy3M4GB4QEIBq7H9w9J+Py+V6+nlOSJqAavKA4zThMeHKyJWoxp6Ao98v68LXjf95PEvOQjVJBCQHCF2FeJT/TDj6/cLhcILmBHkmeqKaDOAvqnOK85IIPS5uSCo4+v0VOSfyxdIXR2eNRrVxM1WZhu4NDZ8X7uCgmxMxyA9Hv79YLNYH2z7wP+JvKybBKe+zD8wO4AWEhoaiGnsKjv4A8Hi8TWs3zdwz08jP45+SMMVD4bF+1XpUY8+Coz8wfkK/+cHzYfqN9iCX20U3oUi4fct2fNpC33D0B2xZ2DJ/R3//OGM8L4BbxPVL9HtnyzvW1pT6ko0u4OhrY/Eri93L3Kd+MdWo9v0uGS6v7Hll3Zvr4MAMNWG9w9EfMIVCsX///hULV8wFc+e+O9cYxv0mHSb+R/2DzwTPfWXu6dOnVSryXd1a/xi7du1CN7F+6Ojo2LNnj5eX16xZswJ9Ak0aTUy+NpEIJK02RK/E328WzRaz98wObA18b8d7QqHw1q1beXl5Pj4+6G6sFzj6A3PkyJG2trZVq1Z1le7j3Uc5jmr4vEFhq2jkN3Y16pNNhc289+eFC8NjomLMzR+fZTRx4sSzZ8+2tra++OKLXX8He7ZOrN/S09O3bt0KU4Xq/6msrIx+O3rql1NZMhbohK+pPjbzFnOvRK9lq5ddvnYZPY7/kclkMTExhYWFqMaeBUe/v8rKyqKjo6urq1H9Wy0tLd98901kdOSkY5NgKHvElNiN8ZDhfsZ96eqlsV/HNjQ0oEfwWzdv3ly9enVNTQ2qsaeYwP+i/T/WOzi13blzJ4w+HEyjpmeBf+3IiSPXRNfyXsv7ZeYvhF99EU5nx14c63PSZ7xg/JrFa7hcLrrjWS5cuPDjjz/+7W9/w6srPxOO/vPBqS0MEJzahoWFoaY+SSSSuIS44qrim9Nv3hPea3BqQHcMAruKPfL6yAnpE0Y7jl4fsd7JqV9flj948KBSqdy0aROqsSfg6D+fdgEqLy+/eOXi1dyrSqAUe4nFvuJ6l/pOxgBebbiPH1YyzCnPaXTuaCtg5ePl84r/Ky4uLujufhjoLy2t4Og/BxwzwJHDYIYNFRUV1/OuXxRdlEllcnd5rUOtkqNsZbeq2KoWhxYVRwXHRaYqU8tGS0uZJauBxVQw4e1h0mG2hbZ2fLupnlP9J/nz+Xz0zw0QHIO98847q1at6nuoRkM4+n0pLi7ev38/zD0hp/7K5fKSkhL4877ifp2irqGxQSFVqBSqTnXnC8wXmGzmULuhdrZ2wzjDeGyera2tQCAgZHVYsVj88ccf//Wvf8VHeZ+Eo98rmNG//OUva9eudXd3R02klZGRcebMmffeew9PebvhExmeTaVS7d69e86cORTIPTRt2jT4RD799FN8GbluOPrPdujQITi8fvXVV1FNfsuXL1er1adOnUI17eHoP0NycrJEIuk+W4EaGAzGpk2bMjMzs7OzURO94ej3VFRUlJKSsmXLFuqt2WRtbQ2f1+HDh6uqqlATjeHo/0Ztbe2+ffvWr19P1WtOOTk5RUZGxsbGNjc3oya6wtH/FZza7tmzZ8mSJW5ubqiJigICAgIDA+FvOM2nvDj6vzpw4ICLi8uMGTNQTV3h4eFw6H/8+HFU0xKOPnLy5EmZTBYVFYVqSoO537hxY05OTkZGBmqiHxz9x/Ly8tLS0uAUkD6rGLBYrG3btsXHx4vFYtREMzj6j0+0/Oqrr2Du6XZNWR6Pt3btWji9USgUqIlO6B59pVIJ+z4yMpKeV9UUCoVBQUH0PMpL6+jD/t63b5+7u/u0adNQE/0sWLAADn4OHTqEatqgdfRPnToF0798+XJU0xWc8j7+dsHFi6imB/pGPzs7OzMzE/Y6XqCPyWTCqc6xY8fgLwBqogGaRr+iouLw4cOwv/ECfV24XG5MTMzevXvlcjlqojo6Rr+5uRlObeE4p5/fcKUJDw+PWbNmwVdGrVajJkqjXfS7praBgYH4OrJPCw0N5fF4cXFxqKY02kX/22+/hYP78PBwVGO/FRUVBUeD586dQzV10Sv6GRkZubm5eGrbh64p75kzZ4qKilATRdEo+mKxOD4+ftu2bSwWyS6EqGcODg4bNmz44osvpFIpaqIiukRfoVDACdzatWvxqgT94ebmFhYWBl8xCq9XTovow6ntp59+GhQUhNei6b+QkBAnJ6eDBw+imnJoEf1Dhw5ZW1svWLAA1Vj/REdHwzFPUlISqqmF+tG/ePFieXn5+vX4coIDZmZmBqe8qampBQUFqIlCKB790tLSY8eOwf7DSy9ph8PhbN68+fPPP5dIJKiJKqgcfblcvm/fvpiYmL4X48b65uLismTJEupNeSkbfbVaDXtr1qxZHh4eqAnT1owZM9zc3OB+BNWUQNnox8XF8Xg8fKV8oqxcubKtre3kyZOoJj9qRj85ObmiooIm3zHXDwaDsWHDhrS0NMos3kbB6Hcvn4antsSCU174qlJm8TaqRV8qlX7xxRfr168nZEV8rAdnZ+fIyEg4iVIqlaiJtCgV/a7l08LCwqi9fJphBQQE+Pj4UGDxNkpF/8CBA05OTiEhIajGdOP111+HuSf74m3UiX5SUpJMJqPYyuDGCU55N2/enJOTk5WVhZpIiCLRLygoSE1NhZMwfCK+frBYLPhqx8fHV1RUoCayoUL0JRLJZ599BvdDdFs+zbD4fP4bb7yxe/duki7eRvrod01tly1bNqALymKE8PX1nT59+v79+8k45SV99LuWT6PDyuDGadGiRRYWFkePHkU1eZA7+idPnmxra8PLpxnWxo0bi4qKSLdeOYmjn52dnZaWtmHDBjy1Nayub7IfOXKEXIu3kTX6VVVVhw8f3rZtG57aGgMej/f222/v3buXRFNeUka/e2VwvHya8fDw8AgODob9QpYpL/miD19ZuHfx8fEJCAhATZhxCAsLs7OzI8s32ckX/a7j56+//npXiRmVNWvW3Llz58cff0S1ESNZ9LOysnJycjZv3oyntsYJTnl///vfJyUlFRcXoyZjZdLZ2YluGhO1Wi0Wi+VyeWNjI5w5QTX1NXKFvEnRZGphyjBl2NjaWLGsRjuO5nK5cI7l4uKCz843iB49BftIUi+pq61rb2s3szQzASawpzgsDs+RZ2w9ZVzRb25uLigoEIlE+YX5JjyTVodWJUcp48ikbKnCXqHiqDrM0BSKJWdZPLDg1HBG1I6wkdgwxAwHnsNE14mThJPc3d27/g6mO109lSnKvFl4s4PXAXvqAeeBgqOoZ9e32Lc83VOjakY51jpaS6wfiR+N4I1wc3UTCoWG7SmjiD7cZ2RnZ4tyReXi8k63ziK/opseN9us29Dd/cBQM2wqbPhF/BevvchqZk31m/rytJfx5z+E6+qpjNyMSnFli1tLvl/+fY/7WvSUV5HXyGsjzZvNp/hNmTZtmkF6ysDRhzsPOC68mHmx1bs1xyvnjsed7r2F1qxrrV2uuAhSBU48p4h5EXhFBkLAnjqWdCwjM6PWu/aW1y2YeEJ6auqVqY6pjs4859B5oXruKYNFH44Rk5OTz6acbQpsOhN2ZkB7jv4w6TBxuurkd9ZvOGP42uVrXV1d0R3YAMGeOp18+nTK6duBt3PDcnXRU75XfT3OejgwHFYsX6G3njJA9Ds6OrKysr5N+PaB4EHy4mQFV7fH/0ZdGRUQH+Dl5hUVEWVra4tasX6APZWRlfGfhP9UCapyFuc0c5vRHbox+cpk93h3oZswIiJCDz2l7+grFIp/xP7jPvP+uaXnapxrUKuOwfGlMEkIh0Drotf5++LrCPUL7Kk/xf6pkll5eellubOeri0Heyo8KZydyl4VvcrX1xe16oZeo19eXv7J3k/Es8Q/hhrgkIet2DZ4X3DgS4Grlq7Cn4T2rbS89P2971+fdb041AAfz48TjwvaF+T3kt/SpUt12FMw+vqRmZkZtTpqQu4EAH/XDLSZtppO/3L6xj9vbGhoQA8Le0pqZmrE6gheLq/Hq6fPDfbU6i9X7/zzTt31lJ6in5iYGL052qbapsczNMg2MXHiqq2rqqur0YPDnvBl4pfhm8OHVg/t8aIZZHs98fUtW7foqKd0Hv329vZ/7v3nindXWDRZ9HhiBtxcUl1WxKzA6X8S7Kkde3eEvBtiVD01O3X2+pj1uugpnUc/Pj5++UfLTdpNejwlg29j0se88fYbeOTT7aP4j4I+CjLCnpqdNvvtzW8T3lO6jX56enr01mjzFvMeT8ZINtcUV/jwmpqa0MOlscT0xPlb5xttT80/M3/bH7a1traih0sEHUa/rKzszdVvGsn4vrfN+4j31o+2okdMVwVlBYtWLzKS8X1v29Kvl3722WfoERNBVyctKxSK2L2xmTGZDbwG1GSUri+9XqQuijtJi0vjP1O9ov79ve/DnmriNaEmo3T8jeOFkkICv/yuk+ir1eqPYj8qnlVc5lGGmoxVJ6MzfUP6+bTzhcWFqIlOYE/9LvZ3hbMK73vcR03GqsOs4/T600cTjhJ1IWudRP/ChQv32PcuhV5CtXFTcVRZ0VmxB2JhDlATbXx+4fNKdqVBjltpoY5f98urv/z78L9RPTjER1+pVJ74/sQPkT+gmgwkQonYVfyvk/9CNT00KZuufH8lPzIf1WRwafalYkkxIRczJT76ycnJMqHMyAeOT8tZnpOelk6N64X00+7k3RXCCnL11OMB6or0uCNxg1/3geDow9lt8vnk8xHnUU0ebdZt+a/l7ztBqYsE9qFWUVt6vvRGxA1Uk8dd4V2ZtSw/f7BvVgRH//iJ49XB1XD0jGpSKZ9ZXlleSd5Vswdk14ldvwT/QtKeypyXefz0YC9sQWT0a2trL4suZ8wn2dqL3TrMOvLn5x84eQDV1FVUWyQVSUvml6CabConVlY3Vw9ynUMio5+RkXE/+P5D1kNUkxDc8d8pvUPUx2dGKy4jriy4jLw9BUf8BcEFKWkpqNYKkdGHu/x8DzJ9XPA0uOMvm1529sJZVFPUPdE94/8gv29if7FIJBrMZJew6MPRTkNLg9SV9PvLshll6Rnpg/8AwWjdqL2hblGTvaeUtsoHvAclJdqP2QiLfl5eXoOnUZ+z0E9NvKZmbvNgXlMj933e9/c9yb3L71LsXZyel46KgSMs+ldEV3L8clBBoBoALgIgAuABatCDMs+y6wXXUUE5N0U3q/x0dvhCAcBdPXVWvWt9QbH2x7aIiX5zc/Odu3fqBHWoJkQ8AAIAhgMQBIAPADYAvKZ5WXWv2qP6au5VVFBLTXNN591Ognuqm0rTWWMAOIkadEo2RtYsaVaptPx8lpjow+FBm1vb4Nck+tWfAVgGwC0AggHYDsBaAOwBSALAHwDdX7lD7ix/oHwgl+tpGQJ9SixJrHOrI7KnngR7TY8fc3QyOpvGNWn9EScx0ZdKpc2OxC3SAl++jzQ3vgPgJwA+BOBLOAoBIFAz/lmnuUvH2sa0UfLY1j3pvQeOuhmOXAAgFt3Um5qRNbclt1ExQMREv7GxsZ5dj4rBOw5AOwBhACxADY8N0fwCQKmaAaWOyUfIJRIJKigE9lQruxUVBII98gYAHADGowb9gL/GZbVanhhPTPQVCoWUQ9yHZXDwNloz1Omhe11e3UdfPFJ8W6zl7sSYPVA80MnJC6vgGwoAXwHgiBr0o8WhpbqmGhUDREz0JXKJ0kaJisH7JwB3AIhB1a+K0J+P3wF0rMW+pa5RN3NBg2qTtxHZU13iNUPThQDo/Uo3bUPampRannlKTPRlMlmrnQ7eRnv4WPPTWzPl1bE267aW5hZUUMgj2SOCe+ouABsAGAmAIa6gpbRVtsvh4FgbxES/pbFFJyPIJ8FdyzeaG7s1P3WsndmuVBG9dzQCpo2mRPYUTN1yzfjzsGagbwiP4H+0Qkz021XtMCuo0IWTmlkUtBOAGZobOtbJ6HzUoeVrasxMVaZE9tQnAGRq9vozUYOeDaabiIk+w4zBUOvsum5xAERodjCbAXgXtekajIgl0xIVFNJh1kFYT+Vr9kTj9fQ+/Eywm8yYZqgYIGKib8WxYip0sCIujPsOAN7S3HhPM/3VF0u5pYOtAyoopIPTQUxPqQBYorlxDADDrVoNnwuLw0LFABETfXsHeyupFSqI8gCARZpjW6aaUf6fULN+2MptKRl94ACI6amrmmPtcJckBMDkie2i5l44OoW339Tc1iWreitbey0vQkFM9LlsLrOR0N99mPs5mjMX7AFIAyASNeuNg9zBzs4OFRRiwbYgpqfgvzH6WVvXvw17Dd7W/Qdxlo2W9hwt/2+IiT6HwxneOBwVhIBvpnD+5AjAJc35C3pnI7eh5NWH4NAUxgUVgzFZc+zl6Q22Q7Ga27qfA8ABjyNHy6NohEWfoyDuw60DAJzVHLf6Sd8HxruxZCz4nFBBIfBJ6WRWZiDwuTixtbzwKEFjfXt7m1obVAwenNFCcMzz0m/Hkd1b14BSl8zrzW1siHtGRoNnz7OutUYF+dnX2js4aDklIyb6rq6u5sXmJh0wlUS4h/40FBgO02ZTZ2dnVFPIAtcF3GIuYT1lUBbNFkNqhmh9uWliog+HxSO4IxxLCTp36akFpntuOj6qNV403k/ohwpq4dvyX+C+4FCqsw+v0jQdtBJVOsXL443xHGNmZtDP9SFfL1+f6z6oIDlXkau/P2WvMerq5Try+khUkJmzyDnEKwQVA0dY9CdNmmSbS4WPRFhylpnETCAQoJpywieFP746Iskx1IxhxcO8hd6oHjjCos/n84eAITYVpJ8aumS7+Hr7Mhg6Oy/D0IR8IRMwyd5T3CIu15nLYml5KBciLPoQHPNMypuECtJyv+Ye6G+IQwl6NMJrBBwoo4KcnEROM7wGNecjMvrTpk3jp/J1eB6b7tmX27OkLFdXV1RT1JvT3nwx9UXy9hRTwRwjGjN98nRUa4XI6Ds5OXmM8wg6F4RqEpp5ZOYbS97Q+kMDsvB08hw2bpjrObL+hnuf8n55+suDPOZIZPShJRFL+Gf55kpzVJPK2Kyxo8CogIAAVFPaOxHvuJ11I2NPWddaj742eklY14mj2iM4+lwuN9AvcG7SXFSTB3z3n3xscnRkNKqpbhR3lLOf84SkCagmj8kJk8PnhQ9mgtuF4OhD4eHhnJ85Q+VDUU0SE5MnTnSdSPlR/pN2hO8Y9/M4lnywGdInW7HtiNIR82bPQ/UgEB99OAKbN2deaGIoqskAdr9bitvKCL0chDQasKe853i/lPgSqslg6rdTV0SsIGQyRnz0oTlz5tiV2k3JmoJq42aqMp27d+6CeQu0PhGKvGLmxIwrHTc6azSqjZswSTju4bhpAdNQPUjoqulEq66ujl4d7Xzb+Tfn3hjlNmfvnE+//BQ9bvqprK6MWB1he9u2x8tibBs/lx8dE93Q0IAe96DpKvpQbm7uWzFvDWkY0uM5GNXmd8zvj7v+2N7ejh40LV3OvbwwZiGzgdnjxTGejV3JXrlu5e3bt9EjJgJj165daP9PtOHDhz96+Ih1ipUfmN/JgM/A6Iy7OC7gYsDfd/ydyaTOtze0wB/Ob3nY0nqqVRwoNsKesmi2CPsgbE3EGk9PT9REBJ2M9buFhYV5OHqsiFuBamPCLeIGJAbs3LLT2po6X93Q2pthb/o4+vjG+aLaaJh0mMzbNy90Sijhx1t0G30oKipqVO2o6C+ijeqwuUuGy6x9s7Zv2s7jkf4cRqJsj9ruV+s3/YvpxtNT5krzhR8v9LfyXxi+EDURxwQOetBNnVGr1QcPHiyqKfp2y7eNnEbUaiBwLzLl2ykeNzzg/h7nvgfYU3sO7rlSc+X8lvMGv5r0UMnQsD1hc7znLFq0SBcn0upwrN8NPm4fHx91o9rsazOlQFlvQ9xK/AMER41z98wNbA18d8e7lPzq7SDBngr0CXyh8QXwNZAIJK02ul9CuBfOBc4hH4VEL45+9dVXX3hBN2OTrtmufohEojXr1sy8PLPH/F0/m81dmyVvL/km8Ruaf57TH7Cnlq9bPuryqB6voX42/xT/1TGrb926hR6NbuhjwPOkqqqq3bG7HwoeJi5ObLDV08VG4ZDRO9nbJdUlJjrG19foZnLGCfbUu7Hv3hXczVqcpbTV06LTNhKbufFzh8uH79i2Q9frIOk7+pBSqUxJSUlOSTYJNkmYn6Bk6fBlhTO2iecmCs4KJntPjlwUScmldXQH9hTsph9SfrgdfFs0X/SQ9RDdoQNMBTP0ROhQ0dCFry2cOXOmHs4bN0D0uygUihMnTlwTXVO9pkqYmUD4Nf3gdHb8xfGTTk7yEHisWLyCy+WiO7ABgj2VcCLhsuhy4WuFhTMLCe8p+J4ckhJil2I3O3j2/PnzB39KZj8ZLPpdJBJJQkJCeVV50/SmS8JLlU6V6I5BYFex3a67Oac7j3UcGxURpfU6LdiTYE8dTThaUlVSMb3ihvBGgxMBg9URpSMmF0zmpHO83b0XL16s55UeDRz9LuXl5VeuXLmee10FVO1e7bm+ufkuAzsADPfxw0qGTcybyM3lsgBritcUf39/FxcXdDdGkK6eupZ7rQW01HvVi3xFtS61A+opOAQdWzrW94qv+Q1zWytbX2/fyZMn8/l8dLceGUX0u1VUVOTl5YlEohppjZm72QOHBw2cBhlbVseuq3WoVXFU8N328UUfGi0tZZbcBq6dwo7TyBkiHQIKwUj+SD9Pv0mTJhnkdaSbrp66KroKe+qR+yOlg7KR8/gCshK2pMWh5cmespXZDmsYNkwxbGjjUCuplbpQPYY/xlvDsKNQ44p+N7lcXlJSAn/CgSbU2NhYJ62DN9rV7WZMM2u2NdeOa2drB6etbDYbvlEKBAI8hTWIp3vqvvR+k6KpQ91hzjSHveNg5wA7qLun3N3djeTMESONPobpms7P4cEw44Sjj9EUjj5GUzj6GE3h6GM0haOP0RSOPkZTOPoYTeHoYzSFo4/RFI4+RlM4+hhN4ehjNIWjj9EUjj5GUzj6GE3h6GM0haOP0RIA/w/IJ5jHCZE2KgAAAABJRU5ErkJggg==\" class=\"img-responsive\">\n<span style=\"font-size:18px\">For the above tree, the maximum GCD\nfor the sibilings is 2, formed for the\nnodes 2 and 4 for the children of node 1.</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>maxBinTreeGCD()</strong>&nbsp;which takes an integer N and a 2-d list denoting the edges as input and returns the maximum GCD of sibilings of the tree.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(E*logE), where E is the number of edges in the Tree.<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\nThere might be edges with similar values</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Maximum GCD of siblings of a binary tree - GFG/maximum-gcd-of-siblings-of-a-binary-tree.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int N = Integer.parseInt(read.readLine());\n            \n            ArrayList<ArrayList<Integer>> arr = new ArrayList<>();\n            \n            for(int i=0; i<N-1; i++)\n            {\n                ArrayList<Integer> temp = new ArrayList<>();\n                String S[] = read.readLine().split(\" \");\n                temp.add(Integer.parseInt(S[0]));\n                temp.add(Integer.parseInt(S[1]));\n                arr.add(temp);\n            }\n\n            Solution ob = new Solution();\n            System.out.println(ob.maxBinTreeGCD(arr,N));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    static int getGCD(int a,int b){\n        // Everything divides 0\n        if (a == 0)\n          return b;\n        if (b == 0)\n          return a;\n      \n        // base case\n        if (a == b)\n            return a;\n      \n        // a is greater\n        if (a > b)\n            return getGCD(a-b, b);\n        return getGCD(a, b-a);\n    }\n    static int maxBinTreeGCD(ArrayList<ArrayList<Integer>> arr, int N) {\n        if(N==1)return 0;\n        arr.sort((arr1,arr2)->arr1.get(0)-arr2.get(0));\n        int ans=0;\n        int i=1;\n        while(i<arr.size()){\n            ArrayList<Integer> arr1=arr.get(i);\n            ArrayList<Integer> arr2=arr.get(i-1);\n            if(arr1.get(0)!=arr2.get(0)) i++;\n            else{\n                ans=Math.max(ans,getGCD(arr1.get(1),arr2.get(1)));\n                i+=2;\n            }\n        }\n        return ans;\n    }\n};"
  },
  {
    "path": "Maximum Number of Words Found in Sentences.java",
    "content": "class Solution {\n    public int mostWordsFound(String[] sentences) {\n        int max=0;\n        for(String s:sentences){\n            int cur=1;\n            for(int i=0;i<s.length();i++){\n                if(s.charAt(i)==' '){\n                    cur++;\n                }\n            }\n            max=Math.max(max,cur);\n        }\n        return max;\n    }\n}\n"
  },
  {
    "path": "Maximum Path Sum between 2 Leaf Nodes.cpp",
    "content": "\nclass Solution {\npublic:\n    int maxSum(Node* root,int &sum){\n        if(!root) return INT_MIN;\n        \n        if(!root->left && !root->right) return root->data;\n        int l = maxSum(root->left,sum);\n        int r = maxSum(root->right,sum);\n        \n        // cout<<l<<\" \"<<root->data<<\" \"<<r<<\"\\n\";\n        if(root->left && root->right)     sum = max(l+r+root->data,sum);\n        return max(l,r) + root->data;\n    }\n    int maxPathSum(Node* root)\n    {\n        int out = 0;\n        Node* tmp = root;\n        int Sum = INT_MIN;\n        out = maxSum(root,Sum);\n        if(root->left== NULL || root->right==NULL) Sum = max(Sum,out);\n        return Sum;\n    }\n};\n"
  },
  {
    "path": "Maximum Path in Triangle.java",
    "content": "public class Solution {\n    int[][]dp;\n    public int solve(int[][] A) {\n        int n=A.length;\n        dp=new int[n][n];\n        for(int i=0;i<n;i++){\n            dp[n-1][i]=A[n-1][i];\n        }\n        return solve(A,0,0);\n    }\n    public int solve(int[][]arr,int i,int j){\n        if(dp[i][j]!=0){\n            return dp[i][j];\n        }\n        int max=arr[i][j]+Math.max(solve(arr,i+1,j),solve(arr,i+1,j+1));\n        dp[i][j]=max;\n        return max;\n    }\n}\n"
  },
  {
    "path": "Maximum Product of Increasing Subsequence of Size 3 - GFG/README.md",
    "content": "# Maximum Product of Increasing Subsequence of Size 3\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:20px\">Given a sequence of non-negative integers, find the subsequence of length 3 having maximum product, with the elements of the subsequence being in increasing&nbsp;order.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:20px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:20px\"><strong>â€‹Input:</strong>\nn = 8\narr[ ] = {6, 7, 8, 1, 2, 3, 9, 10</span><span style=\"font-size:20px\">}\n<strong>Output:\n</strong>8 9 10\n<strong>Explanation: </strong>3 increasing elements of \nthe given arrays are 8,9 and 10 which \nforms the subsequence of size 3 with \nmaximum product.</span><span style=\"font-size:20px\">\n</span></pre>\n\n<p><br>\n<span style=\"font-size:20px\"><strong>â€‹Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:20px\"><strong>Input:\n</strong>n = 4\narr[ ] = {3, 4, 2, 1} <strong>\nOutput:\n</strong>Not Present </span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:20px\"><strong>Your Task:</strong><br>\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function <strong>maxProductSubsequence()</strong> that takes an array <strong>arr</strong>, sizeOfArray <strong>n</strong>, and return the subsequence of size 3 having the maximum product, numbers of subsequence being in increasing order. If no such sequence exists, return&nbsp;<strong>\"-1\"</strong>. The driver code takes care of the printing.</span></p>\n\n<p><br>\n<span style=\"font-size:20px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N*LOG(N)).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(N).</span></p>\n\n<p><br>\n<br>\n<span style=\"font-size:20px\"><strong>Constraints:</strong><br>\n1 &lt;= <strong>N</strong> &lt;= 10<sup>5</sup><br>\n1 &lt;= <strong>Arr[i]</strong> &lt;= 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Maximum Product of Increasing Subsequence of Size 3 - GFG/maximum-product-of-increasing-subsequence-of-size-3.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\n//Initial Template for Java\n\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\n\nclass Array {\n    \n    // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t    String line = br.readLine();\n\t\t    String[] element = line.trim().split(\"\\\\s+\");\n\t\t    int N = Integer.parseInt(element[0]);\n\t\t    int arr [] = new int[N];\n\t\t    line = br.readLine();\n\t\t    String[] elements = line.trim().split(\"\\\\s+\");\n\t\t    for(int i = 0;i<N;i++){\n\t            arr[i] = Integer.parseInt(elements[i]);    \n\t        }\n\t        \n\t\t    Solution obj = new Solution();\n\t\t    ArrayList<Integer> ans;\n\t\t    ans = obj.maxProductSubsequence(arr, N);\n        \tif(ans.get(0) == -1)\n        \t    System.out.println(\"Not Present\");\n        \telse{\n        \t    for(int i: ans)\n        \t        System.out.print(i + \" \");\n        \t    System.out.println();\n        \t}\n        \t\n\t\t}\n\t}\n}\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    \n   \n    public static ArrayList<Integer> maxProductSubsequence (int arr[], int n) {\n        long ans = 0; \n        ArrayList<Integer> list = new ArrayList<>();\n        \n        list.add(-1);\n      \n        TreeSet<Integer> left = new TreeSet<>();\n        left.add(arr[0]);\n        \n        int max[] = new int[n];\n        max[n - 1] = arr[n - 1];\n        for (int i = n - 2; i >= 0; i--) {\n            max[i] = Math.max(arr[i], max[i + 1]);\n        }\n        \n        for (int i = 1; i < n - 1; i++) {\n            Integer l = left.floor(arr[i] - 1);\n            int r = max[i + 1];\n            \n            if (l != null && r > arr[i] && ((long) arr[i]) * l * r > ans) {\n                ans = ((long) arr[i]) * l * r;\n                list.clear();\n                list.add(l);\n                list.add(arr[i]);\n                list.add(r);\n            }\n            left.add(arr[i]);\n        }\n        \n        return list;\n    }\n}\n\n"
  },
  {
    "path": "Maximum Split of Positive Even Integers.py",
    "content": "class Solution:\n    def maximumEvenSplit(self, num: int) -> List[int]:\n        if num&1==1:\n            return []\n        even=2\n        a=[]\n        while num>0:\n            a.append(even)\n            num-=even\n            even+=2\n        if -num in a:\n            a.remove(-num)\n        return a\n            \n                    \n"
  },
  {
    "path": "Maximum Twin Sum of a Linked List.java",
    "content": "class Solution {\n    public int pairSum(ListNode head) {\n        int length=1;\n        ListNode temp=head;\n        while(temp.next!=null){\n            temp=temp.next;\n            length++;\n        }\n        int dp[]=new int[length/2];\n        temp=head;\n        int index=0;\n        while(temp!=null){\n            if(index<length/2){\n                dp[index]+=temp.val;\n            }else{\n                dp[length-1-index]+=temp.val;\n            }\n            index++;\n            temp=temp.next;\n        }\n        int ans=0;\n        for(int i=0;i<dp.length;i++){\n            ans=Math.max(ans,dp[i]);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Maximum Width of Binary Tree.java",
    "content": "class Solution {\n    public int widthOfBinaryTree(TreeNode root) {\n        Queue<TreeNode> q=new LinkedList<>();\n        root.val=0;\n        q.add(root);\n        return bfs(q);\n    }\n    \n    public int bfs(Queue<TreeNode> q){\n        int maxWidth = 1;\n        while(!q.isEmpty()){\n            int sz=q.size();\n            int left = q.peek().val;\n            int right = left;\n            for(int i=0;i<sz;i++){\n                TreeNode node=q.remove();\n                if(node.left!=null){\n                    node.left.val = node.val * 2 - 1;\n                    q.add(node.left);\n                }\n                if(node.right!=null){\n                    node.right.val = node.val * 2;\n                    q.add(node.right);\n                }\n                if(i==sz-1)\n                    right=node.val;\n            }\n            maxWidth=Math.max(maxWidth,right-left+1);\n        }\n        return maxWidth;\n    }\n}\n"
  },
  {
    "path": "Maximum Winning score.java",
    "content": "class Solution:\n    def findMaxScore(self, root):\n        ans = []\n        temp = 1\n        def recur(root,temp):\n            temp = temp*root.data\n            if root.left == None and root.right == None:\n                ans.append(temp)\n            if root.left:\n                recur(root.left,temp)\n            if root.right:\n                recur(root.right,temp)\n        recur(root,temp)\n        return max(ans)\n"
  },
  {
    "path": "Maximum XOR of Two Numbers in an Array.java",
    "content": "//fastest\nclass Solution {\n    public int findMaximumXOR(int[] nums) {\n        int max=0,mask=0;\n        HashSet<Integer> set=new HashSet<Integer>();\n        int maxNum=0;\n        for(int i:nums)\n            maxNum=Math.max(maxNum,i);\n        for(int i=31-Integer.numberOfLeadingZeros(maxNum);i>=0;i--){\n            set.clear();\n            int bit=1<<i;\n            mask=mask|bit;\n            int temp=max|bit;\n            for(int prefix:nums){\n                if(set.contains((prefix & mask)^temp))\n                { \n                    max=temp;\n                    break;\n                }\n                set.add(prefix & mask);\n            }\n        }\n        return max;\n    }\n}\n\n\n\n\n\n//easy to understand\nclass Node {\n    HashMap<Integer, Node> children;\n    Node() {\n        this.children = new HashMap<>();\n    }\n}\n\nclass Trie {\n    Node root;\n    \n    Trie() {\n        this.root = new Node();\n    }\n    \n    public void insert(int[] A) {\n        for(int num : A) {\n            Node curr = this.root;\n            for(int i=31;i>=0;i--) {\n                int currBit = (num >> i) & 1;\n                if(!curr.children.containsKey(currBit)) \n                    curr.children.put(currBit, new Node());\n                curr = curr.children.get(currBit);\n            }\n        }\n    }\n}\nclass Solution {\n    public int findMaximumXOR(int[] nums) {\n        Trie trie = new Trie();\n        trie.insert(nums);\n        \n        int max = 0;\n\n        for(int num : nums) {\n            Node curr = trie.root;\n            int currSum = 0;\n            for(int i=31;i>=0;i--) {\n                int requiredBit = 1-((num >> i) & 1); // if A[i] is 0, we need 1 and if A[i] is 1, we need 0. Thus, 1 - A[i]\n                if(curr.children.containsKey(requiredBit)) {\n                    currSum |= (1<<i); // set ith bit of curr result\n                    curr = curr.children.get(requiredBit);\n                } else {\n                    curr = curr.children.get(1-requiredBit);\n                }\n            }\n            max = Math.max(max, currSum); // get max number\n        }\n        return max;\n    }\n}\n"
  },
  {
    "path": "Maximum average subarray - GFG/README.md",
    "content": "# Maximum average subarray\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array <strong>Arr</strong>&nbsp;of size <strong>N</strong> and a positive integer <strong>K</strong>, find the sub-array of length <strong>K</strong> with the maximum&nbsp;average. </span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>K = 4, N = 6\nArr[] = {1, 12, -5, -6, 50, 3}\n<strong>Output:</strong> 12 -5 -6 50\n<strong>Explanation:</strong> Maximum average is \n(12 - 5 - 6 + 50)/4 = 51/4.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>K = 3, N = 7\nArr[] = {3, -435, 335, 10, -50, 100, 20}\n<strong>Output:</strong> 335 10 -50\n<strong>Explanation:</strong>&nbsp;Maximum average is \n(335 + 10 - 50)/3 = 295/3.\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>findMaxAverage()</strong>&nbsp;which takes the array of integers&nbsp;<strong>arr, </strong>its size <strong>n</strong>&nbsp;and integer&nbsp;<strong>k&nbsp;</strong>as input parameters and returns an integer&nbsp;denoting the starting index of the subarray.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N)<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(1)<br>\n<br>\n<strong>Constraints</strong><br>\n1 &lt;=&nbsp;N &lt;= 10<sup>5</sup><br>\n0 &lt;= |Arr[i]| &lt;= 10<sup>3</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Maximum average subarray - GFG/maximum-average-subarray.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\npublic class GFG {\n    public static void main(String[] args) throws Exception {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int tc = Integer.parseInt(br.readLine().trim());\n        while (tc-- > 0) {\n            String[] inputLine;\n            inputLine = br.readLine().trim().split(\" \");\n            int k = Integer.parseInt(inputLine[0]);\n            inputLine = br.readLine().trim().split(\" \");\n            int n = Integer.parseInt(inputLine[0]);\n            int[] arr = new int[n];\n            inputLine = br.readLine().trim().split(\" \");\n            for (int i = 0; i < n; i++) {\n                arr[i] = Integer.parseInt(inputLine[i]);\n            }\n\n            int ans = new Solution().findMaxAverage(arr, n, k);\n            for(int i=ans; i<ans+k; i++)\n                System.out.print(arr[i]+\" \");\n            System.out.println();\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    int findMaxAverage(int[] arr, int n, int k) {\n        // code here\n        int ans=0;\n        int curr=0;\n        int index=0;\n        for(int i=0;i<k;i++){\n            ans+=arr[i];\n            curr+=arr[i];\n        }\n        for(int i=1;i<=n-k;i++){\n            curr-=arr[i-1];\n            curr+=arr[i+k-1];\n            if(curr>ans){\n                index=i;\n                ans=curr;\n            }\n        }\n        return index;\n        \n    }\n}\n"
  },
  {
    "path": "Maximum level sum.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    public int solve(TreeNode A) {\n        int sum=A.val;\n        Queue<TreeNode> q=new LinkedList<>();\n        q.add(A);\n        while(!q.isEmpty()){\n            int sz=q.size();\n            int curr=0;\n            for(int i=0;i<sz;i++){\n                TreeNode node=q.remove();\n                curr+=node.val;\n                if(node.left!=null){\n                    q.add(node.left);\n                }\n                if(node.right!=null){\n                    q.add(node.right);\n                }\n            }\n            sum=Math.max(sum,curr);\n        }\n        return sum;\n    }\n}\n"
  },
  {
    "path": "Maximum number of 2X2 squares.cpp",
    "content": "//{ Driver Code Starts\n//Initial Template for C++\n\n#include<bits/stdc++.h>\nusing namespace std;\n\n\n// } Driver Code Ends\n//User function Template for C++\n\nclass Solution\n{\n    public:\n    long long int numberOfSquares(long long int base)\n    {\n        //code here\n        base/=2;\n\t      return (base*(base-1))/2;\n    }\n};\n\n//{ Driver Code Starts.\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tlong long int base;\n\t\tcin >> base;\n\n        Solution ob;\n\t\tcout << ob.numberOfSquares(base) << \"\\n\";\n\n\t}\n\n\treturn 0;\n}\n\n// } Driver Code Ends\n"
  },
  {
    "path": "Maximum number of 2X2 squares.java",
    "content": "class Solution\n{\n    public static long numberOfSquares(long n)\n    {\n        //code here\n        if(n<=3)return 0;\n        if(n%2==0){\n            n-=2;\n        }else{\n            n-=3;\n        }\n        n/=2;\n        return n*(n+1)/2;\n    }\n}\n"
  },
  {
    "path": "Maximum number of events that can be attended.java",
    "content": "class Solution {\n    static int maxEvents(int[] start, int[] end, int N) {\n        // code here\n        int[][] arr = new int[N][2];\n        \n        for(int i=0; i<N; i++){\n            arr[i][0] = start[i];\n            arr[i][1] = end[i];\n        }\n        Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));\n        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();\n        int i = 0, res = 0, d = 0;\n        while (!pq.isEmpty() || i < N) {\n            if (pq.isEmpty())\n                d = arr[i][0];\n            while (i < N && arr[i][0] <= d)\n                pq.offer(arr[i++][1]);\n            pq.poll();\n            ++res; ++d;\n            while (!pq.isEmpty() && pq.peek() < d)\n                pq.poll();\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "Maximum selections - GFG/README.md",
    "content": "# Maximum selections\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\"><strong>Note: This&nbsp;<a href=\"http://practice.geeksforgeeks.org/problem-of-the-day\" target=\"_blank\">POTD</a>&nbsp;is a part of&nbsp;<a href=\"https://practice.geeksforgeeks.org/summer-carnival-2022?utm_source=potd&amp;utm_medium=problempage&amp;utm_campaign=gsc22\" target=\"_blank\">Geek Summer Carnival</a>. Solve all POTD consecutively from 5th to 10th April and get a chance to win exclusive discount vouchers on our GfG courses.</strong></span></p>\n\n<hr>\n<p><span style=\"font-size:18px\">Geek wants to select the maximum number of course bundles at the Geek Summer Carnival.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\">You are given a finite number of courses and N range of numbers each depicting a bundle of courses.&nbsp;Select the maximum number of bundles such that no courses overlap in any of the bundle.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Note:</strong> The ending of a range being the same as start of another isn't considered as an overlap.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4\nBundles = \n1 5\n2 3\n1 8\n3 5</span>\n\n<span style=\"font-size:18px\"><strong>Output:</strong>\n2</span>\n\n<span style=\"font-size:18px\"><strong>Explanation: \n<img alt=\"\" src=\"https://media.geeksforgeeks.org/img-practice/ScreenShot2022-04-01at4-1648812950.png\" style=\"height:65px; width:250px\" class=\"img-responsive\"></strong>\nWe can select 2 bundles at max while \nstaying true to the condition. For this, \nwe can pick the ranges (2,3) and (3,5) \nwithout any overlap. </span></pre>\n\n<p>&nbsp;</p>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 5\nBundles = \n7 9 \n2 8 \n1 3 \n10 11 \n10 16</span>\n\n<span style=\"font-size:18px\"><strong>Output:</strong>\n3</span>\n\n<span style=\"font-size:18px\"><strong>Explanation: \n<img alt=\"\" src=\"https://media.geeksforgeeks.org/img-practice/ScreenShot2022-04-01at4-1648813138.png\" style=\"height:60px; width:400px\" class=\"img-responsive\"></strong>\nWe can pick the ranges (1,3), \n(7,9) and (10,11) without any overlap.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Complete the function <strong>max_non_overlapping()</strong> that takes&nbsp;a 2D array representing N ranges as input parameter. &nbsp;Return the maximum number of course bundles.&nbsp;</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected time complexity: </strong>O(NlogN)<br>\n<strong>Expected space complexity:</strong> O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N &lt;= 1000<br>\n0 &lt;= range[i][j] &lt;= 1000</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Maximum selections - GFG/maximum-selections.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.util.*;\nimport java.lang.*; \n\nclass GFG{\n\tpublic static void main(String args[]) throws IOException { \n\t\t\n\t\tScanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n\n        while(t > 0){\n       \t\tint n = sc.nextInt();\n\t\t\t\n\t\t\tint arr[][] = new int[n][2];\n          \n        \tfor( int i=0 ; i<n ; i++ ){            \n            \tfor( int j=0 ; j<2 ; j++ ){\n                \tarr[i][j] = sc.nextInt();\n            \t}\n         \t}\n            \n            solver solve = new solver();\n\t\t\tSystem.out.println( solve.max_non_overlapping(arr,n) ); \n\t\t\tt--;\n\t\t}\n\t} \n}\n\n// } Driver Code Ends\n\n\n// ranges[i][0] is the start of ith range\n// ranges[i][1] is the end of ith range\n\nclass solver\n{\n    static int max_non_overlapping(int ranges[][], int n){\n        // code here\n        int ans=0;\n        Arrays.sort(ranges,(a,b)->{\n          if(a[1]!=b[1]) return a[1]-b[1];\n          else return b[0]-a[0];\n          });\n        int prevMax=Integer.MIN_VALUE;\n        for(int a[]:ranges){\n            if(a[0]>=prevMax){\n                ans++;\n                prevMax=a[1];\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "Maximum sum Rectangle - GFG/README.md",
    "content": "# Maximum sum Rectangle\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:20px\">Given a 2D matrix M of dimensions RxC. Find the maximum sum submatrix in it.</span></p>\n\n<p><strong><span style=\"font-size:20px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:20px\"><strong>Input:</strong>\nR=4\nC=5\nM=[[1,2,-1,-4,-20],\n[-8,-3,4,2,1],\n[3,8,10,1,3],\n[-4,-1,1,7,-6]]\n<strong>Output:</strong>\n29\n<strong>Explanation:</strong>\nThe matrix is as follows and the\nblue rectangle denotes the maximum sum\nrectangle.</span>\n<img alt=\"Thumbnail\" src=\"https://a.disquscdn.com/get?url=http%3A%2F%2Fwww.geeksforgeeks.org%2Fwp-content%2Fuploads%2Frectangle-11.png&amp;key=6UHjdHyGWQGo6f_kdpoBIQ&amp;w=320&amp;h=247\" class=\"img-responsive\">\n</pre>\n\n<p><span style=\"font-size:20px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:20px\"><strong>Input:</strong>\nR=2\nC=2\nM=[[-1,-2],[-3,-4]]\n<strong>Output:</strong>\n-1\n<strong>Explanation:</strong>\nTaking only the first cell is the \noptimal choice.</span></pre>\n\n<p><br>\n<span style=\"font-size:20px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>maximumSumRectangle()</strong> which takes the number R, C, and the 2D matrix M as input parameters and returns the maximum sum submatrix.</span></p>\n\n<p><br>\n<span style=\"font-size:20px\"><strong>Expected Time Complexity:</strong>O(R*R*C)<br>\n<strong>Expected Auxillary Space:</strong>O(R*C)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:20px\"><strong>Constraints:</strong><br>\n1&lt;=R,C&lt;=500<br>\n-1000&lt;=M[i][j]&lt;=1000</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Maximum sum Rectangle - GFG/maximum-sum-rectangle.java",
    "content": "// { Driver Code Starts\n// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int N, M, x, y;\n            String S[] = read.readLine().split(\" \");\n            N = Integer.parseInt(S[0]);\n            M = Integer.parseInt(S[1]);\n            int a[][] = new int[N][M];\n            for (int i = 0; i < N; i++) {\n                String s[] = read.readLine().split(\" \");\n                for (int j = 0; j < M; j++) a[i][j] = Integer.parseInt(s[j]);\n            }\n            Solution ob = new Solution();\n            System.out.println(ob.maximumSumRectangle(N, M, a));\n        }\n    }\n}// } Driver Code Ends\n\n\n// User function Template for Java\n\nclass Solution {\n    int kade(int[]sum){\n        int max = Integer.MIN_VALUE;\n        int cur=0;\n        for(int i : sum){\n            cur += i;\n            if(cur > max){\n                max = cur;\n            }\n            if(cur <0){\n                cur = 0;\n            }\n        }\n        return max;\n    }\n    \n    int maximumSumRectangle(int r, int c, int mat[][]) {\n        int max = Integer.MIN_VALUE;\n        \n        for(int i=0; i<r; i++){\n            int[]sum = new int [c];\n            \n            for(int j=i; j<r; j++){\n             \n                for(int k=0; k<c; k++){\n                    sum[k] += mat[j][k];\n                }   \n                \n                max = Math.max(max, kade(sum));\n            }\n        }\n        return max;\n    }\n};\n/*\nint max = Integer.MIN_VALUE;\n        \n        for(int i=0; i<r; i++){\n            int[]sum = new int [c];\n            \n            for(int j=i; j<r; j++){\n             \n                for(int k=0; k<c; k++){\n                    sum[k] += mat[j][k];\n                }   \n                \n                max = Math.max(max, kade(sum));\n            }\n        }\n        return max;\n*/\n"
  },
  {
    "path": "Maximum sum leaf to root path.java",
    "content": "class Solution\n{\n    public static int maxPathSum(Node root)\n    {\n        //code here\n        if(root==null)return 0;\n        return Math.max(maxPathSum(root.left),maxPathSum(root.right))+root.data;\n    }\n}\n"
  },
  {
    "path": "Maximum sum of Non-adjacent nodes.java",
    "content": "class Solution{\n    \n    public static int solve(Node root, boolean canTake,String path, Map<String,Integer> dp){\n        if(root==null) return 0;\n        if(canTake && dp.containsKey(path+'t')) return dp.get(path+'t');\n        else if(!canTake && dp.containsKey(path+'f')) return dp.get(path+'f');\n        if(canTake){\n            int ans1 = root.data + solve(root.left,false,path+'l',dp) + solve(root.right,false, path+'r',dp);\n            int ans2 = solve(root.left,true,path+'l',dp) + solve(root.right,true,path+'r',dp);\n            int ans = Math.max(ans1,ans2);\n            dp.put(path+'t',ans);\n            return ans;\n        }\n        int ans =  solve(root.left,true,path+'l',dp) + solve(root.right,true,path+'r',dp);\n        dp.put(path+'f',ans);\n        return ans;\n    }\n    \n    //Function to return the maximum sum of non-adjacent nodes.\n    static int getMaxSum(Node root){\n        // add your code here\n        Map<String,Integer> dp = new HashMap<>();\n        return Math.max(solve(root,true,\"\",dp),solve(root,false,\"\",dp));\n    }\n}\n"
  },
  {
    "path": "Maximum sum of increasing order elements from n arrays.java",
    "content": "class Complete{\n    // Function for finding maximum and value pair\n    public static int maximumSum (int n, int m, int arr[][]) {\n        //Complete the function\n        int sum=0;\n        int lastMax=Integer.MAX_VALUE;\n        for(int i=n-1;i>=0;i--){\n            int[]a=arr[i];\n            int val=limitMax(a,lastMax);\n            if(val==0)return 0;\n            sum+=val;\n            lastMax=val;\n        }\n        return sum;\n    }\n    public static int limitMax(int[]a,int lastMax){\n        Arrays.sort(a);\n        for(int i=a.length-1;i>=0;i--){\n            if(a[i]<lastMax){\n                return a[i];\n            }\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Maximum twin sum of a linkedlist.cpp",
    "content": "class Solution {\npublic:    \n    int pairSum(ListNode* head) {\n        //1.\n        ListNode* fast = head;\n        ListNode* slow = head;\n        // get to the middle of the linkedlist\n        while(fast and fast->next){\n            fast = fast->next->next;\n            slow = slow->next;\n        }\n        // reverse half of linkedlist\n        ListNode* nextNode, *prev = NULL;\n        while(slow){\n            nextNode = slow->next;\n            slow->next = prev;\n            prev = slow;\n            slow = nextNode;\n        }        \n        // get max sum of twins\n        int ans = INT_MIN;\n        while(prev){\n            ans = max(ans, head->val + prev->val);\n            head = head->next;\n            prev = prev->next;\n        }\n        return ans;\n        \n        \n            \n        // //2. \n        // stack<ListNode*> st;\n        // ListNode* temp = head;\n        // while(head){\n        //     st.push(head);\n        //     head = head->next;\n        // }\n        // head = temp;\n        // int n = st.size();\n        // int ans = INT_MIN;\n        // while(st.size() > n/2){\n        //     ans = max(ans, head->val + st.top()->val);\n        //     st.pop();\n        //     head = head->next;\n        // }\n        // return ans;\n    }\n};\n"
  },
  {
    "path": "Maximum-number-of-2X2-squares.cpp",
    "content": "class Solution\n{\n    public:\n    long long int numberOfSquares(long long int base)\n    {\n        long long int h=(base/2)-1;\n        long long int ans=h*(h+1)/2;\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Merge Intervals",
    "content": "class Solution {\n    public int[][] merge(int[][] intervals) {\n        Arrays.sort(intervals,(a,b) ->Integer.compare(a[0],b[0]));\n        LinkedList<int[]> ans = new LinkedList<>();\n\n        for(int[] tem:intervals){\n            if(ans.isEmpty() || ans.getLast()[1]<tem[0])\n                ans.add(tem);\n            else if(ans.getLast()[1]>=tem[0])\n                ans.getLast()[1] = Math.max(ans.getLast()[1],tem[1]);\n        }\n        return ans.toArray(new int[ans.size()][]);\n    }\n}\n"
  },
  {
    "path": "Merge K sorted linked lists.java",
    "content": "class Solution\n{\n    Node mergeKList(Node[]arr,int K){\n        PriorityQueue<Node> pq = new PriorityQueue<>((a,b) -> a.data - b.data);\n        for(int i = 0 ; i < arr.length ; ++i){\n            if(arr[i] != null){\n                pq.add(arr[i]);\n            }\n        }\n        Node head = null , curr = null ; \n        while(!pq.isEmpty()){\n            Node temp = pq.poll();\n            if(head == null){\n                head = curr = temp;\n            }\n            else{\n                curr.next = temp;\n                curr = curr.next;\n            }\n            if(temp.next != null){\n                pq.add(temp.next);\n            }\n        }\n        return head;\n    }\n}\n"
  },
  {
    "path": "Merge Nodes in Between Zeros.java",
    "content": "class Solution {\n    public ListNode mergeNodes(ListNode head) {\n        ListNode temp=head.next;\n        ListNode start=head;\n        ListNode end=new ListNode(-1);\n        while(start.next!=null){\n            int sum=0;\n            while(temp.val!=0){\n                sum+=temp.val;\n                temp=temp.next;\n            }\n            end=temp;\n            ListNode newNode=new ListNode(sum);\n            start.next=newNode;\n            newNode.next=end;\n            start=end;\n            temp=temp.next;\n        }\n        \n        temp=head.next;\n        while(temp!=null){\n            temp.next=temp.next.next;\n            temp=temp.next;\n        }\n        return head.next;\n    }\n}\n"
  },
  {
    "path": "Merge Overlapping Intervals.java",
    "content": "/**\n * Definition for an interval.\n * public class Interval {\n *     int start;\n *     int end;\n *     Interval() { start = 0; end = 0; }\n *     Interval(int s, int e) { start = s; end = e; }\n * }\n */\npublic class Solution {\n    public ArrayList<Interval> merge(ArrayList<Interval> arr) {\n        ArrayList<Interval> ans=new ArrayList<>();\n        Collections.sort(arr,(a,b)->a.start-b.start);\n        ans.add(arr.get(0));\n        int idx=0;\n        for(int i=1;i<arr.size();i++){\n            if(ans.get(idx).end<arr.get(i).start){\n                ans.add(arr.get(i));\n                idx++;\n            }else if(ans.get(idx).end>=arr.get(i).start){\n                ans.get(idx).end= Math.max(ans.get(idx).end,arr.get(i).end);\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Merge Two Sorted Array.py",
    "content": "class Solution:\n    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n        \"\"\"\n        Do not return anything, modify nums1 in-place instead.\n        \"\"\"   \n        \n        # Replace the n 0's of \"nums1\" with all n elements of \"nums2\"\n        j = 0\n        for i in range(m, m+n):\n            nums1[i] = nums2[j] \n            j+=1\n        \n        # Sort the list \"nums1\" in ASCENDING order\n        for i in range(len(nums1)):\n            for j in  range(i+1, len(nums1)):\n                if nums1[i] > nums1[j]:\n                    nums1[i], nums1[j] = nums1[j], nums1[i]\n"
  },
  {
    "path": "Merge Two Sorted Lists",
    "content": "public class Solution {\n    public ListNode mergeTwoLists(ListNode A, ListNode B) {\n        ListNode head=new ListNode(-1);\n        ListNode my=head;\n        while(A!=null && B!=null){\n            if(B.val<A.val){\n                ListNode curr=B;\n                B=B.next;\n                curr.next=null;\n                my.next=curr;\n                my=my.next;\n            }else{\n                ListNode curr=A;\n                A=A.next;\n                curr.next=null;\n                my.next=curr;\n                my=my.next;\n            }\n        }\n        if(A==null){\n            my.next=B;\n        }else if(B==null){\n            my.next=A;\n        }\n        return head.next;\n    }\n}\n"
  },
  {
    "path": "Merge Two Sorted Lists.java",
    "content": "class Solution {\n    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n        if(l1==null)return l2;\n        if(l2==null)return l1;\n        \n        ListNode temp;\n        \n        if(l1.val<=l2.val){\n            temp=l1;\n            l1=l1.next;\n        }else{\n            temp=l2;\n            l2=l2.next;\n        }\n        ListNode ansNode=temp; \n        \n        \n        while(l1!=null && l2!=null){\n            if(l1.val<=l2.val){\n                temp.next=l1;\n                l1=l1.next;\n            }else{\n                temp.next=l2;\n                l2=l2.next;\n            }\n            temp=temp.next;\n        }\n        if(l1==null){\n            temp.next=l2;\n        }else{\n            temp.next=l1;\n        }\n        \n        return ansNode;\n    }\n}\n"
  },
  {
    "path": "Merge Without Extra Space.cpp",
    "content": "// Merge Without Extra SpaceMerge Without Extra Space\n\nclass Solution{\n    public:\n        //Function to merge the arrays.\n        void merge(long long arr1[], long long arr2[], int n, int m) \n        { \n            int l = n-1, r =0;\n            while(l>=0 && r<m){\n                if(arr2[r]<arr1[l]){\n                    int tmp = arr2[r];\n                    arr2[r] = arr1[l];\n                    arr1[l] = tmp;\n                    l--, r++;\n                }else break;\n            }\n            sort(arr1, arr1+n);\n            sort(arr2, arr2+m);\n        } \n};\n"
  },
  {
    "path": "Merge k Sorted Lists.java",
    "content": "class Solution {\n    public ListNode mergeKLists(ListNode[] lists) {\n          return partition(lists, 0, lists.length-1);\n    }\n    \n    public ListNode partition(ListNode[] lists, int i, int j){\n        while(i==j){\n            return lists[i];\n        }\n        if(i<j){\n            int mid = i + (j-i)/2;\n            ListNode l1 = partition(lists, i, mid);\n            ListNode l2 = partition(lists, mid+1, j);\n            \n            return sort(l1, l2);\n        }\n        else {\n            return null;\n        }        \n    }\n    \n    public ListNode sort(ListNode l1, ListNode l2){\n        ListNode head= new ListNode(0);\n        ListNode dummy = head;\n        while(l1!=null && l2!=null){\n            if(l1.val<=l2.val){\n                dummy.next = l1;\n                l1 = l1.next;\n            }\n            else if(l2.val<l1.val){\n                dummy.next = l2;\n                l2 = l2.next;\n            }\n            dummy = dummy.next;\n        }\n        if(l1!=null){\n            dummy.next = l1;\n        }\n        if(l2!=null){\n            dummy.next = l2;\n        }\n        return head.next;\n    }\n}\n\n\n\n\n\n============================================================\n  \nclass Solution {\n    public ListNode mergeKLists(ListNode[] lists) {\n        Queue<Integer> pq=new PriorityQueue<>();\n        for(ListNode head:lists){\n            ListNode temp=head;\n            while(temp!=null){\n                pq.offer(temp.val);\n                temp=temp.next;\n            }\n        }\n        ListNode ans=new ListNode(-1);\n        ListNode temp=ans;\n        while(!pq.isEmpty()){\n            temp.next=new ListNode(pq.poll());\n            temp=temp.next;\n        }\n        return ans.next;\n    }\n}\n\n"
  },
  {
    "path": "Merge new Interval.java",
    "content": "class Solution:\n    def insert(self, intervals, newInterval):\n        if len(intervals) == 0:\n            return [newInterval]\n        result = []\n        result.append(newInterval)\n        for i in range(0,len(intervals)):\n            a = result.pop()\n            b = intervals[i]\n            if a.start > b.end:\n                result.append(b)\n                result.append(a)\n            elif a.end < b.start:\n                result.append(a)\n                result.append(b)\n            else:\n                start = min(a.start, b.start)\n                end = max(a.end, b.end)\n                result.append(Interval(start, end))\n            \n        return result\n"
  },
  {
    "path": "Merge two Binary Tree.java",
    "content": "public class Solution {\n    public TreeNode solve(TreeNode A, TreeNode B) {\n        if(A==null && B==null)return null;\n        if(A==null){\n            return B;\n        }\n        if(B==null){\n            return A;\n        }\n        TreeNode node=new TreeNode(A.val+B.val);\n        TreeNode lefty=solve(A.left,B.left);\n        TreeNode righty=solve(A.right,B.right);\n        node.left=lefty;\n        node.right=righty;\n        return node;\n    }\n}\n"
  },
  {
    "path": "Merge two binary Max heaps",
    "content": "class Solution{\n    public int[] mergeHeaps(int[] a, int[] b, int n, int m) {\n        // your code here\n        int ans[]=new int[a.length+b.length];\n        Arrays.sort(a);\n        Arrays.sort(b);\n        int i=a.length-1,j=b.length-1,index=0;\n        while(i>=0 && j>=0){\n            if(a[i]>b[j]){\n                ans[index]=a[i];\n                i--;\n                index++;\n            }else{\n                ans[index]=b[j];\n                j--;\n                index++;\n            }\n        }\n        if(i>=0){\n            while(i>=0){\n                ans[index]=a[i];\n                index++;\n                i--;\n            }\n        }\n        if(j>=0){\n            while(j>=0){\n                ans[index]=b[j];\n                j--;\n                index++;\n            }\n        }\n        return ans;\n        \n    }\n}\n"
  },
  {
    "path": "Merge two sorted linked lists - GFG/README.md",
    "content": "# Merge two sorted linked lists\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two sorted linked lists consisting of <strong>N and M</strong>&nbsp;nodes respectively. The task is to merge both of the list (in-place) and return head of the merged list.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 4, M = 3 \nvalueN[] = {5,10,15,40}\nvalueM[] = {2,3,20}\n<strong>Output: </strong>2 3 5 10 15 20 40<strong>\nExplanation: </strong>After merging the two linked\nlists, we have merged list as 2, 3, 5,\n10, 15, 20, 40.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 2, M = 2\nvalueN[] = {1,1}\nvalueM[] = {2,4}\n<strong>Output:</strong>1 1 2 4<strong>\nExplanation: </strong>After merging the given two\nlinked list , we have 1, 1, 2, 4 as\noutput.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThe task is to complete the function <strong>sortedMerge</strong>() which takes references to the heads of two linked lists as the arguments and returns the head of merged linked list.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity</strong> : O(n+m)<br>\n<strong>Expected Auxilliary Space</strong> : O(1)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N, M &lt;= 10<sup>4</sup><br>\n1 &lt;= Node's data &lt;= 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Merge two sorted linked lists - GFG/merge-two-sorted-linked-lists.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\n\nclass Node\n{\n    int data;\n    Node next;\n    Node(int d) {\n        data = d; \n        next = null;\n    }\n}\n\n\nclass MergeLists\n{\n    Node head;\n\n\n\n  /* Function to print linked list */\n   public static void printList(Node head)\n    {\n        \n        while (head!= null)\n        {\n           System.out.print(head.data+\" \");\n           head = head.next;\n        }  \n        System.out.println();\n    }\n\t\n\t \n \n     /* Driver program to test above functions */\n    public static void main(String args[])\n    {\n       \n         \n        /* Constructed Linked List is 1->2->3->4->5->6->\n           7->8->8->9->null */\n         Scanner sc = new Scanner(System.in);\n\t\t int t=sc.nextInt();\n\t\t \n\t\t while(t>0)\n         {\n\t\t\tint n1 = sc.nextInt();\n\t\t\tint n2 = sc.nextInt();\n\t\t\tNode head1 = new Node(sc.nextInt());\n            Node tail1 = head1;\n            for(int i=0; i<n1-1; i++)\n            {\n                tail1.next = new Node(sc.nextInt());\n                tail1 = tail1.next;\n            }\n\t\t\tNode head2 = new Node(sc.nextInt());\n            Node tail2 = head2;\n            for(int i=0; i<n2-1; i++)\n            {\n                tail2.next = new Node(sc.nextInt());\n                tail2 = tail2.next;\n            }\n\t\t\t\n\t\t\tLinkedList obj = new LinkedList();\n\t\t\tNode head = obj.sortedMerge(head1,head2);\n\t\t\tprintList(head);\n\t\t\t\n\t\t\tt--;\n\t\t\t\n         }\n    }\n}\n// } Driver Code Ends\n\n\n/*\n  Merge two linked lists \n  head pointer input could be NULL as well for empty list\n  Node is defined as \n    class Node\n    {\n        int data;\n        Node next;\n        Node(int d) {data = d; next = null; }\n    }\n*/\nclass LinkedList{\n    Node node=new Node(0);\n    Node ans=node;\n    Node sortedMerge(Node head1, Node head2) {\n        if(head1==null || head2==null){\n            ans.next=(head1==null)?head2:head1;\n            return node.next;\n        }\n        if(head1.data>head2.data){\n            ans.next=head2;\n            ans=ans.next;\n            sortedMerge(head1, head2.next);\n        }else{\n            ans.next=head1;\n            ans=ans.next;\n            sortedMerge(head1.next, head2);\n        }\n        return node.next;\n    } \n}"
  },
  {
    "path": "Merging Details - GFG/Merging Details.cpp",
    "content": "class Solution {\r\n  public:\r\n    vector<vector<string>> mergeDetails(vector<vector<string>>& details) {\r\n       vector<vector<string>>vv;\r\n       for(int i=0;i<details.size();i++)\r\n       {\r\n           if(details[i][0]!=\"-\")\r\n           {\r\n               set<string>s;\r\n               vector<string>v;\r\n               for(int j=1;j<details[i].size();j++)\r\n               {\r\n                   s.insert(details[i][j]);\r\n               }\r\n               for(int j=i+1;j<details.size();j++)\r\n               {\r\n                   if(details[j][0]!=\"-\")\r\n                   {\r\n                       for(int k=1;k<details[j].size();k++)\r\n                       {\r\n                           auto pos=s.find(details[j][k]);\r\n                           if(pos!=s.end())\r\n                           {\r\n                               details[j][0]=\"-\";\r\n                               for(int k=1;k<details[j].size();k++)\r\n                               {\r\n                                   s.insert(details[j][k]);\r\n                               }\r\n                           }\r\n                       }\r\n                   }\r\n               }\r\n               v.push_back(details[i][0]);\r\n               for(auto i=s.begin();i!=s.end();i++) v.push_back(*i);\r\n               vv.push_back(v);\r\n           }\r\n       }\r\n       sort(vv.rbegin(),vv.rend());\r\n       return vv;\r\n   }\r\n};\r\n"
  },
  {
    "path": "Merging Details _GFG.cpp",
    "content": "class Solution {\n public:\n   vector<vector<string>> mergeDetails(vector<vector<string>>& details) {\n      vector<vector<string>>vv;\n      for(int i=0;i<details.size();i++)\n      {\n          if(details[i][0]!=\"-\")\n          {\n              set<string>s;\n              vector<string>v;\n              for(int j=1;j<details[i].size();j++)\n              {\n                  s.insert(details[i][j]);\n              }\n              for(int j=i+1;j<details.size();j++)\n              {\n                  if(details[j][0]!=\"-\")\n                  {\n                      for(int k=1;k<details[j].size();k++)\n                      {\n                          if(s.count(details[j][k]))\n                          {\n                              details[j][0]=\"-\";\n                              for(int k=1;k<details[j].size();k++)\n                              {\n                                  s.insert(details[j][k]);\n                              }\n                          }\n                      }\n                  }\n              }\n              v.push_back(details[i][0]);\n              for(string it : s) v.push_back(it);\n\n\n              vv.push_back(v);\n          }\n      }\n      sort(vv.rbegin(),vv.rend()); \n      return vv;\n   }\n};\n"
  },
  {
    "path": "Merging Details.java",
    "content": "class Solution {\n\n    public List<List<String>> mergeDetails(List<List<String>> details) {\n        // Your code here\n        List<List<String>> ans=new ArrayList<>();\n        for(int i=0;i<details.size();i++){\n            List<String> detail=details.get(i);\n            if(detail.size()==0)continue;\n            Set<String> set=new TreeSet<>();\n            String name=detail.get(0);\n            for(int j=1;j<detail.size();j++){\n                set.add(detail.get(j));\n            }\n            for(int j=i+1;j<details.size();j++){\n                List<String> curr=details.get(j);\n                if(curr.size()==0)continue;\n                for(int k=1;k<curr.size();k++){\n                    if(set.contains(curr.get(k))){\n                        for(int x=1;x<curr.size();x++){\n                            set.add(curr.get(x));\n                        }\n                        curr.clear();\n                        break;\n                    }\n                }\n            }\n            List<String> merged=new ArrayList<>();\n            merged.add(name);\n            for(String s:set){\n                merged.add(s);\n            }\n            ans.add(merged);\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Min Coin - GFG/README.md",
    "content": "# Min Coin\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a list of coins of distinct denominations and total amount of money. Find&nbsp;the minimum number of coins required to make up that amount. Output<strong> -1</strong> if that money cannot be made up using given coins.<br>\nYou may assume that there are infinite numbers of coins of each type.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>arr = [1, 2, 5], amount = 11\n<strong>Output: </strong>3\n<strong>Explanation: </strong>2*5 + 1 = 11. So taking 2 \ndenominations of 5 and 1 denomination of  \n1, </span><span style=\"font-size:18px\">one can make 11.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><strong><span style=\"font-size:18px\">Input: </span></strong><span style=\"font-size:18px\">arr = [2, 6], amount = 7\n<strong>Output: </strong>-1\n<strong>Explanation: </strong>Not possible to make 7 using \ndenominations 2 and 6.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>MinCoin()</strong>&nbsp;which takes list of denominations and amount as input parameter and returns miimum number of coins to make up amount. If not possible returns -1.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(n*amount)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(amount)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Contstraints:</strong><br>\n1 &lt;= number of distinct denominations&nbsp;&lt;= 100</span><br>\n<span style=\"font-size:18px\">1 &lt;= amount &lt;= 10<sup>4</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Min Coin - GFG/min-coin.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String S = br.readLine().trim();\n            String[] S1 = S.split(\" \");\n            int n = Integer.parseInt(S1[0]);\n            int amount  = Integer.parseInt(S1[1]);\n            String s = br.readLine().trim();\n            String[] s1 = s.split(\" \");\n            int[] nums = new int[n];\n            for(int i = 0; i < s1.length; i++)\n                nums[i] = Integer.parseInt(s1[i]);\n            Solution ob = new Solution();\n            int ans = ob.MinCoin(nums, amount);\n            System.out.println(ans);           \n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    public int MinCoin(int[] nums, int amount){\n        \n        int n = nums.length;\n        \n        int dp[] = new int[amount+1];\n        \n        for(int i=1; i<=amount; i++){\n            dp[i] = 100000;\n            for(int j=0; j<n; j++){\n                if(i>=nums[j] && dp[i-nums[j]]!=-1){\n                    dp[i] = Math.min(dp[i],  dp[i-nums[j]] + 1);\n                }\n            }\n            if(dp[i]>=100000)dp[i]=-1;\n        }\n        return dp[amount];\n    }\n}"
  },
  {
    "path": "Min Depth of Binary Tree.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    public int minDepth(TreeNode A) {\n        if(A==null)return Integer.MAX_VALUE;\n        int x=Math.min(minDepth(A.left),minDepth(A.right));\n        if(x==Integer.MAX_VALUE)return 1;\n        return 1+x;\n    }\n}\n"
  },
  {
    "path": "Min Jumps Array.java",
    "content": "public class Solution {\n    public int jump(int[] a) {\n        if(a.length<=1) return 0;\n        int farthest=0,current=0,jumps=0;\n        for(int i=0;i<a.length;i++)\n        {\n            farthest=Math.max(farthest,i+a[i]);\n            if(i==current)\n            {\n                current=farthest;\n                if(i!=a.length-1)\n                    jumps++;\n            }\n            if(i>current) return -1;\n        }\n        return jumps;\n    }\n}\n"
  },
  {
    "path": "Min Stack.java",
    "content": "class Solution {\n    Stack<Integer> st=new Stack<Integer>();\n    Stack<Integer> mst=new Stack<Integer>();\n    public void push(int x) {\n        if (st.empty() && mst.empty()){\n            st.push(x);\n            mst.push(x);\n        }else{\n            st.push(x);\n            if(x<mst.peek()){\n                mst.push(x);\n            }else{\n                mst.push(mst.peek());\n            }\n        }\n    }\n    public void pop() {\n        if(!st.empty()){\n            st.pop();\n            mst.pop();\n        }\n    }\n    public int top() {\n        int k=-1;\n        if(!st.empty()){\n            k=st.peek();\n        }\n        return k;\n    }\n    public int getMin() {\n        int k=-1;\n        if(!mst.empty()){\n            k=(mst.peek());\n        }\n        return k;\n    }\n}\n"
  },
  {
    "path": "Min Steps in Infinite Grid.java",
    "content": "public class Solution {\n    public int coverPoints(int[] A, int[] B) {\n        int x=A[0];\n        int y=B[0];\n        int count=0;\n        for(int i=1;i<A.length;i++){\n            if(x!=A[i] || y!=B[i]){\n                count+=getDistance(x,y,A[i],B[i]);\n                x=A[i];\n                y=B[i];\n            }\n        }\n        return count;\n    }\n    int getDistance(int x1, int y1, int x2, int y2) {\n        return Math.max(Math.abs(x1-x2),Math.abs(y1-y2));\n    }\n}\n"
  },
  {
    "path": "Min Sum Path in Matrix.java",
    "content": "public class Solution {\n    int[][]dp;\n    public int minPathSum(int[][] A) {\n        int n=A.length;\n        int m=A[0].length;\n        dp=new int[n][m];\n        return dfs(A,0,0);\n    }\n    public int dfs(int[][]A,int i,int j){\n        if(dp[i][j]!=0)return dp[i][j];\n        int ans=A[i][j];\n        if(!valid(A,i+1,j) && valid(A,i,j+1)){\n            ans+=dfs(A,i,j+1);\n        }else if(valid(A,i+1,j) && !valid(A,i,j+1)){\n            ans+=dfs(A,i+1,j);\n        }else if(valid(A,i+1,j) && valid(A,i,j+1)){\n            ans+=Math.min(dfs(A,i+1,j),dfs(A,i,j+1));\n        }\n        dp[i][j]=ans;\n        return ans;\n    }\n    public boolean valid(int[][]A,int i,int j){\n        int n=A.length;\n        int m=A[0].length;\n        if(i<0 || j<0 || i==n || j==m)return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "Min Sum Path in Triangle.java",
    "content": "public class Solution {\n\tpublic int minimumTotal(ArrayList<ArrayList<Integer>> list) {\n        int sz=list.size();\n        if(sz==1)\n            return list.get(0).get(0);\n        int dp[]=new int[sz+1];\n        for(int row=sz-1;row>=0;row--){\n            int len=list.get(row).size();\n            for(int col=0;col<len;col++){\n                dp[col]=Math.min(dp[col],dp[col+1])+list.get(row).get(col);\n            }\n        }\n        return dp[0];\n\t}\n}\n"
  },
  {
    "path": "Min sum formed by digits - GFG/README.md",
    "content": "# Min sum formed by digits\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\"><span style=\"font-family:arial,helvetica,sans-serif\">Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of given array must be used to form the two numbers.</span></span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><span style=\"font-family:arial,helvetica,sans-serif\"><strong>Example 1:</strong></span></span></p>\n\n<pre><span style=\"font-size:18px\"><span style=\"font-family:arial,helvetica,sans-serif\"><strong>Input:</strong></span>\n<span style=\"font-family:arial,helvetica,sans-serif\">N = 6</span>\n<span style=\"font-family:arial,helvetica,sans-serif\">arr[] = {6, 8, 4, 5, 2, 3}\n</span><strong><span style=\"font-family:arial,helvetica,sans-serif\">Output:</span></strong>\n<span style=\"font-family:arial,helvetica,sans-serif\">604\n</span><strong><span style=\"font-family:arial,helvetica,sans-serif\">Explanation:</span></strong>\n<span style=\"font-family:arial,helvetica,sans-serif\">The minimum sum is formed by numbers </span>\n<span style=\"font-family:arial,helvetica,sans-serif\">358 and 246</span></span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><span style=\"font-family:arial,helvetica,sans-serif\"><strong>Example 2:</strong></span></span></p>\n\n<pre><span style=\"font-size:18px\"><span style=\"font-family:arial,helvetica,sans-serif\"><strong>Input:</strong></span>\n<span style=\"font-family:arial,helvetica,sans-serif\">N = 5</span>\n<span style=\"font-family:arial,helvetica,sans-serif\">arr[] = {5, 3, 0, 7, 4}</span>\n<strong><span style=\"font-family:arial,helvetica,sans-serif\">Output:</span></strong>\n<span style=\"font-family:arial,helvetica,sans-serif\">82</span>\n<strong><span style=\"font-family:arial,helvetica,sans-serif\">Explanation:</span></strong>\n<span style=\"font-family:arial,helvetica,sans-serif\">The minimum sum is formed by numbers </span>\n<span style=\"font-family:arial,helvetica,sans-serif\">35 and 047</span></span>\n</pre>\n\n<p><br>\n<br>\n<span style=\"font-size:18px\"><span style=\"font-family:arial,helvetica,sans-serif\"><strong>Your Task:</strong><br>\nYou <strong>don't</strong> have to print anything, printing is done by the driver code itself. Your task is to complete the function&nbsp;<strong>minSum()</strong>&nbsp;which takes the array <strong>A[]</strong> and its size <strong>N</strong><strong> </strong>as inputs and returns the required sum.</span></span><br>\n&nbsp;</p>\n\n<p><br>\n<span style=\"font-size:18px\"><span style=\"font-family:arial,helvetica,sans-serif\"><strong>Expected Time Complexity: </strong>O(N. log(N))<br>\n<strong>Expected Auxiliary Space: </strong>O(1)</span></span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><span style=\"font-family:arial,helvetica,sans-serif\"><strong>Constraints:</strong></span><br>\n<span style=\"font-family:arial,helvetica,sans-serif\">1 ≤ N ≤ 35<br>\n0 ≤ A[] ≤ 9</span></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Min sum formed by digits - GFG/min-sum-formed-by-digits.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG {\n\tpublic static void main(String[] args) throws IOException\n\t{\n\t        BufferedReader br =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t =\n            Integer.parseInt(br.readLine().trim()); // Inputting the testcases\n        while(t-->0)\n        {\n            int n = Integer.parseInt(br.readLine().trim());\n            int a[] = new int[(int)(n)];\n            String inputLine[] = br.readLine().trim().split(\" \");\n            for (int i = 0; i < n; i++) {\n                a[i] = Integer.parseInt(inputLine[i]);\n            }\n            \n            Solution obj = new Solution();\n            System.out.println(obj.minSum(a, n));\n            \n        }\n\t}\n}\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n\n//2 3 4 5 6 \n//246\n//35\n\nclass Solution {\n    \n    public static long minSum(int arr[], int n)\n    {\n        // Your code goes here\n        Arrays.sort(arr);\n        long a=0;\n        long b=0;\n        int i=0;\n        while(i<n){\n            a= a*10 + arr[i];\n            i++;\n            if(i<n)b=b*10 +arr[i];\n            i++;\n        }\n        return a+b;\n    }\n}"
  },
  {
    "path": "Minimize Deviation in Array.java",
    "content": "class Solution {\n    public int minimumDeviation(int[] nums) {\n        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1,o2)->o2-o1);\n        int min = Integer.MAX_VALUE;\n        int diff=min;\n        for(int i=0;i<nums.length;i++) {\n            if(nums[i]%2==1) {\n                nums[i]*=2;\n            }\n            maxHeap.add(nums[i]);\n            min=Math.min(min,nums[i]);\n        }\n        \n        while(!maxHeap.isEmpty()) {\n            int max = maxHeap.poll();\n            diff=Math.min(diff,max-min);\n            if(max%2==1) {\n                break;\n            }\n            maxHeap.add(max/2);\n            min=Math.min(min,max/2);\n        }\n        return diff;\n    }\n}\n"
  },
  {
    "path": "Minimum Add to Make Parentheses Valid/Minimum-Add-to-Make-Parentheses-Valid.cpp",
    "content": "class Solution {\npublic:\n    int minAddToMakeValid(string s) {        \n        int n = s.size();\n        int a=0, b=0;\n        for(int i=0;i<n;i++){\n            if(s[i] == '(') a++;\n            else{\n                if(a==0) b++; // if close bracket comes before open like ))(()) or (())((\n                else a--; // if valid parenthesis is found till that index like (())/*till here a=0 and b=0*/(( and here b=2 and a=0\n            }\n        }\n        return a + b;\n    }\n};\n"
  },
  {
    "path": "Minimum Cost to Set Cooking Time.java",
    "content": "class Solution {\n    public int minCostSetTime(int startAt, int moveCost, int pushCost, int tar) {\n     \n        int min=tar/60, sec=tar%60, minCost=moveCost*4+pushCost*4;\n        if(min>99)\n        {\n            min--;\n            sec+=60;\n        }\n        while(min>=0&&sec<=99)\n        {\n            tar=min*100+sec;\n            char arr[]=(\"\"+tar).toCharArray();\n            int mul=0;\n            for(int i=0;i<arr.length-1;i++)\n                if(arr[i]==arr[i+1])\n                    mul++;\n            if(startAt==arr[0]-'0')\n                minCost=Math.min(minCost,pushCost*arr.length+moveCost*(arr.length-1-mul));\n            else\n                minCost=Math.min(minCost,pushCost*arr.length+moveCost*(arr.length-mul));\n            min--;\n            sec+=60;\n        }\n        return minCost;\n    }\n}\n"
  },
  {
    "path": "Minimum Cost to cut a board into squares.cpp",
    "content": "class Solution {\npublic:\n    int minimumCostOfBreaking(vector<int> X, vector<int> Y, int M, int N){\n        //Write your code here\n    \n        int ans = 0;\n        \n        sort(X.begin(), X.end(), greater<int>());\n        sort(Y.begin(), Y.end(), greater<int>());\n        \n        int i=0, j=0;\n        \n        while(i<M-1 and j<N-1)\n        {\n            if(X[i] >= Y[j])\n            ans += (j+1)*X[i++];\n            else\n            ans += (i+1)*Y[j++];\n        }\n        \n        while(i<M-1)\n        ans += (j+1)*X[i++];\n        \n        while(j<N-1)\n        ans += (i+1)*Y[j++];\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "Minimum Cost to cut a board into squares.java",
    "content": "class Solution {\n    public static int minimumCostOfBreaking(int[] X, int[] Y,int M,int N) {\n        // code here\n        Arrays.sort(X);\n        Arrays.sort(Y);\n        int i=X.length-1;\n        int j=Y.length-1;\n        int row=1;\n        int col=1;\n        int ans=0;\n        while(i>=0 || j>=0){\n            int a=i>=0?X[i]:-1;\n            int b=j>=0?Y[j]:-1;\n            if(a>=b){\n                ans+=(a*row);\n                col++;\n                i--;\n            }else{\n                ans+=(b*col);\n                row++;\n                j--;\n            }\n        }\n        return ans;\n    }\n}\n        \n"
  },
  {
    "path": "Minimum Cost to cut a board into squares.py",
    "content": "from typing import List\nclass Solution:\n    def minimumCostOfBreaking(self, X, Y, M, N):\n        X.sort()\n        Y.sort()\n        xCut = 1\n        yCut = 1\n        currPrice = 0\n        i = len(X)-1\n        j = len(Y)-1\n        while i>=0 and j>=0:\n            if X[i] > Y[j]:\n                currPrice += X[i]*xCut\n                yCut +=1\n                i-=1\n            elif X[i] < Y[j]:\n                currPrice += Y[j]*yCut\n                xCut +=1\n                j -= 1\n            elif X[i] == Y[j]:\n                if xCut > yCut:\n                    currPrice += X[i]*xCut\n                    yCut +=1\n                    i-=1\n                else:\n                    currPrice += Y[j]*yCut\n                    xCut +=1\n                    j-=1\n                    \n        while i>=0:\n            currPrice += X[i]*xCut\n            yCut +=1\n            i-=1\n        while j>=0:\n            currPrice += Y[j]*yCut\n            xCut +=1\n            j-=1\n            \n        return currPrice\n"
  },
  {
    "path": "Minimum Exchange GFG/MinimumExchange.cpp",
    "content": "class Solution {\npublic:\nint MinimumExchange(vector<vector<char>>matrix){\n    // Code here\n    int ans1=0;\n    int ans2=0;\n    for(int i=0;i<matrix.size();i++){\n        for(int j=0;j<matrix[0].size();j++){\n            \n             if((i+j)%2==1 && matrix[i][j]=='A'){\n                ans1++;\n            }\n            if((i+j)%2==0 && matrix[i][j]=='B'){\n                ans1++;\n            }\n           \n        }\n    }\n    \n      for(int i=0;i<matrix.size();i++){\n        for(int j=0;j<matrix[0].size();j++){\n            if((i+j)%2==0 && matrix[i][j]=='A'){\n                ans2++;\n            }\n            if((i+j)%2==1 && matrix[i][j]=='B'){\n                ans2++;\n            }\n        }\n    }\n    return min(ans1,ans2);\n}\n\n};\n\n//  More concise code\n \n//  int MinimumExchange(vector<vector<char>>matrix){\n//     // Code here\n//     int m = matrix.size(), n = matrix[0].size();\n//     int cnt = 0;\n    \n//     for(int i=0; i<m; i++)\n//     {\n//         for(int j=0; j<n; j++)\n//         {\n//             if((i+j)%2 == 0 and matrix[i][j] == 'B')\n//             cnt++;\n            \n//             if((i+j)%2 and matrix[i][j] == 'A')\n//             cnt++;\n//         }\n//     }\n    \n//     return min(cnt, m*n - cnt);\n// }\n"
  },
  {
    "path": "Minimum Exchange gfg easy sep12.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\nint MinimumExchange(vector<vector<char>>matrix){\n    // Code here\n    int m = matrix.size(), n = matrix[0].size();\n    int case1=0, case2 = 0;\n    for(int i =0; i<m; i++){\n        for(int j =0; j<n; j++){\n            if(i%2==0 && j%2==0){\n                if(matrix[i][j] != 'A') case1++;\n                else case2++;\n            }\n            if(i%2==0 && j%2==1){\n                if(matrix[i][j]!= 'B')case1++;\n                else case2++;\n            }\n            if(i%2==1 && j%2==0){\n                if(matrix[i][j]!= 'B') case1++;\n                else case2++;\n            }\n            if(i%2==1 && j%2==1){\n                if(matrix[i][j]!= 'A') case1++;\n                else case2++;\n            }\n        }\n    }\n    return min(case1, case2);\n    /*TC : O(m*n)\n\nSC : O(1)\n*/\n}\n\n};\nint main(){\n\tint tc;\n\tcin >> tc;\n\twhile(tc--){\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tvector<vector<char>>matrix(n, vector<char>(m,'x'));\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tfor(int j = 0; j < m; j++)\n\t\t\t\tcin >> matrix[i][j];\n\t\t}\n\t\tSolution obj;\n\t\tint ans = obj.MinimumExchange(matrix);\n\t\tcout << ans <<\"\\n\";\n\t}\n\treturn 0;\n}"
  },
  {
    "path": "Minimum Exchange.java",
    "content": "class Solution\n{\n    public int MinimumExchange(char[][] matrix) {\n        int a = 0, b = 0;\n        int m = matrix.length, n = matrix[0].length;\n        for(int i = 0; i < m; ++i){\n            for(int j = 0; j < n; ++j){\n                if(matrix[i][j] == 'A'){\n                    a++;\n                } else {\n                    b++;\n                }\n            }\n        }\n        if(a > b){\n            return Count('A', 'B', matrix);\n        } else if(a < b){\n            return Count('B', 'A', matrix) ;\n        } else {\n            return Math.min(Count('A', 'B', matrix), Count('B', 'A', matrix));\n        }\n    }\n\n    private int Count(char x, char y, char[][] matrix) {\n        int m = matrix.length, n = matrix[0].length;\n        int cnt = 0;\n        for(int i = 0; i < m; ++i){\n            char ch = x;\n            if(i % 2 == 1){\n                ch = y;\n            }\n            for(int j = 0; j < n; ++j){\n                if(matrix[i][j] != ch){\n                    cnt++;\n                }\n                if(ch == x){\n                    ch = y;\n                } else {\n                    ch = x;\n                }\n            }\n        }\n        return cnt / 2;\n    }\n}\n"
  },
  {
    "path": "Minimum Lights to Activate.java",
    "content": "public class Solution {\n    public int solve(int[] a, int b) {\n        int n=a.length;\n        int i=0,curr=-1;\n        int cnt=0;\n        while(i<n){\n            curr=-1;\n            for(int j=Math.max(0,i-b+1);j<Math.min(n,i+b);j++){\n                if(a[j]==1)\n                    curr=j;\n            }\n            if(curr==-1){\n                return -1;\n            }\n            cnt++;\n            i=curr+b;\n        }\n        return cnt;\n    }\n}\n"
  },
  {
    "path": "Minimum Number in a sorted rotated array - GFG/README.md",
    "content": "# Minimum Number in a sorted rotated array\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array of distinct elements which was initially sorted.&nbsp;This array&nbsp;is rotated at some unknown point. The task is to find the minimum element in the given sorted and rotated array.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 10\narr[] = {2,3,4,5,6,7,8,9,10,1}\n<strong>Output: </strong>1<strong>\nExplanation: </strong>The array is rotated \nonce anti-clockwise. So minium \nelement is at last index (n-1) \nwhich is 1.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 5\narr[] = {3,4,5,1,2}\n<strong>Output: </strong>1<strong>\nExplanation: </strong>The array is rotated \nand the minimum element present is\nat index (n-2) which is 1.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThe task is to complete the function <strong>minNumber</strong>() which takes the array arr[] and its starting and ending indices (low and high) as inputs and returns the minimum element in the given sorted and rotated array.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(LogN).<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(LogN).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N &lt;= 10<sup>7</sup><br>\n1 &lt;= arr[i] &lt;= 10<sup>7</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Minimum Number in a sorted rotated array - GFG/minimum-number-in-a-sorted-rotated-array.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass Array\n{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        \n        while(t-- > 0)\n        {\n            int n = Integer.parseInt(read.readLine());\n            String st[] = read.readLine().trim().split(\"\\\\s+\");\n            \n            int arr[] = new int[n];\n            \n            for(int i = 0; i < n; i++)\n              arr[i] = Integer.parseInt(st[i]);\n              \n            System.out.println(new Solution().minNumber(arr,0,n-1));\n        }\n    }\n    \n}// } Driver Code Ends\n\n\n\n\nclass Solution\n{\n    //Function to find the minimum element in sorted and rotated array.\n    static int minNumber(int arr[], int l, int h){\n        while(l<=h){\n            int m=(l+h)/2;\n            if(m==0 || arr[m-1]>arr[m])\n                return arr[m];\n            if(arr[m]<arr[h])\n                h=m-1;\n            else if(arr[m]>arr[h])\n                l=m+1;\n        }\n        return -1;\n    }\n}"
  },
  {
    "path": "Minimum Number in a sorted rotated array - GFG/minimum-number-in-a-sorted-rotated-array.py",
    "content": "#User function Template for python3\n\n\nclass Solution:\n    \n    #Function to find the minimum element in sorted and rotated array.\n    def minNumber(self, arr,low,high):\n        return min(arr)\n\n#{ \n#  Driver Code Starts\n#Initial Template for Python 3\n\nimport math\n\n\ndef main():\n        T=int(input())\n        while(T>0):\n            \n            N=int(input())\n\n            A=[int(x) for x in input().strip().split()]\n            obj = Solution()\n            print(obj.minNumber(A,0,N-1))\n            \n            T-=1\n\n\nif __name__ == \"__main__\":\n    main()\n# } Driver Code Ends"
  },
  {
    "path": "Minimum Number of Arrows to Burst Balloons(Non Overlapping intervals)",
    "content": "class Solution {\n    public int findMinArrowShots(int[][] points) {\n        \n        // This Problem is similar to Non Overlapping Interval Problem of Greedy Approach\n        // Link for detiled discussion : http://www.leetcode-solution.com/2019/06/01/0452-minimum-number-of-arrows-to-burst-balloons.html\n        \n        // Base case\n        if(points.length == 0)\n            return 0;\n        \n        // Sort the point accroding to their end points i.e., a[1] - b[1]\n        Arrays.sort(points, (a,b) -> a[1] - b[1]);\n        \n        // Position arrow at end (Extreme Right) as it has maximum chance of hittng there\n        int arrPos = points[0][1];\n        int count = 1; // Minimun 1 arrow is required to shoot any points\n        \n        for(int i = 1; i < points.length; i++ ) // start with 1 as 0th index end will be check for start of 1st \n        {\n            int left  = points[i][0];\n            int right = points[i][1];\n            \n            \n            //check whether the arrowFired can burst other balloons.\n            //if not fire arrow at the next point end value\n            if (!(arrPos >= left && arrPos <= right)) \n            {\n                \n                count++; // increase the arrowsFired by 1.\n                arrPos = points[i][1];  // next point end value.\n                \n            }\n          /*  if(arrPos >= points[i][0]) // Since Current arrow position than start pos of array that means we can \n            {                          // continue, but as soon as it not true we break as our current arrow pos\n                continue;              // cant handle beyond that point . so update its pos and count++\n            }\n            count++ ;                 // As we are done with current pos \n            arrPos = points[i][1];    // Update as we already exhausted our option with previous position\n        */\n        \n        }\n        \n        return count;\n    }\n}\n"
  },
  {
    "path": "Minimum Number of Vertices to Reach All Nodes.java",
    "content": "class Solution {\n    public List<Integer> findSmallestSetOfVertices(int n, List<List<Integer>> edges) {\n        List<List<Integer>> adj=new ArrayList<>();\n        List<Integer> ansList=new ArrayList<>();\n        \n        for(int i=0;i<n;i++){\n            List<Integer> l=new ArrayList<>();\n            adj.add(l);\n        }\n        \n        for(int i=0;i<edges.size();i++){\n            adj.get(edges.get(i).get(1)).add(edges.get(i).get(0));\n        }\n        \n        \n        for(int i=0;i<n;i++){\n            if(adj.get(i).size()==0){\n                ansList.add(i);\n            }\n        }\n        \n        return ansList;\n    }\n\n}\n"
  },
  {
    "path": "Minimum Operations to Make the Array Alternating.java",
    "content": "class Solution {\n    public int minimumOperations(int[] nums) {\n        Map<Integer, Integer> oddMap = new HashMap<>();\n        Map<Integer, Integer> evenMap = new HashMap<>();\n        for(int i=0; i<nums.length; i++){\n            if(i % 2 != 0){\n                oddMap.put(nums[i], oddMap.getOrDefault(nums[i], 0) + 1);\n            }else{\n                evenMap.put(nums[i], evenMap.getOrDefault(nums[i], 0) + 1);\n            }\n        }\n        \n        Queue<Node> odd = new PriorityQueue<>((a, b) -> b.freq - a.freq);\n        Queue<Node> even = new PriorityQueue<>((a, b) -> b.freq - a.freq);\n        for(Map.Entry<Integer, Integer> entry : oddMap.entrySet()){\n            odd.offer(new Node(entry.getKey(), entry.getValue()));\n        }\n        for(Map.Entry<Integer, Integer> entry : evenMap.entrySet()){\n            even.offer(new Node(entry.getKey(), entry.getValue()));\n        }\n        \n        while(!odd.isEmpty() && !even.isEmpty() && odd.peek().val == even.peek().val){\n            if(odd.peek().freq < even.peek().freq){\n                odd.poll();\n            }else{\n                even.poll();\n            }\n        }\n        \n        int n = nums.length;\n        if(n % 2 == 0){\n            return (odd.isEmpty() ? n / 2 : n / 2 - odd.poll().freq) + (even.isEmpty() ? n / 2 : n / 2 - even.poll().freq);\n        }else{\n            return (odd.isEmpty() ? n / 2 + 1 : n / 2 + 1 - odd.poll().freq) + (even.isEmpty() ? n / 2 : n / 2 - even.poll().freq);\n        }\n    }\n    \n    class Node {\n        int freq;\n        int val;\n        public Node(int val, int freq){\n            this.freq = freq;\n            this.val = val;\n        }\n        public String toString(){\n            return val + \": \" + freq;\n        }\n    }\n}\n"
  },
  {
    "path": "Minimum Parantheses!.java",
    "content": "public class Solution {\n    public int solve(String A) {\n        int ans=0;\n        Deque<Character> st=new ArrayDeque<>();\n        for(int i=0;i<A.length();i++){\n            char ch=A.charAt(i);\n            if(ch=='('){\n                st.push(ch);\n            }else{\n                if(st.size()>0){\n                    st.pop();\n                }else{\n                    ans++;\n                }\n            }\n        }\n        ans+=st.size();\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Minimum Platforms.java",
    "content": "class Solution\n{\n    //Function to find the minimum number of platforms required at the\n    //railway station such that no train waits.\n    static int findPlatform(int arr[], int dep[], int n)\n    {\n        // add your code here\n        Arrays.sort(arr);\n        Arrays.sort(dep);\n        int plat=1;\n        int max=1;\n        int i=1;\n        int j=0;\n        while(i<n && j<n){\n            if(arr[i]<=dep[j]){\n                i++;\n                plat++;\n                max=Math.max(max,plat);\n            }else{\n                j++;\n                plat--;\n            }\n        }\n        return max;\n    }\n}\n"
  },
  {
    "path": "Minimum Remove to Make Valid Parentheses/Minimum-Remove-to-Make-Valid-Parentheses.cpp",
    "content": "class Solution {\npublic:\n    string minRemoveToMakeValid(string s) {\n        string ans = \"\";\n        int n = s.size();\n        stack<int> st;\n        int i = 0;\n        // we are removing open bracket if extra and marking them with # and finally not including the character # in the ans string\n        while(i < n){\n            if(s[i] == '(') st.push(i);\n            else if(s[i] == ')'){\n                if(st.empty()){\n                    s[i] = '#';\n                }else{\n                    st.pop(); // removing the relavent open bracket for closing bracket and finally we will be left with extra open brackets and we will mark them as #\n                }\n            }\n            i++;\n        }\n        // here we are marking extra open brackets as #\n        while(!st.empty()){\n            s[st.top()] = '#';\n            st.pop();\n        }\n        i = 0;\n        while(i<n){\n            if(s[i] != '#') ans += s[i];\n            i++;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Minimum Remove to Make Valid Parentheses.java",
    "content": "class Solution {\n    public String minRemoveToMakeValid(String s) {\n        Deque<Integer> stack=new ArrayDeque<>();\n        int[]dp=new int[s.length()];\n        for(int i=0;i<s.length();i++){\n            char c=s.charAt(i);\n            if(c=='('){\n                stack.push(i);\n            }else if(c==')'){\n                if(stack.isEmpty()){\n                    dp[i]=1;\n                }else{\n                    stack.pop();\n                }\n            }\n        }\n        \n        while(!stack.isEmpty()){\n            dp[stack.pop()]=1;  \n        }\n        \n        StringBuilder sb=new StringBuilder();\n        for(int i=0;i<s.length();i++){\n            if(dp[i]==0){\n                sb.append(s.charAt(i));\n            }\n        }\n        return sb.toString();\n        \n    }\n}\n"
  },
  {
    "path": "Minimum Sum of Absolute Differences of Pairs gfg easy.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nclass Solution{\npublic:\n    long long findMinSum(vector<int> &A,vector<int> &B,int N){\n        long long res =0;\n        sort(A.begin(), A.end());\n        sort(B.begin(), B.end());\n        for(int i =0; i<N; i++)\n        res+=abs(A[i]-B[i]);\n        return res;\n    }\n    // TC: O(N)\n};"
  },
  {
    "path": "Minimum Sum of Absolute Differences of Pairs.java",
    "content": "class Solution { \n    long findMinSum(int[] A,int[] B,int N) { \n        Arrays.sort(A);\n        Arrays.sort(B);\n        long s=0;\n        for(int i=0;i<N;i++){\n            s=s+Math.abs(A[i]-B[i]);\n        }\n        return s;\n    }\n}\n"
  },
  {
    "path": "Minimum Sum of Absolute Differences of Pairs.py",
    "content": "class Solution:\n    def findMinSum(self, A,B,N):\n        s = zip(sorted(A), sorted(B))\n        ans = 0\n        for i, j in s: ans += abs(i - j)\n        return ans\n"
  },
  {
    "path": "Minimum Sum of Four Digit Number After Splitting Digits.java",
    "content": "class Solution {\n    public int minimumSum(int num) {\n        int list[]=new int[4];\n        list[0]=num%10;\n        num/=10;\n        list[1]=num%10;\n        num/=10;\n        list[2]=num%10;\n        num/=10;\n        list[3]=num%10;\n        Arrays.sort(list);\n        return list[0]*10+list[2]+list[1]*10+list[3];\n    }\n}\n"
  },
  {
    "path": "Minimum Swaps GFG (easy solution with comments).cpp",
    "content": "//{ Driver Code Starts\n//Initial Template for C++\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// } Driver Code Ends\n//User function Template for C++\n\nclass Solution {\npublic:\n    int minimumSwaps(int c[],int v[],int n,int k,int b,int T)\n    {\n            // code here\n            int good_sheep = 0;         //to count how many sheeps can reach target\n            int bad_sheep = 0;          //to count how many sheeps can NOT reach target\n            int swap = 0;               //no. of sweeps\n            \n            for(int i=n-1;i>=0;i--){\n                //check if it is able to reach destination\n                \n                if(v[i]*T + c[i] >= b){\n                    \n                    good_sheep++;\n                    \n                    //now check no of bad sheep infront of it and swap it with that\n                    swap+=bad_sheep;\n                }\n                else{\n                    bad_sheep++;\n                }\n                \n                //check whether atleast k sheep reach the barn\n                //if YES then break\n                \n                if(good_sheep>=k)   break;\n            }\n            if(good_sheep>=k)\n                return swap;\n                \n            return -1;\n    }\n};\n\n//{ Driver Code Starts.\nint main(){\n    int t=1,testcases=1;\n    cin>>t;\n    while(t>=testcases)\n    {\n        int n,k,b,T;\n        cin>>n>>k>>b>>T;\n        int c[n];\n        int v[n];\n        for(auto &j:c)\n            cin>>j;\n        for(auto &j:v)\n            cin>>j;\n        Solution s;\n        int ans=s.minimumSwaps(c,v,n,k,b,T);\n        cout<<ans<<endl;\n        testcases++;\n    }\n    // TIME;\n    return 0;\n}\n// } Driver Code Ends\n"
  },
  {
    "path": "Minimum Swaps to Group All 1's Together II.cpp",
    "content": "class Solution {\npublic:\n    int minSwaps(vector<int>& nums) \n    {\n        int n = nums.size();\n        int k = 0 , ans = n;\n        for(int i = 0;i<n;i++)\n        {\n            if(nums[i] == 1) k+=1;\n        }\n        \n        int i = 0 , j = 0 , cnt0 = 0;\n        for(j = 0;j<k;j++)\n        {\n            if(nums[j] == 0) cnt0 += 1;\n        }\n        j-=1;\n        \n        while(i < n)\n        {\n            ans = min(ans , cnt0);\n            j = (j+1)%n;\n            if(nums[j] == 0) cnt0 += 1;\n            if(nums[i] == 0) cnt0 -= 1;\n            i+=1;\n        }\n        ans = min(ans , cnt0);\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Minimum Swaps to Sort.java",
    "content": "class Solution\n{\n    //Function to find the minimum number of swaps required to sort the array.\n    public int minSwaps(int nums[]){\n        Map<Integer,Integer> map=new HashMap<>();\n        for(int i=0;i<nums.length;i++){\n            map.put(nums[i],i);\n        }\n        int ans=0;\n        int temp[]=new int[nums.length];\n        temp=nums.clone();\n        Arrays.sort(temp);\n        for(int i=0;i<nums.length;i++){\n            if(nums[i]==temp[i]){\n                continue;\n            }else{\n                ans++;\n                int tep=nums[i];\n                nums[i]=nums[map.get(temp[i])];\n                nums[map.get(temp[i])]=tep;\n                map.put(tep,map.get(temp[i]));\n                map.put(temp[i],i);\n            }\n            \n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Minimum Swaps.java",
    "content": "class Solution {\n    public static int minimumSwaps(int[] c, int[] v,int n,int k,int b,int t) {\n        // code here\n        int slow=0;\n        int totalSwaps=0;\n        for(int i=n-1;i>=0;i--){\n            int pos=c[i]+(v[i]*t);\n            if(pos>=b){\n                k--;\n                totalSwaps+=slow;\n                if(k==0)return totalSwaps;\n            }else{\n                slow++;\n            }\n        }\n        \n        return -1;\n    }\n}\n"
  },
  {
    "path": "Minimum Time To Fulfill All Orders Using BinarySearch And ApSeries Formula.java",
    "content": "class Solution {\n    public static int findMinTime(int n, int l, int[] arr) {\n        int start=1;\n        int end=Integer.MAX_VALUE;\n        int ans=0;\n        while(start<=end) {\n            int mid=start +(end-start)/2;\n            if(isAnswer(arr, mid, n)) {\n                ans=mid;\n                end=mid-1;\n            }\n            else {\n                start=mid+1;\n            }\n        }\n        return ans;\n    }\n    \n    public static boolean isAnswer(int arr[], int mid, int n) {\n        int curAns=0;\n        for(int i=0;i<arr.length;i++) {\n            curAns+=getNumber(arr[i], mid);  //used Binary search using formula of Ap series of sum Sn=n(2*a+(n-1)d)/2, from formula we know a->arr[i], Sn->mid found n using binary search\n            if(curAns>=n) return true;\n        }\n        // System.out.println(curAns+\" \"+n+\" \"+mid);\n        return curAns>=n;\n    }\n    \n    public static int getNumber(int a, int sum) {\n        int start=1;\n        int end=sum;\n        int n=0;\n        if(sum<a) return 0;\n        while(start<=end) {\n            long mid=start +(end-start)/2; // taken mid as long beacause (mid)*(2*a+(mid-1)*a)/2 might exceed int range\n            if((mid)*(2*a+(mid-1)*a)/2>=sum) {\n                n=(int)mid;\n                end=(int)mid-1;\n            }\n            else {\n                start=(int)mid+1;\n            }\n        }\n        if(n*(2*a+(n-1)*a)/2==sum) \n            return n;\n        else \n            return n-1>=0?n-1:0;\n           \n    }\n}\n"
  },
  {
    "path": "Minimum Time to Remove All Cars Containing Illegal Goods.java",
    "content": "class Solution {\n    public int minimumTime(String s) {\n        int n = s.length();\n        int min = s.length();\n        int[] nums = new int[n];\n        for (int i = 0; i < n; i++)\n            nums[i] = s.charAt(i) - '0';\n\n\t\t// step1\n        int[] leftOptimized = new int[n + 2];\n        for (int i = 1; i <= n; i++) {\n            leftOptimized[i] = Math.min(i, leftOptimized[i - 1] + (nums[i - 1] == 1? 2: 0));\n        }\n\n\t\t// step2\n        int[] rightOptimized = new int[n + 2];\n        for (int i = n; i > 0; i--) {\n            rightOptimized[i] = Math.min(n - i + 1, rightOptimized[i + 1] + (nums[i - 1] == 1? 2: 0));\n        }\n\n\t\t// step3\n        for (int p = 0; p <= n; p++) {\n            min = Math.min(min, leftOptimized[p] + rightOptimized[p + 1]);\n        }\n\n        return min;\n    }\n}\n"
  },
  {
    "path": "Minimum X (xor) A - GFG/README.md",
    "content": "# Minimum X (xor) A\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two integers&nbsp;<strong>A</strong>&nbsp;and&nbsp;<strong>B</strong>, the task is to find an integer&nbsp;<strong>X</strong>&nbsp;such that&nbsp;<strong>(X XOR A)</strong>&nbsp;is minimum possible and the count of set bit in&nbsp;<strong>X</strong>&nbsp;is equal to the count of set bits in&nbsp;<strong>B</strong>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> \nA = 3, B = 5\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\nBinary(A) = Binary(3) = 011\nBinary(B) = Binary(5) = 101\nThe XOR will be minimum when x = 3\ni.e. (3 XOR 3) = 0 and the number\nof set bits in 3 is equal\nto the number of set bits in 5.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> \nA = 7, B = 12\n<strong>Output:</strong> 6\n<strong>Explanation:</strong>\n(7)<sub>2</sub>= 111\n(12)<sub>2</sub>= 1100\nThe XOR will be minimum when x = 6 \ni.e. (6 XOR 7) = 1 and the number \nof set bits in 6 is equal to the \nnumber of set bits in 12.</span></pre>\n\n<div><strong><span style=\"font-size:18px\">Your task :</span></strong></div>\n\n<div><span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function <strong>minVal()</strong> that takes integer A and B as input and returns the value of X according to the question.</span></div>\n\n<div>&nbsp;</div>\n\n<div><strong><span style=\"font-size:18px\">Expected Time Complexity : </span></strong><span style=\"font-size:18px\">O(log N)</span></div>\n\n<div><strong><span style=\"font-size:18px\">Expected Auxiliary Space : </span></strong><span style=\"font-size:18px\">O(1)</span></div>\n\n<div>&nbsp;</div>\n\n<div><strong><span style=\"font-size:18px\">Constraints :</span></strong></div>\n\n<div><span style=\"font-size:18px\">1 &lt;= A, B &lt;= 10<sup>9</sup></span></div>\n\n<div>&nbsp;</div>\n <p></p>\n            </div>"
  },
  {
    "path": "Minimum X (xor) A - GFG/minimum-x-xor-a.java",
    "content": "// { Driver Code Starts\n// Initial Template for Java\n\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass GFG {\n    public static void main(String[] args) throws IOException {\n        BufferedReader br =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t =\n            Integer.parseInt(br.readLine().trim()); // Inputting the testcases\n        while (t-- > 0) {\n\n            int a = Integer.parseInt(br.readLine().trim());\n            int b = Integer.parseInt(br.readLine().trim());\n\n            Solution ob = new Solution();\n            System.out.println(ob.minVal(a, b));\n        }\n    }\n}// } Driver Code Ends\n\n\n// User function Template for Java\n//1001\n//1011\n//bitsA=2\n//bitsB=3\n\n//1101\n//1001\n//0100\n\n\n\nclass Solution {\n    public static int minVal(int a, int b) {\n        int bitsA=Integer.bitCount(a);\n        int bitsB=Integer.bitCount(b);\n        int diff=Math.abs(bitsA-bitsB);\n        \n        if(diff==0)return a;\n        else if(bitsA>bitsB){\n            while(diff>0){\n                a = a&(a-1);\n                diff--;\n            }\n        }else{\n            while(diff>0){\n                a = a|(a+1);\n                diff--;\n            }\n        }\n        return a;\n    }\n}"
  },
  {
    "path": "Minimum increment/decrement to make array non-Increasing - GFG/README.md",
    "content": "# Minimum increment/decrement to make array non-Increasing\n##  Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\"><strong>Note: This&nbsp;<a href=\"http://practice.geeksforgeeks.org/problem-of-the-day\" target=\"_blank\">POTD</a>&nbsp;is a part of&nbsp;<a href=\"https://practice.geeksforgeeks.org/summer-carnival-2022?utm_source=potd&amp;utm_medium=problempage&amp;utm_campaign=gsc22\" target=\"_blank\">Geek Summer Carnival</a>. Solve all POTD consecutively from 5th to 10th April and get a chance to win exclusive discount vouchers on our GfG courses.</strong></span></p>\n\n<hr>\n<p><span style=\"font-size:18px\">Given an array <strong>a</strong> of length <strong>n</strong>, find the <strong>minimum</strong> number of operations required to make it <strong>non-increasing</strong>.&nbsp;You can select any one of the following operations and preform it any number of times on an array element.</span></p>\n\n<ul>\n\t<li><span style=\"font-size:18px\">increment the array element by 1.</span></li>\n\t<li><span style=\"font-size:18px\">decrement the array element by 1.&nbsp;</span></li>\n</ul>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:</span></strong>\n<span style=\"font-size:18px\">N = 4 \narray = {3, 1, 2, 1}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong> 1</span>\n<span style=\"font-size:18px\"><strong>Explanation: </strong>\nDecrement array[2] by 1. \nNew array becomes {3,1,1,1} which is non-increasing. \nTherefore, only 1 step is required. </span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:</span></strong>\n<span style=\"font-size:18px\">N = 4 \narray = {3, 1, 5, 1}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong> 4</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Complete the function <strong>minOperations()</strong> that takes <strong>n</strong>&nbsp;and array <strong>a</strong> as input parameters and returns the <strong>minimum </strong>number of operations required.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected time complexity:</strong> O(nlogn)<br>\n<strong>Expected space complexity:</strong> O(n)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n&nbsp;&lt;= 10^4<br>\n1 &lt;= a[i] &lt;= 10^4</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Minimum increment/decrement to make array non-Increasing - GFG/minimum-incrementdecrement-to-make-array-non-increasing.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.util.PriorityQueue; \n\n // } Driver Code Ends\n//User function Template for Java\n\nclass Solution \n{ \n\tpublic static int minOperations(int a[], int n){ \n\t    int ans=0;\n\t    PriorityQueue<Integer> pq = new PriorityQueue<>();\n\t    for(int i=0;i<n;i++){\n\t        if(!pq.isEmpty() && pq.peek()<a[i]){\n\t            ans+=a[i]-pq.remove();\n\t            pq.add(a[i]);\n\t        }\n\t        pq.add(a[i]);\n\t    }\n\t    return ans;\n\t} \n} \n\n\n// { Driver Code Starts.\nclass GFG \n{ \n\t\n\tpublic static void main(String args[]) throws IOException { \n\t\tScanner sc = new Scanner(System.in);\t\n\t    int t = sc.nextInt();\n\t    while (t > 0) {\n\t        int n;\n\t        n = sc.nextInt();\n\t        int[] a = new int[n];\n\t        for (int i = 0; i < n; i++) \n\t        \ta[i] = sc.nextInt();\n\t        Solution ob = new Solution();\n\t        System.out.println(ob.minOperations(a,n));\n\t        t--;\n\t    }\n\t}\n}\n\n  // } Driver Code Ends"
  },
  {
    "path": "Minimum sum of absolute difference of pairs.cpp",
    "content": "\n#include <bits/stdc++.h>\nusing namespace std;\n\n\n// } Driver Code Ends\n//User function Template for C++\n\nclass Solution{\npublic:\n    long long findMinSum(vector<int> &A,vector<int> &B,int N){\n        \n        \n       \n        sort(A.begin(),A.end());\n        sort(B.begin(),B.end());\n        \n        long long res = 0;\n        \n        for(int i=0;i<N;i++){\n            res += abs(A[i]-B[i]);\n        }\n        \n        return res;\n    }\n};\n\n//{ Driver Code Starts.\n\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int N;\n        cin>>N;\n        vector<int> A(N),B(N);\n        for(int i=0;i<N;i++){\n            cin>>A[i];\n        }\n        for(int i=0;i<N;i++){\n            cin>>B[i];\n        }\n        Solution ob;\n        cout<<ob.findMinSum(A,B,N)<<endl;\n    }\n}\n"
  },
  {
    "path": "Minimum time to fulfil all orders",
    "content": "class Solution {\n    public static int findMinTime(int n, int l, int[] arr) {\n        int low = 1;\n        int high = 10000000;\n        int ans = Integer.MAX_VALUE;\n        while(low <= high){\n            int mid = (low + high) / 2;\n            if(canMake(arr , n , mid)){\n                high = mid - 1;\n                ans = Math.min(mid , ans);\n            }else{\n                low = mid + 1;\n            }\n        }\n        return ans;\n    }\n    private static boolean canMake(int[] arr , int time , int mid){\n        int can = 0;\n        for(int i = 0 ; i < arr.length ; i++){\n            int sum = 0;\n            for(int j = arr[i] ; j + sum <= mid ; j += arr[i]){\n                sum += j;\n                can++;\n            }\n        }\n        if(can >= time) return true;\n        return false;\n    }\n}\n"
  },
  {
    "path": "Minimum time to fulfil all orders gfg hard.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nclass Solution{\n    public:\n    int getDonuts(int rank, int time){\n        int i =1, currSum =1, numDonuts =0;\n        while((rank*currSum) <= time){\n            numDonuts++; i++;\n            currSum+=i;\n        }\n        return numDonuts;\n    }\n    bool isPossible(vector<int>&A, int time, int donuts){\n        int currSum =0;\n        for(int i=0;i<A.size(); i++)\n        currSum+=getDonuts(A[i], time);\n        return currSum >=donuts;\n    }\n    int findMinTime(int N, vector<int>&A, int L){\n        //write your code here\n        int start =0, maxi =0;\n        for(int i =0; i<L; i++)\n        maxi = max(maxi, A[i]);\n        int end  = maxi*((1LL*N*(N+1))/2);\n        // getting mid element binary search\n        while(start <=end){\n            int mid = (start+end)/2;\n            if(isPossible(A,mid,N))\n            end = mid-1;\n            else start = mid+1;\n        }\n        return start;\n    }\n    // TC:O(n*Log(n)) SC:O(1)\n};"
  },
  {
    "path": "Minimum time to fulfil all orders.java",
    "content": "class Solution {\n    public static int findMinTime(int n, int x, int[] arr) {\n        // code here\n        Arrays.sort(arr);\n        int l=arr[0];\n        int h=arr[x-1]*n*(n+1)/2;\n        int time=0;\n        while(l<=h){\n            int mid=(l+h)/2;\n            if(isPossible(mid,n,arr)){\n                time=mid;\n                h=mid-1;\n            }else{\n                l=mid+1;\n            }\n        }\n        return time;\n    }\n    static boolean isPossible(int mid,int n,int[]arr){\n        int donots=0;\n        for(int t:arr){\n            int timeTaken=0;\n            int timeWillTake=t;\n            while(timeTaken+timeWillTake<=mid){\n                donots++;\n                timeTaken+=timeWillTake;\n                timeWillTake+=t;\n            }\n        }\n        return donots>=n;\n    }\n}\n        \n"
  },
  {
    "path": "Minimum time to fulfill  all orders.java",
    "content": "class Solution {\n    public static int donutCount(int min,int rank[])\n    {\n        int dCount = 0;\n        for(int i = 0;i < rank.length;i++)\n        {\n            int chefRank = rank[i];\n            if(chefRank > min) continue;\n            int curDount = 1;\n            int curTime = chefRank;\n            \n            while(curTime <= min)\n            {\n                dCount++;\n                curDount++;\n                curTime += curDount*chefRank;\n            }\n        }\n        return dCount;\n    }\n    public static int findMinTime(int n, int arrLength, int[] arr) {\n        int l = 1, h = 10000000;\n        while(l <= h)\n        {\n            int mid = (l+h)/2;\n            int midRes = donutCount(mid,arr);\n            if(n <= midRes) h = mid-1;\n            else l = mid+1;\n        }\n        return l;\n    }\n}\n"
  },
  {
    "path": "Minimum times A has to be repeated such that B is a substring of it - GFG/README.md",
    "content": "# Minimum times A has to be repeated such that B is a substring of it\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two strings <strong>A </strong>and<strong> B. </strong>Find minimum number of times A has to be repeated such that B is a Substring of it. If <strong>B</strong> can never be a substring then return <strong>-1</strong>.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>A = \"abcd\"\nB = \"cdabcdab\"\n<strong>Output:\n</strong>3\n<strong>Explanation:</strong>\n</span><span style=\"font-size:18px\">Repeating A three times (“abcdabcdabcd”),\nB is a substring of it. B is not a substring\nof A when it is repeated less than 3 times.</span>\n</pre>\n\n<div><span style=\"font-size:18px\"><strong>Example 2:</strong></span></div>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>A = \"ab\"\nB = \"cab\"\n<strong>Output :</strong>\n-1</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\nNo matter how many times we repeat A, we can't\nget a string such that B is a substring of it.</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>minRepeats()</strong>&nbsp;which takes 2 strings A, and B respectively and returns the minimum number of times A has to be repeated such that B is a substring of it. Return -1 if it's not possible.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(|A| * |B|)<br>\n<strong>Expected Auxiliary Space:</strong> O(|B|)</span></p>\n\n<div><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ |A|, |B| ≤ 10<sup>3</sup></span></div>\n\n<div><span style=\"font-size:18px\">String A and B consists of lower case alphabets</span></div>\n <p></p>\n            </div>"
  },
  {
    "path": "Minimum times A has to be repeated such that B is a substring of it - GFG/minimum-times-a-has-to-be-repeated-such-that-b-is-a-substring-of-it.py",
    "content": "#User function Template for python3\n\nclass Solution:\n    def minRepeats(self, A, B):\n        parent=str(A)\n        ans=1\n        while(len(parent)<len(B)):\n            parent=parent+str(A)+''\n            ans+=1\n        if (parent.find(B) == -1):\n            parent=parent+str(A)+''\n            ans+=1\n            if (parent.find(B) == -1):\n                return -1\n        return ans\n\n#{ \n#  Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__': \n    t = int (input ())\n    for _ in range (t):\n        A=input()\n        B=input()\n        \n        ob = Solution()\n        print(ob.minRepeats(A,B))\n# } Driver Code Ends"
  },
  {
    "path": "Minimum-Exchange/Solution.java",
    "content": "class Solution\n{\n    public int MinimumExchange(char[][] m)\n    {\n        char ch = 'A';int c1=0;int c2=0;\n      for(int i =0;i<m.length;i++){\n          for(int j=0;j<m[0].length;j++){\n              if(m[i][j]!=ch) c1++;\n              else c2++;\n              if(j==m[0].length-1 && m[0].length%2==0)continue;\n              if(ch=='A')ch='B';\n              else ch='A';\n          } }\n      return Math.min(c1,c2); \n    }\n}"
  },
  {
    "path": "Minimum-Exchange/question.md",
    "content": "### Minimum Exchange\n\n**Easy**Accuracy: **61.11%**Submissions: **18**Points: **2**\n\nGiven a matrix of size n*m. Every cell of matrix contains either 'A' or 'B'. Exchange is defined as swaping the characters between two cells. Your task is to find the minimum number of exchange needed to rearrange the given matrix such that no adjacent cell contains the same characters.\nTwo cells are adjacent if they share one of their common sides (left,right,front or back if exists).\n\n**Example 1:**\n\n```\nInput: matrix = {{A,A,B,A},{B,A,B,A},{B,B,A,B}}\nOutput: 4\nExplanation: Minimum number of students whose \nsets got changed are 4 (indexes: ((0,1),(0,2),\n(0,3),(2,0))). The final alloted sets are:\nA B A B\nB A B A\nA B A B\n```\n\n**Example 2:**\n\n```\nInput: matrix = {{A,B},{B,A}}\nOutput: 0\nExplanation: No two adjacent cell contains same\ncharacter.\n```\n\n**Your Task:**\nYou don' t need to read or print anything. Your task is to complete the function **MinimumExchange() **which takes matrix as input parameter and returns minimum number of  exchange needed.\n\n**Expected Time Complexity: **O(n*m)\n**Expected Space Compelxity: **O(1)\n\n**Constraints:**\n1 <= n, m <= 100\n"
  },
  {
    "path": "Minimum-swaps.cpp",
    "content": "class Solution {\npublic:\n    int minimumSwaps(int c[],int v[],int n,int k,int b,int T)\n    {\n        int g = 0, bad = 0, s = 0;\n        for(int i = n-1; i >= 0; i--){\n            if(v[i]*T+c[i] >= b){   //Distance = speed*time so a sheep can reach to barn if its postion*time+cost is greater than equal to barn position\n                g++;                // If yes then we will not swap that sheep\n                s += bad;           \n            }else\n                bad++;              // If not than that sheep can exploit other sheeps also which have higher\n                                    //cost and are on left side of bad sheep so we increase count of bad sheeps\n            if(g >= k) break;       // number of good sheeps is equal to k we will break and return no. of swap required\n        }\n        if(g >= k) return s;\n        return -1;                  // else return -1;\n    }\n};\n"
  },
  {
    "path": "Minimum_Cost_to_cut_a_board_into_squares_gfg_greedy.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n    int minimumCostOfBreaking(vector<int> X, vector<int> Y, int M, int N){\n        //Write your code here\n        sort(X.begin(), X.end(), greater<int>());\n        sort(Y.begin(), Y.end(), greater<int>());\n        \n        int i =0,j =0, cost =0, hor=1, ver =1;\n        while(i<X.size() || j <Y.size()){\n            if(i<X.size() && j<Y.size()){\n                if(X[i]<=Y[j]){\n                    // cut horixontally\n                    cost+=(Y[j++]*hor); ver++;\n                }else{\n                    cost+=(X[i++]*ver); hor++;\n                }\n            }\n            else if(i<X.size()){\n                cost+=(X[i++]*ver);\n            }else if(j<Y.size()){\n                cost+=(Y[j++]*hor);\n            }\n        }\n        return cost;\n    }\n};"
  },
  {
    "path": "Mirror Reflection.java LeetCode",
    "content": "class Solution {\n    public int mirrorReflection(int p, int q) {\n      \n        while(p%2==0 && q%2==0){\n            p=p/2;\n            q=q/2;\n        }\n       \n        if(p%2==0 && q%2!=0){\n            return 2;\n        }\n        else if(p%2!=0 && q%2==0){\n            return 0;\n        }\n        else{\n            return 1;\n        }\n    }\n}\n\n"
  },
  {
    "path": "Move Last Element to Front of a Linked List - GFG/README.md",
    "content": "# Move Last Element to Front of a Linked List\n## Easy\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">You are given the head of a Linked List. You have to move the last element to the front of the Linked List and return the list.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span><span style=\"font-size:18px\"><strong>\n</strong>N = 5\nList = {2,5,6,2,1}<strong>\nOutput:</strong></span><span style=\"font-size:18px\"><strong>\n</strong>{1,2,5,6,2}<strong>\nExplanation:\n</strong>In the given linked list, the last element is 1,\nafter moving the last element to the front the\nlinked list will be {1,2,5,6,2}.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 1\nList = {2}<strong>\nOutput:\n</strong>{2}<strong>\nExplanation:\n</strong>Here 2 is the only element so, the linked list\nwill remain the same.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong></span></p>\n\n<p><span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function <strong>moveToFront()</strong>&nbsp;which takes the address of the head of the linked list&nbsp;and returns the modified linked list.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N)<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N&nbsp;&lt;= 10<sup>5</sup><br>\n0 &lt;= Elements of List&nbsp;&lt;= 10<sup>9</sup><br>\nSum of N over all test cases doesn't exceeds 10<sup>6</sup></span></p>\n</div>"
  },
  {
    "path": "Move Last Element to Front of a Linked List - GFG/move-last-element-to-front-of-a-linked-list.java",
    "content": "//{ Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\n\nclass Node\n{\n    int data;\n    Node next;\n    \n    Node(int x)\n    {\n        data = x;\n        next = null;\n    }\n    \n    public static Node inputList(BufferedReader br) throws IOException\n    {\n        int n = Integer.parseInt(br.readLine().trim()); // Length of Linked List\n        \n        String[] s = br.readLine().trim().split(\" \");\n        Node head = new Node(Integer.parseInt(s[0])), tail = head;\n        for(int i = 1; i < s.length; i++)\n            tail = tail.next = new Node(Integer.parseInt(s[i]));\n        \n        return head;\n    }\n    \n    public static void printList(Node node)\n    {\n        while (true)\n        { \n    \t\tSystem.out.print(node.data);\n    \t\tnode = node.next; \n    \t\tif(node == null)\n    \t\t    break;\n    \t\tSystem.out.print(\" \");\n    \t}  \n    \tSystem.out.println();\n    }\n}\n\nclass GFG {\n    public static void main(String[] args) throws IOException {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int t;\n        t = Integer.parseInt(br.readLine());\n        while(t-- > 0){\n            \n            Node head = Node.inputList(br);\n            \n            Solution obj = new Solution();\n            Node res = obj.moveToFront(head);\n            \n            Node.printList(res);\n            \n        }\n    }\n}\n\n// } Driver Code Ends\n\n\n/*\n\nDefinition for singly Link List Node\nclass Node\n{\n    int data;\n    Node next;\n    \n    Node(int x){\n        data = x;\n        next = null;\n    }\n}\n\nYou can also use the following for printing the link list.\nNode.printList(Node node);\n*/\n\nclass Solution {\n    public static Node moveToFront(Node head) {\n        // code here\n        if(head.next==null)return head;\n        Node temp=head;\n        while(temp.next.next!=null){\n            temp=temp.next;\n        }\n        Node last=temp.next;\n        temp.next=null;\n        last.next=head;\n        return last;\n    }\n}\n        \n"
  },
  {
    "path": "Move Zeroes.java",
    "content": "public class Solution {\n    public int[] solve(int[] A) {\n        int cnt=0;\n        for(int i:A){\n            if(i==0)cnt++;\n        }\n        int pos=0;\n        int i=0;\n        while(i<A.length){\n            if(A[i]!=0){\n                A[pos]=A[i];\n                pos++;\n            }\n            i++;\n        }\n        i--;\n        while(cnt-->0){\n            A[i--]=0;\n        }\n        return A;\n    }\n}\n"
  },
  {
    "path": "Move all zeroes to end of the array.java",
    "content": "public class Solution {\n    public ArrayList<Integer> solve(ArrayList<Integer> A) {\n        ArrayList<Integer> ans=new ArrayList<>();\n        for(int i:A){\n            if(i!=0){\n                ans.add(i);\n            }\n        }\n        int diff=A.size()-ans.size();\n        while(diff!=0){\n            ans.add(0);\n            diff--;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Move all zeros to the front of the linked list - GFG/README.md",
    "content": "# Move all zeros to the front of the linked list\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a linked list, the task is to move all 0s to the front of the linked list. The order of all another element except 0 should be same after rearrangement. </span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong> 0 -&gt; 4 -&gt; 0 -&gt; 5 -&gt; 0<strong>\nOutput: </strong>0 -&gt; 0 -&gt; 0 -&gt; 4 -&gt; 5\n<strong>Explanation: </strong>After moving all 0s of the given\nlist to the front, the list is:\n0 -&gt; 0 -&gt; 0 -&gt; 4 -&gt; 5</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>0 -&gt; 1 -&gt; 0 -&gt; 1 -&gt; 2<strong>\nOutput: </strong>0 -&gt; 0 -&gt; 1 -&gt; 1 -&gt; 2</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>moveZeroes()&nbsp;</strong>which takes head node of the linked list as input parameter.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N)<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(1)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N&nbsp;&lt;= 50</span><br>\n<br>\n&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Move all zeros to the front of the linked list - GFG/move-all-zeros-to-the-front-of-the-linked-list.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nclass Node{\n    int data;\n    Node next;\n    Node(int d){\n        data=d;\n        next=null;\n    }\n}\nclass Zeroes{\n    public static void main(String[] args){\n        Scanner sc=new Scanner(System.in);\n        int t=sc.nextInt();\n        while(t-->0){\n            int n=sc.nextInt();\n            Node head=null;\n            while(n-->0){\n                int a=sc.nextInt();\n                if(head==null){\n                    head=new Node(a);\n                }\n                else{\n                    Node temp=new Node(a);\n                    temp.next=head;\n                    head=temp;\n                }\n            }\n            GfG g=new GfG();\n            head = g.moveZeroes(head);\n            while(head!=null){\n                System.out.print(head.data+\" \");\n                head=head.next;\n            }\n            System.out.println();\n        }\n    }\n}\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n/*\nclass Node{\n    int data;\n    Node next;\n    Node(int d){\n        data=d;\n        next=null;\n    }\n}\n*/\n\nclass GfG{\n    public Node moveZeroes(Node head){\n        Node temp=head;\n        while(temp.next!=null){\n            if(temp.next.data==0){\n                Node zero=temp.next;\n                temp.next=temp.next.next;\n                zero.next=head;\n                head=zero;\n            }else{\n                temp=temp.next;\n            }\n        }\n        return head;\n    }\n}"
  },
  {
    "path": "Moving on grid - GFG/README.md",
    "content": "# Moving on grid\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a grid with dimensions r&nbsp;x c, the two&nbsp;players (say JON&nbsp;and ARYA&nbsp;) can move the coin over the grid satisfying the following rules:</span></p>\n\n<ul>\n\t<li><span style=\"font-size:18px\">There is a coin on (1,1) cell initially.</span></li>\n\t<li><span style=\"font-size:18px\">JON&nbsp;will move first.</span></li>\n\t<li><span style=\"font-size:18px\">Both will play on alternate moves.</span></li>\n\t<li><span style=\"font-size:18px\">In each move they can place coin on following positions if current position of coin is x,y<br>\n\t(x+1,y), (x+2,y), (x+3,y), (x,y+1), (x,y+2), (x,y+3), (x,y+4), (x,y+5), (x,y+6)</span></li>\n\t<li><span style=\"font-size:18px\">They can't go outside the grid.</span></li>\n\t<li><span style=\"font-size:18px\">Player who cannot make any move will lose this game.</span></li>\n\t<li><span style=\"font-size:18px\">Both play optimally.</span></li>\n</ul>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>: r = 1, c = 2\n<strong>Output:</strong>&nbsp;JON&nbsp;\n<strong>Explanation</strong>: ARYA lost the game because\nhe won't able to move after JON's move.  </span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>r = 2, c = 2\n<strong>Output:&nbsp;</strong>ARYA\n<strong>Explanation</strong>: After first move by JON(1,2 or 2,1)\nand second move by ARYA(2,2) JON won't able to\nmove so ARYA wins.   </span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou dont need to read input or print anything. Complete the function <strong>movOnGrid()&nbsp;</strong>which takes r&nbsp;and c&nbsp;as input parameter and returns the name of the winner ( either JON&nbsp;or ARYA)</span><span style=\"font-size:18px\">.<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(1)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)<br>\n<br>\n<strong>Constraints:</strong><br>\n1 &lt;= r, c&nbsp;&lt;=10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Moving on grid - GFG/moving-on-grid.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String[] input = new String[2]; \n            input = br.readLine().split(\" \"); \n            int r = Integer.parseInt(input[0]); \n            int c = Integer.parseInt(input[1]); \n            Solution ob = new Solution();\n            System.out.println(ob.movOnGrid(r,c));\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\nclass Solution\n{\n    public String movOnGrid(int r, int c){\n        r=(r-1)%7;\n        c=(c-1)%4;\n        return(r==c?\"ARYA\":\"JON\");\n   }\n}"
  },
  {
    "path": "Multiple left rotations of the array.java",
    "content": "public class Solution {\n    Map<Integer,int[]> map=new HashMap<>();\n    public int[][] solve(int[] A, int[] B) {\n        int[][]ans=new int[B.length][A.length];\n        for(int i=0;i<B.length;i++){\n            if(!map.containsKey(B[i])){\n                int[]copy=A.clone();\n                int[]rotated=rotate(copy,B[i]);\n                ans[i]=rotated;\n                map.put(B[i],rotated);\n            }else{\n                ans[i]=map.get(B[i]);\n            }\n        }\n        return ans;\n    }\n\n    int[] rotate(int[]arr,int n){\n        for(int i = 0; i < n; i++){  \n            int j, first;\n            first = arr[0];  \n            for(j = 0; j < arr.length-1; j++){\n                arr[j] = arr[j+1];  \n            }\n            arr[j] = first;  \n        }  \n        return arr;\n    }\n}\n"
  },
  {
    "path": "N Digit numbers with digits in increasing order",
    "content": "class Solution{\n    static ArrayList<Integer> increasingNumbers(int n){\n        // code here\n        ArrayList<Integer> list=new ArrayList<Integer>();\n        if(n==1){\n            for(int i=0;i<10;i++){\n                list.add(i);       \n            }\n            \n            return list;\n        }else if(n==9){\n            list.add(123456789);\n            return list;\n        }else if(n==8){\n            list.add(12345678);\n            list.add(12345679);\n            list.add(12345689);\n            list.add(12345789);\n            list.add(12346789);\n            list.add(12356789);\n            list.add(12456789);\n            list.add(13456789);\n            list.add(23456789);\n            return list;\n        }else{\n            int start=(int)Math.pow(10,n-1);\n            int end=(int)Math.pow(10,n);\n            while(start<end){\n                if(isValid(start)){\n                    list.add(start);\n                }\n                start++;\n            }\n            return list;\n        }\n    }\n    static boolean isValid(int num){\n        while(num!=0){\n            if((num%10)<=(num/10)%10){\n                return false;    \n            }\n            num/=10;\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "N by 3 Repeating Number",
    "content": "public class Solution {\n    // DO NOT MODIFY THE LIST\n    public int repeatedNumber(final List<Integer> a) {\n        int n = a.size();\n        HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();\n        for(int i = 0; i < n; i++){\n            int x = a.get(i), times = 0;\n            if(h.containsKey(x)){\n                times = h.get(x);\n                h.put(x, times + 1);\n                times++;\n                \n            }else{\n                h.put(x, 1);\n                times = 1;\n            }\n            if(times > n / 3){\n                return x;\n            }\n        }\n        return -1;\n    }\n}\n\n"
  },
  {
    "path": "N-th_Tribonacci_Number_leetcode1137.cpp",
    "content": "class Solution {\npublic:\n    int tribonacci(int n) {\n        if (n < 2) return n;\n        int a = 0, b = 1, c = 1, d = a + b + c;\n        while (n-- > 2) {\n            d = a + b + c, a = b, b = c, c = d;\n        }\n        return c;\n    }\n};\n"
  },
  {
    "path": "Nearest Smaller Element.java",
    "content": "public class Solution {\n    public int[] prevSmaller(int[] A) {\n        int n=A.length;\n        int[]ans=new int[n];\n        for(int i=0;i<n;i++){\n            ans[i]=findMin(A,i);\n        }\n        return ans;\n    }\n    public int findMin(int[]a,int index){\n        int i=index;\n        while(i>=0){\n            if(a[i]<a[index]){\n                return a[i];\n            }\n            i--;\n        }\n        return -1;\n    }\n}\n\n//======================================\npublic class Solution {\n    public ArrayList<Integer> prevSmaller(ArrayList<Integer> A) {\n    ArrayList<Integer> result=new ArrayList<>();\n    result.add(-1);\n    Stack<Integer> stack=new Stack<>();\n    stack.push(A.get(0));\n    for(int i=1;i<A.size();i++){\n        while(!stack.isEmpty() && stack.peek()>=A.get(i))\n            stack.pop();\n        result.add(stack.isEmpty()?-1:stack.peek());\n        stack.add(A.get(i));\n    }\n    return result;\n}\n}\n"
  },
  {
    "path": "Nearly sorted - GFG/README.md",
    "content": "# Nearly sorted\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array of <strong>n</strong> elements, where each element is at most <strong>k</strong> away from its target position, you need to sort the array optimally.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>n = 7, k = 3\narr[] = {6,5,3,2,8,10,9}\n<strong>Output: </strong>2 3 5 6 8 9 10<strong>\nExplanation: </strong>The sorted array will be\n2 3 5 6 8 9 10</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>n = 5, k = 2\narr[] = {3,1,4,2,5}\n<strong>Output: </strong>1 2 3 4 5 </span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Note: DO NOT</strong> use STL sort() function for this question.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou are required to complete the&nbsp;method&nbsp;<strong>nearlySorted()</strong> which takes 3&nbsp;arguments and returns the sorted array.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity</strong> : O(nlogk)<br>\n<strong>Expected Auxilliary Space</strong> : O(n)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤&nbsp;n ≤&nbsp;10<sup>6</sup><br>\n1 ≤&nbsp;k &lt;&nbsp;n<br>\n1 ≤&nbsp;arr<sub>i </sub>≤&nbsp;10<sup>7</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Nearly sorted - GFG/nearly-sorted.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass gfg\n{\n    public static void main(String args[])\n    {\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n        \n        while(t-- > 0)\n        {\n            int num = sc.nextInt();\n            int k = sc.nextInt();\n            \n            int arr[] = new int[num];\n            for(int i = 0; i < num; i++)\n                arr[i] = sc.nextInt();\n            \n            ArrayList <Integer> res = new Solution().nearlySorted(arr, num, k);\n            for (int i = 0; i < res.size (); i++)\n                System.out.print (res.get (i) + \" \");\n            System.out.println();\n        }\n    }\n}\n\n// } Driver Code Ends\n\n\nclass Solution\n{\n    //Function to return the sorted array.\n    ArrayList <Integer> nearlySorted(int arr[], int num, int k)\n    {\n        ArrayList<Integer> ans=new ArrayList<>();\n        PriorityQueue<Integer> pq=new PriorityQueue<>();\n        int i=0;\n        while(i<=k){\n            pq.add(arr[i]);\n            i++;\n        }\n        while(!pq.isEmpty()){\n            int ele=pq.remove();\n            ans.add(ele);\n            if(i<num){\n                pq.add(arr[i]);\n                i++;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Negative weight cycle - GFG/README.md",
    "content": "# Negative weight cycle\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a weighted directed graph with n nodes and m edges. Nodes are labeled from 0 to n-1, the task is to check if it contains a negative weight cycle or not.<br>\n<strong>Note:&nbsp;</strong>edges[i] is&nbsp;defined as u, v and weight.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>n = 3, edges = {{0,1,-1},{1,2,-2},\n{2,0,-3}}\n<strong>Output: </strong>1\n<strong>Explanation: </strong>The graph contains negative weight\ncycle as 0-&gt;1-&gt;2-&gt;0 with weight -1,-2,-3.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>n = 3, edges = {{0,1,-1},{1,2,-2},\n{2,0,3}}\n<strong>Output: </strong>0\n<strong>Explanation: </strong>The graph does not contain any\nnegative weight cycle.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anyhting. Your task is to complete the function&nbsp;<strong>isNegativeWeightCycle()&nbsp;</strong>which takes n and edges as input paramater and returns 1 if graph contains negative weight cycle otherwise returns 0.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(n*m)<br>\n<strong>Expected Space Compelxity:&nbsp;</strong>O(n)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n &lt;= 100<br>\n1 &lt;= m &lt;= n*(n-1)</span><span style=\"font-size:18px\">, where m is the total number of Edges in the directed graph.</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Negative weight cycle - GFG/negative-weight-cycle.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String[] S1 = br.readLine().trim().split(\" \");\n            int n = Integer.parseInt(S1[0]);\n            int m = Integer.parseInt(S1[1]);\n            int[][] edges = new int[m][3];\n            for(int i = 0; i < m; i++){\n                String S2[] = br.readLine().trim().split(\" \");\n                for(int j = 0; j < 3; j++)\n                    edges[i][j] = Integer.parseInt(S2[j]);\n            }\n            Solution obj = new Solution();\n            int ans = obj.isNegativeWeightCycle(n, edges);\n            System.out.println(ans);\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    public int isNegativeWeightCycle(int n, int[][] edges){\n        if (edges == null || n == 0) {\n            return 0;\n        }\n        int [] distance = new int [n];\n        Arrays.fill(distance, Integer.MAX_VALUE);\n        distance[0] = 0;\n        // n - 1 number of relaxation steps\n        for (int i = 1; i <= n - 1; i++) {\n            for (int [] edge : edges) {\n                int source = edge[0];\n                int destination = edge[1];\n                int weight = edge[2];\n                // condition\n                if (distance[source] != Integer.MAX_VALUE) {\n                    distance[destination] =Math.min(distance[destination], distance[source] + weight);\n                }\n            }\n        }\n        // relaxation step once more to make sure about the negative cycle\n        for (int [] edge : edges) {\n            int source = edge[0];\n            int destination = edge[1];\n            int weight = edge[2];\n            if (distance[source] != Integer.MAX_VALUE && distance[source] + \n            weight < distance[destination]) {\n                // there is a negative cycle as distance will get updated\n                return 1;\n            }\n        }\n        return 0;\n    }\n}"
  },
  {
    "path": "Next Permutation",
    "content": "class Solution{\n    static List<Integer> nextPermutation(int N, int a[]){\n        // code here\n        int k=-1;\n        for(int i=0;i<N-1;i++){\n            if(a[i]<a[i+1]){\n                k=i;\n            }\n        }\n        if(k==-1){\n            List<Integer> list=new ArrayList<>();\n            for(int i=N-1;i>=0;i--){\n                list.add(a[i]);\n            }\n            return list;\n        }\n        int l=k+1;\n        for(int i=k+1;i<N;i++){\n            if(a[i]>a[k]){\n                l=i;\n            }\n        }\n        int temp=a[k];\n        a[k]=a[l];\n        a[l]=temp;\n        List<Integer> list=new ArrayList<>();\n        for(int i=0;i<=k;i++){\n            list.add(a[i]);\n        }\n        for(int i=N-1;i>k;i--){\n            list.add(a[i]);\n        }\n        return list;\n        \n    }\n}\n\n//=============================================================\npublic class Solution {\n    public ArrayList<Integer> nextPermutation(ArrayList<Integer> a) {\n        // code here\n        int k=-1;\n        int N=a.size();\n        for(int i=0;i<N-1;i++){\n            if(a.get(i)<a.get(i+1)){\n                k=i;\n            }\n        }\n        if(k==-1){\n            ArrayList<Integer> list=new ArrayList<>();\n            for(int i=N-1;i>=0;i--){\n                list.add(a.get(i));\n            }\n            return list;\n        }\n        \n        int l=k+1;\n        \n        for(int i=k+1;i<N;i++){\n            if(a.get(i)>a.get(k)){\n                l=i;\n            }\n        }\n        \n        int temp=a.get(k);\n        a.set(k,a.get(l));\n        a.set(l,temp);\n        ArrayList<Integer> list=new ArrayList<>();\n        for(int i=0;i<=k;i++){\n            list.add(a.get(i));\n        }\n        for(int i=N-1;i>k;i--){\n            list.add(a.get(i));\n        }\n        return list;\n    }\n}\n"
  },
  {
    "path": "Next Pointer Binary Tree.java",
    "content": "public class Solution {\n    public void connect(TreeLinkNode root) {\n        TreeLinkNode prev=null;\n        Queue<TreeLinkNode> q=new LinkedList<>();\n        q.add(root);\n        while(q.size()>0){\n            int sz=q.size();\n            prev=null;\n            for(int i=0;i<sz;i++){\n                TreeLinkNode cur=q.remove();\n                if(prev==null){\n                    prev=cur;\n                }else{\n                    prev.next=cur;\n                    prev=prev.next;\n                }\n                if(cur.left!=null)q.add(cur.left);\n                if(cur.right!=null)q.add(cur.right);\n            }\n            prev.next=null;\n        }\n    }\n}\n"
  },
  {
    "path": "Next Right Node.cpp",
    "content": "class Solution\n{\npublic:\n    Node *nextRight(Node *root, int key)\n    {\n        //code here\n        if(key == root->data) return new Node(-1);\n        queue<Node*> q;\n        q.push(root);\n        while(!q.empty()){\n            int n = q.size();\n            vector<Node*> v;\n            for(int i=0;i<n;i++){\n                Node* node = q.front();\n                if(node->left) q.push(node->left);\n                if(node->right) q.push(node->right);\n                v.push_back(node);\n                q.pop();\n            }\n            for(int i=0;i<v.size()-1;i++){\n                if(v[i]->data == key) return v[i+1];\n            }\n            if(v[v.size()-1]->data == key) return new Node(-1);\n        }\n        return new Node(-1);\n    }\n};\n\n// Another approach\n\n// class Solution\n// {\n// public:\n//     Node *nextRight(Node *root, int key)\n//     {\n//         //code here\n//         queue<Node*> Q;\n//         Q.push(root);\n        \n//         while(!Q.empty())\n//         {\n//             int sz = Q.size();\n            \n//             while(sz--)\n//             {\n//                 Node* cur = Q.front();\n//                 Q.pop();\n                \n//                 if(cur->data == key)\n//                 {\n//                     if(sz == 0)\n//                     return new Node(-1);\n//                     else\n//                     return Q.front();\n//                 }\n                \n//                 if(cur->left)\n//                 Q.push(cur->left);\n                \n//                 if(cur->right)\n//                 Q.push(cur->right);\n//             }\n//         }\n        \n//         return new Node(-1);\n//     }\n// };\n"
  },
  {
    "path": "Next Right Node.java",
    "content": "class Solution{\n\tNode nextRight(Node root, int key)\n    {\n\t\t//Write your code here\n\t\tQueue<Node> q=new LinkedList<>();\n\t\tq.add(root);\n\t\tboolean found=false;\n\t\twhile(q.size()>0){\n\t\t    int sz=q.size();\n\t\t    //level\n\t\t    while(sz-->0){\n\t\t        Node node=q.remove();\n\t\t        if(found)return node;\n\t\t        if(node.data==key)found=true;\n\t\t        if(node.left!=null)q.add(node.left);\n\t\t        if(node.right!=null)q.add(node.right);\n\t\t    }\n\t\t    if(found)return new Node(-1);\n\t\t}\n\t\treturn null;\n    }\n}\n\n"
  },
  {
    "path": "Next element with greater frequency - GFG/README.md",
    "content": "# Next element with greater frequency\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array&nbsp;<strong>arr[ ]</strong>&nbsp;of&nbsp;<strong>n</strong>&nbsp;integers, for every element, find the closest element on it's right that has a greater frequency than its own frequency.</span></p>\n\n<blockquote>\n<p><span style=\"font-size:18px\">Frequency is the number of times the&nbsp;element appears in the array.</span></p>\n</blockquote>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nn = 6\narr[] = {2 1 1 3 2 1}<strong>\nOutput:</strong>\n1 -1 -1 2 1 -1 \n<strong>Explanation:\n</strong>1 appears 3 times.\n2 appears 2 times.\n3 appears 1 time. \n\nFor arr[0] ie, 2\narr[1] ie 1 is the closest element on its \nright which has greater frequency than the \nfrequency of 2. For the arr[1] and arr[2] no element \non the right has greater frequency than 1, \nso -1 will be printed. and so on. </span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>n = 10\narr[] = {5 1 2 3 2 5 5 4 5 2}\n<strong>Output:</strong>\n-1 2 5 2 5 -1 -1 5 -1 -1</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your task:</strong><br>\nYour task is to complete the function&nbsp;<strong>print_next_greater_freq() </strong>which take two parameters <strong>arr</strong> and <strong>n</strong>.This function returns&nbsp;answer(as a list of integers)&nbsp;as explained above.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected time complexity:</strong> O(n)<br>\n<strong>Expected space complexity: </strong>O(n)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n &lt;= 10<sup>4</sup><br>\n1 &lt;= arr[i] &lt;=&nbsp;10<sup>4</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Next element with greater frequency - GFG/next-element-with-greater-frequency.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\nimport java.io.*;\n\nclass GFG\n{\n    public static void main (String[] args)\n    {\n        Scanner sc = new Scanner(System.in);\n        // int arr[] = new int[10000];\n        \n        int t = sc.nextInt();\n        \n        while(t-->0)\n        {\n            int n = sc.nextInt();\n            int arr[]=new int[n];\n            for(int i=0; i<n; i++)\n            {\n                arr[i] = sc.nextInt();\n            }\n            \n            solver x = new solver();\n            int res[]=x.print_next_greater_freq(arr,n);\n            StringBuffer sb=new StringBuffer(\"\");\n            for(int i : res){\n                sb.append(i+\" \");\n            }\n            System.out.println(sb);\n        }\n    }\n}\n// } Driver Code Ends\n\n\nclass solver\n{\n    static int[] print_next_greater_freq(int arr[], int n)\n    {\n        int[]freq=new int[10001];\n        for(int i:arr){\n            freq[i]++;\n        }\n        int ans[]=new int[n];\n        ans[n-1]=-1;\n        for(int i=0;i<n-1;i++){\n            boolean got=false;\n            for(int j=i+1;j<n;j++){\n                if(freq[arr[j]]>freq[arr[i]]){\n                    ans[i]=arr[j];\n                    got=true;\n                    break;\n                }\n            }\n            if(!got){\n                ans[i]=-1;\n            }\n        }\n        return ans;\n    }\n}\n\n"
  },
  {
    "path": "Noble Integer.java",
    "content": "public class Solution {\n    public int solve(ArrayList<Integer> A) {\n        Collections.sort(A);\n        for(int i=1;i<A.size();i++){\n            if(A.get(i)!=A.get(i-1)){\n                if(A.get(i-1)==A.size()-i)\n                    return 1;\n            }\n        }\n        if(A.get(A.size()-1)==0)return 1;\n        return -1;\n    }\n}\n"
  },
  {
    "path": "Node with highest edge score.cpp",
    "content": "class Solution {\npublic:\n    int edgeScore(vector<int>& e) {\n        int n = e.size();\n        vector<long long > v(n);\n        for(int i =0;i<n;i++){\n            v[e[i]]+=i;\n        }\n        long long sum = INT_MIN;\n        int index=-1;\n        for(int i =0;i<v.size();i++){\n            if(v[i]>sum){\n                 sum = v[i];\n                index = i;\n            }\n        }\n        return index;\n    }\n};\n"
  },
  {
    "path": "Nodes at even distance - GFG/README.md",
    "content": "# Nodes at even distance\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a connected acyclic graph with n&nbsp;nodes and n-1 edges, count the pair&nbsp;of nodes that are at even distance(number of edges) from each other.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nn = 3\ngraph = {{}, {2}, {1, 3}, {2}}\n<strong>Output:</strong> 1\n<strong>Explaination:</strong> Here there are three pairs {1,2},{1,3}\nand {2,3} and only {1,3} has even distance between them.\n</span><span style=\"font-size:18px\">i.e</span> <span style=\"font-size:18px\">          1\n             /\n            2\n           /\n          3</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nn = 5\ngraph = {{}, {2,4}, {1,3}, {2}, {1,5}, {4}}\n<strong>Output:</strong> 4\n<strong>Explaination:</strong> There are four pairs {1,3},{1,5},{2,4}\nand {3,5} which has even distance.</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>countOfNodes()</strong>&nbsp;which takes the array <strong>graph[]</strong>&nbsp;(given as <a href=\"https://en.wikipedia.org/wiki/Adjacency_list#:~:text=In%20graph%20theory%20and%20computer,particular%20vertex%20in%20the%20graph.\" target=\"_blank\">Adjacency list</a>)&nbsp;</span><span style=\"font-size:18px\">and its size <strong>n&nbsp;</strong>as input parameters&nbsp;and returns the count&nbsp;of&nbsp;pair of nodes that are at even distance from each other</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(V+E)<br>\n<strong>Expected Auxiliary Space:</strong> O(V)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ n&nbsp;≤ 10<sup>4</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Nodes at even distance - GFG/nodes-at-even-distance.java",
    "content": "// { Driver Code Starts\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\n\nclass GFG{\n\tpublic static void main(String [] args) throws IOException{\n\t\tScanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n        while(t-- > 0)\n        {\n            int n = sc.nextInt();\n            ArrayList<ArrayList<Integer>> graph = new ArrayList<>();\n\n            for(int i = 0; i <= n; i++) {\n            \tgraph.add(new ArrayList<>());\n            }\n            \n            int temp = n;\n            while(temp-- > 1){\n                int u = sc.nextInt();\n                int v = sc.nextInt();\n                graph.get(u).add(v);\n                graph.get(v).add(u);\n            }\n            Solution ob = new Solution();\n            System.out.println(ob.countOfNodes(graph, n));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n   int countOfNodes(ArrayList<ArrayList<Integer>> graph, int n) \n   {\n       // Write your code here\n       Integer[] arr=new Integer[n+1];\n       dfs(1,graph,arr,0);\n       int ev=0,od=0;\n       for(Integer i:arr)\n       {\n           if(i!=null)\n           if(i%2==0)\n           ev++;\n           else\n           od++;\n       }\n       return ev*(ev-1)/2+od*(od-1)/2;\n   }\n   static void dfs(int src,ArrayList<ArrayList<Integer>> adj,Integer[] arr,int di)\n   {\n       arr[src]=di;\n       for(int i:adj.get(src))\n       if(arr[i]==null)\n       dfs(i,adj,arr,di+1);\n   }\n}\n\n"
  },
  {
    "path": "Nth item through sum - GFG/README.md",
    "content": "# Nth item through sum\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two sorted arrays <strong>A</strong> and <strong>B</strong> of length <strong>L1</strong>&nbsp;and <strong>L2</strong>, we can get a set of sums(add one element from the first and one from second). Find the <strong>N</strong>th element in the set considered in sorted order.<br>\n<strong>Note:&nbsp;</strong>Set of sums should have unique elements.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> L1 = 2, L2 = 2\nA = {1, 2}\nB = {3, 4}\nN = 3\n<strong>Output:</strong> 6\n<strong>Explaination:</strong> The set of sums are in \nthe order 4, 5, 6.</span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> L1 = 5, L2 = 4\nA = {1, 3, 4, 8, 10}\nB = {20, 22, 30, 40}\nN = 4\n<strong>Output:</strong> 25\n<strong>Explaination:</strong> The numbers before it \nare 21, 23 and 24.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>nthItem() </strong>which takes L1, L2, A, B, and the value N as input parameters and returns the Nth value of the set. If N is greater than the size of the set then it returns <strong>-1</strong>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O((L1*L2)*log(L1*L2))<br>\n<strong>Expected Auxiliary Space:</strong> O(L1*L2)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ L1, L2 ≤ 500<br>\n1 ≤ A[i], B[i] ≤ 10000<br>\n1 ≤ N ≤ L1*L2</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Nth item through sum - GFG/nth-item-through-sum.py",
    "content": "#User function Template for python3\n\nclass Solution:\n    def nthItem(self, L1, L2, A, B, N):\n       s = sorted({i+j for j in B for i in A})\n       if N > len(s) : return -1 \n       else : return s[N-1]\n\n#{ \n#  Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n    t = int(input())\n    for _ in range(t):\n        L1, L2 = [int(x) for x in input().split()]\n        A = input().split()\n        for itr in range(L1):\n            A[itr] = int(A[itr])\n        B = input().split()\n        for it in range(L2):\n            B[it] = int(B[it])\n        N = int(input())\n        \n        ob = Solution()\n        print(ob.nthItem(L1, L2, A, B, N))\n# } Driver Code Ends"
  },
  {
    "path": "Number Formation - GFG/README.md",
    "content": "# Number Formation\n## Hard\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Given three integers <strong>x, y,</strong> and <strong>z,</strong> the task is to find the sum of all the numbers formed by&nbsp;<br>\nhaving 4 at most x times, having 5 at most y times, and having 6 at most z times as a digit.</span></p>\n\n<p><span style=\"font-size:20px\"><strong>Note: </strong></span><span style=\"font-size:18px\">Output&nbsp;the sum modulo 10<sup>9</sup>+7.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>: X = 1, Y = 1, Z = 1 \n<strong>Output:</strong> 3675</span>\n<span style=\"font-size:18px\"><strong>Explanation</strong>: 4 + 5 + 6 + 45 + 54 + 56 \n+ 65 + 46 + 64 + 456 + 465 \n+ 546 + 564 + 645 + 654 = 3675</span></pre>\n\n<div><span style=\"font-size:18px\"><strong>Example 2:</strong></span></div>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>X = 0, Y = 0, Z = 0\n<strong>Output: </strong>0\n<strong>Explanation</strong>: No number can be formed</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Complete the function <strong><code>getSum</code>()&nbsp;</strong>which takes <strong>X, Y</strong> and <strong>Z </strong>as input parameters and returns the integer value<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(<strong>X*Y*Z</strong>)<br>\n<strong>Expected Auxiliary Space:</strong> O(<strong>X*Y*Z</strong>)<br>\n<br>\n<strong>Constraints:</strong><br>\n0 ≤ <strong>X, Y, Z</strong> ≤ 60</span></p>\n</div>"
  },
  {
    "path": "Number Formation - GFG/number-formation.java",
    "content": "//{ Driver Code Starts\n// Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nclass GfG {\n    public static void main(String args[]) {\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n        while (t-- > 0) {\n            int x = sc.nextInt();\n            int y = sc.nextInt();\n            int z = sc.nextInt();\n\n            Solution ob = new Solution();\n            System.out.println(ob.getSum(x, y, z));\n        }\n    }\n}\n// } Driver Code Ends\n\n\n// User Function template for JAVA\n\nclass Solution {\n\n    public int getSum(int X, int Y, int Z) {\n        // Your code goes here\n        int mod=1000000007;\n        long[][][] exactSum=new long[X+1][Y+1][Z+1];\n        long[][][] num=new long[X+1][Y+1][Z+1];\n        num[0][0][0]=1L;\n        \n        long ans=0L;\n        for(int i=0;i<=X;i++){\n            for(int j=0;j<=Y;j++){\n                for(int k=0;k<=Z;k++){\n                    if(i>0){\n                        exactSum[i][j][k]+=(exactSum[i-1][j][k]*10 +4*num[i-1][j][k])%mod;\n                        num[i][j][k]+=num[i-1][j][k]%mod;\n                    }\n                    if(j>0){\n                        exactSum[i][j][k]+=(exactSum[i][j-1][k]*10 +5*num[i][j-1][k])%mod;\n                        num[i][j][k]+=num[i][j-1][k]%mod;\n                    }\n                    if(k>0){\n                        exactSum[i][j][k]+=(exactSum[i][j][k-1]*10 +6*num[i][j][k-1])%mod;\n                        num[i][j][k]+=num[i][j][k-1]%mod;\n                    }\n                    ans+=exactSum[i][j][k]%mod;\n                    ans%=mod;\n                }\n            }\n        }\n        return (int)ans;\n    }\n}"
  },
  {
    "path": "Number of 1 Bits.java",
    "content": "public class Solution {\n\tpublic int numSetBits(long a) {\n        int ans=0;\n        while(a!=0){\n            ans+=(a&1);\n            a=a>>1;\n        }\n        return ans;\n\t}\n}\n"
  },
  {
    "path": "Number of Provinces.java",
    "content": "class Solution {\n    static int numProvinces(ArrayList<ArrayList<Integer>> adj, int V) {\n        // code here\n        boolean[]vis=new boolean[V];\n        int count=0;\n        for(int i=0;i<V;i++){\n            if(!vis[i]){\n                count++;\n                dfs(vis,adj,i,V);\n            }\n        }\n        return count;\n    }\n    static void dfs(boolean[]vis,ArrayList<ArrayList<Integer>> adj,int curr,int V){\n        vis[curr]=true;\n        \n        for(int i=0;i<V;i++){\n            if(!vis[i] && adj.get(curr).get(i)==1){\n                dfs(vis,adj,i,V);\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "Number of Sundays.java",
    "content": "public class Solution {\n    public int solve(String A, int B) {\n        int ans=0;\n        int num=0;\n        if(A.equals(\"Sunday\")){\n            num=1;\n        }else if(A.equals(\"Monday\")){\n            num=7;\n        }else if(A.equals(\"Tuesday\")){\n            num=6;\n        }else if(A.equals(\"Wednesday\")){\n            num=5;\n        }else if(A.equals(\"Thursday\")){\n            num=4;\n        }else if(A.equals(\"Friday\")){\n            num=3;\n        }else if(A.equals(\"Saturday\")){\n            num=2;\n        }\n        if(num>B)return 0;\n        ans++;\n        ans+=(B-num)/7;\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Number of Ways to Arrive at Destination gfg med sep16.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\n  public:\n    int countPaths(int n, vector<vector<int>>& roads) {\n        // code here\n        vector<vector<pair<int, int>>> adj(n);\n        for(auto road : roads){\n            int u = road[0], v = road[1], t = road[2];\n            adj[u].push_back({v, t});\n            adj[v].push_back({u, t});\n        }\n        priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, greater<pair<long long, long long>>> pq;\n        pq.push({0, 0});\n        vector<long long> dist(n, 1e18);\n        dist[0] = 0;\n        long long ans = 0, mod = 1000000007;\n        while(!pq.empty()){\n            long long node = pq.top().second, d = pq.top().first;    \n            pq.pop();\n            if(node == n - 1 && d == dist[n - 1]){\n                ans = (ans + 1) % mod;\n                continue;\n            } \n            for(auto child : adj[node]){\n                if(d + child.second <= dist[child.first]){\n                    dist[child.first] = d + child.second;\n                    pq.push({dist[child.first], child.first});\n                } \n            }    \n        }\n        return ans;\n    }\n};\nint main() {\n    int T;\n    cin >> T;\n    while (T--) {\n        int n, m;\n        cin >> n >> m;\n        int u, v;\n\n        vector<vector<int>> adj;\n\n        for (int i = 0; i < m; ++i) {\n            vector<int> temp;\n            for (int j = 0; j < 3; ++j) {\n                int x;\n                cin >> x;\n                temp.push_back(x);\n            }\n            adj.push_back(temp);\n        }\n\n        Solution obj;\n        cout << obj.countPaths(n, adj) << \"\\n\";\n    }\n\n    return 0;\n}"
  },
  {
    "path": "Number of Ways to Arrive at Destination.cpp",
    "content": "class Solution {\n  public:\n    int countPaths(int n, vector<vector<int>>& roads) {\n        \n        long long mod = 1e9+7;\n        long long ans = 0;\n        vector<vector<pair<int,int>>> adj(n);\n        vector<long long> dist(n,INT_MAX);\npriority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;\n        for(int i=0;i<roads.size();++i) {\n            adj[roads[i][0]].push_back({roads[i][2],roads[i][1]});\n            adj[roads[i][1]].push_back({roads[i][2],roads[i][0]});\n        }\n\n        dist[0]=0;\n        pq.push({0,0});\n        \n        while(!pq.empty()) {\n            auto a = pq.top();pq.pop();\n            \n            int wtillnow = a.first;\n            int curr= a.second;\n            for(auto it : adj[curr]){ \n                int wtwithadj = it.first + wtillnow;\n                int u=it.second;\n                \n                if( u == (n-1)) {\n                    if(dist[u] > wtwithadj) {\n                        dist[u] = wtwithadj;\n                        ans = 0;\n                    }\n                    if(dist[u] == wtwithadj)  ans =(ans+1)%mod;\n                    continue;\n                }\n                if(dist[u] >= wtwithadj) {\n                    dist[u] = wtwithadj;\n                    pq.push({dist[u], u});\n                }\n            }\n        }\n        return ans;\n    }\n};\n\n"
  },
  {
    "path": "Number of Ways to Arrive at Destination.java",
    "content": "class Solution {\n    static int minTime;\n    static int noOfRoads;\n    static int countPaths(int n, List<List<Integer>> roads) {\n        // Your code here\n        minTime=Integer.MAX_VALUE;\n        noOfRoads=0;\n        Map<Integer,List<int[]>> map=new HashMap<>();// node -> list({des,time})\n        for(List<Integer> curr:roads){\n            int src=curr.get(0);\n            int des=curr.get(1);\n            int time=curr.get(2);\n            map.putIfAbsent(src,new ArrayList<>());\n            map.putIfAbsent(des,new ArrayList<>());\n            map.get(src).add(new int[]{des,time});\n            map.get(des).add(new int[]{src,time});\n        }\n        boolean[]vis=new boolean[n];\n        dfs(0,map,vis,0);\n        return noOfRoads;\n    }\n    static void dfs(int node,Map<Integer,List<int[]>> map,boolean[]vis,int currTime){\n        if(node==vis.length-1){\n            if(currTime<minTime){\n                minTime=currTime;\n                noOfRoads=1;\n            }else if(currTime==minTime){\n                noOfRoads++;\n            }\n            return;\n        }\n        if(currTime>minTime)return;\n        vis[node]=true;\n        //find in nebs\n        List<int[]> nebList=map.get(node);\n        if(nebList!=null){\n            for(int[] neb:nebList){\n                int des=neb[0];\n                int time=neb[1];\n                if(!vis[des]){\n                    dfs(des,map,vis,currTime+time);\n                }\n            }\n        }\n        vis[node]=false;\n    }\n}\n"
  },
  {
    "path": "Number of distict Words with k maximum contiguous vowels.java",
    "content": "class Solution{\n    private static final int mod = 1000000007;\n    private static int reset;\n    private static Integer[][] dp;\n    \n    private static int find(int N, int K){\n        if(N == 0){\n            return 1;\n        }\n        if(dp[N][K] != null) return dp[N][K];\n        \n        int count = 0;\n        \n        for(char c = 'a'; c <= 'z'; c++){\n            if(c=='a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){\n                if(K > 0){\n                    count = (count + find(N-1, K-1)) % mod;\n                }\n            }\n            else{\n                count = (count + find(N-1, reset)) % mod;\n            }\n        }\n        \n        return dp[N][K] = count;\n    }\n    \n    \n    \n    public int kvowelwords(int N,int K){\n        dp = new Integer[N+1][K+1];\n        reset = K;\n        return find(N, K);\n    }\n}\n"
  },
  {
    "path": "Number of distinct Words with k maximum contiguous vowels - GFG/README.md",
    "content": "# Number of distinct Words with k maximum contiguous vowels\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Find the number of unique words consisting of lowercase alphabets only of length N that can be formed with at-most K contiguous vowels.&nbsp;</span></p>\n\n<p><br>\n<strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 2</span>\n<span style=\"font-size:18px\">K = 0</span>\n<span style=\"font-size:18px\"><strong>Output:</strong>\n441\n</span><span style=\"font-size:18px\"><strong>Explanation:</strong>\nTotal of 441 unique words are possible\nof length 2 that will have K( =0) vowels\ntogether, e.g. \"bc\", \"cd\", \"df\", etc are\nvalid words while \"ab\" (with 1 vowel) is\nnot a valid word.</span>\n\n</pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 1</span>\n<span style=\"font-size:18px\">K = 1</span>\n<span style=\"font-size:18px\"><strong>Output:</strong>\n26</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\nAll the english alphabets including</span>\n<span style=\"font-size:18px\">vowels and consonants; as atmost K( =1)\nvowel can be taken.</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong>&nbsp;&nbsp;<br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>kvowelwords</strong>()&nbsp;which takes an Integer N, an intege K and returns the total number of words of size N with atmost K vowels. As the answer maybe to large please <strong>return answer modulo 1000000007</strong>.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N*K)<br>\n<strong>Expected Auxiliary Space:</strong> O(N*K)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 1000</span><br>\n<span style=\"font-size:18px\">0 ≤ K ≤ N</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Number of distinct Words with k maximum contiguous vowels - GFG/number-of-distinct-words-with-k-maximum-contiguous-vowels.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n        while(t-- > 0)\n        {\n            int N = sc.nextInt();\n            int K = sc.nextInt();\n\n            Solution ob = new Solution();\n            int ans = ob.kvowelwords(N,K);\n            System.out.println(ans);\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    private static final int mod = 1000000007;\n    private static int reset;\n    private static Integer[][] dp;\n    private static int find(int N, int K){\n        if(N == 0){\n            return 1;\n        }\n        if(dp[N][K] != null) return dp[N][K];\n        \n        int count = 0;\n        \n        for(char c = 'a'; c <= 'z'; c++){\n            if(c=='a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){\n                if(K > 0){\n                    count = (count + find(N-1, K-1)) % mod;\n                }\n            }\n            else{\n                count = (count + find(N-1, reset)) % mod;\n            }\n        }\n        \n        return dp[N][K] = count;\n    }\n    \n    \n    \n    public int kvowelwords(int N,int K){\n        dp = new Integer[N+1][K+1];\n        reset = K;\n        return find(N, K);\n    }\n}\n"
  },
  {
    "path": "Number of positive integral solutions - GFG/README.md",
    "content": "# Number of positive integral solutions\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:20px\">You are given an equation of the form x<sub>1</sub>+x<sub>2</sub>+...+x<sub>N</sub>=K. You need to find the total number of positive integral solutions of this equation.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> s = a+b=5\n<strong>Output:</strong> 4\n<strong>Explanation</strong>: (4,1) , (1,4) , (2,3) , (3,2)\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>: s = a+b=1\n<strong>Output:</strong> 0\n<strong>Explanation</strong>: No solution exist.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>posIntSol()&nbsp;</strong>which takes a string&nbsp;as input and returns number of solutions.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity</strong>&nbsp;: O(Length of given string)<br>\n<strong>Expected Auxiliary Space</strong>&nbsp;:&nbsp;O(1)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= K &lt;= 25<br>\n2 &lt;= N &lt;= 10</span></p>\n\n<p>&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Number of positive integral solutions - GFG/number-of-positive-integral-solutions.py",
    "content": "#User function Template for python3\nfrom math import factorial as fact\nclass Solution:\n\n   def posIntSol(self,s):\n       #code here\n       r=1\n       n=\"\"\n       for i in range(len(s)):\n           if(s[i]==\"+\"):\n               r+=1\n           if(s[i]==\"=\"):\n               n=s[i+1:]\n               break;\n       n=int(n)\n       \n       if(n-1>=r-1):\n           return fact(n-1)//(fact(n-r)*fact(r-1))\n       else:\n           return 0\n#{ \n#  Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n\n    t = int(input())\n\n    for _ in range(t):\n        s = input()\n\n        solObj = Solution()\n\n        print(solObj.posIntSol(s))\n# } Driver Code Ends"
  },
  {
    "path": "Number of ways - GFG/README.md",
    "content": "# Number of ways\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a value <strong>N</strong>. In how many ways you can construct a grid&nbsp;of size N x 4 using tiles of size 1 x 4.</span></p>\n\n<p><br>\n<strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> N = 1\n<strong>Output:</strong> 1\n<strong>Explaination:</strong> We can arrange the tiles horizontally \nand this is the only way.</span></pre>\n\n<p><br>\n<strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> N = 4\n<strong>Output:</strong> 2\n<strong>Explaination:</strong> The first way can be when all \nthe 1 x 4 tiles are arranged horizontally. \nSecond way can be when all the 1 x 4 tiles \nare arranged vertically.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>arrangeTiles()</strong> which takes the value N as input parameter and returns the number of ways to make N x 4 grid&nbsp;using 1 x 4 tiles.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N)<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 80</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Number of ways - GFG/number-of-ways.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            int N = Integer.parseInt(in.readLine().trim());\n            \n            Solution ob = new Solution();\n            System.out.println(ob.arrangeTiles(N));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static long arrangeTiles(int n){\n        // code here\n        if(n<4)return 1;\n        int four=n/4;\n        long sum=0;\n        for(int i=1;i<=four;i++){\n            int rem=n-4*i;\n            sum=sum+nCr(rem+i,i);\n        }\n\n        return sum+1;\n    }\n  \n    static  long nCr(int n,int r){\n        long sum=1;\n        int max=Math.max(r,n-r);\n       int min=Math.min(r,n-r);\n       int st=1;\n       for(int i=n;i>max;i--){\n           sum= sum*i;\n           sum/=st;\n           st++;\n       }\n       return sum;\n    }\n}"
  },
  {
    "path": "Number-of-ways-to-arrive-destination/Solution.cpp",
    "content": "typedef pair<int,int> ip;\nlong long int M=1e9+7;\nclass Solution {\n  public:\n    int countPaths(int n, vector<vector<int>>& roads) {\n        int ans=0;\n        vector<int> dis(n,INT_MAX);\n        vector<ip> adj[n];\n        for(auto it: roads)\n            adj[it[0]].push_back({it[1],it[2]}),adj[it[1]].push_back({it[0],it[2]});\n            \n        priority_queue<ip,vector<ip>,greater<ip> > pq;\n        dis[0]=0;\n        pq.push({dis[0],0});\n        while(!pq.empty()){\n            int src=pq.top().second,wt=pq.top().first;\n            pq.pop();\n            for(auto it: adj[src]){\n                int v=it.first,nw=wt+it.second;\n                if(v==n-1){\n                    if(dis[v]==nw)\n                        ans=(ans+1ll)%M;\n                    else if(dis[v]>nw)\n                        dis[v]=nw,ans=1;\n                }\n                else{\n                    if(dis[v]>=nw)\n                        dis[v]=nw,pq.push({dis[v],v});\n                }\n            }\n        }\n        return ans;\n    }\n};"
  },
  {
    "path": "Number-of-ways-to-arrive-destination/question.md",
    "content": "### Number of Ways to Arrive at Destination\n\n**Medium**Accuracy: **48.81%**Submissions: **127**Points: **4**\n\nYou 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] = [u<sub>i</sub>, v<sub>i</sub>, time<sub>i</sub>]` means that there is a road between intersections `u<sub>i</sub>` and `v<sub>i</sub>` that takes `time<sub>i</sub>` 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** `10<sup>9</sup> + 7`.\n\n```\nExample:\nInput:\nn=7, m=10\nedges= [[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]]\n\nOutput:\n4\nExplaination:\n\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\n```\n\n**Constraints:**\n`1 <= n <= 200<br/>n - 1 <= roads.length <= n * (n - 1) / 2<br/>roads[i].length == 3<br/>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1<br/>1 <= time<sub>i</sub> <= 10<sup>9</sup><br/>u<sub>i </sub>!= v<sub>i</sub>`\nThere is at most one road connecting any two intersections.\nYou can reach any intersection from any other intersection.\n\nExpected Time Complexity: O(M * logN + N)\nExpected Space Complexity: O(M+N)\n"
  },
  {
    "path": "Numbers-With-Same-Consecutive-Differences.cpp",
    "content": "class Solution {\npublic:\n    vector<int> ans;\n    \n    void solve(int idx, int n, int k, int num){\n        if(idx == n){\n            if(ans.empty() || ans.back() != num)\n                ans.push_back(num);\n            return;\n        }\n        \n        int lastDigit = num % 10;\n        \n        if(lastDigit+k < 10){                                     \n        solve(idx+1,n,k, num*10 + (lastDigit+k));    \n        }\n        if(lastDigit-k >= 0){                                     \n            solve(idx+1,n,k, num*10 + (lastDigit-k));\n        }\n        return;\n    }\n    \n    vector<int> numsSameConsecDiff(int n, int k) {\n        \n        for(int i = 1; i < 10; i++){\n            solve(1,n,k,i);\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Occurence of Each Number.java",
    "content": "public class Solution {\n    public ArrayList<Integer> findOccurences(ArrayList<Integer> A) {\n        ArrayList<Integer> ans=new ArrayList<>();\n        Collections.sort(A);\n        int cnt=1;\n        int prev=A.get(0);\n        for(int i=1;i<A.size();i++){\n            if(A.get(i)==prev){\n                cnt++;\n            }else{\n                ans.add(cnt);\n                prev=A.get(i);\n                cnt=1;\n            }\n        }\n        ans.add(cnt);\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Odd Even Rule.java",
    "content": "public class Solution {\n    public int solve(int[] A, int B, int C) {\n        boolean even= B%2==0;\n        int fine=0;\n        if(even){\n            for(int i:A){\n                if(i%2!=0)fine+=C;\n            }\n        }else{\n            for(int i:A){\n                if(i%2==0)fine+=C;\n            }\n        }\n        return fine;\n    }\n}\n"
  },
  {
    "path": "POTD_gfg_The_Bit_Game .py",
    "content": "#User function Template for python3\n\nclass Solution:\n    def swapBitGame (self,N):\n        # code here \n        lis=list(bin(N).replace(\"0b\",\"\") # this will convert the given (N) number to binary Number \n        if (lis.count('1')%2!=0) :\n            return(1)\n        else:\n            return (2)\n            \n\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__': \n    t = int (input ())\n    for _ in range (t):\n        \n        N=int(input())\n        \n\n        ob = Solution()\n        print(ob.swapBitGame(N))\n# } Driver Code Ends\n"
  },
  {
    "path": "Pair With Given Difference.java",
    "content": "public class Solution {\n    public int solve(int[] A, int B) {\n        int[] nums = A;\n        Arrays.sort(nums);\n        int low = 0;\n        int high = 1;\n        while(low<A.length && high<A.length){\n            if(high!=low && nums[high] - nums[low] == B){\n                return 1;\n            }\n            if(nums[high] - nums[low] > B){\n                low++;\n            } else high++;\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Pairs With Given Xor.java",
    "content": "public class Solution {\n    public int solve(int[] A, int B) {\n        Set<Integer> set = new HashSet<>();\n        int count = 0;\n        for(int i : A){\n            if(set.contains(i)){\n                count++;\n            }else{\n                set.add(i^B);\n            }\n        }\n        return count;\n    }\n}\n\n"
  },
  {
    "path": "Pairs of Non Coinciding Points - GFG/README.md",
    "content": "# Pairs of Non Coinciding Points\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">In a given cartesian plane, there are <strong>N</strong> points. We need to find the Number of Pairs of &nbsp;points(<strong>A, B</strong>) such that</span></p>\n\n<ul>\n\t<li><span style=\"font-size:18px\">Point A and Point B do not coincide.</span></li>\n\t<li><span style=\"font-size:18px\">Manhattan Distance&nbsp;and the Euclidean Distance between the points should be equal.</span></li>\n</ul>\n\n<p><span style=\"font-size:18px\"><strong>Note:</strong> Pair of 2 points(A,B) is considered same as Pair of 2 points(B ,A).<br>\nManhattan Distance = |x2-x1|+|y2-y1|</span><br>\n<span style=\"font-size:18px\">Euclidean Distance &nbsp; = ((x2-x1)^2 + (y2-y1)^2)^0.5, where points are (x1,y1) and (x2,y2).</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>N = </strong></span><span style=\"font-size:18px\">2</span>\n<span style=\"font-size:18px\"><strong>X = </strong>{1, 7}</span>\n<span style=\"font-size:18px\"><strong>Y = </strong>{1, 5}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">0</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">None of the pairs of points have\nequal Manhatten and Euclidean distance.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>N = </strong></span><span style=\"font-size:18px\">3</span>\n<span style=\"font-size:18px\"><strong>X = </strong>{1, 2, 1}</span>\n<span style=\"font-size:18px\"><strong>Y = </strong>{2, 3, 3}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">2</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">The pairs {(1,2), (1,3)}, and {(1,3), (2,3)}\nhave equal Manhatten and Euclidean distance.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>numOfPairs()</strong> which takes an Integer N and two arrays X, and Y of length N as input and returns the number of pairs with equal Manhattan and Euclidean Distance. (X[i], Y[i]) denotes a point.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N)<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 &lt;= N &lt;= 10<sup>5</sup></span><br>\n&nbsp;<span style=\"font-size:18px\">-10^9</span> <span style=\"font-size:18px\">&lt;= X[i], Y[i] &lt;= 10^9</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Pairs of Non Coinciding Points - GFG/pairs-of-non-coinciding-points.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int N = Integer.parseInt(read.readLine());\n            \n            String S1[] = read.readLine().split(\" \");\n            String S2[] = read.readLine().split(\" \");\n            \n            int[] X = new int[N];\n            int[] Y = new int[N];\n            \n            for(int i=0; i<N; i++)\n            {\n                X[i] = Integer.parseInt(S1[i]);\n                Y[i] = Integer.parseInt(S2[i]);\n            }\n\n            Solution ob = new Solution();\n            System.out.println(ob.numOfPairs(X,Y,N));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n   public int numOfPairs(int[] x, int[] y, int n) {\n       // code here\n       HashMap<Integer, Integer> xCount = new HashMap<>();\n       HashMap<Integer, Integer> yCount = new HashMap<>();\n       HashMap<ArrayList<Integer>, Integer> visited = new HashMap<>();\n       int ans = 0;\n       int count1 = 0;\n       int count2 = 0;\n       int count3 = 0;\n\n       for (int i = 0; i < n; ++i) {\n           count1 += xCount.getOrDefault(x[i], 0);\n           xCount.put(x[i], xCount.getOrDefault(x[i], 0) + 1);\n       }\n       \n       for (int i = 0; i < n; ++i) {\n           count2 += yCount.getOrDefault(y[i], 0);\n           yCount.put(y[i], yCount.getOrDefault(y[i], 0) + 1);\n       }\n       \n       for (int i = 0; i < n; ++i) {\n           ArrayList<Integer> current = new ArrayList<>(Arrays.asList(x[i], y[i]));\n           count3 += visited.getOrDefault(current, 0);\n           visited.put(current, visited.getOrDefault(current, 0) + 1);\n       }\n       \n       ans = count1 + count2 - 2 * count3;\n       \n       return ans;\n   }\n};"
  },
  {
    "path": "Palindrome List.java",
    "content": "public class Solution {\n    public int lPalin(ListNode A) {\n        if(A==null || A.next==null)return 1;\n        int sz=0;\n        ListNode temp=A;\n        while(temp!=null){\n            temp=temp.next;\n            sz++;\n        }\n        ListNode prev=null;\n        ListNode curr=A;\n        for(int i=0;i<sz/2;i++){\n            ListNode next=curr.next;\n            curr.next=prev;\n            prev=curr;\n            curr=next;\n        }\n        return check(curr,prev) | check(prev,curr.next);\n    }\n    public int check(ListNode A,ListNode B){\n        ListNode a=A;\n        ListNode b=B;\n        while(a!=null && b!=null){\n            if(a.val!=b.val)return 0;\n            a=a.next;\n            b=b.next;\n        }\n        return (a==null && b==null)?1:0;\n    }\n}\n"
  },
  {
    "path": "Palindrome Numbers.java",
    "content": "public class Solution {\n    public int solve(int A, int B, int C) {\n          int i;\n    ArrayList<Integer> pal=new ArrayList<>();\n    for(i=A;i<=B;i++)\n    {\n        if(check(Integer.toString(i)))pal.add(i);\n    }\n    // int ans=0;/\n    int l=0;\n    int n=pal.size();\n    int ans=0;\n    i=0;\n    while(i<n)\n    {\n        while(i<n&&pal.get(i)-pal.get(l)<=C)i++;\n        ans=Math.max(ans,i-l);\n        if(i==n)break;\n        while(l<n&&pal.get(i)-pal.get(l)>C)l++;\n    }\n    return ans;\n    }\n    boolean check(String s)\n{\n    int n=s.length();\n    int i;\n    for(i=0;i<n/2;i++)\n    {\n    if(s.charAt(i)!=s.charAt(n-i-1))return false;\n    }\n    return true;\n}\n}\n"
  },
  {
    "path": "Palindrome Partitioning II.java",
    "content": "public class Solution {\n    static int dp[][] = new int[501][501];\n    Solution(){\n        for(int row[]: dp)\n            Arrays.fill(row,-1);\n    }\n    static public int minCut(String str) {\n        return solve(str,0,str.length()-1);\n    }\n    \n    static int solve(String str,int i,int j){\n        if(i>=j)\n            return dp[i][j] = 0;\n        if(dp[i][j] != -1)\n            return dp[i][j];\n        if(isPalindrome(str,i,j))\n            return 0;\n        int min = Integer.MAX_VALUE;    \n        for(int k=i;k<=j-1;k++){\n            int left = 0,right = 0;\n            if(dp[i][k] != -1)\n                left = dp[i][k];\n            else{\n                left = solve(str,i,k);\n                dp[i][k] = left;\n            }\n            if(dp[k+1][j] != -1)\n                right = dp[k+1][j];\n            else{\n                right = solve(str,k+1,j);\n                dp[k+1][j] = right;\n            }\n            int temp = right + left + 1;\n            min = Math.min(min,temp);\n        }\n        return dp[i][j] = min;\n    }\n    static boolean isPalindrome(String str,int i,int j){\n        String x = str.substring(i,j+1);\n        int k=0,l=x.length()-1;\n        while(k<l){\n            if(x.charAt(k++) != x.charAt(l--))\n                return false;\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "Palindrome Partitioning.java",
    "content": "public class Solution {\n\tpublic ArrayList<ArrayList<String>> partition(String a) {\n        ArrayList<ArrayList<String>> ans=new ArrayList<>();\n        ArrayList<String> path=new ArrayList<>();\n        helper(a,0,path,ans);\n        return ans;\n\t}\n    void helper(String s,int index,ArrayList<String> path,ArrayList<ArrayList<String>> ans){\n        if(index==s.length()){\n            ans.add(new ArrayList<>(path));\n            return;\n        }\n        for(int i=index;i<s.length();i++){\n            if(isPalindrome(s,index,i)){\n                path.add(s.substring(index,i+1));\n                helper(s,i+1,path,ans);\n                path.remove(path.size()-1);\n            }\n        }\n    }\n    boolean isPalindrome(String s,int i,int j){\n        while(i<j){\n            if(s.charAt(i)!=s.charAt(j))return false;\n            i++;\n            j--;\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "Palindromic Substrings.java",
    "content": "public class Solution {\n    public int solve(String str) {\n        int n = str.length();\n \n        int c=0;\n        boolean table[][] = new boolean[n][n];\n \n        // All substrings of length 1 are palindromes\n        //int maxLength = 0;\n        for (int gap = 0; gap < n; gap++)\n        {\n          for (int i = 0,j=gap; j < n ; i++,j++)\n          {\n            if(gap==0)\n            {\n                table[i][j]=true;\n            }\n            else if(gap==1)\n            {\n            if (str.charAt(i) == str.charAt(j)) \n                table[i][j] = true;\n                \n            else\n                table[i][j]=false;\n            }\n            else\n            {\n                if (table[i + 1][j - 1]==true && str.charAt(i) == str.charAt(j)) \n                    table[i][j] = true;\n                    else\n                        table[i][j]=false;\n \n            }\n            if(table[i][j])\n                 c++;\n                 \n            }\n        }        \n        return c;\n\n    }\n}\n\n"
  },
  {
    "path": "Palindromic Time.java",
    "content": "public class Solution {\n    public int solve(String A) {\n        int h= (A.charAt(0)-'0')*10 + (A.charAt(1)-'0');\n        int r= (A.charAt(1)-'0')*10 + (A.charAt(0)-'0');\n        int m=(A.charAt(3)-'0')*10 + (A.charAt(4)-'0');\n        int ans=0;\n        if(r>=m && r<60) return r-m;\n        else{\n        h=(h+1)%24;\n        ans+=60-m;\n        if(h>=10 && (h<16 || h>=20)){\n           r=(h%10)*10 + h/10;\n            if(r==10)\n                r=1;\n        }else if(h>=16){\n           ans+=(20-h)*60;\n           r=2;\n        }\n\n       else if(h<6)\n\n       r=h*10;\n\n       else\n\n       {\n\n           ans+=(10-h)*60;\n\n           r=1;\n\n       }\n\n       \n\n    }\n\n    return ans+r;\n\n\n}\n}\n"
  },
  {
    "path": "Palindromic Words.java",
    "content": "public class Solution {\n    public int solve(String A) {\n        int ans=0;\n        String[]arr=A.split(\" \");\n        for(String a:arr){\n            if(isPalindrome(a))ans++;\n        }\n        return ans;\n    }\n    boolean isPalindrome(String str){\n \n        // Pointers pointing to the beginning\n        // and the end of the string\n        int i = 0, j = str.length() - 1;\n \n        // While there are characters to compare\n        while (i < j) {\n \n            // If there is a mismatch\n            if (str.charAt(i) != str.charAt(j))\n                return false;\n \n            // Increment first pointer and\n            // decrement the other\n            i++;\n            j--;\n        }\n \n        // Given string is a palindrome\n        return true;\n    }\n}\n"
  },
  {
    "path": "Partition Array According to Given Pivot.java",
    "content": "class Solution {\n    public int[] pivotArray(int[] nums, int pivot) {\n        List<Integer> small=new ArrayList<>();\n        List<Integer> large=new ArrayList<>();\n        int pivs=0;\n        int n=nums.length;\n        for(int i=0;i<n;i++){\n            if(nums[i]<pivot){\n                small.add(nums[i]);\n            }else if(nums[i]>pivot){\n                large.add(nums[i]);\n            }else{\n                pivs++;\n            }\n        }\n        int index=0;\n        for(int i=0;i<small.size();i++){\n            nums[index]=small.get(i);\n            index++;\n        }\n        while(pivs!=0){\n            nums[index]=pivot;\n            pivs--;\n            index++;\n        }\n        for(int i=0;i<large.size();i++){\n            nums[index]=large.get(i);\n            index++;\n        }\n        return nums;\n    }\n}\n"
  },
  {
    "path": "Partition Labels .cpp",
    "content": "class Solution {\npublic:\n    vector<int> partitionLabels(string s) {\n        unordered_map<char,int> mp;\n        for(int i=0;i<s.size();i++)\n        {\n            mp[s[i]]=i;\n        }\n        vector<int> ans;\n        int prev=-1,mx=0;\n        for(int i=0;i<s.size();i++)\n        {\n            mx=max(mx,mp[s[i]]);\n            if(i==mx)\n            {\n                ans.push_back(mx-prev);\n                prev=mx;\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Partition List.java",
    "content": "/**\n * Definition for singly-linked list.\n * class ListNode {\n *     public int val;\n *     public ListNode next;\n *     ListNode(int x) { val = x; next = null; }\n * }\n */\npublic class Solution {\n    public ListNode partition(ListNode A, int B) {\n        ListNode ans=new ListNode(-1);\n        ListNode largers=new ListNode(-1);\n        ListNode currLar=largers;\n        ListNode curr=ans;\n        ListNode temp=A;\n        while(temp!=null){\n            ListNode node=temp;\n            temp=temp.next;\n            node.next=null;\n            if(node.val<B){\n                curr.next=node;\n                curr=curr.next;\n            }else{\n                currLar.next=node;\n                currLar=currLar.next;\n            }\n        }\n        curr.next=largers.next;\n        return ans.next;\n    }\n}\n"
  },
  {
    "path": "Partition a Linked List around a given value - GFG/README.md",
    "content": "# Partition a Linked List around a given value\n## Medium \n<div class=\"problem-statement\">\n                <p></p><div><span style=\"font-size:18px\">Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with value equal to x and finally nodes with value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in-place.</span></div>\n\n<div>&nbsp;</div>\n\n<div><strong><span style=\"font-size:18px\">Example 1:</span></strong></div>\n\n<pre><strong><span style=\"font-size:18px\">Input:</span></strong>\n<span style=\"font-size:18px\">1-&gt;4-&gt;3-&gt;2-&gt;5-&gt;2-&gt;3,\nx = 3</span>\n<strong><span style=\"font-size:18px\">Output:</span></strong>\n<span style=\"font-size:18px\">1-&gt;2-&gt;2-&gt;3-&gt;3-&gt;4-&gt;5</span>\n<strong><span style=\"font-size:18px\">Explanation: </span></strong>\n<span style=\"font-size:18px\">Nodes with value less than 3 come first, </span>\n<span style=\"font-size:18px\">then equal to 3 and then greater than 3.</span>\n</pre>\n\n<div><strong><span style=\"font-size:18px\">Example 2:</span></strong></div>\n\n<pre><strong><span style=\"font-size:18px\">Input:</span></strong>\n<span style=\"font-size:18px\">1-&gt;4-&gt;2-&gt;10 </span>\n<span style=\"font-size:18px\">x = 3</span>\n<strong><span style=\"font-size:18px\">Output: </span></strong>\n<span style=\"font-size:18px\">1-&gt;2-&gt;4-&gt;10</span>\n<strong><span style=\"font-size:18px\">Explanation:</span></strong>\n<span style=\"font-size:18px\">Nodes with value less than 3 come first,</span>\n<span style=\"font-size:18px\">then equal to 3 and then greater than 3.</span>\n</pre>\n\n<div><strong><span style=\"font-size:18px\">Your task:</span></strong></div>\n\n<div><span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function <strong>partition()</strong> which takes the head of the inked list and an integer x as input, and returns the head of the modified linked list after arranging the values according to x.</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Expected time complexity :</strong> O(n)</span></div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Auxiliary Space:</strong> O(n)</span></div>\n\n<div>&nbsp;</div>\n\n<div><strong><span style=\"font-size:18px\">Constraints:</span></strong></div>\n\n<div><span style=\"font-size:18px\">1 &lt;= N &lt;= 10<sup>5</sup></span></div>\n\n<div><span style=\"font-size:18px\">1 &lt;= k &lt;= 10<sup>5</sup></span></div>\n <p></p>\n            </div>"
  },
  {
    "path": "Partition a Linked List around a given value - GFG/partition-a-linked-list-around-a-given-value.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass Node {\n    int data;\n    Node next;\n    Node(int key) {\n        data = key;\n        next = null;\n    }\n}\n\nclass Partition {\n    static Node head;\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n\n        while (t-- > 0) {\n            int n = sc.nextInt();\n            int a1 = sc.nextInt();\n            Node head = new Node(a1);\n            Node tail = head;\n            for (int i = 1; i < n; i++) {\n                int a = sc.nextInt();\n                // addToTheLast(new Node(a));\n                tail.next = new Node(a);\n                tail = tail.next;\n            }\n\n            int k = sc.nextInt();\n            Solution ob = new Solution();\n            Node res = ob.partition(head, k);\n            printList(res);\n            System.out.println();\n        }\n    }\n\n    public static void printList(Node node) {\n        while (node != null) {\n            System.out.print(node.data + \" \");\n            node = node.next;\n        }\n    }\n}// } Driver Code Ends\n\n\n// User function Template for Java\n\n/*class Node\n{\n    int data;\n    Node next;\n    Node(int key)\n    {\n        data = key;\n        next = null;\n    }\n}\n\n*/\n\nclass Solution {\n    public static Node partition(Node node, int x) {\n        Queue<Node> fis=new LinkedList<>();\n        Queue<Node> sec=new LinkedList<>();\n        Queue<Node> thir=new LinkedList<>();\n        Node temp=node;\n        while(temp!=null){\n            if(temp.data<x){\n                Node curr=temp;\n                temp=temp.next;\n                curr.next=null;\n                fis.add(curr);\n            }else if(temp.data==x){\n                Node curr=temp;\n                temp=temp.next;\n                curr.next=null;\n                sec.add(curr);\n            }else{\n                Node curr=temp;\n                temp=temp.next;\n                curr.next=null;\n                thir.add(curr);\n            }\n        }\n        Node head=new Node(-1);\n        temp=head;\n        while(fis.size()>0){\n            temp.next=fis.remove();\n            temp=temp.next;\n        }\n        while(sec.size()>0){\n            temp.next=sec.remove();\n            temp=temp.next;\n        }\n        while(thir.size()>0){\n            temp.next=thir.remove();\n            temp=temp.next;\n        }\n        return head.next;\n    }\n}"
  },
  {
    "path": "Partition a number into two divisible parts - GFG/README.md",
    "content": "# Partition a number into two divisible parts\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a number (as string) and two integers a and b, divide the string in two non-empty parts such that the first part is divisible by a and the second part is divisible by b. In case multiple answers exist, return the string such that the first non-empty part has minimum length.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\">Example 1:</span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\n1200 4 3\n<strong>Output:</strong>\n12 00\n<strong>Explanation:</strong>\n12 is divisible by 4, and\n00 is divisible by 3.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\">Example 2:</span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> </span>\n<span style=\"font-size:18px\">125 12 5</span>\n<span style=\"font-size:18px\"><strong>Output:</strong> </span>\n<span style=\"font-size:18px\">12 5</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong> </span>\n<span style=\"font-size:18px\">12 is divisible by 12, and </span>\n<span style=\"font-size:18px\">5 is divisible by 5.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><strong><span style=\"font-size:18px\">Your Task:</span></strong></p>\n\n<p><span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function stringPartition() which takes the string S and returns a string which will be in the form of&nbsp;</span><span style=\"font-size:18px\">first sub-string + \" \" (Single Space) + second sub-string</span><span style=\"font-size:18px\">. </span><span style=\"font-size:18px\">If not found return -1 as a string.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\">Expected Time Complexity: O(N)<br>\nExpected Auxiliary Space: O(N)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span></p>\n\n<p><span style=\"font-size:18px\">1&lt;=N&lt;=10<sup>6</sup></span></p>\n\n<p><span style=\"font-size:18px\">1&lt;=a,b&lt;=N</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Partition a number into two divisible parts - GFG/partition-a-number-into-two-divisible-parts.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String str[] = read.readLine().split(\" \");\n            String S= str[0];\n            int a = Integer.parseInt(str[1]);\n            int b = Integer.parseInt(str[2]);\n            Solution ob = new Solution();\n            System.out.println(ob.stringPartition(S,a,b));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\nclass Solution{\n    static String stringPartition(String S, int a, int b){\n        int n=S.length();\n        String[]pre=new String[n-1];\n        String[]post=new String[n-1];\n        for(int i=0;i<n-1;i++){\n            pre[i]=S.substring(0,i+1);\n            post[i]=S.substring(i+1,n);\n        }\n        for(int i=0;i<n-1;i++){\n            if(div(pre[i],a) && div(post[i],b)){\n                return pre[i]+\" \"+post[i];\n            }\n        }\n        return \"-1\";\n    }\n    static boolean div(String s,int a){\n        int num=Integer.parseInt(s);\n        if(num%a==0)return true;\n        return false;\n    }\n}"
  },
  {
    "path": "Partition array to K subsets - GFG/README.md",
    "content": "# Partition array to K subsets\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an integer array <strong>a[ ]</strong> of <strong>N</strong> elements and an integer <strong>K</strong>, the task is to check if the array <strong>a[ ]</strong>&nbsp;could be divided into <strong>K</strong> non-empty subsets with equal sum of elements.<br>\n<strong>Note:</strong>&nbsp;All elements of this array should be part of exactly one partition.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> \nN = 5\na[] = {2,1,4,5,6}\nK = 3\n<strong>Output:</strong> \n1\n<strong>Explanation:</strong> we can divide above array \ninto 3 parts with equal sum as (2, 4), \n(1, 5),&nbsp;(6)\n</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>: \nN = 5 \na[] = {2,1,5,5,6}\nK = 3\n<strong>Output:</strong> \n0\n<strong>Explanation</strong>: It is not possible to divide\nabove array into 3 parts with equal sum.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>isKPartitionPossible()</strong>&nbsp;which takes the array a[],&nbsp;the size of the array N, and the value of K as inputs and returns true(same as 1) if possible, otherwise false(same as 0).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N*2<sup>N</sup>).<br>\n<strong>Expected Auxiliary&nbsp;Space:</strong>&nbsp;O(2<sup>N</sup>).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤&nbsp;K ≤ N ≤ 10<br>\n1 ≤ a[i] ≤ 100</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Partition array to K subsets - GFG/partition-array-to-k-subsets.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\n\nclass Partition_Arr_To_K_Subsets\n{\n\tpublic static void main(String args[])\n\t{\n\t\tScanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();\n\t\twhile(t>0)\n\t\t{\n\t\t\tint n = sc.nextInt();\n\t\t\tint a[] = new int[n];\n\t\t\tfor(int i=0;i<n;i++)\n\t\t\t\ta[i] = sc.nextInt();\n\t\t\tint k = sc.nextInt();\n\t\t\tSolution g = new Solution();\n\t\t\tif(g.isKPartitionPossible(a,n,k)==true)\n\t\t\t\tSystem.out.println(1);\n\t\t\telse \n\t\t\t\tSystem.out.println(0);\n\t\t\t\n\t\tt--;\n\t\t}\n\t}\n}// } Driver Code Ends\n\n\n/*You are required to complete this method */\nclass Solution {\n    public boolean isKPartitionPossible(int[] arr,int n, int k) {\n        int sum=0;\n        for(int i:arr) sum+=i;\n        if(sum%k!=0) return false;\n        Arrays.sort(arr);\n        \n        return (dfs(n-1,arr,new int[k],k,sum/k));\n    }\n    public boolean dfs(int ind,int[] arr,int[] sum, int k,int target){\n        if(ind == -1)return true;\n        for(int i=0;i<k;i++){\n            if((sum[i] + arr[ind]>target) || (i>0 && sum[i] == sum[i-1]))continue;\n            \n            sum[i]+=arr[ind];\n            \n            if(dfs(ind-1,arr,sum,k,target))return true;\n            sum[i]-= arr[ind];\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "Partition array to K subsets - GFG/partition-array-to-k-subsets.py",
    "content": "#User function Template for python3\n\nfrom functools import lru_cache\nclass Solution:\n    def isKPartitionPossible(self, nums, k):\n        #code here\n        if sum(nums)%k:\n            return False\n        visited=[False]*len(nums)\n        nums.sort(reverse=True)\n        \n        target=sum(nums)/k\n        \n        @lru_cache(None)\n        def solve(i,k,ans):\n            if k==0:\n                return True\n            if ans==target:\n                return solve(0,k-1,0)\n            for j in range(i,len(nums)):\n                if visited[j] or ans+nums[j]>target:\n                    continue\n                visited[j]=True\n                if solve(j+1,k,ans+nums[j]):\n                    return True\n                visited[j]=False\n            return False\n        return solve(0,k,0)\n        \n#{ \n#  Driver Code Starts\n\n\nif __name__ == '__main__':\n    tcs = int(input())\n    for _ in range(tcs):\n        N=int(input())\n        arr=[int(x) for x in input().split()]\n        k=int(input())\n        if Solution().isKPartitionPossible(arr, k):\n            print(1)\n        else:\n            print(0)\n# } Driver Code Ends"
  },
  {
    "path": "Partition array to K subsets.java",
    "content": "class Solution\n{\n    public boolean isKPartitionPossible(int a[], int n, int k)\n    {\n\t// Your code here\t\n\t    int sum=0;\n\t    for(int i:a)sum+=i;\n\t    \n\t    if(sum%k != 0)return false;\n\t    \n\t    int target=sum/k;\n\t    int[] subsets=new int[k];\n\t    Arrays.sort(a);\n\t    \n\t    return dfs(a,subsets,n-1,target);\n    }\n    \n    boolean dfs(int[]a,int[]subsets,int ind,int target){\n        if(ind==-1)return true;\n        \n        for(int i=0;i<subsets.length;i++){\n            if(subsets[i]+a[ind] >target)continue;\n            subsets[i]+=a[ind];\n            if(dfs(a,subsets,ind-1,target)){\n                return true;\n            }\n            subsets[i]-=a[ind];\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "Party in Town - GFG/README.md",
    "content": "# Party in Town\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Geek town has N Houses numbered from 1 to N. They are connected with each other via N-1 bidirectional roads and an adjacency list is used to represent the connections.&nbsp;Find the house from which the distance to the farthest house is the minimum to host the optimal party.</span></p>\n\n<p><br>\n<strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>\nN = 4\nRoads = {{1,2},{2,3},{2,4}} \nadj = {{2},{1,3,4},{2},{2}} </span>\n\n<span style=\"font-size:18px\"><strong>Output:</strong> 1</span>\n\n<span style=\"font-size:18px\"><strong>Explaination:</strong> Maximum distance from house number 2 is 1.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>partyHouse() </strong>which takes N and adj as input parameters and returns the minimum possible distance to the farthest house from the house where the party is happening.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N*N)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 1000</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Party in Town - GFG/party-in-town.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            int N = Integer.parseInt(in.readLine());\n            ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();\n    \t\tfor(int i = 0;i < N+1;i++){\n    \t        ArrayList<Integer> arr = new ArrayList<Integer>();\n    \t        adj.add(arr);\n    \t\t}\n    \t\tfor(int i = 0;i < N-1;i++){\n    \t\t    String a[] = in.readLine().trim().split(\"\\\\s+\");\n    \t\t    int x = Integer.parseInt(a[0]);\n    \t\t    int y = Integer.parseInt(a[1]);\n    \t\t    adj.get(x).add(y);\n    \t\t    adj.get(y).add(x);\n    \t\t}\n    \t\t\n    \t\tSolution ob = new Solution();\n    \t\tSystem.out.println(ob.partyHouse(N, adj));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\nclass Solution{\n   static int dfs(ArrayList<ArrayList<Integer>> adj, int start, boolean[]visited){\n        Queue<Integer> q = new LinkedList<>();\n        q.add(start);\n        int level = 0;\n        while(!q.isEmpty()){\n            int size = q.size();\n            while(size-->0){\n               int val = q.remove();\n               visited[val] = true;\n               for(int i : adj.get(val)){\n                   if(visited[i]==false){\n                       q.add(i);\n                   }\n               }\n           }\n           level++;\n       }\n       return level-1;\n   }\n   static int partyHouse(int N, ArrayList<ArrayList<Integer>> adj)\n   {\n       int ans = Integer.MAX_VALUE;\n       for(int i=1; i<=N;i++){\n           boolean[]visited = new boolean[N+1];\n           ans = Math.min(ans, dfs(adj, i,visited));    \n       }    \n       return ans;\n   }\n}"
  },
  {
    "path": "Pascal's Triangle.java",
    "content": "class Solution {\n    public List<List<Integer>> generate(int numRows) {\n        List<List<Integer>> triangle=new ArrayList<>();\n        triangle.add(new ArrayList<>());\n        triangle.get(0).add(1);\n        for(int i = 1; i < numRows; i++){\n\t\t    List<Integer> row = new ArrayList<>();\n\t\t    List<Integer> prevRow = triangle.get(i-1);\n\t\t\n\t\t    row.add(1);\n\t\t\n\t\t    for(int j = 1; j < i; j++){\n\t\t\t    row.add(prevRow.get(j-1) + prevRow.get(j));\n\t\t    }\n\t\t\n\t\t    row.add(1);\n\t\t    triangle.add(row);\n\t    }\n\t    return triangle;  \n    }    \n}\n"
  },
  {
    "path": "Path in Directed Graph.java",
    "content": "public class Solution {\n    public int solve(int A, int[][] B) {\n        Map<Integer,ArrayList<Integer>>map=new HashMap<>();\n        for(int i=0;i<A;i++){\n            map.put(i+1,new ArrayList<>());\n        }\n        for(int i=0;i<B.length;i++){\n            ArrayList<Integer> arr=map.get(B[i][0]);\n            arr.add(B[i][1]);\n            map.put(B[i][0],arr);\n        }\n        Queue<Integer> q=new LinkedList<>();\n        q.add(1);\n        boolean[]vis=new boolean[A+1];\n        while(!q.isEmpty()){\n            int sz=q.size();\n            for(int i=0;i<sz;i++){\n                int ele=q.remove();\n                if(ele==A)return 1;\n                if(!vis[ele]){\n                    q.addAll(map.get(ele));\n                }\n                vis[ele]=true;\n            }\n        }\n        return 0;\n    }\n}\n\n//----------------------------------------------------------------------------\n\npublic class Solution {\n    public int solve(int A, int[][] B) {\n        Map<Integer,ArrayList<Integer>>map=new HashMap<>();\n        for(int i=0;i<A;i++){\n            map.put(i+1,new ArrayList<>());\n        }\n        for(int i=0;i<B.length;i++){\n            ArrayList<Integer> arr=map.get(B[i][0]);\n            arr.add(B[i][1]);\n            map.put(B[i][0],arr);\n        }\n        Queue<Integer> q=new LinkedList<>();\n        q.add(1);\n        boolean[]vis=new boolean[A+1];\n        while(!q.isEmpty()){\n            int sz=q.size();\n            for(int i=0;i<sz;i++){\n                int ele=q.remove();\n                if(ele==A)return 1;\n                if(!vis[ele]){\n                    q.addAll(map.get(ele));\n                }\n                vis[ele]=true;\n            }\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Path in Matrix.java",
    "content": "public class Solution {\n    public int checkPath(int[][] A) {\n        for(int i=0;i<A.length;i++){\n            for(int j=0;j<A.length;j++){\n                if(A[i][j]==1){\n                    return dfs(i,j,A)?1:0;\n                }\n            }\n        }\n        return 0;\n    }\n    boolean dfs(int i,int j,int[][]A){\n        if(i<0 || j<0 || i==A.length || j==A.length || A[i][j]==0)return false;\n        if(A[i][j]==2)return true;\n        A[i][j]=0;\n        return dfs(i+1,j,A) || dfs(i,j+1,A) || dfs(i-1,j,A) || dfs(i,j-1,A);\n    }\n}\n"
  },
  {
    "path": "Path to Given Node.java",
    "content": "vpublic class Solution {\n    int target;\n    ArrayList<Integer> ans=new ArrayList<>();\n    public ArrayList<Integer> solve(TreeNode A, int B) {\n        target=B;\n        solve(A,new ArrayList<Integer>());\n        return ans;\n    }\n    public void solve(TreeNode curr,ArrayList<Integer> arr){\n        if(curr==null)return;\n        arr.add(curr.val);\n        if(curr.val==target){\n            ans=arr;\n            return;\n        }else{\n            if(curr.left!=null){\n                solve(curr.left,(ArrayList)arr.clone());\n            }\n            if(curr.right!=null){\n                solve(curr.right,(ArrayList)arr.clone());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Path with good nodes!.java",
    "content": "public class Solution {\n    public int solve(int[] type, int[][] B, int C) {\n        int n = type.length;\n        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n        for(int i = 0; i < n; i++) adj.add(new ArrayList<>());\n\n        for(int[] edge : B){\n            adj.get(edge[0] - 1).add(edge[1] - 1);\n            adj.get(edge[1] - 1).add(edge[0] - 1);\n        }\n        return dfs(0, type, C - type[0], -1, adj);\n    }\n    private int dfs(int root,int[] type, int goodNodes, int par, ArrayList<ArrayList<Integer>> adj){\n        if(goodNodes < 0) return 0;\n        int cnt = 0;\n        // we are at leaf node\n        if(adj.get(root).size() == 1) {\n            return 1;\n        }\n\n        for(int  child :adj.get(root)){\n            if(child == par)continue;\n            cnt += dfs(child, type, goodNodes - type[child], root, adj);\n        }\n        return cnt;\n    }\n}\n"
  },
  {
    "path": "Perfect Peak of Array.java",
    "content": "public class Solution {\n    public int perfectPeak(int[] A) {\n        int n=A.length;\n        int[] maxArr=new int[n];\n        int[] minArr=new int[n];\n        maxArr[0]=A[0];\n        for(int i=1;i<n;i++){\n            maxArr[i]=Math.max(A[i],maxArr[i-1]);\n        }\n        minArr[n-1]=A[n-1];\n        for(int i=n-2;i>=0;i--){\n            minArr[i]=Math.min(A[i],minArr[i+1]);\n        }\n        for(int i=1;i<n-1;i++){\n            if(A[i]>maxArr[i-1] && A[i]<minArr[i+1]){\n                return 1;\n            }\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Permutation in String.java",
    "content": "class Solution {\n    public boolean checkInclusion(String s1, String s2) {\n        int len_s1 = s1.length(), len_s2 = s2.length();\n        if (len_s1 > len_s2) return false;\n        \n        int[] count = new int[26];\n        for (int i = 0; i < len_s1; i++) {\n            count[s1.charAt(i) - 'a']++;\n            count[s2.charAt(i) - 'a']--;\n        }\n        if (zeroCount(count)) return true;\n        \n        for (int i = len_s1; i < len_s2; i++) {\n            count[s2.charAt(i) - 'a']--;\n            count[s2.charAt(i - len_s1) - 'a']++;\n            if (zeroCount(count)) return true;\n        }\n        \n        return false;\n    }\n    \n    private boolean zeroCount(int[] count) {\n        for (int i = 0; i < 26; i++) {\n            if (count[i] != 0) \n                return false;\n        }\n        return true;\n    }\n}\n\n==================================================================================================\n  \n  class Solution {\n    public boolean checkInclusion(String s1, String s2) {\n        int[] arr=new int[26];\n        for(char c:s1.toCharArray()){\n            arr[(int)c-97]++;\n        }\n        \n        int[] a=new int[26];\n        for(int i=0;i<=s2.length()-s1.length();i++){\n            a=arr.clone();\n            boolean present=false;\n            for(int j=i;j<i+s1.length();j++){\n                if(a[(int)s2.charAt(j)-97]<=0){\n                    present=false;\n                    break;\n                }else{\n                    a[(int)s2.charAt(j)-97]--;\n                    present=true;\n                }\n            }\n            if(present)return present;\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "Permutation with Spaces - GFG/README.md",
    "content": "# Permutation with Spaces\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. The output should be printed in <strong>sorted</strong> <strong>increasing</strong> order of strings</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>:\nS = \"ABC\"\n<strong>Output: </strong>(A B C)(A BC)(AB C)(ABC)\n<strong>Explanation</strong>:\nABC\nAB C\nA BC\nA B C\nThese are the possible combination of \"ABC\".</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nS = \"AB\"\n<strong>Output: </strong>(A B)(AB)\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>permutation()</strong>&nbsp;which takes the string S as input parameters and returns the <strong>sorted array&nbsp;</strong>of the string denoting the different permutation <strong>(DON'T ADD '(' and ')' it will be handled by the driver code only)</strong>.<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(2^n)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>CONSTRAINTS:</strong><br>\n1 &lt; |S| &lt; 10<br>\nS only contains <strong>lowercase and Uppercase English</strong> letters.</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Permutation with Spaces - GFG/permutation-with-spaces.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        \n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String S = read.readLine().trim();\n            Solution ob = new Solution();\n            ArrayList<String> ans = new ArrayList<String>();\n            ans = ob.permutation(S);\n            \n            for(int i=0;i<ans.size();i++){\n                System.out.print(\"(\"+ans.get(i)+\")\");\n            }\n            System.out.println();\n        }\n    }\n}\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n\n\nclass Solution{\n    ArrayList<String> ans;\n    ArrayList<String> permutation(String S){\n        ans=new ArrayList<>();\n        helper(\"\",S);\n        return ans;\n    }\n    public void helper(String curr,String s){\n        if(s.length()==0){\n            ans.add(curr);\n            return;\n        }\n        if(curr.length()==0){\n            helper(s.charAt(0)+\"\",s.substring(1));    \n            return;\n        }\n        helper(curr+\" \"+s.charAt(0),s.substring(1));\n        helper(curr+s.charAt(0),s.substring(1));\n    }\n    \n}"
  },
  {
    "path": "Permutations.java",
    "content": "public class Solution {\n    ArrayList<ArrayList<Integer>> ans;\n    public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> A) {\n        int n=A.size();\n        ans=new ArrayList<>();\n        boolean[] vis=new boolean[n];\n        dfs(new ArrayList<>(),A,vis);\n        return ans;\n    }\n    public void dfs(ArrayList<Integer> curr,ArrayList<Integer> A,boolean[]vis){\n        if(curr.size()==A.size()){\n            if(!ans.contains(curr)){\n                ans.add(new ArrayList(curr));\n            }\n            return;\n        }\n        for(int i=0;i<A.size();i++){\n            if(!vis[i]){\n                curr.add(A.get(i));\n                vis[i]=true;\n                dfs(curr,A,vis);\n                curr.remove(curr.size()-1);\n                vis[i]=false;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Polynomial Addition - GFG/README.md",
    "content": "# Polynomial Addition\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two polynomial numbers represented by a linked list. The task is to complete the function <strong>addPolynomial()</strong>&nbsp;that adds these lists meaning&nbsp;adds the coefficients who have the same variable powers.<br>\n<strong>Note:</strong>&nbsp;</span>&nbsp;<span style=\"font-size:18px\">G</span><span style=\"font-size:18px\">iven polynomials are sorted in decreasing order of power.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>LinkedList1:  (1,x<sup>2) </sup>\nLinkedList2:  (1,x<sup>3</sup>)\n<strong>Output:\n</strong>1x^3 + 1x^2\n<strong>Explanation: </strong>Since, x<sup>2</sup> and x<sup>3</sup> both have\ndifferent powers as 2 and 3. So, their\ncoefficient can't be added up.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>LinkedList1:  (1,x<sup>3</sup>) -&gt; (2,x<sup>2</sup>)\nLinkedList2:  (3,x<sup>3</sup>) -&gt; (4,x<sup>2</sup>)\n<strong>Output:\n</strong>4x^3&nbsp;+ 6x^2\n<strong>Explanation: </strong>Since, x<sup>3</sup> has two different\ncoefficients as 3 and 1. Adding them up\nwill lead to 4x<sup>3</sup>. Also, x<sup>2</sup> has two\ncoefficients as 4 and 2. So, adding them\nup will give 6x<sup>2</sup>.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThe task is to complete the function&nbsp;<strong>addPolynomial</strong>() which should add the polynomial with same powers&nbsp;return the required polynomial in decreasing order of the power in the form of a linked list.<br>\n<strong>Note</strong>: Try to solve the question without using any extra space.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N+M)<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(1)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N, M &lt;= 10<sup>5</sup><br>\n1 &lt;= x, y &lt;= 10<sup>6</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Polynomial Addition - GFG/polynomial-addition.java",
    "content": "// { Driver Code Starts\nimport java.util.Scanner;\nimport java.io.*;\nclass Node{\n    int coeff;\n    int pow;\n    Node next;\n    Node(int a,int b)\n    {\n        coeff=a;\n        pow=b;\n        next=null;\n    }\n}\nclass GFG2\n{\n    public static void main(String args[])\n    {\n        Scanner sc=new Scanner(System.in);\n        int t=sc.nextInt();\n        while(t-->0)\n        {\n            int n=sc.nextInt();\n            Node start1=null,cur1=null,start2=null,cur2=null;\n            while(n-->0)\n            {\n                int a=sc.nextInt();\n                int b=sc.nextInt();\n                Node ptr=new Node(a,b);\n                if(start1==null)\n                {\n                    start1=ptr;\n                    cur1=ptr;\n                }\n                else{\n                    cur1.next=ptr;\n                    cur1=ptr;\n                }\n            }\n            n=sc.nextInt();\n            while(n-->0)\n            {\n                int a=sc.nextInt();\n                int b=sc.nextInt();\n                Node ptr=new Node(a,b);\n                if(start2==null)\n                {\n                    start2=ptr;\n                    cur2=ptr;\n                }\n                else{\n                    cur2.next=ptr;\n                    cur2=ptr;\n                }\n            }\n            Solution obj=new Solution();\n            Node sum = obj.addPolynomial(start1,start2);\n            for(Node ptr=sum ; ptr != null; ptr=ptr.next  )\n            {\n                // printing polynomial\n                System.out.print(ptr.coeff + \"x^\" + ptr.pow);\n                if(ptr.next != null)\n                System.out.print(\" + \");\n            }\n            System.out.println();\n        }\n    }\n}// } Driver Code Ends\n\n\n/*class Node{\n    int coeff;\n    int pow;\n    Node next;\n    Node(int a,int b)\n    {\n        coeff=a;\n        pow=b;\n        next=null;\n    }\n}*/\n\n//Print the polynomial formed by adding both LL in the function itself.\nclass Solution\n{\n    public static Node addPolynomial(Node p1,Node p2)\n    {\n        //Add your code here.\n        Node ans =new Node(-1,-1);\n        Node curr=ans;\n        Node temp1=p1;\n        Node temp2=p2;\n        while(temp1!=null && temp2!=null){\n            if(temp1.pow==temp2.pow){\n                temp1.coeff=temp1.coeff+temp2.coeff;\n                curr.next=temp1;\n                curr=curr.next;\n                temp1=temp1.next;\n                temp2=temp2.next;\n            }else if(temp2.pow<temp1.pow){\n                curr.next=temp1;\n                curr=curr.next;\n                temp1=temp1.next;\n            }else{\n                curr.next=temp2;\n                curr=curr.next;\n                temp2=temp2.next;\n            }\n        }\n        \n        if(temp1!=null){\n            curr.next=temp1;\n        }\n        if(temp2!=null){\n            curr.next=temp2;\n        }\n        \n        return ans.next;\n    }\n}"
  },
  {
    "path": "Positive Negative Pair",
    "content": "class Solution\n{\n    //Function to return list containing all the pairs having both\n    //negative and positive values of a number in the array.\n    public static ArrayList<Integer>findPairs(int arr[], int n) \n    { \n    \tArrayList< Integer > results = new ArrayList<>();\n        Set< Integer > set = new HashSet<>();\n        for (int a : arr) {\n            if (set.contains(-a)) {\n                int x = Math.abs(a);\n                results.add(-x);\n                results.add(x);\n            }\n            set.add(a);\n        }\n        return results;\n    }\n}\n"
  },
  {
    "path": "Postorder Traversal (Iterative).java",
    "content": "class Tree {\n    ArrayList<Integer> postOrder(Node node) {\n        // code here\n        Map<Node,Boolean> map=new HashMap<>();\n        Deque<Node> s=new ArrayDeque<>();\n        ArrayList<Integer> ans=new ArrayList<>();\n        if(node!=null){\n            s.push(node);\n            map.put(node,true);\n        }\n        if(node.right!=null){\n            s.push(node.right);\n            map.put(node.right,false);\n        }\n        if(node.left!=null){\n            s.push(node.left);\n            map.put(node.left,false);\n        }\n        while(!s.isEmpty()){\n            Node cur=s.pop();\n            if(map.get(cur)){\n                ans.add(cur.data);\n            }else{\n                s.push(cur);\n                if(cur.right!=null){\n                    s.push(cur.right);\n                    map.put(cur.right,false);\n                }\n                if(cur.left!=null){\n                    s.push(cur.left);\n                    map.put(cur.left,false);\n                }\n                map.put(cur,true);\n            }\n        }\n        return ans;\n        \n    }\n}\n"
  },
  {
    "path": "Postorder Traversal.py",
    "content": "class Solution:\n\t# @param A : root node of tree\n\t# @return a list of integers\n\tdef postorderTraversal(self, A):\n\t\tans=[]\n\t\tif A==None:\n\t\t\treturn ans\n\t\tstack=[(A,0)]\n\t\twhile len(stack)>0:\n\t\t\t(curr,vis)=stack.pop()\n\t\t\tif vis==1:\n\t\t\t\tans.append(curr.val)\n\t\t\telse:\n\t\t\t\tstack.append((curr,1))\n\t\t\t\tif curr.right!=None:\n\t\t\t\t\tstack.append((curr.right,0))\n\t\t\t\tif curr.left!=None:\n\t\t\t\t\tstack.append((curr.left,0))\n\t\treturn ans\n"
  },
  {
    "path": "Pots of Gold Game.java",
    "content": "class GfG\n{\n\tpublic static int maxCoins(int A[],int n)\n\t{\n          //add code here.\n          int[][]dp=new int[n+1][n+1];\n          return dfs(A,0,n-1,dp);\n    }\n    static int dfs(int[]A,int i,int j,int[][]dp){\n        if(i==j)return A[i];\n        if(i+1==j)return Math.max(A[i],A[j]);\n        if(dp[i][j]==0){\n            int start=A[i]+Math.min(dfs(A,i+2,j,dp),dfs(A,i+1,j-1,dp));\n            int end=A[j]+Math.min(dfs(A,i+1,j-1,dp),dfs(A,i,j-2,dp));\n            dp[i][j]=Math.max(start,end);\n        }\n        return dp[i][j];\n    }\n}\n"
  },
  {
    "path": "Power Of 2 and Subsequences GFG/powerOf2Sub.cpp",
    "content": "long long numberOfSubsequences(int N, long long A[]){\n         int mod=1e9+7;\n             long long count=0;\n             for(int i=0;i<N;i++){\n                 if((A[i]&A[i]-1)==0){\n                     count++;\n                 }\n             }\n             long long res=1;\n             for(int i=0;i<count;i++){\n                 res=(res*2)%mod;\n             }\n        return res-1;\n    }"
  },
  {
    "path": "Power Of 2 and Subsequences.cpp",
    "content": "    int mod = 1e9 + 7;\n    bool isPowerOfTwo(long long x){\n        return x && (!(x & (x - 1)));\n    }\n    long long numberOfSubsequences(int N, long long A[]){\n        // only numbers with power of 2 will give product as power of 2\n        \n        long long n = 0; // count of numbers of power of two in ans and \n    \n        for(int i=0;i<N;i++){\n            if(isPowerOfTwo(A[i])) n++;\n        }\n        \n        int ans = 1;\n        // our ans is nC1 + nC2 + ......... + nCn = 2^n - nC0 = 2^n - 1\n        \n        while(n--){\n            ans = (ans * 2) % mod; //finding 2^n\n        }\n        return ans - 1; // 2^n - 1\n    }\n"
  },
  {
    "path": "Power Of 2 and Subsequences.java",
    "content": "class Solution{\n    static Long numberOfSubsequences(int N, ArrayList<Long> A){\n        // code here\n        int cnt=0;\n        long mod=1000000007l;\n        for(Long i:A){\n            if((i&(i-1))==0){\n                cnt++;\n            }\n        }\n        return (long)(Math.pow(2,cnt)%mod-1)%mod;\n    }\n}\n"
  },
  {
    "path": "Power Of 2 and Subsequences.py",
    "content": "class Solution:\n    def numberOfSubsequences (ob,N,A):\n        import math\n        A2 = []\n        for i in A:\n            if math.ceil((math.log(i, 2) )) ==  math.floor((math.log(i, 2))):\n                A2.append(i)\n        n = len(A2)\n        return (2**n - 1) % (10**9+7)\n"
  },
  {
    "path": "Power of 2 and Subsequences.cpp",
    "content": "class Solution{   \npublic:\n    \n    long long numberOfSubsequences(int N, long long A[]){\n        // code here \n        long long ans = 0, MOD = 1e9+7;\n        \n        for(int i=0; i<N; i++)\n        {\n            long long temp = A[i];\n            bool f = true;\n            \n            while(temp > 1)\n            {\n                if(temp%2)\n                {\n                    f = false;\n                    break;\n                }\n                \n                temp /= 2;\n            }\n            \n            if(f)\n            {\n                ans *= 2;\n                ans++;\n                \n                ans %= MOD;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "Power of 2 and Subsequences.java",
    "content": "class Solution{\n    static Long numberOfSubsequences(int N, ArrayList<Long> A){\n        // code here\n        long m=(long)1e9+7;\n        long count=0;\n        for(int i=0;i<N;i++){\n            long num=A.get(i);\n            if((num & num-1)==0){\n               count++; \n            }\n        }\n        long ans=1;\n        while(count!=0){\n            ans=(ans*2)%m;\n            count--;\n        }\n        return ans-1;\n    }\n    \n}\n"
  },
  {
    "path": "Power-of-2-&-Subsequences/Solution.cpp",
    "content": "class Solution{\n    public:\n    long long numberOfSubsequences(int N, long long A[]){\n   \n        long long MOD = 1e9+7;\n        \n        long long t=0;\n        \n        for(int i=0 ; i<N ;i++)\n        {\n       \n            if((A[i] & A[i]-1)==0)\n            t++;\n        }\n    \n        long long ans = 1;\n        \n        while(t--)\n        ans = (ans*2)%MOD;\n        \n        if(t!=0)\n        return ans-1;\n        else\n        return 0;\n       \n    }\n \n};"
  },
  {
    "path": "Power-of-2-&-Subsequences/question.md",
    "content": "### Power Of 2 and Subsequences\n\n**Medium**Accuracy: **59.92%**Submissions: **1406**Points: **4**\n\nGiven is an array** A[]** of size  **N** . Return the number of non-empty subsequences such that the product of all numbers in the subsequence is  **Power of 2** . Since the answer may be too large, return it modulo 10^9^ + 7.\n\n**Example 1:**\n\n<pre><strong><span>Input:</span></strong>\n<span>N = 3\nA[] = {1, 6, 2}</span>\n<strong><span>Output:</span></strong>\n<span>3</span>\n<span><strong>Explanation:</strong></span>\n<span>The subsequence that </span>\n<span>can be chosen is {1},</span>\n<span>{2} and {1,2}.</span></pre>\n\n**Example 2:**\n\n<pre><strong><span>Input:</span></strong>\n<span>N = 3\nA[] = {3, 5, 7}</span>\n<strong><span>Output:</span></strong>\n<span>0</span>\n<strong><span>Explanation:</span></strong>\n<span>No subsequences exist.</span>\n</pre>\n\n**Your Task:**\n\nYou don't need to read input or print anything. Your task is to complete the function numberOfSubsequences() which takes an integer N and an array A and returns the number of subsequences that exist. As this number can be very large return the result under modulo 10 ^9^ +7.\n\n**Expected Time Complexity:** O(N)\n**Expected Auxiliary Space:** O(1)\n\n**Constraints:**\n1 <= N <= 10^5^\n1 <= A[i] <= 10^9^\n"
  },
  {
    "path": "Preorder Traversal.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    ArrayList<Integer> ans;\n    public ArrayList<Integer> preorderTraversal(TreeNode A) {\n        ans=new ArrayList<>();\n        pre(A);\n        return ans;\n    }\n    void pre(TreeNode root){\n        if(root==null)return;\n        ans.add(root.val);\n        pre(root.left);\n        pre(root.right);\n    }\n    \n}\n"
  },
  {
    "path": "Preorder to BST.java",
    "content": "public static Node post_order(int pre[], int size) \n{\n    //Your code here\n    Node root=new Node(pre[0]);\n    for(int i=1;i<size;i++){\n        root=dfs(pre[i],root);\n    }\n    return root;\n} \nstatic Node dfs(int key,Node head){\n    if(head==null){\n        Node node=new Node(key);\n        return node;\n    }\n    if(key<head.data){\n        head.left=dfs(key,head.left);\n    }else{\n        head.right=dfs(key,head.right);\n    }\n    return head;\n}\n"
  },
  {
    "path": "Previous number in one swap - GFG/README.md",
    "content": "# Previous number in one swap\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a non-negative number N in the form of string. The task is to apply at most one swap operation on the number N so that the result is just a previous possible number.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Note:&nbsp; </strong>Leading zeros are not allowed.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\">Example 1:</span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :\n</strong>S = \"12435\"\n<strong>Output: \n</strong>12345\n<strong>Explanation:\n</strong>Although the number 12354 \nwill be the largest smaller \nnumber from 12435. But it is \nnot possible to make it using \nonly one swap. So swap \n4 and 3 and get 12345.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\">Example 2:</span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: \n</strong>S = \" 12345\"\n<strong>Output: \n</strong>-1\n<strong>Explanation:\n</strong>Digits are in increasing order. \nSo it is not possible to \nmake a smaller number from it.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><strong><span style=\"font-size:18px\">Your Task:</span></strong></p>\n\n<p><span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function previousNumber() which takes the string S and returns the previous number of S. If no such number exists return -1;</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\">Expected Time Complexity: O(N)<br>\nExpected Auxiliary Space: O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n2&lt;=|Number length |&lt;=10<sup>5</sup></span></p>\n\n<p>&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Previous number in one swap - GFG/previous-number-in-one-swap.py",
    "content": "#User function Template for python3\nclass Solution:\n    def previousNumber (ob,S):\n        i=len(S)-2\n        while i>=0 and S[i]<=S[i+1]:\n            i-=1\n        if i<0:\n            return '-1'\n        j=len(S)-1\n        while j>i and S[i]<=S[j]:\n            j-=1\n        while j>0 and S[j-1]==S[j]:\n            j-=1\n        S=list(S)\n        S[i],S[j]=S[j],S[i]\n        if S[0]=='0':\n            return '-1';\n        return ''.join(S)\n        \n        \n\n#{ \n#  Driver Code Starts\n#Initial Template for Python 3\nif __name__ == '__main__': \n    t = int (input ())\n    for _ in range (t):\n        \n        S=str(input())\n\n        ob = Solution()\n        print(ob.previousNumber(S))\n# } Driver Code Ends"
  },
  {
    "path": "Prim's_Algorithm.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n    int m,n;\n    cin>>m>>n;\n    vector<pair<int,int>> adj[m];\n    for(int i =0;i<n;i++){\n        int x,y,w;\n        cin>>x>>y>>w;\n        adj[x].push_back({y,w});\n        adj[y].push_back({x,w});\n    }\n\n    vector<int> key(m,INT_MAX),parent(m,-1),mst(m,false);\n    key[0]=0;\n    parent[0]=-1;\n\n    for(int i =0;i<m-1;i++){\n        int mini=INT_MAX,u;\n        for(int i =0;i<m;i++){\n            if(key[i]<mini&&mst[i]==false){\n                mini = key[i];\n                u = i;\n            }\n        }\n        mst[u]=true;\n        for(auto it: adj[u]){\n            int v = it.first;\n            int weight = it.second;\n            if(mst[v]==false&&weight<key[v]){\n                parent[v] = u;\n                key[v]=weight;\n            }\n        }\n    }\n\n    for(int i =0;i<m;i++){\n        cout<<parent[i]<<\" -> \"<<i<<endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Prime Sum.java",
    "content": "public class Solution {\n    static boolean[] prime(int n) {\n        boolean isPrime[]=new boolean[n+1];\n        isPrime[0]=true;\n        isPrime[1]=true;\n        for(int i=2;i<=Math.sqrt(n);i++) {\n            for(int j=2*i;j<=n;j+=i) {\n                isPrime[j]=true;\n            }\n        }\n        return isPrime;\n    }\n    public ArrayList<Integer> primesum(int A) {\n        ArrayList<Integer> al=new ArrayList<>();\n        boolean a[]=prime(A);\n        for(int i=2;i<=A;i++){\n            if(a[i]==false && a[A-i]==false){\n                al.add(i);\n                al.add(A-i);\n                break;\n            }   \n        }\n        return al;\n    }\n}\n"
  },
  {
    "path": "Print Diagonally - GFG/README.md",
    "content": "# Print Diagonally\n## Easy\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Give a <strong>N * N</strong> square matrix <strong>A</strong>, return all the elements of its anti-diagonals from <strong>top to bottom</strong>. </span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> \nN = 2\nA = [[1, 2],\n     [3, 4]]\n<strong>Output:</strong>\n1 2 3 4\n<strong>Explanation:</strong> \n<img alt=\"\" src=\"https://media.geeksforgeeks.org/img-practice/ScreenShot2022-10-17at9-1665980852.png\">\n</span><span style=\"font-size:18px\">Hence, elements will be returned in the \norder {1, 2, 3, 4}.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: \n</strong>N = 3 \nA = [[1, 2, 3],\n     [4, 5, 6],\n     [7, 8, 9]]\n<strong>Output:</strong> \n1 2 4 3 5 7 6 8 9\n<strong>Explanation:</strong> \n<img alt=\"\" src=\"https://media.geeksforgeeks.org/img-practice/ScreenShot2022-10-17at9-1665980941.png\">\nHence, elements will be returned in \nthe order {1, 2, 4, 3, 5, 7, 6, 8, 9}.\n</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>downwardDigonal()</strong> which takes an integer <strong>N</strong> and a 2D matrix <strong>A[ ][ ]</strong> as input parameters and returns the list of all elements of its anti-diagonals from <strong>top to bottom</strong>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(N*N)<br>\n<strong>Expected Auxillary Space:&nbsp;</strong>O(N*N)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N, M ≤ 10<sup>3</sup><br>\n0 ≤ A[i][j] ≤ 10<sup>6</sup></span></p>\n</div>"
  },
  {
    "path": "Print Diagonally - GFG/print-diagonally.java",
    "content": "//{ Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n        \n        while(t-- > 0)\n        {\n            int n = sc.nextInt();\n            \n            int matrix[][] = new int[n][n];\n            \n            for(int i = 0; i < n; i++)\n            {\n                for(int j = 0; j < n; j++)\n                 matrix[i][j] = sc.nextInt();\n            }\n            Solution ob = new Solution();\n            ArrayList<Integer> ans = ob.downwardDigonal(n, matrix);\n            for (Integer val: ans) \n                System.out.print(val+\" \"); \n            System.out.println();\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static ArrayList<Integer> downwardDigonal(int N, int A[][])\n    {\n        // code here \n        ArrayList<Integer> ans=new ArrayList<>();\n        int row=0;\n        int col=0;\n        while(col<N){\n            int r=row;\n            int c=col;\n            while(r<N && c>=0){\n                ans.add(A[r][c]);\n                r++;\n                c--;\n            }\n            col++;\n        }\n        col=N-1;\n        row=1;\n        while(row<N){\n            int r=row;\n            int c=col;\n            while(r<N && c>=0){\n                ans.add(A[r][c]);\n                r++;\n                c--;\n            }\n            row++;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Print Pattern using String.java",
    "content": "class Solution{\n    static List<String> pattern(int n){\n        // code here\n        List<String> r=new ArrayList<>();\n        int first=1;\n        int end=n*(n+1);\n        int spaces=0;\n        for(int i=0;i<n;i++) {\n            String res=\"\";\n            for(int j=0;j<spaces;j++) {\n                res+=\"-\";\n            }\n            for(int j=first;j<=first+n-i-1;j++) {\n                res+=\"\"+j+\"*\";\n            }\n            for(int j=end-n+i+1;j<=end;j++) {\n                res+=\"\"+j+\"*\";\n            }\n            r.add(res.substring(0, res.length()-1));\n            spaces+=2;\n            first=first+n-i;\n            end=end-n+i;\n        }\n        return r;\n    }\n}\n"
  },
  {
    "path": "Print the pattern gfg sep_4.cpp",
    "content": "// 2 approaches \n\n\n// 1.\n#include<bits/stdc++.h>\nusing namespace std;\nclass Solution{\n    public:\n        vector<string> pattern(int n){\n        // code here\n        vector<string> res;\n        int cnt=1;\n        for(int i=0;i<n;i++){\n            string t=\"\";\n            for(int j=0;j<2*i;j++){\n                t.push_back('-');\n            }\n            for(int j=1;j<=n-i;j++){\n                t+=to_string(cnt++)+\"*\";\n            }\n            res.push_back(t);\n        }\n        \n        for(int i=n-1;i>=0;i--){\n            string t=\"\";\n            for(int j=n-1;j>=i;j--){\n                t+= to_string(cnt++)+\"*\";\n            }\n            t.pop_back();\n            res[i]+= t;\n        }\n        \n        return res;\n    }\n};\n\n\n// 2.\nclass Solution{\npublic:\n    vector<string> pattern(int n){\n        // code here\n        vector<string> v;\n        int curr=n, next=n*n+1;\n        for(int i=0;i<n;i++){\n            string s=\"\";\n            int tar=2*i;\n            while(tar--){\n                s += '-';\n            }\n            for(int k=curr-n+i+1;k<=curr;k++){\n                string t = to_string(k);\n                s += t;\n                s += '*';\n            }\n            for(int k=next;k<=next+n-i-1;k++){\n                string t = to_string(k);\n                s += t;\n                if(k==next+n-i-1)break;\n                s += '*';\n            }\n            curr += (n-i-1);\n            next -= (n-i-1);\n            v.push_back(s);\n        }\n        return v;\n    }\n};\n"
  },
  {
    "path": "Print the pattern.java",
    "content": "class Solution{\n    static List<String> pattern(int n){\n        // code here\n        int num=1;\n        List<String> ans=new ArrayList<>();\n        for(int row=0;row<n;row++){\n            StringBuilder sb=new StringBuilder();\n            \n            //print -\n            for(int times=0;times<row;times++){\n                sb.append(\"--\");\n            }\n            \n            //printing nums\n            for(int times=0;times<n-row;times++){\n                sb.append(num+\"*\");\n                num++;\n            }\n            ans.add(sb.toString());\n        }\n        \n        for(int row=n-1;row>=0;row--){\n            StringBuilder sb=new StringBuilder(ans.get(row));\n            for(int times=0;times<n-row;times++){\n                sb.append(num+\"*\");\n                num++;\n            }\n            sb.deleteCharAt(sb.length()-1);\n            ans.set(row,sb.toString());\n        }\n        return ans;\n    }\n} \n"
  },
  {
    "path": "Probability of Knight - GFG/README.md",
    "content": "# Probability of Knight\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an NxN chessboard and a Knight at position (x, y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. Find&nbsp;the probability that the Knight remains in the chessboard after taking K steps, with the condition that it cant enter the board again once it leaves it.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input : </strong>N = 8, x = 0, y = 0, K = 3\n<strong>Output: </strong>0.125000</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>N = 4, x = 1, y = 2, k = 4\n<strong>Output: </strong>0.024414</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:&nbsp;</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>findProb()&nbsp;</strong>which takes N, x, y and K as input parameter and returns the probability.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity :&nbsp;</strong>O(N <sup>3</sup>)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(N<sup>3</sup>)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N &lt;= 100<br>\n0 &lt;= x, y &lt;= N</span></p>\n\n<p><span style=\"font-size:18px\">0 &lt;= K &lt;= N</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Probability of Knight - GFG/probability-of-knight.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String s = br.readLine().trim();\n            String []S = s.split(\" \");\n            int N = Integer.parseInt(S[0]);\n            int start_x = Integer.parseInt(S[1]);\n            int start_y = Integer.parseInt(S[2]);\n            int step = Integer.parseInt(S[3]);\n            Solution ob = new Solution();\n            double ans = ob.findProb(N, start_x, start_y, step);\n            System.out.println(String.format(\"%.6f\", ans));           \n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n// code starts\n\nclass Solution\n{\n    public static boolean isValid(int ni, int nj, int n){\n      \n      if(ni>=0 && nj>=0 && ni<n && nj<n){\n          return true;\n      }else{\n          return false;\n      }\n    }\n    public double findProb(int N, int start_x, int start_y, int step){\n        double curr[][] = new double[N][N];\n        double next[][] = new double[N][N];\n \n        curr[start_x][start_y] = 1;\n \n        for (int m = 1; m<=step; m++){\n            for (int i = 0; i<N; i++){\n                for (int j = 0; j<N; j++){\n                    if(curr[i][j] != 0){\n                        int ni = 0;\n                        int nj = 0;\n                        ni = i-2;\n                        nj = j+1;\n                        if(isValid(ni, nj, N)){\n                            next[ni][nj] += curr[i][j]/8.0;\n                        }\n                    \n                        ni = i-1;\n                        nj = j+2;\n                        if(isValid(ni, nj, N)){\n                            next[ni][nj] += curr[i][j]/8.0;\n                        }\n                     \n                         ni = i+1;\n                         nj = j+2;\n                         if(isValid(ni, nj, N)){\n                             next[ni][nj] += curr[i][j]/8.0;\n                         }\n                         \n                         ni = i+2;\n                         nj = j+1;\n                         if(isValid(ni, nj, N)){\n                             next[ni][nj] += curr[i][j]/8.0;\n                         }\n                         \n                         ni = i+2;\n                         nj = j-1;\n                         if(isValid(ni, nj, N)){\n                             next[ni][nj] += curr[i][j]/8.0;\n                         }\n                         \n                         ni = i+1;\n                         nj = j-2;\n                         if(isValid(ni, nj, N)){\n                             next[ni][nj] += curr[i][j]/8.0;\n                         }\n                         \n                         ni = i-1;\n                         nj = j-2;\n                         if(isValid(ni, nj, N)){\n                             next[ni][nj] += curr[i][j]/8.0;\n                         }\n                         \n                        ni = i-2;\n                        nj = j-1;\n                        if(isValid(ni, nj, 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        }\n     \n       double sum = 0;\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}"
  },
  {
    "path": "Product of Digits.java",
    "content": "public class Solution {\n    public int solve(int A) {\n        String s=Integer.toString(A);\n        int product=1;\n        for(char c:s.toCharArray()){\n            product*=(c-48);\n        }\n        return product;\n    }\n}\n"
  },
  {
    "path": "Product of Primes - GFG/README.md",
    "content": "# Product of Primes\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two numbers <strong>L</strong> and <strong>R</strong> (inclusive) find the<strong> product of primes </strong>within this range. Print the product modulo <strong>10<sup>9</sup>+7</strong>.&nbsp;If there are no primes in that range you must print 1.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> L = 1, R = 10\n<strong>Output:</strong> 210\n<strong>Explaination:</strong> The prime numbers are \n2, 3, 5 and 7.</span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> L = 1, R = 20\n<strong>Output:</strong> 9699690\n<strong>Explaination:</strong> The primes are 2, 3, \n5, 7, 11, 13, 17 and 19.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>primeProduct()</strong> which takes L and R and returns the product of the primes within the range. If there are no primes&nbsp;in that range then return 1.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O((R-L)*(logR))<br>\n<strong>Expected Auxiliary Space:</strong> O(sqrt(R))</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ L ≤ R ≤ 10<sup>9</sup><br>\n0 ≤ L - R ≤ 10<sup>6</sup>&nbsp;&nbsp;</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Product of Primes - GFG/product-of-primes.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            String a[] = in.readLine().trim().split(\"\\\\s+\");\n            long L = Long.parseLong(a[0]);\n            long R = Long.parseLong(a[1]);\n            \n            Solution ob = new Solution();\n            System.out.println(ob.primeProduct(L, R));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static int mod=1000000007;\n    static long primeProduct(long L, long R){\n       // code here\n       long ans=1;\n       for(long i=L;i<=R;i++){\n           if(isPrime(i)){\n               ans=(ans%mod*i)%mod;\n           }\n       }\n       return ans;\n    }\n    static boolean isPrime(long n){\n        if(n<=1)\n            return false;\n        if(n==2)\n            return true;\n        for(long i=2;i<=Math.sqrt(n);i++){\n            if(n%i==0)\n                return false;\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "Profit Maximisation.java",
    "content": "public class Solution {\n    public int solve(int[] A, int B) {\n        PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());\n        for(int i:A){\n            pq.add(i);\n        }\n        int ans=0;\n        while(B>0){\n            int val=pq.remove();\n            ans+=val;\n            val--;\n            pq.add(val);\n            B--;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Pythagorean Triplets.java",
    "content": "public class Solution {\n    public int solve(int n) {\n        int ans=0;\n        for(int i=3;i<=n-2;i++){\n            for(int j=i+1;j<=n-1;j++){\n                for(int k=j+1;k<=n;k++){\n                    if(isTriplet(i,j,k))ans++;\n                }\n            }\n        }\n        return ans;\n    }\n\n    public boolean isTriplet(int a,int b,int c){\n        return (a*a)+(b*b)==c*c;\n    }\n}\n"
  },
  {
    "path": "Queries on Strings - GFG/README.md",
    "content": "# Queries on Strings\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string <strong>str</strong>&nbsp;you have to answer several queries on that string. In each query you will be provided two values <strong>L</strong> and <strong>R</strong> and you have to find the number of <strong>distinct</strong> characters in the sub string from index <strong>L</strong> to index <strong>R</strong>&nbsp;(inclusive) of the original string.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>str = \"abcbaed\",\nQuery = {{1,4},{2,4},{1,7}}\n<strong>Output: </strong>{3,2,5}\n<strong>Explanation: </strong>For the first query distinct \ncharacters from [1, 4] are a, b and c.\nFor the second query distinct characters from\n[2, 4] are b and c.\nFor the third query distinct characters from\n[1, 7] are a, b, c, d and e.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anyhting. Your task is to complete the function&nbsp;<strong>SolveQueries()&nbsp;</strong>which takes str and Query as input parameter and returns a list containing answer for each query.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(max(26*length of str, 26 * No of queries))<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(26 * length of str)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= |str| &lt;= 10<sup>5</sup><br>\n1 &lt;= No of Queries &lt;= 10<sup>4</sup><br>\n1 &lt;= L<sub>i</sub>&nbsp;&lt;= R<sub>i</sub>&nbsp;&lt;= |str|</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Queries on Strings - GFG/queries-on-strings.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String str = br.readLine().trim();\n            int q = Integer.parseInt(br.readLine().trim());\n            int[][] Query = new int[q][2];\n            for(int i = 0; i < q; i++){\n                String[] s = br.readLine().trim().split(\" \");\n                for(int j = 0; j < 2; j++){\n                    Query[i][j] = Integer.parseInt(s[j]);\n                }\n            }\n            Solution obj = new Solution();\n            int[] ans = obj.SolveQueris(str, Query);\n            for(int i = 0; i < ans.length; i++)\n                System.out.print(ans[i] + \" \");\n            System.out.println();\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n   public int[] SolveQueris(String str, int[][] Query)\n   {\n       Set<Character> set = new HashSet<>();\n       int a[]= new int[Query.length];\n       for(int i=0;i<Query.length;i++){\n           set.clear();\n           for(int j=Query[i][0]-1;j<Query[i][1];j++){\n               set.add(str.charAt(j));\n           }\n           a[i]=set.size();\n       }\n       return a;\n   }\n}"
  },
  {
    "path": "Queries on a Matrix.java",
    "content": "class Solution {\n    public int[][] solveQueries(int n, int[][] Queries) {\n        // Code here\n        int[][] mat = new int[n][n];\n        for(int[] q : Queries) {\n            int a=q[0];\n            int b=q[1];\n            int c=q[2];\n            int d=q[3];\n            for(int row=a;row<=c;row++){\n                mat[row][b]++;\n                if(d+1<n)mat[row][d+1]--;\n            }\n        }\n        for(int col=1;col<n;col++){\n            for(int row=0;row<n;row++){\n                mat[row][col]+=mat[row][col-1];\n            }\n        }\n        \n        return mat;\n    }\n}\n"
  },
  {
    "path": "Queue using two Stacks.java",
    "content": "class StackQueue\n{\n    Stack<Integer> s1 = new Stack<Integer>();\n    Stack<Integer> s2 = new Stack<Integer>();\n\n    //Function to push an element in queue by using 2 stacks.\n    void Push(int x)\n    {\n\t   // Your code here\n\t   s1.push(x);\n    }\n\t\n    \n    //Function to pop an element from queue by using 2 stacks.\n    int Pop()\n    {\n\t   // Your code here\n\t   while(s1.size()>0){\n\t       s2.push(s1.pop());\n\t   }\n\t   int num=-1;\n\t   if(s2.size()>0){\n\t       num=s2.pop();\n\t   }\n\t   while(s2.size()>0){\n\t       s1.push(s2.pop());\n\t   }\n\t   return num;\n    }\n}\n"
  },
  {
    "path": "QuickSort on Doubly Linked List.java",
    "content": "class GfG\n{\n    public static Node partition(Node l, Node h)\n    {\n        //code here.\n        Node pivot=l;\n        Node left=l;\n        Node right=h;\n        boolean flag=false;\n        while(!flag){       \n            while(left!=null && left.data<=pivot.data){\n                if(left==right)flag=true;\n                left=left.next;\n            }\n            while(right!=null && right.data>pivot.data){\n                if(right==left)flag=true;\n                right=right.prev;\n            }\n            if(!flag)swap(left,right);\n        }\n        swap(pivot,right);\n        return right;\n    }\n    static void swap(Node a,Node b){\n        int temp=a.data;\n        a.data=b.data;\n        b.data=temp;\n    }\n}\n"
  },
  {
    "path": "README.md",
    "content": "# DSA\n> Building the largest DSA solutions repository TOGETHER.\n\n# Note:\n> All DsA repositories are excluded from Hacktoberfest\n\n# Beginner's Guide\n<a href=\"https://www.youtube.com/watch?v=7r05126pOk8\" target=\"_blank\"><img src=\"https://i.ytimg.com/vi/7r05126pOk8/mqdefault.jpg\" height=\"200px\" border=\"20\"></a>\n\n---\n# 🔥Find your solution\n- Press \"T\" in windows/mac/linux to open the file finder.\n- Enter your problem name. We support only following naming formats to find files! Note: We are slowly migrating to normal word spacing format for new files, see [Contributing.md](https://github.com/Sagar0-0/DsA/blob/main/CONTRIBUTING.md).\n  - ### Old questions finding\n    - PascalCase (ThisIsTheExampleOfPascalCaseWritingWriting)\n    - Snake case (this_is_the_example_of_snake_case_writing)\n    - Caterpillar case (this-is-the-example-of-catarpillar-case-writing)\n    - Normal (A question name with proper words and spacings)\n    - Most of Leetcode Questions also have question numbers. Eg. 1007-minimum-domino-rotations-f...\n  - ### New questions finding\n    - Normal (A question name with proper words and spacings)\n    - Proper structure with folders/directories according to coding platforms.\n- If exists, select your solution file according to your programming language.\n- If your problem's solution doesn't exist\n  - Either create an new [Issue](https://github.com/Sagar0-0/DsA/issues) and request public to solve it for you.(Coming soon...)\n  - Or [Contribute](https://github.com/Sagar0-0/DsA/pulls) it by yourself🔥\n\n---\n\n# ✅Open To Contribute \n- Start your open source journey with us🚀\n- Share your code with the world✨\n- Become an active member🔥\n- Contribute and get Appreciated🤝\n- Must read [CONTRIBUTING.md](https://github.com/Sagar0-0/DsA/blob/main/CONTRIBUTING.md) before contributing.\n\n> *No more DSA contributions from my side.*\n---\n\n# ➡️Platforms covered:\n<a href=\"https://leetcode.com/problemset/all/\">\n<img src=\"https://assets.leetcode.com/static_assets/public/webpack_bundles/images/logo-dark.e99485d9b.svg\" width=500px>\n</a>\n\n<br>\n<br>\n<br>\n\n<a href=\"https://practice.geeksforgeeks.org/explore?page=1&sortBy=submissions\">\n<img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200817185016/gfg_complete_logo_2x-min.png\" width=500px>\n</a>\n\n<br>\n<br>\n<br>\n\n<a href=\"https://www.interviewbit.com/coding-interview-questions/#difficulties[]=medium&difficulties[]=hard&status[]=unsolved\">\n<img src=\"https://assets.interviewbit.com/packs/images/logo.87a398.svg\" width=500px>\n</a>\n\n<br>\n<br>\n<br>\n\n---\n\n# ✅Contributors\n> Thanks to these amazing contributors who helps us in building the LARGEST DSA SOLUTIONS REPOSITORY\n\n<a href=\"https://github.com/Sagar0-0/DsA/graphs/contributors\">\n  <img src=\"https://contrib.rocks/image?repo=Sagar0-0/DsA\" />\n</a>\n\n---\n\n## Love my work?\n<a href=\"https://www.buymeacoffee.com/0sagar0\">\n<img src=\"https://user-images.githubusercontent.com/85388413/197355117-e4a5f6e7-44ee-4303-adb8-3ef39cd18246.jpg\" width=200px>\n</a>\n\n\n# ☕My Coding Profiles:\n<a href=\"https://leetcode.com/sagar0_0/\">\n<img src=\"https://assets.leetcode.com/static_assets/public/webpack_bundles/images/logo-dark.e99485d9b.svg\" width=200px>\n</a>\n\n<br>\n<br>\n\n<a href=\"https://auth.geeksforgeeks.org/user/0sagar0/practice\">\n<img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200817185016/gfg_complete_logo_2x-min.png\" width=200px>\n</a>\n\n<br>\n<br>\n\n<a href=\"https://www.interviewbit.com/profile/sagar0_0\">\n<img src=\"https://assets.interviewbit.com/packs/images/logo.87a398.svg\" width=200px>\n</a>\n"
  },
  {
    "path": "Rank The Permutations - GFG/README.md",
    "content": "# Rank The Permutations\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string, find the rank of the string amongst its permutations sorted lexicographically.&nbsp;</span><br>\n<br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nS = \"abc\"</span>\n<span style=\"font-size:18px\"><strong>Output:</strong>\n1</span>\n<strong><span style=\"font-size:18px\">Explanation:</span></strong>\n<span style=\"font-size:18px\">The order permutations with letters \n'a', 'c', and 'b' : \nabc\nacb\nbac\nbca\ncab\ncba</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nS = \"acb\"</span>\n<span style=\"font-size:18px\"><strong>Output:</strong>\n2</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your&nbsp;task is to complete the function&nbsp;<strong>findRank()</strong>&nbsp;which takes the string&nbsp;<strong>S</strong>&nbsp;as input parameter&nbsp;and returns the rank of the string amongst its permutations.</span><br>\n<span style=\"font-size:18px\">It is guaranteed no characters are repeated in the string.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(|S|*26)<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(|S|)</span><br>\n<span style=\"font-size:18px\"><strong>Note:</strong>&nbsp;|S| represents the length of string S.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 ≤ |S| ≤ 18</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Rank The Permutations - GFG/rank-the-permutations.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String str = br.readLine().trim();\n            Solution obj = new Solution();\n            long ans = obj.findRank(str);\n            System.out.println(ans);\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n    public long findRank(String s){\n        // Code here\n        if(s.length()==0){\n            return 0;\n        }\n        long  res=1;\n        for(int i=0; i<s.length()-1; i++){\n            long cou=0;\n            for(int j=i+1; j<s.length(); j++){\n                if(s.charAt(i) > s.charAt(j)){\n                    cou++;\n                }\n            }\n            res += cou * fact(s.length()-1-i);\n        }\n        return res;\n    }\n    long fact(int n){\n        if(n<=1){\n            return 1;\n        }\n        return n * fact(n-1);\n    }\n}"
  },
  {
    "path": "Rat Maze With Multiple Jumps - GFG/README.md",
    "content": "# Rat Maze With Multiple Jumps\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">A Maze is given as <strong>n*n</strong>&nbsp;matrix of blocks where source block is the upper left most block i.e., <strong>matrix[0][0]</strong> and destination block is lower rightmost block i.e., <strong>matrix[n-1][n-1]</strong>. A rat starts from source and has to reach the destination. The rat can move in only two directions: first forward if possible or down. If multiple solutions exist, the shortest earliest hop will be accepted. For the same hop distance at any point, forward will be preferred over downward. In the maze matrix, 0 means the block is the dead end and non-zero number means the block can be used in the path from source to destination. The non-zero value of mat[i][j] indicates number of maximum jumps rat can make from cell mat[i][j]. In this variation, Rat is allowed to jump multiple steps at a time instead of 1. Find a matrix which describes the position the rat to reach at the destination.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>{{2,1,0,0},{3,0,0,1},{0,1,0,1},\n{0,0,0,1}}\n<strong>Output: </strong>{{1,0,0,0},{1,0,0,1},{0,0,0,1},\n{0,0,0,1}}\n<strong>Explanation: </strong>Rat started with matrix[0][0] and \ncan jump up to 2 steps right/down. First check \nmatrix[0][1] as it is 1, next check \nmatrix[0][2] ,this won't lead to the solution. \nThen check matrix[1][0], as this is 3(non-zero)\n,so we can make 3 jumps to reach matrix[1][3]. \nFrom matrix[1][3] we can move downwards taking \n1 jump each time to reach destination at \nmatrix[3][3].</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>{{2,1,0,0},{2,0,0,1},{0,1,0,1},\n{0,0,0,1}}\n<strong>Output:</strong> {{-1}}\n<strong>Explanation: </strong>As no path exists so, -1.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anyhting, Your task is to complete the function&nbsp;<strong>ShortestDistance()&nbsp;</strong>which takes the matrix as input parameter and returns a matrix of size n if path exists otherwise returns a matrix of 1x1 which contains -1. In output matrix, 1&nbsp;at (i, j) represents the cell is taken into the path otherwise 0 if any path exists.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(n*n*k) where k is max(matrix[i][j])<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(1)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n &lt;= 50<br>\n1 &lt;= matrix[i][j] &lt;= 20</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Rat Maze With Multiple Jumps - GFG/rat-maze-with-multiple-jumps.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            int n = Integer.parseInt(br.readLine().trim());\n            int[][] matrix = new int[n][n];\n            for(int i = 0; i < n; i++){\n                String[] S = br.readLine().trim().split(\" \");\n                for(int j = 0; j < n; j++)\n                    matrix[i][j] = Integer.parseInt(S[j]);\n            }\n            Solution ob = new Solution();\n            int[][] ans = ob.ShortestDistance(matrix);\n            for(int i = 0; i < ans.length; i++){\n                for(int j = 0; j < ans[i].length; j++){\n                    System.out.print(ans[i][j] + \" \");\n                }\n                System.out.println();\n            }\n        }\n    }\n}\n// } Driver Code Ends\n\n\nclass Solution\n{\n    public int[][] ShortestDistance(int[][] matrix){\n        // Code here\n        int m= matrix.length;\n        int n= matrix[0].length;\n        \n        if(matrix[0][0]==0 && n!=1){\n\t        int ans[][]={{-1}};\n            return ans;\n\t    }\n\t    int ans[][] = new int[m][n];\n        if(solver(matrix, ans,0,0)==false){\n            ans[0][0]=-1;\n            return ans;\n        }\n        return ans;\n    }\n    \n    public boolean solver(int[][] matrix,int[][] ans,int i,int j){\n        if(i==matrix.length-1 && j==matrix[0].length-1){\n            ans[i][j]=1;\n            return true;\n        }\n        if(isValid(i,j,matrix)){\n            ans[i][j] = 1;\n            for(int k=1;k<=matrix[i][j] && k<matrix.length;k++){\n                if(solver(matrix,ans,i,j+k)) return true;\n                if(solver(matrix,ans,i+k,j)) return true;\n            }\n            ans[i][j]=0;\n            return false;\n        }\n        return false;\n    }\n    \n    public boolean isValid(int x,int y,int[][] matrix){\n        if(x>=matrix.length || y>=matrix[0].length||matrix[x][y]==0){\n            return false;\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "Reaching the heights - GFG/README.md",
    "content": "# Reaching the heights\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">The teacher gives a mental ability question to Raju. The question is as follows:-</span></p>\n\n<p><span style=\"font-size:18px\">Raju is in an elevator. Given by his teacher is an array of size N which denotes the number of floors and has a 1 based indexing. The elevator starts from the ground and moves up and down, X and Y floors respectively. There is a code used in the elevator according to which it moves up X floors given at odd indexes of the array and moves down Y floors given at even indexes of the array. He is asked to go to the highest floor possible. Help him to sort the array such that he reaches the highest floor after traversing the whole array from starting till the end, without skipping any index.</span></p>\n\n<p><span style=\"font-size:18px\">He always prefers to move more number of floors up and less number of floors down. Once he gets into the elevator, the elevator should not reach the ground again, if it does print Not Possible.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[ ] = {2, 3, 4, 5}\n<strong>Output :</strong> 5 2 4 3\n<strong>Explanation:</strong>\nArray can be arranged as {5,3,4,2} or \n{4,3,5,2} or {4,2,5,3} but it will get \narranged as {5,2,4,3} because he always \nprefer to move more number of floors up \nand less number of floors down.\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[ ] = {1, 1} <strong>\nOutput :</strong>  Not Possible </span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function <strong>game_with_number()</strong> that takes sizeOfArray <strong>(n)</strong>, an array <strong>(arr)</strong>, and return the sorted array or if it is Not Possible return <strong>-1</strong>. The driver code takes care of the printing.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N*LOG(N)).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(1).</span></p>\n\n<p>&nbsp;</p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong></span></p>\n\n<p><span style=\"font-size:18px\">1&nbsp;≤&nbsp;N ≤&nbsp;10<sup>5</sup><br>\n1&nbsp;≤ arr[i]&nbsp;≤&nbsp;10<sup>3</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Reaching the heights - GFG/reaching-the-heights.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\n\nclass Array {\n    \n    // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t    String line = br.readLine();\n\t\t    String[] element = line.trim().split(\"\\\\s+\");\n\t\t    int N = Integer.parseInt(element[0]);\n\t\t    int arr [] = new int[N];\n\t\t    line = br.readLine();\n\t\t    String[] elements = line.trim().split(\"\\\\s+\");\n\t\t    for(int i = 0;i<N;i++){\n\t            arr[i] = Integer.parseInt(elements[i]);    \n\t        }\n\t\t    \n\t\t    \n\t\t    Complete obj = new Complete();\n\t\t    ArrayList<Integer> ans;\n\t\t    ans = obj.reaching_height(N, arr);\n        \t\n        \tif(ans.size() == 1 && ans.get(0) == -1){\n        \t    System.out.println(\"Not Possible\");\n        \t    continue;\n        \t}\n        \t\n        \tfor(int i: ans)\n        \t    System.out.print(i + \" \");\n        \tSystem.out.println();\n\t\t}\n\t}\n}\n\n\n\n\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n//2 4 10\n//10 2 4\n\n\n\nclass Complete{\n    \n   \n    // Function for finding maximum and value pair\n    public static ArrayList<Integer> reaching_height (int n, int arr[]) {\n        //Complete the function\n        ArrayList<Integer> ans=new ArrayList<>();\n        Arrays.sort(arr);\n        int flag=0;\n        \n        int end=arr.length-1;\n        int start=0;\n        while(end>=start){\n            ans.add(arr[end]);\n            flag+=arr[end];\n            if(end!=start){\n                ans.add(arr[start]);\n                flag-=arr[start];\n            }\n            end--;\n            start++;\n        }\n        if(flag==0){\n            ans.clear();\n            ans.add(-1);\n        }\n        \n        return ans;\n    }\n    \n    \n}\n"
  },
  {
    "path": "Rearrange Geek and his Classmates.java",
    "content": "class Solution \n{ \n    void prank(long[] a, int n)  \n    { \n        for(int i=0;i<n;i++){\n            a[i]=a[i]+(a[(int)a[i]]%n)*n;\n        }\n        for(int i=0;i<n;i++)\n            a[i]/=n;\n   }\n} \n\n\n===================================================================\n    \n    class Solution \n{ \n    void prank(long[] a, int n)  \n    { \n       // code here\n       long[] b=new long[n];\n       for(int i=0;i<n;i++){\n           long temp=a[i];\n           b[i]= a[(int)temp];\n          }\n       for(int i=0;i<n;i++)\n       {\n           a[i]=b[i];\n       }\n      \n   }\n} \n"
  },
  {
    "path": "Recursively remove all adjacent duplicates - GFG/README.md",
    "content": "# Recursively remove all adjacent duplicates\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string s, remove all its adjacent duplicate characters recursively.&nbsp;</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nS = \"geeksforgeek\"\n<strong>Output:</strong> \"gksforgk\"\n<strong>Explanation: </strong>\ng(ee)ksforg(ee)k -&gt; gksforgk</span></pre>\n\n<p><br>\n<strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: \n</strong>S = \"abccbccba\"\n<strong>Output:</strong> \"\"\n<strong>Explanation: \n</strong>ab(cc)b(cc)ba-&gt;abbba-&gt;a(bbb)a-&gt;aa-&gt;(aa)-&gt;\"\"(empty string)</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>remove()</strong> which takes the string S as input parameter and returns the resultant string.<br>\n<strong>Note:</strong> For some test cases, the resultant string would be an <strong>empty</strong> string. For that case, the function should return the empty string only.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(|S|)<br>\n<strong>Expected Auxiliary Space:</strong> O(|S|)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1&lt;=|S|&lt;=10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Recursively remove all adjacent duplicates - GFG/recursively-remove-all-adjacent-duplicates.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main (String[] args) throws IOException {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases\n        while(t-->0){\n            String S = br.readLine();\n            Solution ob = new Solution();\n            System.out.println(ob.remove(S));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    String remove(String s) {\n        if(s.length()<=1) return s;\n        StringBuilder str = new StringBuilder();\n        for(int i =0;i<s.length()-1;i++){\n            if(s.charAt(i)==s.charAt(i+1) ){\n                int j =i;\n                while(j<s.length() && s.charAt(i)==s.charAt(j) ) j++;\n                i=j-1;\n            }else str.append(s.charAt(i));\n        }\n        if(s.charAt(s.length()-2)!=s.charAt(s.length()-1)) str.append(s.charAt(s.length()-1));\n        if(s.length()==str.length()) return s;\n        return remove(str.toString());\n   }\n}"
  },
  {
    "path": "Redundant Braces.java",
    "content": "public class Solution {\n    public int braces(String s) {\n        Deque<Character> stack=new ArrayDeque<>();\n        int n=s.length();\n        for(int i=0;i<n;i++){\n            if(s.charAt(i)!=')'){\n                stack.push(s.charAt(i));\n            }else{\n                int count=0;\n                while(stack.size()>0){\n                    char ch=stack.pop();\n                    if(ch=='(')break;\n                    if(ch=='+' || ch=='-' || ch=='*' || ch=='/'){\n                        count++;\n                    }\n                }\n                if(count==0)return 1;\n            }\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Region in BinaryMatrix.java",
    "content": "public class Solution {\n    int[][]arr;\n    boolean[][]vis;\n    public int solve(int[][] A) {\n        arr=A;\n        int n=A.length;\n        int m=A[0].length;\n        vis=new boolean[n][m];\n        int ans=0;\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(A[i][j]==1 && vis[i][j]==false){\n                    int curr=dfs(i,j);\n                    ans=Math.max(ans,curr);\n                }\n            }\n        }\n        return ans;\n    }\n    public int dfs(int i,int j){\n        if(i<0 || j<0)return 0;\n        if(i==arr.length || j==arr[0].length)return 0;\n        if(arr[i][j]==0)return 0;\n        if(vis[i][j]==false){\n            vis[i][j]=true;\n            int val=1+dfs(i+1,j)+dfs(i,j+1)+dfs(i-1,j)+dfs(i,j-1)+dfs(i-1,j-1)+dfs(i+1,j+1)+dfs(i+1,j-1)+dfs(i-1,j+1);\n            return val;\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "Remove Consecutive Characters.java",
    "content": "public class Solution {\n    public String solve(String A, int B) {\n\n\n        int count=1;\n        String res=\"\";\n        for(int i=0;i<A.length()-1;i++){\n\n            if(A.charAt(i) == A.charAt(i+1))\n                count++;\n            else{\n                if(count%B !=0)\n                    res += A.charAt(i);\n                count = 1;\n            }\n        }\n        if(count ==1 || count>B)\n            res += A.charAt(A.length()-1);\n        return res;        \n    }\n}\n"
  },
  {
    "path": "Remove Covered Intervals.java",
    "content": "class Solution {\n    public int removeCoveredIntervals(int[][] nums) {\n        Arrays.sort(nums, new Comparator<int[]>() {\n            public int compare(int[] o1, int[] o2){\n                if(o1[0]==o2[0])return o2[1]-o1[1];\n                return o1[0]-o2[0];\n        }});\n        int count = 0, cur = 0;\n        for(int interval[] : nums){\n            if(cur < interval[1]){\n                cur = interval[1];\n                count++;\n            }\n        }\n        return count;\n    }\n}\n"
  },
  {
    "path": "Remove Duplicates from Sorted Array II.java",
    "content": "class Solution {\n    public int removeDuplicates(int[] nums) {\n        int count=1;\n        int i=0;\n        int j=1;\n        while(j<nums.length){\n            if(nums[i]==nums[j]){\n                if(count<2){\n                    i++;\n                    nums[i]=nums[j];\n                    count++;\n                }\n            }else{\n                i++;\n                count=1;\n                nums[i]=nums[j];\n            }\n            j++;\n        }\n        return i+1;\n    }\n}\n\n\n\n//====================================================================================\n  \n//faster\nclass Solution {\n    public int removeDuplicates(int[] nums) {\n        int count=0;\n        for(int i=1;i<nums.length;i++){\n            if(nums[count] != nums[i] || (count-1<0 || nums[count-1] != nums[i])){\n                nums[++count] = nums[i];\n            } \n        }\n        return count+1;\n    }\n}\n\n//=========================================================\npublic class Solution {\n\tpublic int removeDuplicates(ArrayList<Integer> a) {\n        int extras=0;\n        int i=0;\n        int x=0;\n        while(i<a.size()){\n            int cnt=1;\n            int j=i+1;\n            while(j<a.size() && Objects.equals(a.get(j), a.get(i))){\n                cnt++;\n                j++;\n            }\n            if(cnt>1){\n                a.set(x,a.get(i));\n                x++;\n                a.set(x,a.get(i));\n                x++;\n                i=j;\n                extras+=cnt-2;\n            }else{\n                a.set(x,a.get(i));\n                x++;\n                i=j;\n            }\n        }\n        return a.size()-extras;\n\t}\n}\n"
  },
  {
    "path": "Remove Duplicates from Sorted List II.java",
    "content": "class Solution {\n    public ListNode deleteDuplicates(ListNode head) {\n        // sentinel\n        ListNode sentinel = new ListNode(0, head);\n\n        // predecessor = the last node \n        // before the sublist of duplicates\n        ListNode pred = sentinel;\n        \n        while (head != null) {\n            if (head.next != null && head.val == head.next.val) {\n                while (head.next != null && head.val == head.next.val) {\n                    head = head.next;    \n                }\n                pred.next = head.next;     \n            } else {\n                pred = pred.next;    \n            }\n            head = head.next;    \n        }  \n        return sentinel.next;\n    }\n}\n"
  },
  {
    "path": "Remove Duplicates from Sorted List.java",
    "content": "public class Solution {\n    public ListNode deleteDuplicates(ListNode A) {\n        ListNode temp=A;\n        while(temp.next!=null){\n            if(temp.val==temp.next.val){\n                temp.next=temp.next.next;\n            }else{\n                temp=temp.next;\n            }\n        }\n        return A;\n    }\n}\n"
  },
  {
    "path": "Remove Half Nodes.java",
    "content": "public class Solution {\n    public TreeNode solve(TreeNode A) {\n        if(A==null)return A;\n        if(A.left!=null && A.right!=null){\n            A.left=solve(A.left);\n            A.right=solve(A.right);\n        }else if(A.left!=null){\n            A=solve(A.left);\n        }else if(A.right!=null){\n            A=solve(A.right);\n        }\n        return A;\n    }\n}\n"
  },
  {
    "path": "Remove K Digits.java",
    "content": "class Solution {\n    public String removeKdigits(String num, int k) {\n        Deque<Character> stack = new ArrayDeque<>();\n        for(char c : num.toCharArray()){\n            while(!stack.isEmpty() && k > 0 && stack.peek() > c) {\n                stack.pop();\n                k--;\n            }   \n            stack.push(c);   \n        }\n        while(!stack.isEmpty() && k > 0){\n            stack.pop();\n            k--;\n        }\n        StringBuilder sb = new StringBuilder();\n        while(!stack.isEmpty()){\n            sb.append(stack.pop());\n        }\n        sb.reverse();\n        while(sb.length() > 1 && sb.charAt(0) == '0'){\n            sb.deleteCharAt(0);\n        }\n        return sb.length() > 0 ? sb.toString() : \"0\";\n    }\n}\n"
  },
  {
    "path": "Remove Nth Node from List End.java",
    "content": "public class Solution {\n    public ListNode removeNthFromEnd(ListNode A, int B) {\n        int size=0;\n        ListNode temp=A;\n        while(temp!=null){\n            size++;\n            temp=temp.next;\n        }\n        if(B>=size)return A.next;\n        int toGo=size-B;\n        temp=A;\n        for(int i=1;i<toGo;i++){\n            temp=temp.next;\n        }\n        if(temp.next==null){\n            return A;\n        }\n        temp.next=temp.next.next;\n        return A;\n    }\n}\n"
  },
  {
    "path": "Remove leading zeros from an IP address.java",
    "content": "class Solution\n{\n    public String newIPAdd(String S)\n    {\n        // your code here\n        String[]arr=S.split(\"\\\\.\");\n        for(int j=0;j<arr.length;j++){\n            String s=arr[j];\n            int index=-1;\n            for(int i=0;i<s.length();i++){\n                if(s.charAt(i)!='0'){\n                    index=i;\n                    break;\n                }\n            }\n            if(index==-1){\n                arr[j]=\"0\";\n            }else{\n                arr[j]=s.substring(index,s.length());\n            }\n        }\n        S=\"\";\n        S+=arr[0];\n        for(int i=1;i<arr.length;i++){\n            S+=\".\"+arr[i];\n        }\n        return S;\n    }\n}\n"
  },
  {
    "path": "Repeat and Missing Number Array.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public int[] repeatedNumber(final int[] A) {\n\n        long sum, actsum, sqsum, actsqsum;\n        sum = actsum = sqsum = actsqsum = 0;\n        for(long i : A){\n            actsum += i;\n            actsqsum += i*i;\n        }\n        long n = A.length;\n        sum = (n * (n+1))/2;\n        sqsum = (n*(n+1)*(2*n+1))/6;\n\n        long  x = sum - actsum;\n        long  y = (sqsum - actsqsum)/x;\n        long  a = (x+y)/2;\n        long  b = a - x;\n        int [] out = {(int)b,(int)a};\n    \n        return out;\n\n    }\n\n}\n\n"
  },
  {
    "path": "Repeated Character.java",
    "content": "//O(n)\n//O(n)\nclass Solution\n{\n    char firstRep(String S)\n    {\n        // your code here\n        Map<Character,Integer> map=new HasMap<>();\n        for(char c:S.toCharArray())map.put(c,map.getOrDefault(c,0)+1);\n        \n        for(int i=0;i<S.length();i++){\n            char c=S.charAt(i);\n            if(map.get(c)>1)return c;\n        }\n        return '#';\n        \n    }\n}\n\n//O(n)\n//O(1)\nclass Solution\n{\n    char firstRep(String S)\n    {\n        \n        for(int i=0;i<S.length();i++){\n            char c=S.charAt(i);\n            String temp=S.substring(i+1);\n            if(temp.indexOf(c)!=-1){\n                return c;\n            }\n        }\n        return '#';\n        \n    }\n}\n"
  },
  {
    "path": "Replace every element with the least greater element on its right - GFG/README.md",
    "content": "# Replace every element with the least greater element on its right\n## Medium\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Given an array <strong>arr[]</strong> of <strong>N</strong> integers and replace every element with the least greater element on its right side in the array. If there are no greater elements on the right side, replace it with <strong>-1.</strong>&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\narr[] = {8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28}\n<strong>Output: </strong>{18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1}\n<strong>Explanation:</strong> \nThe least next greater element of 8 is 18.\nThe least next greater element of 58 is 63 and so on.\n\n</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\narr[] = {2, 6, 9, 1, 3, 2}\n<strong>Output: </strong>{3, 9, -1, 2, -1, -1}\n<strong>Explanation:</strong> \nThe least next greater element of 2 is 3. \nThe least next greater element of 6 is 9.\nleast next greater element for 9 does not\nexist and so on.\n</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>findLeastGreater</strong>()&nbsp;which takes an array <strong>arr[]</strong> of size <strong>N</strong>&nbsp;and returns a&nbsp;list as an output.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N* log N)<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= N &lt;= 10<sup>5</sup><br>\n1&nbsp;&lt;= A[i] &lt;= 10<sup>5</sup></span></p>\n</div>"
  },
  {
    "path": "Replace every element with the least greater element on its right - GFG/replace-every-element-with-the-least-greater-element-on-its-right.java",
    "content": "//{ Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\n\nclass IntArray\n{\n    public static int[] input(BufferedReader br, int n) throws IOException\n    {\n        String[] s = br.readLine().trim().split(\" \");\n        int[] a = new int[n];\n        for(int i = 0; i < n; i++)\n            a[i] = Integer.parseInt(s[i]);\n        \n        return a;\n    }\n    \n    public static void print(int[] a)\n    {\n        for(int e : a)\n            System.out.print(e + \" \");\n        System.out.println();\n    }\n    \n    public static void print(ArrayList<Integer> a)\n    {\n        for(int e : a)\n            System.out.print(e + \" \");\n        System.out.println();\n    }\n}\n\nclass GFG {\n    public static void main(String[] args) throws IOException {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int t;\n        t = Integer.parseInt(br.readLine());\n        while(t-- > 0){\n            \n            int n; \n            n = Integer.parseInt(br.readLine());\n            \n            \n            int[] arr = IntArray.input(br, n);\n            \n            Solution obj = new Solution();\n            ArrayList<Integer> res = obj.findLeastGreater(n, arr);\n            \n            IntArray.print(res);\n            \n        }\n    }\n}\n\n// } Driver Code Ends\n\n\nclass Solution {\n    public static ArrayList<Integer> findLeastGreater(int n, int[] arr) {\n        // code here\n        TreeSet<Integer> set=new TreeSet<>();\n        ArrayList<Integer> ans =new ArrayList<>();\n        for(int i=n-1;i>=0;i--){\n            set.add(arr[i]);\n            if(set.higher(arr[i])==null)ans.add(-1);\n            else ans.add(set.higher(arr[i]));\n        }\n        Collections.reverse(ans);\n        return ans;\n    }\n}\n        \n"
  },
  {
    "path": "Return two prime numbers.java",
    "content": "class Solution{\n    static Set<Integer> set=new HashSet<>();\n    \n    static List<Integer> primeDivision(int n){\n        // code here\n        List<Integer> ans=new ArrayList<>();\n        for(int i=2;i<n;i++){\n            if(set.contains(i) || isPrime(i)){\n                if(set.contains(n-i) || isPrime(n-i)){\n                    ans.add(i);\n                    ans.add(n-i);\n                    break;\n                }\n            }\n        }\n        return ans;\n    }\n    \n    static boolean isPrime(int n){\n        // Corner cases\n        if (n <= 1)\n            return false;\n        if (n <= 3){\n            set.add(n);\n            return true;\n        }\n  \n        // This is checked so that we can skip\n        // middle five numbers in below loop\n        if (n % 2 == 0 || n % 3 == 0)\n            return false;\n  \n        for (int i = 5; i * i <= n; i = i + 6)\n            if (n % i == 0 || n % (i + 2) == 0)\n                return false;\n        \n        set.add(n);\n        return true;\n    }\n}\n"
  },
  {
    "path": "Reverse Bits.java",
    "content": "class Solution:\n    # @param A : unsigned integer\n    # @return an unsigned integer\n    def reverse(self, A):\n        #bit manipulation\n        ans = 0\n        for i in range(32):\n            ans = (ans << 1) | (A&1)\n            A = A >> 1\n        return ans\n"
  },
  {
    "path": "Reverse First K elements of Queue",
    "content": "public Queue<Integer> modifyQueue(Queue<Integer> q, int k) {\n        // using a stack and another queue to reverse first k elements.\n        Stack<Integer> s = new Stack<>();\n        Queue<Integer> qq = new LinkedList<>();\n\n        // we pop first k elements from queue and push it in the stack.\n        while (k-- > 0) {\n            int a = q.peek();\n            q.poll();\n            s.push(a);\n        }\n        // while stack is not empty, we push the elements into the new queue.\n        while (!s.isEmpty()) {\n            int a = s.peek();\n            s.pop();\n            qq.add(a);\n        }\n        // then we add rest of the elements of original queue to the new queue.\n        while (!q.isEmpty()) {\n            int a = q.peek();\n            q.poll();\n            qq.add(a);\n        }\n        // returning the new queue.\n        return qq;\n    }\n"
  },
  {
    "path": "Reverse Level Order.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\n import java.util.*;\npublic class Solution {\n    public ArrayList<Integer> solve(TreeNode node) {\n        ArrayList<Integer> list=new ArrayList<>();\n        Stack<TreeNode> S = new Stack();\n        Queue<TreeNode> Q = new LinkedList();\n        Q.add(node);\n  \n        // Do something like normal level order traversal order.Following\n        // are the differences with normal level order traversal\n        // 1) Instead of printing a node, we push the node to stack\n        // 2) Right subtree is visited before left subtree\n        while (Q.isEmpty() == false)\n        {\n            /* Dequeue node and make it root */\n            node = Q.peek();\n            Q.remove();\n            S.push(node);\n  \n            /* Enqueue right child */\n            if (node.right != null)\n                // NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT\n                Q.add(node.right);\n                 \n            /* Enqueue left child */\n            if (node.left != null)\n                Q.add(node.left);\n        }\n  \n        // Now pop all items from stack one by one and print them\n        while (S.empty() == false)\n        {\n            node = S.peek();\n            System.out.print(node.val + \" \");\n            S.pop();\n        }\n            return list;\n    }\n}\n\n\n"
  },
  {
    "path": "Reverse Spiral Form of Matrix - GFG/README.md",
    "content": "# Reverse Spiral Form of Matrix\n## Medium\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Given a matrix as 2D array. Find the reverse&nbsp;spiral traversal of the matrix.&nbsp;<br>\n<br>\n<strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>: R = 3, C = 3\n  a = {{9, 8, 7},\n       {6, 5, 4},\n&nbsp;      {3, 2, 1}}\n<strong>Output: </strong>5 6 3 2 1 4 7 8 9\n<strong>Explanation</strong>: Spiral form of the matrix\nin reverse order starts from the centre \nand goes outward.\n<img alt=\"\" src=\"https://media.geeksforgeeks.org/img-practice/ScreenShot2022-10-17at10-1665981362.png\" style=\"height:181px; width:200px\"></span>\n\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>R = 4, C = 4<strong> \n</strong>  a = {{1, 2, 3, 4},\n       {5, 6, 7, 8},\n&nbsp;      {9, 10, 11, 12}, \n&nbsp;      {13, 14, 15, 16}}\n<strong>Output: </strong>10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1\n<strong>Explanation</strong>: \n<img alt=\"\" src=\"https://media.geeksforgeeks.org/img-practice/ScreenShot2022-10-17at10-1665981582.png\">\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou dont need to read input or print anything. Complete the function <strong>reverseSpiral()&nbsp;</strong>which takes <strong>R, C </strong>and<strong> a</strong>&nbsp;as input parameters and returns the matrix in reverse spiral form.</span><br>\n<br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(R*C)<br>\n<strong>Expected Auxiliary Space:</strong> O(R*C)<br>\n<br>\n<strong>Constraints:</strong><br>\n1&nbsp;&lt;= R,C&nbsp;&lt;=100<br>\n1&nbsp;&lt;= a[R][C] &lt;=100</span></p>\n</div>"
  },
  {
    "path": "Reverse Spiral Form of Matrix - GFG/reverse-spiral-form-of-matrix.java",
    "content": "//{ Driver Code Starts\n//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String[] input = new String[2]; \n            input = read.readLine().split(\" \"); \n            int R = Integer.parseInt(input[0]); \n            int C = Integer.parseInt(input[1]); \n            String s1[] = read.readLine().trim().split(\"\\\\s+\");\n            int a[][] = new int[R][C];\n            for(int i = 0;i < R*C;i++)\n                a[i/C][i%C] = Integer.parseInt(s1[i]);\n            Solution ob = new Solution();\n            int[] ans = ob.reverseSpiral(R,C,a);\n            for(int i = 0; i < ans.length; i++)\n            {\n                System.out.print(ans[i] + \" \");\n            }\n            System.out.println();\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\nclass Solution\n{\n    public int[] reverseSpiral(int R, int C, int[][] a)\n    {\n        // code here\n        int[] ans=new int[R*C];\n        int idx=R*C-1;\n        \n        int up=0;\n        int down=a.length-1;\n        int left=0;\n        int right=a[0].length-1;\n        \n        \n        \n        while(idx>=0){\n            //upper row\n            for(int i=left;i<=right && idx>=0;i++){\n                ans[idx--]=a[up][i];\n            }\n            up++;\n            \n            //last col\n            for(int i=up;i<=down && idx>=0;i++){\n                ans[idx--]=a[i][right];\n            }\n            right--;\n            \n            //lower row\n            for(int i=right;i>=left && idx>=0;i--){\n                ans[idx--]=a[down][i];\n            }\n            down--;\n            \n            for(int i=down;i>=up && idx>=0;i--){\n                ans[idx--]=a[i][left];\n            }\n            left++;\n        }\n        \n        return ans;\n        \n    }\n}"
  },
  {
    "path": "Reverse a Stack using Recursion.cpp",
    "content": "class Solution\n{\n    \n    void insertAtBottom(stack<int> &s,int &x)\n    {\n        if(s.empty())\n        {\n            s.push(x);\n            return;\n        }\n        \n        int num = s.top();\n        s.pop();\n        \n        insertAtBottom(s,x);\n        s.push(num);\n    }\n    \n    void solve(stack<int> &st)\n    {\n        if(st.empty())  return;\n        \n        int x = st.top();\n        st.pop();\n        \n        solve(st);\n        \n        insertAtBottom(st,x);\n    }\n\n    public:\n    stack<int> Reverse(stack<int> st)\n    {\n        solve(st);\n        return st;\n    }\n};\n"
  },
  {
    "path": "Reverse a string using Stack.java",
    "content": "class Solution {\n    \n    public String reverse(String S){\n        //code here\n        Deque<Character> s=new ArrayDeque<>();\n        for(char c:S.toCharArray()){\n            s.push(c);\n        }\n        S=\"\";\n        while(!s.isEmpty()){\n            S+=s.pop()+\"\";\n        }\n        return S;\n    }\n}\n"
  },
  {
    "path": "Reverse a sublist of a linked list - GFG/README.md",
    "content": "# Reverse a sublist of a linked list\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a linked list and positions m and n. Reverse the linked list from position m to n.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input :</span></strong>\n<span style=\"font-size:18px\">N = 10</span>\n<span style=\"font-size:18px\">Linked List = 1-&gt;7-&gt;5-&gt;3-&gt;9-&gt;8-&gt;10\n</span><span style=\"font-size:18px\">                      -&gt;2-&gt;2-&gt;5-&gt;NULL</span>\n<span style=\"font-size:18px\">m = 1, n = 8</span>\n<span style=\"font-size:18px\"><strong>Output :</strong> 2 10 8 9 3 5 7 1 2 5 </span>\n<strong><span style=\"font-size:18px\">Explanation :</span></strong>\n<span style=\"font-size:18px\">The nodes from position 1 to 8 \nare reversed, resulting in \n</span><span style=\"font-size:18px\">2 10 8 9 3 5 7 1 2 5.</span>\n\n</pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 6\nLinked List = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;NULL\nm = 2, n = 4</span>\n<span style=\"font-size:18px\"><strong>Output:</strong> 1 4 3 2 5 6</span>\n<strong><span style=\"font-size:18px\">Explanation:</span></strong>\n<span style=\"font-size:18px\">Nodes from position 2 to 4 \nare reversed resulting in</span>\n<span style=\"font-size:18px\">1 4 3 2 5 6.</span></pre>\n\n<div><strong><span style=\"font-size:18px\">Your task :</span></strong></div>\n\n<div><span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function <strong>reverseBetween()</strong> which takes the head of the linked list and two integers m and n as input and returns the head of the new linked list after reversing the nodes from position m to n.</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N)</span></div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Auxiliary Space: </strong>O(1)</span></div>\n\n<div>&nbsp;</div>\n\n<div><strong><span style=\"font-size:18px\">Constraints:</span></strong></div>\n\n<div><span style=\"font-size:18px\">1&lt;=N&lt;=10^5</span></div>\n <p></p>\n            </div>"
  },
  {
    "path": "Reverse a sublist of a linked list - GFG/reverse-a-sublist-of-a-linked-list.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\nclass Node\n    {\n        int data;\n        Node next;\n        Node(int d) {data = d; next = null; }\n    }\nclass insertion\n{\n    Node head;  \n    Node tail;\n\tpublic void addToTheLast(Node node) \n\t{\n\t  if (head == null) \n\t  {\n\t   head = node;\n\t   tail = node;\n\t  } \n\t  else \n\t  {\n\t   tail.next = node;\n\t   tail = node;\n\t  }\n\t}\n      void printList(Node head)\n    {\n        Node temp = head;\n        while (temp != null)\n        {\n           System.out.print(temp.data+\" \");\n           temp = temp.next;\n        }  \n        System.out.println();\n    }\n\t/* Drier program to test above functions */\n\tpublic static void main(String args[])throws IOException\n    {\n         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        // Scanner sc = new Scanner(System.in);\n\t\t int t=Integer.parseInt(br.readLine());\n\t\t while(t>0)\n         {\n            String S[] = br.readLine().split(\" \");\n\t\t\tint N = Integer.parseInt(S[0]);\n            int m = Integer.parseInt(S[1]);\n            int n = Integer.parseInt(S[2]);\n\t\t\n\t\t    String S1[] = br.readLine().split(\" \");\n\t\t\tinsertion llist = new insertion(); \n\t\t\tint a1=Integer.parseInt(S1[0]);\n\t\t\tNode head= new Node(a1);\n            llist.addToTheLast(head);\n            for (int i = 1; i < N; i++) \n\t\t\t{\n\t\t\t\tint a = Integer.parseInt(S1[i]);\n\t\t\t\tllist.addToTheLast(new Node(a));\n\t\t\t}\n\t\t\t\n        Solution ob = new Solution();\n\t\tNode newhead=ob.reverseBetween(llist.head, m, n);\n\t\tllist.printList(newhead);\n\t\t\n        t--;\t\t\n        }\n    }}// } Driver Code Ends\n\n\n//User function Template for Java\n\n/*\nclass Node\n    {\n        int data;\n        Node next;\n        Node(int d) {data = d; next = null; }\n    }\n    */\nclass Solution\n{\n    public static Node reverseBetween(Node head, int m, int n)\n    {\n        if(m > n)\n          return head;\n        \n        Node prev = null;\n        Node curr = head;\n        \n        for(int i=1; i<m && curr != null; i++){\n            prev = curr;\n            curr = curr.next;\n        }\n        \n        Node start = curr;\n        Node end = null;\n        \n        for(int i=1; i<=n-m+1 && curr != null; i++){\n            Node temp = curr.next;\n            curr.next = end;\n            end = curr;\n            curr = temp;\n        }\n        \n        if(start != null){\n            start.next = curr;\n            if(prev != null){\n                prev.next = end;    \n            }else{\n                head = end;\n            }\n        }\n        return head;\n    }\n}"
  },
  {
    "path": "Reverse array in groups(GFG))",
    "content": "Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K.\n\nNote: If at any instance, there are no more subarrays of size greater than or equal to K, then reverse the last subarray (irrespective of its size).\n\nExample 1:\n\nInput:\nN = 5, K = 3\narr[] = {1,2,3,4,5}\nOutput: 3 2 1 5 4\nExplanation: First group consists of elements\n1, 2, 3. Second group consists of 4,5.\n\nExample 2:\n\nInput:\nN = 4, K = 3\narr[] = {5,6,8,9}\nOutput: 8 6 5 9\n \nYour Task:\nYou don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place. \n\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n\nConstraints:\n1 ≤ N, K ≤ 107\n1 ≤ A[i] ≤ 1018\n\n\n\n\n\nSolution(JAVA):\n\nclass Solution\n{\n    //Function to reverse every sub-array group of size k.\n    void reverseInGroups(ArrayList<Integer> arr, int n, int k)\n    {\n        for (int i = 0; i < n; i += k)\n        {\n            // Get the left element ==========\n            int starting = i;\n            // Get the right most element ====\n            int ending = Math.min(i + k - 1, n - 1);\n            \n            // Now swap reverse the small piece of sub-arry in the arraylist\n            while(starting < ending){\n                int aux = arr.get(starting);\n                arr.set(starting, arr.get(ending));\n                arr.set(ending, aux);\n                starting++;\n                ending--;\n                \n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Reverse the String.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nint getLength(char ayu[]){\n    int count=0;\n    for (int i=0; ayu[i]!='\\0';i++){\n        count++;\n    }\n    return count;\n}\n\nvoid reverse(char ayu[], int n){\n    int s=0;\n    int e=n-1;\n    while(s<e)\n    swap(ayu[s++], ayu[e--]);\n}\n\nint main(){\n    char ayu[20];\n    cout<<\"Enter your name: \"<<endl;\n    cin>>ayu;\n    \n    cout<<\"My name is \"<<ayu;\n    int len = getLength(ayu);\n    cout<<\" Length: \"<<getLength(ayu)<<endl;\n    reverse(ayu, len);\n    cout<<\"My name is \"<<ayu;\n}\n"
  },
  {
    "path": "Reverse the String.java",
    "content": "public class Solution {\n    public String solve(String s) {\n        String ans=\"\";\n        StringBuilder sb=new StringBuilder();\n        for(int i=s.length()-1;i>=0;i--){\n            if(s.charAt(i)==' '){\n                if(sb.length()!=0){\n                    ans+=sb.reverse()+\" \";\n                    sb.setLength(0);\n                }\n            }else{\n                sb.append(s.charAt(i));\n            }   \n        }\n        ans+=sb.reverse();\n        return ans.trim();\n    }\n}\n"
  },
  {
    "path": "Reverse-Interger.java",
    "content": "class Solution {\n    public int reverse(int x) {\n        int result = 0; \n        while ( x != 0){\n            int d = x % 10 ;\n            int next  = result * 10 + d;\n        if((next - d)/10 != result){\n            return 0;\n        }\n             result = next;\n        x = x / 10 ;\n        }\n        \n        \n       \n        return result;\n        \n        \n        \n    }\n}\n"
  },
  {
    "path": "Richest Customer Wealth.java",
    "content": "class Solution {\n    public int maximumWealth(int[][] a) {\n        int max=0;\n        for(int i=0;i<a.length;i++){\n            max=Math.max(max,sum(a,i));\n        }\n        return max;\n    }\n    public int sum(int[][]a,int i){\n        int sum=0;\n        for(int j=0;j<a[i].length;j++){\n            sum+=a[i][j];\n        }\n        return sum;\n    }\n}\n"
  },
  {
    "path": "RightView in a Binary Tree",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    public ArrayList<Integer> solve(TreeNode A) {\n        ArrayList<Integer> ans=new ArrayList<>();\n        dfs(A,ans,0);\n        return ans;\n    }\n    public void dfs(TreeNode a,ArrayList<Integer> ans,int level){\n        if(a==null)return;\n        if(ans.size()==level){\n            ans.add(a.val);\n        }\n        dfs(a.right,ans,level+1);\n        dfs(a.left,ans,level+1);\n    }\n}\n"
  },
  {
    "path": "Robot Bounded In Circle",
    "content": "class Solution {\n    public boolean isRobotBounded(String instructions) {\n        int dir[][] = {{0,1}, {-1, 0}, {0, -1}, {1,0}};\n        int i = 0;\n        int x = 0;\n        int y = 0;\n       \n        for(int s = 0; s < instructions.length(); s++){\n            if(instructions.charAt(s) == 'L'){\n                i = (i + 1) % 4;\n            }\n            else if(instructions.charAt(s) == 'R'){\n                i = (i + 3) % 4;\n            }\n            else{\n                x = x + dir[i][0];\n                y = y + dir[i][1];\n            }\n        }\n        return x == 0 && y == 0 || i != 0;\n    }\n}\n"
  },
  {
    "path": "Robots.java",
    "content": "class Solution {\n    public String moveRobots(String s1, String s2) {\n        int i = 0, j = 0, n = s1.length();\n        while(i < n && j < n) {\n            if(s1.charAt(i) == '#') {\n                i++;\n            }\n            else if(s2.charAt(j) == '#') {\n                j++;\n            }\n            else if(s1.charAt(i) != s2.charAt(j)) {\n                return \"No\";\n            }\n            else if(s1.charAt(i) == 'B' && i > j) {\n                return \"No\";\n            }\n            else if(s1.charAt(i) == 'A' && i < j) {\n                return \"No\";\n            }\n            else {\n                i++;\n                j++;\n            }\n        }\n        return \"Yes\";\n    }\n}\n"
  },
  {
    "path": "Roman To Integer.java",
    "content": "public class Solution {\n    public int romanToInt(String A) {\n        int ans=0;\n        int i=0;\n        while(i<A.length()){\n            if(i+1<A.length()){\n                if(getValue(A.charAt(i+1))>getValue(A.charAt(i))){\n                    ans+=getValue(A.charAt(i+1))-getValue(A.charAt(i));\n                    i+=2;\n                }else{\n                    ans+=getValue(A.charAt(i));\n                    i++;\n                }\n            }else{\n                ans+=getValue(A.charAt(i));\n                i++;\n            }\n        }\n        return ans;\n    }\n    int getValue(char ch){\n        switch(ch){\n            case 'I':\n                return 1;\n            case 'V':\n                return 5;\n            case 'X':\n                return 10;\n            case 'L':\n                return 50;\n            case 'C':\n                return 100;\n            case 'D':\n                return 500;\n            case 'M':\n                return 1000;\n            default:\n                return -1;\n        }\n    }\n}\n"
  },
  {
    "path": "Root to Leaf Paths With Sum.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    ArrayList<ArrayList<Integer>> ans;\n    public ArrayList<ArrayList<Integer>> pathSum(TreeNode A, int B) {\n        ans=new ArrayList<>();\n        ArrayList<Integer> curr=new ArrayList<>();\n        curr.add(A.val);\n        dfs(A,B,curr,A.val);\n        return ans;\n    }\n    public void dfs(TreeNode a,int b,ArrayList<Integer> list,int curr){\n        if(a.left==null && a.right==null){\n            if(curr==b){\n                ans.add(new ArrayList<>(list));\n            }\n            return;\n        }\n        \n        if(a.left!=null){\n            list.add(a.left.val);\n            curr+=a.left.val;\n            dfs(a.left,b,list,curr);\n            curr-=a.left.val;\n            list.remove(list.size()-1);\n        }\n        \n        if(a.right!=null){\n            list.add(a.right.val);\n            curr+=a.right.val;\n            dfs(a.right,b,list,curr);\n            curr-=a.right.val;\n            list.remove(list.size()-1);\n        }\n    }\n}\n"
  },
  {
    "path": "Rotate Image.cpp",
    "content": "class Solution {\npublic:\n    void rotate(vector<vector<int>>& matrix) {\n        transpose(matrix);\n        reflect(matrix);\n    }\n    public: void transpose(vector<vector<int>>& matrix){\n        int n = matrix.size();\n        for(int i =0; i<n; i++){\n            for(int j =i+1; j<n; j++){\n                int temp = matrix[j][i];\n                matrix[j][i] =matrix[i][j];\n                matrix[i][j] = temp;\n            }\n        }\n    }\n    public: void reflect(vector<vector<int>>& matrix){\n        int n = matrix.size();\n        for(int i =0; i<n; i++){\n            for(int j =0; j<n/2; j++){\n                int temp = matrix[i][j];\n                matrix[i][j] = matrix[i][n-j-1];\n                matrix[i][n-j-1] = temp;\n            }\n        }\n\n    }\n};"
  },
  {
    "path": "Rotate List.java",
    "content": "class Solution {\n    public ListNode rotateRight(ListNode head, int k) {\n        if(head==null)return null;\n        int length=0;\n        ListNode temp=head;\n        while(temp!=null){\n            length++;\n            temp=temp.next;\n        }\n        if(length==1)return head;\n        k=k%length;\n        ListNode newHead=rotate(head,k);\n        return newHead;\n    }\n    public ListNode rotate(ListNode head,int k){\n        if(k==0)return head;\n        while(k!=0){\n            ListNode temp=head;\n            ListNode prev=null;\n            while(temp.next!=null){\n                prev=temp;\n                temp=temp.next;\n            }\n            prev.next=null;\n            temp.next=head;\n            head=temp;\n            k--;\n        }\n        return head;\n        \n    }\n}\n\n//=================================================================================\nclass Solution {\n    public ListNode rotateRight(ListNode head, int k) {\n        if (head == null)\n            return head;\n        int size = getListSize(head);\n        k %= size;\n        if (k == 0)\n            return head;\n        ListNode fast = head;\n        ListNode slow = head;\n        for (int i = 0; i < size-k; i++) {\n            slow = fast;\n            fast = fast.next;\n        }\n        slow.next = null;\n        ListNode oldHead = head;\n        head = fast;\n        while (fast.next != null)\n            fast = fast.next;\n        fast.next = oldHead;\n        return head;\n    }\n    \n    public int getListSize(ListNode head) {\n        if (head == null)\n            return 0;\n        return 1 + getListSize(head.next);\n    }\n}\n//==================================================================================\n/**\n * Definition for singly-linked list.\n * class ListNode {\n *     public int val;\n *     public ListNode next;\n *     ListNode(int x) { val = x; next = null; }\n * }\n */\npublic class Solution {\n    public ListNode rotateRight(ListNode A, int B) {\n        ListNode temp=A;\n        int sz=0;\n        while(temp!=null){\n            temp=temp.next;\n            sz++;\n        }\n        B=B%sz;\n        int size=sz;\n        temp=A;\n        while(sz-B-1>0){\n            sz--;\n            temp=temp.next;\n        }\n        ListNode Alast=temp;\n        ListNode Bfist=Alast.next;\n        if(Bfist==null)return A;\n        Alast.next=null;\n        temp=Bfist;\n        while(temp.next!=null){\n            temp=temp.next;\n        }\n        temp.next=A;\n        return Bfist;\n    }\n}\n"
  },
  {
    "path": "Rotate Matrix.java",
    "content": "public class Solution {\n\tpublic void rotate(ArrayList<ArrayList<Integer>> arr) {\n        int n=arr.size();\n        int a=0;\n        int b=n-1;\n        while(a<b){\n            ArrayList<Integer> temp=arr.get(a);\n            arr.set(a,arr.get(b));\n            arr.set(b,temp);\n\t\t\ta++;\n\t\t\tb--;\n        }\n        int num=0;\n        while(num<n){\n            int i=num;\n            while(i<n){\n                int temp=arr.get(i).get(num);\n                arr.get(i).set(num,arr.get(num).get(i));\n                arr.get(num).set(i,temp);\n                i++;\n            }\n            num++;\n        }\n    }\n}\n"
  },
  {
    "path": "Salutes.java",
    "content": "public class Solution {\n    public Long countSalutes(String A) {\n        Long ans=0l;\n        Long left=0l;\n        for(int i=0;i<A.length();i++){\n            if(A.charAt(i)=='<')left++;\n        }\n        \n        for(int i=0;i<A.length();i++){\n            if(A.charAt(i)=='>'){\n                ans+=left;\n            }else{\n                left--;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Save Your Life - GFG/README.md",
    "content": "# Save Your Life\n## Medium\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Given a string&nbsp;<strong>w</strong>, integer array <strong>b,</strong> &nbsp;character array <strong>x&nbsp;</strong>and an integer <strong>n</strong>. <strong>n</strong>&nbsp;is the size of array <strong>b</strong> and array&nbsp;<strong>x</strong>. Find a substring which has the sum of the ASCII values of its every character, as maximum. ASCII values of some characters&nbsp;are redefined.<br>\n<strong>Note:</strong></span><strong>&nbsp;</strong><span style=\"font-size:18px\">Uppercase &amp; lowercase both will be present in the string&nbsp;<strong>w</strong>. Array <strong>b</strong>&nbsp;and Array <strong>x</strong>&nbsp;contain corresponding redefined ASCII values. For each i,&nbsp;0&lt;=ib[i] contain redefined ASCII value of character&nbsp;<strong>x[i]</strong>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nW = abcde\nN = 1\nX[] = { 'c' }\nB[] = { -1000 }\n<strong>Output:</strong>\nde\n<strong>Explanation:\n</strong>Substring \"de\" has the\nmaximum sum of ascii value,\nincluding c decreases the sum value</span>\n</pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nW = dbfbsdbf \nN = 2\nX[] = { 'b','s' }\nB[] = { -100, 45  }\n<strong>Output:</strong>\ndbfbsdbf</span><span style=\"font-size:18px\">\n<strong>Explanation:\n</strong>Substring \"dbfbsdbf</span><span style=\"font-size:18px\">\" has the maximum\nsum of ascii value.</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>maxSum()</strong>&nbsp;which takes&nbsp;string <strong>W</strong>, character array <strong>X</strong>, integer array <strong>B</strong>, integer <strong>N</strong> as length of array <strong>X</strong> and <strong>B</strong>&nbsp;as input parameters and returns the substring with the maximum sum of ascii value.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity: </strong>O(|W|)<br>\n<strong>Expected Auxiliary Space: </strong>O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong></span></p>\n\n<p><span style=\"font-size:18px\">1&lt;=|W|&lt;=100000<br>\n1&lt;=|X|&lt;=52<br>\n-1000&lt;=B<sub>i</sub>&lt;=1000</span></p>\n\n<p><span style=\"font-size:18px\">Each character of W and A will be from a-z, A-Z.</span></p>\n</div>"
  },
  {
    "path": "Save Your Life - GFG/save-your-life.java",
    "content": "//{ Driver Code Starts\nimport java.io.*;\nimport java.util.*;\n\n// } Driver Code Ends\nclass Solution{\n    static String maxSum(String w,char x[],int b[], int n){\n        //code here\n        Map<Character,Integer> map=new HashMap<>();\n        for(int i=0;i<n;i++){\n            map.put(x[i],b[i]);\n        }\n        StringBuilder ans=new StringBuilder();\n        StringBuilder temp=new StringBuilder();\n        \n        int maxSum=Integer.MIN_VALUE;\n        int currSum=0;\n        \n        for(int i=0;i<w.length();i++){\n            char ch=w.charAt(i);\n            currSum+=map.containsKey(ch)?map.get(ch):ch;\n            temp.append(ch);\n            if(currSum>maxSum){\n                maxSum=currSum;\n                ans=new StringBuilder(temp);\n            }\n            if(currSum<0){\n                currSum=0;\n                temp=new StringBuilder();\n            }\n        }\n    \n        return ans.toString();\n    }\n}\n\n//{ Driver Code Starts.\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String w = read.readLine();\n            int n = Integer.parseInt(read.readLine());\n            String TE[] = read.readLine().trim().split(\" \");\n            char x[] = new char[n];\n            for(int i = 0;i<n;i++)\n            {\n                x[i] = TE[i].charAt(0);\n            }\n            \n            String TR[] = read.readLine().trim().split(\" \");\n            int b[] = new int[n];\n            for(int i = 0;i<n;i++)\n            {\n                b[i] = Integer.parseInt(TR[i]);\n            }\n           \n            Solution ob = new Solution();\n            System.out.println(ob.maxSum(w,x,b,n));\n        }\n    }\n}\n// } Driver Code Ends"
  },
  {
    "path": "Score of Parentheses.java",
    "content": "class Solution {\n    public int scoreOfParentheses(String s) {\n             int score = 0;\n        int depth = 0;\n\n        for (int i = 0; i < s.length(); i++) {\n            if (s.charAt(i) == '(') {\n                depth++;\n            } else {\n                depth--;\n            }\n\n            if (s.charAt(i) == ')' && s.charAt(i - 1) == '(') {\n                // Whenever you meet a () pair, you multiply 1 by all the 2 outside of it, and accumulate the result\n                score += Math.pow(2, depth);\n            }\n        }\n\n        return score; \n    }\n}\n//=================================================================\nclass Solution {\n    public int scoreOfParentheses(String S) {\n        int ans = 0, bal = 0;\n        for (int i = 0; i < S.length(); ++i) {\n            if (S.charAt(i) == '(') {\n                bal++;\n            } else {\n                bal--;\n                if (S.charAt(i-1) == '(')\n                    ans += 1 << bal;\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Search for a Range.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public int[] searchRange(final int[] A, int B) {\n        int[]ans=new int[2];\n        ans[0]=A.length;\n        ans[1]=-1;\n        dfs(A,B,ans,0,A.length-1);\n        if(ans[0]==A.length)ans[0]=-1;\n        return ans;\n    }\n    void dfs(int[]a,int b,int[]ans,int i,int j){\n        if(i<=j){\n            int mid=i+(j-i)/2;\n            if(a[mid]==b){\n                ans[0]=Math.min(ans[0],mid);\n                ans[1]=Math.max(ans[1],mid);\n                dfs(a,b,ans,i,mid-1);\n                dfs(a,b,ans,mid+1,j);\n            }else if(a[mid]>b){\n                dfs(a,b,ans,i,mid-1);\n            }else{\n                dfs(a,b,ans,mid+1,j);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Search in Bitonic Array!.java",
    "content": "public class Solution {\n    public int solve(ArrayList<Integer> A, int B) {\n        int l=0;\n        int h=A.size()-1;\n        while(l<=h){\n            int mid=(l+h)/2;\n            if(A.get(mid)==B){\n                return mid;\n            }else if(A.get(mid)<B){\n                if(A.get(h)<A.get(mid)){\n                    h=mid-1;\n                }else{\n                    l=mid+1;\n                }\n            }else if(A.get(mid)>B){\n                if(A.get(l)<A.get(mid)){\n                    h=mid-1;\n                }else{\n                    l=mid+1;\n                }\n            }\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "Search insert position of K in a sorted array - GFG/README.md",
    "content": "# Search insert position of K in a sorted array\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a sorted array&nbsp;<strong>Arr[]</strong>(0-index based)&nbsp;consisting of&nbsp;<strong>N&nbsp;</strong>distinct integers and an integer <strong>k</strong>, the task is to find the index of k, if its present in the array <strong>Arr[]</strong>. Otherwise, find the index where <strong>k</strong>&nbsp;must be inserted to keep the array sorted.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4\nArr = {1, 3, 5, 6}\nk = 5\n<strong>Output:</strong> 2\n<strong>Explaination:</strong> Since 5 is found at index 2 \nas Arr[2] = 5, the output is 2.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4\nArr = {1, 3, 5, 6}\nk = 2\n<strong>Output:</strong> 1\n<strong>Explaination:</strong> Since 2 is not present in \nthe array but can be inserted at index 1 \nto make the array sorted.</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>searchInsertK()</strong>&nbsp;which takes the array <strong>Arr[]</strong> and its size <strong>N </strong>and <strong>k&nbsp;</strong>as input parameters&nbsp;and returns the index.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(logN)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>4</sup><br>\n-10<sup>3</sup> ≤ Arr[i]&nbsp;≤ 10<sup>3</sup><br>\n-10<sup>3</sup>&nbsp;≤ k&nbsp;≤ 10<sup>3</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Search insert position of K in a sorted array - GFG/search-insert-position-of-k-in-a-sorted-array.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            int N = Integer.parseInt(read.readLine());\n            String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n            int Arr[]= new int[N];\n            for(int i = 0; i < N; i++)\n                Arr[i] = Integer.parseInt(input_line[i]);\n            int k = Integer.parseInt(read.readLine());\n            \n            Solution ob = new Solution();\n            System.out.println(ob.searchInsertK(Arr, N, k));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n    static int searchInsertK(int a[], int N, int k){\n        int i=0;\n        int j=a.length;\n        while(i<j){\n            int mid=(i+j)/2;\n            if(a[mid]==k){\n                return mid;\n            }else if(a[mid]<k){\n                i=mid+1;\n            }else{\n                j=mid;\n            }\n        }\n        return i;\n\t}\n}"
  },
  {
    "path": "Searching all indices for matching substring.py",
    "content": "S =input()\nk = input()\nimport re\npattern = re.compile(k)\nr = pattern.search(S)\nif not r: print(\"(-1, -1)\")\nwhile r:\n    print(\"({0}, {1})\".format(r.start(), r.end() - 1))\n    r = pattern.search(S,r.start() + 1)\n"
  },
  {
    "path": "Segregate 0s and 1s in an array.java",
    "content": "public class Solution {\n    public ArrayList<Integer> solve(ArrayList<Integer> arr) {\n        Collections.sort(arr);\n        return arr;\n    }\n}\n"
  },
  {
    "path": "Self Permutation.java",
    "content": "public class Solution {\n    public int permuteStrings(String A, String B) {\n        HashMap<Character, Integer> hm = new HashMap<>();\n\n        if(A.length()!=B.length()) return 0;\n\n        for(int i=0; i<A.length(); i++)\n        {\n            char val = A.charAt(i); \n            hm.put(val, hm.getOrDefault(val, 0)+1);\n        }\n\n        for(int i=0; i<B.length(); i++)\n        {\n            char val = B.charAt(i);\n            if(!hm.containsKey(val)) return 0;\n            if(hm.get(val)==0) hm.remove(val);\n            else hm.put(val, hm.get(val)-1);\n        }\n        return 1;\n    }\n}\n\n"
  },
  {
    "path": "Sequential Digits.java",
    "content": "class Solution {\n    int low=0;\n    int high=0;\n    public List<Integer> sequentialDigits(int low, int high) {\n        List<Integer> list=new ArrayList<>();\n        this.high=high;\n        this.low=low;\n        for(int i=1;i<=9;i++){\n            dfs(i,list);\n        }\n        Collections.sort(list);\n        return list;\n    }\n    public void dfs(int num,List<Integer> list){\n        int add=(num%10)+1;\n        if(add!=10){\n            num=(num*10)+add;\n            if(num<=high){\n                if(num>=low){\n                    list.add(num);\n                }\n                dfs(num,list);\n            }\n        }\n        \n    }\n}\n"
  },
  {
    "path": "Serialize.java",
    "content": "public class Solution {\n    public String serialize(ArrayList<String> A) {\n        StringBuilder sb=new StringBuilder();\n        for(String s:A){\n            sb.append(s);\n            sb.append(s.length());\n            sb.append(\"~\");\n        }\n        return sb.toString();\n    }\n}\n"
  },
  {
    "path": "Shop in Candy Store - GFG/README.md",
    "content": "# Shop in Candy Store\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">In a candy store, there are <strong>N</strong> different types of candies available and the prices of all the N different types of candies are provided to you.<br>\nYou are now provided with an attractive offer.<br>\nYou can buy a single candy from the store and get at most <strong>K</strong> other candies ( all are different types ) for free.<br>\nNow you have to answer two questions. Firstly, you have to find what is the <strong>minimum amount of money</strong> you have to spend to buy all the<strong> N </strong>different candies. Secondly, you have to find what is the <strong>maximum amount of money</strong> you have to spend to buy all the N different candies.<br>\nIn both the cases you must utilize the offer i.e. you buy one candy and get <strong>K </strong>other candies for free.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4\nK = 2\ncandies[] = {3 2 1 4}</span>\n\n<span style=\"font-size:18px\"><strong>Output:</strong>\n3 7</span>\n\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\nAs according to the offer if you buy \none candy you can take at most two \nmore for free. So in the first case, \nyou buy the candy which costs 1 and \ntakes candies worth 3 and 4 for free, \nalso you buy candy worth 2 as well.\nSo <strong>min cost</strong> : 1+2 =3.\nIn the second case, you can buy the \ncandy which costs 4 and takes candies \nworth 1 and 2 for free, also you need \nto buy candy worth 3 as well. \nSo <strong>max cost :</strong> 3+4 =7.</span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> </span>\n<span style=\"font-size:18px\">N = 5\nK = 4</span>\n<span style=\"font-size:18px\">candies[] = {3 2 1 4 5}\n</span><span style=\"font-size:18px\"><strong>\nOutput:</strong> </span>\n<span style=\"font-size:18px\">1 5\n\n<strong>Explanation:\n</strong></span><span style=\"font-size:18px\">For minimimum cost buy the candy with\nthe cost 1 and get all the other candies\nfor free.\nFor maximum cost buy the candy with\nthe cost 5 and get all other candies\nfor free.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong></span><br>\n<span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function <strong>candyStore()</strong>&nbsp;which takes the array candies[], its size N<strong>&nbsp;</strong>and an integer K<strong>&nbsp;</strong>as input parameters&nbsp;and returns the minimum amount and maximum amount of money to buy all candies according to the offer.<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(NLogN)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;=&nbsp;<strong>N&nbsp;</strong>&lt;= 100000<br>\n&nbsp;0 &lt;= <strong>K</strong> &lt;= N-1<br>\n1 &lt;= <strong>candies[i]</strong>&nbsp;&lt;= 10000</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Shop in Candy Store - GFG/shop-in-candy-store.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n            int N = Integer.parseInt(input_line[0]);\n            int K = Integer.parseInt(input_line[1]);\n            input_line = read.readLine().trim().split(\"\\\\s+\");\n            int candies[]= new int[N];\n            for(int i = 0; i < N; i++)\n                candies[i] = Integer.parseInt(input_line[i]);\n\n            Solution ob = new Solution();\n            ArrayList<Integer> cost = ob.candyStore(candies,N,K);\n            System.out.println(cost.get(0)+\" \"+cost.get(1));\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n\nclass Solution{\n    static ArrayList<Integer> candyStore(int arr[],int N,int k){\n        // code here\n        ArrayList<Integer> ans=new ArrayList<>();\n        Arrays.sort(arr);\n        int i=0;\n        int j=N-1;\n        int minCost=0;\n        while(i<=j){\n            minCost+=arr[i];\n            j-=k;\n            i++;\n        }\n        ans.add(minCost);\n        i=0;\n        j=N-1;\n        int maxCost=0;\n        while(i<=j){\n            maxCost+=arr[j];\n            j--;\n            i+=k;\n        }\n        ans.add(maxCost);\n        return ans;\n    }\n}"
  },
  {
    "path": "Shortest Distance in a Binary Maze - GFG/README.md",
    "content": "# Shortest Distance in a Binary Maze\n## Medium\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">Given a <strong>n * m</strong>&nbsp;matrix <strong>grid</strong> where each element can either be <strong>0</strong> or <strong>1</strong>. You&nbsp;need to find the shortest distance&nbsp;between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\">If the path is not possible between source cell and destination cell, then return <strong>-1</strong>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Note :&nbsp;</strong>You can move into an adjacent cell if that adjacent cell is filled with element 1. Two cells are adjacent if they share a side. In other words,&nbsp;you can move in one of the four&nbsp;directions, Up, Down, Left&nbsp;and Right.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:</span></strong>\n<span style=\"font-size:18px\">grid[][] = {{1, 1, 1, 1},\n            {1, 1, 0, 1},\n            {1, 1, 1, 1},\n            {1, 1, 0, 0},\n            {1, 0, 0, 1}}</span>\n<span style=\"font-size:18px\">source = {0, 1}</span>\n<span style=\"font-size:18px\">destination = {2, 2}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">3</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">1 <strong>1</strong> 1 1\n1 <strong>1</strong> 0 1\n1 <strong>1</strong> <strong>1</strong> 1\n1 1 0 0\n1 0 0 1\nThe highlighted part in the matrix denotes the \nshortest path from source to destination cell.</span>\n</pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:</span></strong>\n<span style=\"font-size:18px\">grid[][] = {{1, 1, 1, 1, 1},\n            {1, 1, 1, 1, 1},\n            {1, 1, 1, 1, 0},\n            {1, 0, 1, 0, 1}}</span>\n<span style=\"font-size:18px\">source = {0, 0}</span>\n<span style=\"font-size:18px\">destination = {3, 4}</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">-1</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">The path is not possible between source and</span>&nbsp;\n<span style=\"font-size:18px\">destination, hence return -1.</span>\n</pre>\n\n<p><strong><span style=\"font-size:18px\">Your Task:</span></strong></p>\n\n<p><span style=\"font-size:18px\">You don't need to read or print anything. Your task is to complete the function <strong>shortestPath()&nbsp;</strong>which takes the a 2D integer array&nbsp;<strong>grid</strong>, <strong>source</strong> cell and <strong>destination</strong> cell&nbsp;as an input parameters and returns the shortest distance between source and destination cell.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(n * m)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(n * m)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span></p>\n\n<ul>\n\t<li><span style=\"font-size:18px\">1 ≤ n, m ≤ 500</span></li>\n\t<li><span style=\"font-size:18px\">grid[i][j] == 0 or grid[i][j] == 1</span></li>\n\t<li><span style=\"font-size:18px\">The source and destination cells are always inside the given matrix.</span></li>\n\t<li><span style=\"font-size:18px\">The source and destination cells always contain 1.</span></li>\n</ul>\n</div>"
  },
  {
    "path": "Shortest Distance in a Binary Maze - GFG/shortest-distance-in-a-binary-maze.java",
    "content": "//{ Driver Code Starts\n// Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\n// Position this line where user code will be pasted.\n\nclass GFG {\n    public static void main(String[] args) throws IOException {\n        Scanner sc = new Scanner(System.in);\n        int T = sc.nextInt();\n        while (T-- > 0) {\n            int n = sc.nextInt();\n            int m = sc.nextInt();\n            int[][] grid = new int[n][m];\n\n            for (int i = 0; i < n; i++) {\n\n                for (int j = 0; j < m; j++) {\n                    grid[i][j] = sc.nextInt();\n                }\n            }\n            int[] source = new int[2];\n            for (int i = 0; i < 2; i++) {\n                int x = sc.nextInt();\n                source[i] = x;\n            }\n            int[] dest = new int[2];\n            for (int i = 0; i < 2; i++) {\n                int x = sc.nextInt();\n                dest[i] = x;\n            }\n            Solution ob = new Solution();\n            int ans = ob.shortestPath(grid, source, dest);\n            System.out.println(ans);\n        }\n    }\n}\n// } Driver Code Ends\n\n\n// User function Template for Java\n\nclass Solution {\n\n    class Pair{\n        int x;\n        int y;\n        Pair(int i,int j){\n            x=i;\n            y=j;\n        }\n    }\n    int shortestPath(int[][] grid, int[] src, int[] des) {\n        Queue<Pair> q=new LinkedList<>();\n        q.add(new Pair(src[0],src[1]));\n        grid[src[0]][src[1]]=0;\n        int dis=0;\n        while(!q.isEmpty()){\n            int sz=q.size();\n            while(sz-->0){\n                Pair curr=q.remove();\n                int i=curr.x;\n                int j=curr.y;\n                if(i==des[0] && j==des[1])return dis;\n                if(i>0 && grid[i-1][j]==1){\n                    grid[i-1][j]=0;\n                    q.add(new Pair(i-1,j));\n                }\n                if(j>0 && grid[i][j-1]==1){\n                    grid[i][j-1]=0;\n                    q.add(new Pair(i,j-1));\n                }\n                if(i<grid.length-1 && grid[i+1][j]==1){\n                    grid[i+1][j]=0;\n                    q.add(new Pair(i+1,j));\n                }\n                if(j<grid[0].length-1 && grid[i][j+1]==1){\n                    grid[i][j+1]=0;\n                    q.add(new Pair(i,j+1));\n                }\n            }\n            dis++;\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "Shortest Path Visiting All Nodes.java",
    "content": "class Solution {\n    public int shortestPathLength(int[][] graph) {\n        int n = graph.length;\n        if(n==1) return 0;\n        int target = (1 << n) - 1;\n        boolean[][] seen = new boolean[n][target];\n        Queue<int[]> q = new LinkedList<>();\n        \n        for (int i = 0; i < n; i++) {\n            int source = 1 << i;\n            q.add(new int[] {i,source});\n            seen[i][source] = true;\n        }\n        \n        int level = 0;\n        while (!q.isEmpty()) {\n            int size = q.size();\n            for (int i = 0; i < size; i++) {\n                int[] currentPair = q.remove();\n                int node = currentPair[0];\n                int mask = currentPair[1];\n                for (int nei : graph[node]) {\n                    int nextMask = mask | (1 << nei);\n                    if (nextMask == target) return level + 1;\n                    \n                    if (!seen[nei][nextMask]) {\n                        seen[nei][nextMask] = true;\n                        q.add(new int[] {nei, nextMask});\n                    }\n                }\n            }\n            level++;\n        }\n        \n        return -1;\n    }\n}\n"
  },
  {
    "path": "Shortest Path between Cities - GFG/README.md",
    "content": "# Shortest Path between Cities\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Geek lives in a special city where houses are arranged in a hierarchial manner. Starting from house number 1, each house leads to two more houses. &nbsp;<br>\n1 leads to 2 and 3.&nbsp;<br>\n2 leads to 4 and 5.&nbsp;<br>\n3 leads to 6 and 7. and so on.&nbsp;<br>\nGiven the house numbers on two houses x and y, find the length of the shortest path between them.&nbsp;</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nx = 2, y = 6\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\n              1\n          /      \\\n        /          \\\n       2             3\n     /   \\         /   \\\n    4     5       6     7         \n   / \\   / \\     / \\   / \\\n  8  9  10 11   12 13 14 15</span>\n<span style=\"font-size:18px\">\nThe length of the shortest path between 2 \nand 6 is 3. ie </span><span style=\"font-size:18px\">2-&gt; 1-&gt; 3-&gt; 6.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nx = 8, y = 10\n<strong>Output: </strong>4\n<strong>Explanation: </strong>8-&gt; 4-&gt; 2-&gt; 5-&gt; 10\nThe length of the shortest path between 8 \nand 10 is 4. </span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Complete the function <strong>shortestPath()</strong> which takes integers x and y as input parameters and returns the length of the shortest path from x to y.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(log(max(x,y)))<br>\n<strong>Expected Auxiliary Space: </strong>O(1)</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:&nbsp;</strong><br>\n1 &lt;= x,y &lt;= 10<sup>9</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Shortest Path between Cities - GFG/shortest-path-between-cities.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*; \nclass GFG{\n    public static void main(String args[]) throws IOException { \n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0){\n        \tString input_line[] = read.readLine().trim().split(\"\\\\s+\");\n        \tint x = Integer.parseInt(input_line[0]);\n        \tint y = Integer.parseInt(input_line[1]);\n            Solution ob = new Solution();\n            System.out.println(ob.shortestPath(x,y));\n        }\n    } \n} // } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    Map<Integer,Integer> map;\n    int shortestPath( int x, int y){ \n        int max=Math.max(x,y);\n        int min=Math.min(x,y);\n        int ans=0;\n        while(max!=min){\n            max/=2;\n            ans++;\n            if(max<min){\n                min/=2;\n                ans++;\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "Shortest Uncommon Subsequence - GFG/README.md",
    "content": "# Shortest Uncommon Subsequence\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two strings <strong>S</strong> and <strong>T</strong>, find length of the shortest subsequence in <strong>S</strong> which is not a subsequence in <strong>T</strong>. If no such subsequence is possible, return -1. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. A string of length n has&nbsp;<img alt=\"2^n\" src=\"http://www.geeksforgeeks.org/wp-content/ql-cache/quicklatex.com-e4249a2b3de09582eb567b98f8cd62b1_l3.svg\" style=\"height:12px; width:17px\" title=\"Rendered by QuickLaTeX.com\" class=\"img-responsive\">&nbsp;different possible subsequences.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>S = </strong>\"babab\"</span>\n<span style=\"font-size:18px\"><strong>T = </strong>\"babba\"</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">3</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">There are no subsequences of S with\nlength less than 3 which is not a\nsubsequence of T. \"aab\" is an example of\na subsequence of length 3 which isn't a\nsubsequence of T.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong></span>\n<span style=\"font-size:18px\"><strong>S = </strong>\"babhi\"</span>\n<span style=\"font-size:18px\"><strong>T = </strong>\"babij\"</span>\n<span style=\"font-size:18px\"><strong>Output:</strong></span>\n<span style=\"font-size:18px\">1</span>\n<span style=\"font-size:18px\"><strong>Explanation:</strong></span>\n<span style=\"font-size:18px\">\"h\" is a subsequence of S that is\nnot a subsequence of T.</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>shortestUnSub()</strong> which takes two Strings S, and T as input and returns the shortest Uncommon Subsequence.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(|S|<sup>2</sup>*|T|)<br>\n<strong>Expected Auxiliary Space:</strong> O(|S|*|T|)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 &lt;= |S|, |T| &lt;= 500</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Shortest Uncommon Subsequence - GFG/shortest-uncommon-subsequence.cpp",
    "content": "// { Driver Code Starts\n#include <bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\nclass Solution {\n  public:\n      int findShortest(vector<vector<int>> &dp, string &S, string &T, int n, int m, int i, int j){\n        if(i >= n){\n            return 501;\n        }\n        if(j >= m){\n            return 1;\n        }\n        if(dp[i][j] != -1){\n            return dp[i][j];\n        }\n        int k = j;\n        for(; k < m; k++){\n            if(S[i] == T[k]){\n                break;\n            }\n        }\n        if(k == m){\n            return 1;\n        }\n        return dp[i][j] = min(findShortest(dp, S, T, n, m, i + 1, j), 1 + findShortest(dp, S, T, n, m, i + 1, k + 1));\n    }\n  \n  \n    int shortestUnSub(string S, string T) {\n        int n = S.size();\n        int m = T.size();\n        vector<vector<int>> dp (n + 1, vector<int> (m + 1, -1));\n        int ans = findShortest(dp, S, T, n, m, 0, 0);\n        return ans >= 501 ? -1 : ans;\n    }\n};\n\n// { Driver Code Starts.\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        string S,T;\n        cin>>S>>T;\n\n        Solution ob;\n        cout << ob.shortestUnSub(S,T) << endl;\n    }\n    return 0;\n}  // } Driver Code Ends"
  },
  {
    "path": "Shortest Uncommon Subsequence - GFG/shortest-uncommon-subsequence.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            String A[] = read.readLine().split(\" \");\n            \n            String S = A[0];\n            String T = A[1];\n\n            Solution ob = new Solution();\n            System.out.println(ob.shortestUnSub(S,T));\n        }\n    }\n}// } Driver Code Ends\n\n\n//bcda\n//bcd\n\n\n//dp[i][j]=Math.min(dp[i-1][j],dp[i-1][k]+ 1)\n\n\n//User function Template for Java\n\nclass Solution {\n    static int shortestUnSub(String S, String T) {\n        // code here\n        int n=S.length();\n        int m=T.length();\n        int[][]dp=new int[n+1][m+1];\n        \n        for(int i=0;i<=n;i++){\n            dp[i][0]=1;\n        }\n        \n        int MAX=501;\n        for(int j=0;j<=m;j++){\n            dp[0][j]=MAX;\n        }\n        \n        \n        for(int i=1;i<=n;i++){\n            for(int j=1;j<=m;j++){\n                int k;\n                for(k=j-1;k>=0;k--){\n                    if(S.charAt(i-1)==T.charAt(k))break;\n                }\n                \n                if(k==-1){\n                    dp[i][j]=1;\n                }else{\n                    dp[i][j]=Math.min(dp[i-1][j],dp[i-1][k]+ 1);\n                }\n            }\n        }\n        \n        if(dp[n][m]>=MAX)return -1;\n        \n        return dp[n][m];\n        \n    }\n};"
  },
  {
    "path": "Shortest Unique prefix for every word.java",
    "content": "class Trie{\n   Trie[] children;\n   int count;\n   \n   Trie(){\n       children = new Trie[26];\n       count = 0;\n   }\n   static void insert(Trie root, String s){\n       Trie temp = root;\n       for(char ch : s.toCharArray()){\n           int index = ch-'a';\n           if(temp.children[index] == null){\n              temp.children[index] = new Trie();\n           }\n          temp.children[index].count++;\n          temp = temp.children[index];\n       }\n   }\n   static String searchPrefix(Trie root, String s){\n       StringBuilder ans = new StringBuilder();\n       Trie temp = root;\n       for(char ch : s.toCharArray()){\n           int index = ch-'a';\n           ans.append(ch);\n           if(temp.children[index].count == 1){\n               break;\n           }\n           temp = temp.children[index];\n       }\n       return ans.toString();\n   }\n}\n\nclass Solution {\n    static String[] findPrefixes(String[] arr, int n) {\n        // code here\n        String[]ans=new String[n];\n        Trie root=new Trie();\n        for(String s:arr){\n            Trie.insert(root,s);\n        }\n        for(int i=0;i<n;i++){\n            String prefix=Trie.searchPrefix(root,arr[i]);\n            ans[i]=prefix;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Shortest_distance_in_Directed_acyclic_graph.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\n\nvoid toposort(vector<pair<int, int>> adj[], vector<int> &vis, stack<int> &st, int node)\n{\n  vis[node] = 1;\n  for (auto it : adj[node])\n  {\n    if (!vis[it.first])\n    {\n      toposort(adj, vis, st, it.first);\n    }\n  }\n  st.push(node);\n}\n\nvoid sdd(vector<pair<int, int>> adj[], int n, int src)\n{\n  vector<int> vis(n, 0);\n  stack<int> st;\n\n  for (int i = 0; i < n; i++)\n  {\n    if (!vis[i])\n    {\n      toposort(adj, vis, st, i);\n    }\n  }\n  vector<int> dist(n, INT_MAX);\n  dist[src] = 0;\n  while (!st.empty())\n  {\n    int node = st.top();\n    st.pop();\n\n    if(dist[node]!=INT_MAX){\n        for(auto it: adj[node]){\n            if(dist[node]+it.second<dist[it.first] ){\n                dist[it.first]=dist[node]+it.second;\n            }\n        }\n    }\n  }\n\n\n  for(int i =0;i< n;i++){\n    dist[i]==INT_MAX?cout<<\"INF\"<<\" \" : cout<<dist[i]<<\" \";\n  }\n  cout<<endl;\n}\n\nint main()\n{\n  int m, n;\n  cin >> m >> n;\n  vector<pair<int, int>> adj[m];\n  for (int i = 0; i < n; i++)\n  {\n    int x, y, w;\n    cin >> x >> y >> w;\n    adj[x].push_back({y, w});\n  }\n  int src;\n  cin >> src;\n  sdd(adj, m, src);\n  return 0;\n}\n"
  },
  {
    "path": "Simplify Path.java",
    "content": "class Solution {\n    public String simplifyPath(String path) {\n        Deque<String> dq = new LinkedList<>();\n        \n        int i = 0;\n        while (i < path.length()) {\n            i++;\n            int l = i;\n            while (i < path.length() && path.charAt(i) != '/') i++;\n            String segment = path.substring(l, i);\n            \n            if (segment.equals(\".\") || segment.isEmpty()) continue;\n            if (segment.equals(\"..\")) {\n                if (!dq.isEmpty()) dq.pollLast();\n            } else {\n                dq.offerLast(segment);\n            }\n        }\n        \n        if (dq.isEmpty()) return \"/\";\n        \n        StringBuilder result = new StringBuilder();\n        while (!dq.isEmpty()) {\n            result.append(\"/\").append(dq.pollFirst());\n        }\n        return result.toString();\n    }\n}\n"
  },
  {
    "path": "Single Element in Sorted Array.py",
    "content": "\"\"\"LEETCODE\"\"\"\n\n#QUESTION LINK:-https://leetcode.com/problems/single-element-in-a-sorted-array/\n\n#SOLUTION:-\nclass Solution(object):\n    def singleNonDuplicate(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: int\n        \"\"\"\n        l,r=0,len(nums)-1\n        if r==0:\n            return nums[-1]\n        while l<=r:\n            mid=(l+r)//2\n            if (mid==0 and nums[mid]!=nums[mid+1]) or (mid==r and nums[mid]!=nums[mid-1]) or nums[mid]!=nums[mid-1] and nums[mid]!=nums[mid+1]:\n                return nums[mid]\n            elif (mid%2==0 and nums[mid]==nums[mid-1]) or (mid%2!=0 and nums[mid]==nums[mid+1]):\n                r=mid-1\n            else:\n                l=mid+1\n        return -1\n            \n#EXPLANATION:-\n    #This question is tricky. From examples we can observe that among the repeated elements, the first occur at even index and second at odd index (until the single element is found.) We will use that trick.\n    #We will initialize a left and right (l and r) variable as 0 and len(nums)-1. \n    #If r==0(only one element of the array), we will return the only element of the array.\n    #After that we will start a while loop till l is less than r, and we will initialize a mid variable as l+r//2. \n    # Now here the tricky part comes, as first condition, we will check if the mid is at index 0 and it is not equal to next index element, OR if mid is the last index and mid is not equal to the previous index element OR if the element is neither equal to the previous nor to the next element, if it fulfills any condition, we will return the mid index.\n    # If the first condition is not fulfilled, we will check if the mid is at even index and the element before the mid is equal to current element OR if the index is odd and the next element is equal to to the current element, we will increment the r index.\n    #If none of the conditions meet, we will increment the l index.\n    #If none element found in loop, we will return -1 as element not found.\n\n#SUBMISSION REPORT:-\n    # Runtime: 147 ms, faster than 92.46% of Python online submissions for Single Element in a Sorted Array.\n    # Memory Usage: 20.6 MB, less than 20.29% of Python online submissions for Single Element in a Sorted Array.\n"
  },
  {
    "path": "Single Number II.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public int singleNumber(final int[] A) {\n        \n        int num=0,n=A.length;\n        for(int i=0;i<32;i++)\n        {\n            int count=0;\n            for(int j=0;j<n;j++)\n            {\n                if((A[j]&(1<<i))==0)count++;\n            }\n            if(count%3==0)num|=(1<<i);\n        }\n        return num;\n    }\n}\n\n"
  },
  {
    "path": "Single Number.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE LIST. IT IS READ ONLY\n    public int singleNumber(final List<Integer> A) {\n        int ans=0;\n        for(int i:A){\n            ans=ans^i;\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Sliding Window Maximum.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public int[] slidingMaximum(final int[] arr, int B) {\n        int ans[]=new int[arr.length-B+1];\n        int idx=0;\n        if(arr.length==1){\n            ans[0]=arr[0];\n            return ans;\n        }\n        Deque<Integer> q=new ArrayDeque<>();\n        int i;\n        for(i=0;i<B;i++){\n            while(!q.isEmpty() && arr[i]>=arr[q.peekLast()]){\n                q.removeLast();\n            }\n            q.addLast(i);\n        }\n        for(i=B;i<arr.length;i++){\n            ans[idx]=arr[q.peekFirst()];\n            idx++;\n            while(!q.isEmpty() && q.peekFirst()<=i-B)q.removeFirst();\n            while(!q.isEmpty() && arr[i]>=arr[q.peekLast()])q.removeLast();\n            q.addLast(i);\n        }\n        ans[idx]=arr[q.peekFirst()];\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Smaller on Left - GFG/README.md",
    "content": "# Smaller on Left\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array <strong>arr</strong>[ ] of <strong>N</strong> positive integers,&nbsp;the task is to find the greatest element on the left of every element in the array which is strictly smaller than itself, if this element does not exist for an index print \"-1\".</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 5\narr[] = {2, 3, 4, 5, 1}\n<strong>Output: \n</strong>-1 2 3 4 -1\n<strong>Explanation:</strong>\nGreatest element on the left of 3 smaller \nthan itself is 2, for 4 it is 3 and for 5 \nit is 1. Since 2 is the first element and \nno element on its left is present, so it's \ngreatest smaller element will be -1 and for \n1 no element smaller than itself is present \non its left, so it's greatest smaller element \nis -1.\n</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 3\narr[] = {1, 2, 3} <strong>\nOutput:\n</strong>-1 1 2 </span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function <strong>Smallestonleft()</strong> that takes an array <strong>arr[ ]&nbsp;</strong>and&nbsp;sizeOfArray <strong>N</strong>, and return the required answer. The driver code takes care of the printing.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N*Log(N)).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(N).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤&nbsp;10<sup>6</sup><br>\n1 ≤&nbsp;arr[i] ≤&nbsp;10<sup>8</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Smaller on Left - GFG/smaller-on-left.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\n//Initial Template for Java\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\n\nclass Array {\n    \n    // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t    int sizeOfArray = Integer.parseInt(br.readLine());\n\t\t    int arr [] = new int[sizeOfArray];\n\t\t    \n\t\t    String line = br.readLine();\n\t\t    String[] elements = line.trim().split(\"\\\\s+\");\n\t\t    for(int i = 0;i<sizeOfArray;i++){\n\t\t        arr[i] = Integer.parseInt(elements[i]);\n\t\t    }\n\t\t    \n\t\t    Complete obj = new Complete();\n\t\t    arr = obj.Smallestonleft(arr, sizeOfArray);\n\t\t    for(int i=0; i< sizeOfArray;i++){\n\t\t        System.out.print(arr[i] + \" \");\n\t\t    }\n\t\t    System.out.println();\n\t\t}\n\t}\n}\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n\n\nclass Complete{\n    public static int[] Smallestonleft (int arr[], int n) {\n        TreeSet<Integer> set = new TreeSet<>();\n        int ans[] = new int[n];\n        \n        for(int i=0; i<n; i++){\n            Integer num = set.lower(arr[i]);\n            if(num!=null){\n                ans[i] = num;\n            }else{\n                ans[i] = -1;\n            }\n            set.add(arr[i]);\n        }\n        return ans;\n    }\n}\n\n"
  },
  {
    "path": "Smallest Subset With Greater Sum.Java",
    "content": "class Solution { \n    int minSubset(int[] Arr,int N) { \n        Arrays.sort(Arr);\n        long sum=0;\n        int count=1;\n        for(int i=0;i<N;i++){\n            sum+=Arr[N-1-i];\n            if(sum> sumOf(Arr,0,N-i-2)){\n                return count;\n            }\n            count++;\n        }\n        return 0;\n    }\n    \n    long sumOf(int[] Arr ,int beg, int end){\n        long sum=0;\n        for(int i=beg;i<=end;i++){\n            sum+=Arr[i];\n        }\n     return sum;\n    }\n}\n"
  },
  {
    "path": "Smallest Subset With Greater Sum.java",
    "content": "class Solution { \n    int minSubset(int[] arr,int n) { \n        Arrays.sort(arr);\n       long sum=0;\n       for(int i=0;i<n;i++){\n           sum=sum+arr[i];\n       }\n       long sum2=0;\n       int index=n-1;\n       int count=0;\n       while(sum2<=sum){\n           sum2=sum2+arr[index];\n           sum=sum-arr[index];\n           index--;\n           count++;\n           \n       }\n       return count;\n        \n    }\n}\n"
  },
  {
    "path": "Smallest Subset with Greater Sum GFG/SmallestSubsetWithGreterSum.cpp",
    "content": "int minSubset(vector<int> &Arr,int N){\n        sort(Arr.begin(),Arr.end());\n        int count=0;\n        long long sum=0;\n        for(int i=0;i<N;i++){\n            sum+=Arr[i];\n        }\n        \n        int j=N-1;\n        long long rev=0;\n        while(j>=0){\n            sum-=Arr[j];\n            rev+=Arr[j];\n            if(rev>sum)\n            return N-j;\n            else{\n                j--;\n            }\n        }\n        return N;\n    }"
  },
  {
    "path": "Smallest Subset with Greater Sum gfg s15.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nclass Solution{\n    public:\n    int minSubset(vector<int> &Arr,int N){\n        sort(Arr.begin(), Arr.end());\n    long long sum =0;\n    for(int i =0; i<N; i++) sum+=Arr[i];\n    long long s =0;\n    for(int i =N-1; i>=1; i--){\n        s+=Arr[i];\n        sum-=Arr[i];\n        \n        if(s >sum) return N-i;\n        \n    }\n    return 1;\n    }\n};\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int N;\n        cin>>N;\n        vector<int> Arr(N);\n        for(int i=0;i<N;i++){\n            cin>>Arr[i];\n        }\n        Solution ob;\n        cout<<ob.minSubset(Arr,N)<<endl;\n    }\n    return 0;\n}"
  },
  {
    "path": "Smallest Subset with Greater Sum.Cpp",
    "content": "int minSubset(vector<int> &Arr,int N){\n        sort(Arr.begin(),Arr.end());\n        long long int sum=0;\n        for(int i=0;i<N;i++)\n        sum+=Arr[i];\n        long long int x=0;\n        int count=1;\n        for(int j=N-1;j>=1;j--)\n        {\n            x+=Arr[j];\n            if(x>sum-x)\n            break;\n            count++;\n        }\n        return count;\n    }\n"
  },
  {
    "path": "Smallest Subset with Greater Sum.java",
    "content": "class Solution { \n    int minSubset(int[] Arr,int N) { \n        if(N == 1) return 1;\n        \n        Arrays.sort(Arr);\n        int start = 0; \n        int end = N-1;\n        \n        int count = 1;\n        \n        \n        int sum = Arr[end];\n        \n        while(start < end) {\n            if(Arr[start] < sum) {\n                sum -= Arr[start++];\n            } else {\n                sum += Arr[--end];\n                count++;\n            }\n        }\n        \n        return count;\n    }\n}\n"
  },
  {
    "path": "Smallest Subset with Max Sum.py",
    "content": "class Solution:\n    def minSubset(self, A,N):\n        A.sort()\n        totalSum = sum(A)\n        currSum = 0\n        for i in range(N-1, -1, -1):\n            currSum += A[i]\n            totalSum -= A[i]\n            if totalSum<currSum:\n                return N-i\n"
  },
  {
    "path": "Smallest Value of the Rearranged Number.java",
    "content": "class Solution {\n    public long smallestNumber(long num) {\n        int sign=1;\n        if(num<0){\n            sign=-1;\n            num=0-num;\n        }\n        String s=Long.toString(num);\n        int[] digits=new int[10];\n        for(int i=0;i<s.length();i++){\n            digits[s.charAt(i)-48]++;\n        }\n        if(sign==1){//positive\n            //increasing\n            StringBuilder sb=new StringBuilder();\n            for(int i=1;i<10;i++){\n                if(digits[i]!=0){\n                    sb.append((char)(i+48));\n                    digits[i]--;\n                    break;\n                }\n            }\n            if(digits[0]!=0){\n                while(digits[0]!=0){\n                        sb.append('0');\n                        digits[0]--;\n                }\n            }\n            for(int i=1;i<10;i++){\n                if(digits[i]!=0){\n                    while(digits[i]!=0){\n                        sb.append((char)(i+48));\n                        digits[i]--;\n                    }\n                }\n            }\n            return Long.parseLong(sb.toString());\n            \n        }else{//negative\n            //decreasing \n            StringBuilder sb=new StringBuilder();\n            for(int i=9;i>=0;i--){\n                if(digits[i]!=0){\n                    while(digits[i]!=0){\n                        sb.append((char)(i+48));\n                        digits[i]--;\n                    }\n                }\n            }\n            return -Long.parseLong(sb.toString());\n        }\n    }\n}\n"
  },
  {
    "path": "Smallest distinct window - GFG/README.md",
    "content": "# Smallest distinct window\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string '<strong>s</strong>'. The task is to find the <strong>smallest </strong>window length&nbsp;that contains all the characters of the given string at least one time.<br>\nFor eg. A = <strong>aabcbcdbca</strong>, then the result would be 4 as of the smallest window will be <strong>dbca</strong>.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<div>\n<pre><span style=\"font-size:18px\">Input : \"AABBBCBBAC\"\nOutput : 3\nExplanation : Sub-string -&gt; \"BAC\"\n</span></pre>\n</div>\n\n<div><span style=\"font-size:18px\"><strong>Example 2:</strong></span></div>\n\n<pre><span style=\"font-size:18px\">Input : \"aaab\"\nOutput : 2\nExplanation : Sub-string -&gt; \"ab\"</span></pre>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Example 3:</strong></span></div>\n\n<pre><span style=\"font-size:18px\">Input : \"GEEKSGEEKSFOR\"\nOutput : 8\nExplanation : Sub-string -&gt; \"GEEKSFOR\"</span></pre>\n\n<p>&nbsp;</p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>findSubString()</strong>&nbsp;which takes the string&nbsp; <strong>S</strong><strong> </strong>as input&nbsp;and returns the length of the smallest such window of the string.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(256.N)<br>\n<strong>Expected Auxiliary Space:</strong> O(256)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ |S| ≤ 10<sup>5</sup><br>\nString may contain both type of English Alphabets.</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Smallest factorial number - GFG/README.md",
    "content": "# Smallest factorial number\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a number&nbsp;<strong>n</strong>. The task is to find the smallest number whose factorial contains at least n trailing zeroes.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>n = 1<strong>\nOutput: </strong>5\n<strong>Explanation : </strong>5! = 120 which has at\nleast 1 trailing 0.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nn = 6\n<strong>Output: </strong>25\n<strong>Explanation :</strong><strong> </strong>25! has at least\n6 trailing 0.\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>User Task:</strong><br>\nComplete the function&nbsp;<strong>findNum()</strong>&nbsp;which takes an integer N as input parameters, and returns the answer.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(log<sub>2</sub> N * log<sub>5</sub>&nbsp;N).<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(1).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= n &lt;= 10<sup>4</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Smallest factorial number - GFG/smallest-factorial-number.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\n\npublic class GFG\n{\n    public static void main(String args[])\n    {\n        Scanner sc = new Scanner(System.in);\n        \n        int t = sc.nextInt();\n        \n        while (t-- > 0)\n        {\n            int n = sc.nextInt();\n            \n            System.out.println(new Solution().findNum(n));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution\n{\n    int findNum(int n)\n    {\n        int ans = 0;\n        int low = 5;\n        int high = 5*n;\n        \n        while(low <= high){\n            int mid = low + (high-low)/2;\n            int count = 0;\n            \n            for(int i=5; mid/i >= 1; i *= 5){\n                count += mid/i;\n            }\n            \n            if(count >= n){\n                ans = mid;\n                high = mid-1;\n            }else{\n                low = mid+1;\n            }\n        }\n        return ans;\n    }\n}"
  },
  {
    "path": "Smallest greater elements in whole array - GFG/README.md",
    "content": "# Smallest greater elements in whole array\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array <strong>A</strong> of <strong>N</strong> length. We need to calculate the next greater element for each element in a given array. If the next greater element is not available in a given array then we need to fill <strong>-10000000</strong> at that index place.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[] = {13, 6, 7, 12}\n<strong>Output :</strong> _ 7 12 13 \n<strong>Explanation:</strong>\nHere, at index 0, 13 is the greatest value \nin given array and no other array element \nis greater from 13. So at index 0 we fill \n'-10000000'.\n</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input :</strong> arr[] = {6, 3, 9, 8, 10, 2, 1, 15, 7} <strong>\nOutput :</strong>  7 6 10 9 15 3 2 _ 8\n<strong>Explanation:</strong> Here, at index 7, 15 is the greatest\nvalue in given array and no other array element is\ngreater from 15. So at index 7 we fill '-10000000'.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function <strong>greaterElement()</strong> that takes an array <strong>(arr)</strong>, sizeOfArray <strong>(n)</strong>, and return an&nbsp;array that displays the next greater element to element at that index.&nbsp;The driver code takes care of the printing.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N*LOG(N)).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(N).</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n-10<sup>6</sup> ≤ A<sub>i</sub> ≤ 10<sup>6</sup></span></p>\n\n<p>&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Smallest greater elements in whole array - GFG/smallest-greater-elements-in-whole-array.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\n//Initial Template for Java\n\n/*package whatever //do not write package name here */\n\nimport java.io.*;\nimport java.util.*;\n\n\nclass Array {\n    \n    // Driver code\n\tpublic static void main (String[] args) throws IOException{\n\t\t// Taking input using buffered reader\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tint testcases = Integer.parseInt(br.readLine());\n\t\t\n\t\t// looping through all testcases\n\t\twhile(testcases-- > 0){\n\t\t    int sizeOfArray = Integer.parseInt(br.readLine());\n\t\t    int arr [] = new int[sizeOfArray];\n\t\t    \n\t\t    String line = br.readLine();\n\t\t    String[] elements = line.trim().split(\"\\\\s+\");\n\t\t    for(int i = 0;i<sizeOfArray;i++){\n\t\t        arr[i] = Integer.parseInt(elements[i]);\n\t\t    }\n\t\t    \n\t\t    Complete obj = new Complete();\n\t\t    arr = obj.greaterElement(arr, sizeOfArray);\n\t\t    for(int i=0; i< sizeOfArray;i++){\n\t\t        if(arr[i] == -10000000)\n\t\t            System.out.print(\"_ \");\n\t\t        else\n\t\t            System.out.print(arr[i] + \" \");\n\t\t    }\n\t\t    System.out.println();\n\t\t}\n\t}\n}\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\n//User function Template for Java\n\n//User function Template for Java\n\n            \n\nclass Complete{\n    \n    public static int[] greaterElement (int arr[], int n) {\n        int max = Integer.MIN_VALUE;\n        HashSet<Integer> set = new HashSet<>();\n        for(int i=0;i<n;i++){\n            set.add(arr[i]);\n            max = Math.max(max,arr[i]);\n        }\n        int[] ans = new int[n];\n        for(int i=0;i<n;i++){\n            boolean flag = false;\n            for(int j=arr[i]+1;j<=max;j++){\n                if(set.contains(j)){\n                    ans[i]=j;\n                    flag = true;\n                    break;\n                }\n            }\n            if(!flag)\n                ans[i]=-10000000;\n        }\n        return ans;\n    }\n}\n\n\n"
  },
  {
    "path": "Smallest number on left gfg med.cpp",
    "content": "//{ Driver Code Starts\n// Initial Template for C++\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// } Driver Code Ends\n// User function Template for C++\n\nclass Solution{\npublic:\n    vector<int> leftSmaller(int n, int a[]){\n        // code here\n        stack<int>s;\n        vector<int>v;\n        s.push(-1);\n        for(int i =0; i<n; i++){\n            while(!s.empty() && a[i]<=s.top()){\n                s.pop();\n            }\n            v.push_back(s.top());\n            s.push(a[i]);\n        }\n        return v;\n        \n    }\n};\n\n//{ Driver Code Starts.\n\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int a[n];\n        for(int i = 0;i < n;i++)\n            cin>>a[i];\n        \n        Solution ob;\n        vector<int> ans = ob.leftSmaller(n, a);\n        for(int i = 0;i < n;i++)\n            cout<<ans[i]<<\" \";\n        cout<<endl;\n    }\n    return 0;\n}\n// } Driver Code Ends"
  },
  {
    "path": "Smallest number on left.cpp",
    "content": "//{ Driver Code Starts\n// Initial Template for C++\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// } Driver Code Ends\n// User function Template for C++\n\nclass Solution{\npublic:\n    vector<int> leftSmaller(int n, int a[]){\n        // code here\n        stack<int>s;\n        vector<int>ans;                             //to store the answer\n        \n        for(int i=0;i<n;i++){\n            \n            if(s.empty())                           //if all element are greater or for the first element\n                ans.push_back(-1);\n                \n            else if(s.top()<a[i])\n                ans.push_back(s.top());\n                \n            else if(s.top()>=a[i]){                 //Remove elements from stack which are greater than current element\n                while(!s.empty() && s.top()>=a[i])\n                    s.pop();                        // poping till we find smaller element\n                    \n                if(s.empty())\n                    ans.push_back(-1);\n                else\n                    ans.push_back(s.top());\n            }\n            \n            s.push(a[i]);                           //push the element\n        }\n        return ans;\n    }\n};\n\n//{ Driver Code Starts.\n\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int a[n];\n        for(int i = 0;i < n;i++)\n            cin>>a[i];\n        \n        Solution ob;\n        vector<int> ans = ob.leftSmaller(n, a);\n        for(int i = 0;i < n;i++)\n            cout<<ans[i]<<\" \";\n        cout<<endl;\n    }\n    return 0;\n}\n// } Driver Code Ends\n"
  },
  {
    "path": "Smallest number on left.java",
    "content": "class Solution{\n    static List<Integer> leftSmaller(int n, int a[])\n    {\n        //code here\n        List<Integer> ans=new ArrayList<>();\n        ans.add(-1);\n        Stack<Integer> s=new Stack<>();\n        s.push(a[0]);\n        for(int i=1;i<n;i++){\n            while(!s.isEmpty() && s.peek()>=a[i]){\n                s.pop();\n            }\n            if(s.isEmpty()){\n                ans.add(-1);\n            }else{\n                ans.add(s.peek());\n            }\n            s.push(a[i]);\n        }\n        return ans;\n    }\n}\n\n\nclass Solution{\n    static List<Integer> leftSmaller(int n, int a[])\n    {\n        List<Integer> res=new ArrayList<>();\n        Stack<Integer> st=new Stack<>();\n\n        for(int i=0;i<a.length;i++) {\n            if(st.isEmpty()) {\n                res.add(-1);\n            }\n            else {\n                while(!st.isEmpty() && st.peek()>=a[i]) {\n                    st.pop();\n                }\n\n                if(st.isEmpty()) {\n                    res.add(-1);\n                }\n                else {\n                    res.add(st.peek());\n                }\n            }\n            st.push(a[i]);\n        }\n        return res;\n    }\n}\n"
  },
  {
    "path": "Smallest number with sum of digits as N and divisible by 10^N.cpp",
    "content": "class Solution{\n\tpublic:\n\tstring digitsNum(int N)\n\t{\n\t    // Code here.\n\t    string ans = \"\";\n\t    int n = N;\n\t    \n\t    while(n >= 9)\n\t    {\n\t        n -= 9;\n\t        ans.push_back('9');\n\t    }\n\t    \n\t    if(n)\n\t        ans.push_back('0'+n);\n\t    \n\t    reverse(ans.begin(), ans.end());\n\t    \n\t    for(int i=0; i<N; i++)\n\t    ans.push_back('0');\n\t    \n\t    return ans;\n\t}\n};\n"
  },
  {
    "path": "Smallest number with sum of digits as N and divisible by 10^N.java",
    "content": "class Solution\n{\n    public String digitsNum(int N)\n    {\n        // Code here\n        StringBuilder sb=new StringBuilder();\n        for(int i=0;i<N;i++){\n            sb.append(\"0\");\n        }\n        while(N!=0){\n            if(N>9){\n                sb.insert(0,9);\n                N-=9;\n            }else{\n                sb.insert(0,N);\n                N-=N;\n            }\n        }\n        return sb.toString();\n    }\n}\n"
  },
  {
    "path": "Smallest number with sum of digits as N and divisible by 10^N.py",
    "content": "class Solution:\n\tdef digitsNum(self, N):\n\t\t# Code here\n\t\tans = \"\"\n\t\tif N == 0:\n\t\t    ans += \"0\"\n\t\t    return ans\n\t\t\n\t\tif (N%9 != 0):\n\t\t    ans += chr(N%9 + ord(\"0\"))\n\t\t\n\t\tfor i in range(1, (N//9) + 1):\n\t\t    ans += \"9\"\n\t\t\n\t\tfor i in range(1, N+1):\n\t\t    ans += \"0\"\n\t\t\n\t\treturn ans\n"
  },
  {
    "path": "Smallest number with sum of digits as N and divisible by 10powerN.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n\n// } Driver Code Ends\nclass Solution{\n\tpublic:\n\tstring digitsNum(int N)\n\t{\n\t    // Code here.\n\t    \n\t    int n = N;\n\t    \n\t    string ans =\"\";\n\t    \n\t    int i=9;\n\t    while(i>=1){\n\t        \n\t        if(n>=i){\n\t            ans = to_string(i)+ans;\n\t            n -= i;\n\t        }else{\n\t            i--;\n\t        }\n\t        \n\t        if(n==0){\n\t            break;\n\t        }\n\t    }\n\t    \n\t    \n\t    for(int i=1;i<=N;i++){\n\t        ans += '0';\n\t    }\n\t    return ans;\n\t}\n};\n\n//{ Driver Code Starts.\nint main(){\n\tint tc;\n\tcin >> tc;\n\twhile(tc--){\n\t\tint n;\n\t\tcin >> n;\n\t\tSolution ob;\n\t\tstring ans = ob.digitsNum(n);\n\t\tcout << ans <<\"\\n\";\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "Smallest sum contiguous subarray.cpp",
    "content": "class Solution{\n  public:\n  int smallestSumSubarray(vector<int>& a){\n      //Code here\n      \n      int n = a.size();\n      int sum = a[0], ans = a[0];\n      \n      for(int i=1; i<n; i++)\n      {\n          if(sum > 0)\n          {\n              if(sum > a[i])\n              sum = a[i];\n          }\n          else\n            sum += a[i];\n            \n        ans = min(ans, sum);\n      }\n      \n      return ans;\n  }\n};\n\n\n// Another Approach - 2\n\nclass Solution{\n  public:\n  int smallestSumSubarray(vector<int>& a){\n      int ans = INT_MAX,sum=0;\n     for(int i=0;i<a.size();i++){\n         sum+=a[i];\n         sum = min(sum,a[i]);\n         ans = min(ans,sum);\n     }\n      return ans;\n  }\n};\n"
  },
  {
    "path": "Smallest sum contiguous subarray.java",
    "content": "\nclass Solution\n{\n    static int smallestSumSubarray(int a[], int size)\n    {\n        // your code here\n        int ans=Integer.MAX_VALUE;\n        int curSum=0;\n        for(int i=0;i<size;i++){\n            curSum+=a[i];\n            ans=Math.min(ans,curSum);\n            if(curSum>0)curSum=0;\n        }\n        return ans;\n    }\n}\n\n//Approach 2\n\nclass Solution\n{\n    static int smallestSumSubarray(int a[], int size)\n    {\n        int ans=Integer.MAX_VALUE;\n        int i=0, j=0, sum=0;\n        while(j<a.length) {\n            sum+=a[j];\n            ans=Math.min(ans, sum);\n            while(i<=j && sum>0) {  //In the question , they asked smallest sum contiguous sub array, hence we reduce the sum if sum>0 using sliding window\n                sum-=a[i];\n                i+=1;\n            }\n            j+=1;\n        }\n        return ans;\n\n    }\n}\n"
  },
  {
    "path": "Smallest sum contiguous subarray.py",
    "content": "def smallestSumSubarray(A):\n        currSum, minSum = 0, float('inf')\n        for i in A:\n            currSum += i\n            minSum = min(currSum, minSum)\n            if currSum>0: currSum = 0\n        return minSum\n"
  },
  {
    "path": "Smallest window containing 0, 1 and 2.java",
    "content": "class Solution {\n   public int smallestSubstring(String S) {\n       // Code here\n        int i=0,j=0,n=S.length();\n        int count0=0,count1=0,count2=0,size=Integer.MAX_VALUE;\n        while(j<n){\n            if(S.charAt(j)=='0')\n                count0++;\n            else if(S.charAt(j)=='1')\n                count1++;\n            else\n                count2++;\n            if(count0>=1 && count1>=1 && count2>=1){\n                while(count0>=1 && count1>=1 && count2>=1){\n                    if(S.charAt(i)=='0'){\n                        i++;\n                        count0--;\n                    }\n                    else if(S.charAt(i)=='1'){\n                        i++;\n                        count1--;\n                    }\n                    else if(S.charAt(i)=='2')\n                    {\n                        i++;\n                        count2--;\n                    }\n                }\n                size=Math.min(size,j-i+2);\n            }\n            j++;\n       }\n        if(size==Integer.MAX_VALUE)\n            return -1;\n        return size;\n   }\n};\n"
  },
  {
    "path": "SmallestNumberWithSumOfDigitsAsNAndDivisbileBy10ToThePowerN.java",
    "content": "/* \n * \nFind the smallest number such that the sum of its digits is N and it is divisible by 10N.\n\nExample 1:\n\nInput: N = 5\nOutptut: 500000\nExplanation: Sum of digits of 500000\nis 5 and divisible by 105.\nExample 2:\n\nInput: N = 20\nOutput: 29900000000000000000000\nExplanation: Sum of digits of \n29900000000000000000000 is 20 and\ndivisible by 1020.\n\nYour Task:\nYou don't need to read or print anything. Your task is to complete the function digitsNum() which takes the input parameter N and returns the smallest number such that sum of its digits is N and divisible by 10N.\n \n\nExpected Time Complexity: O(N)\nExpected Space Complexity: O(N)\n \n\nConstraints:\n1 <= N <= 10000\n * \n */\n\n\npublic class SmallestNumberWithSumOfDigitsAsNAndDivisbileBy10ToThePowerN {\n  \n    public static void main(String[] args) {\n        SmallestNumberWithSumOfDigitsAsNAndDivisbileBy10ToThePowerN obj = \n        new SmallestNumberWithSumOfDigitsAsNAndDivisbileBy10ToThePowerN();\n\n        System.out.println(obj.digitsNum(5));\n        System.out.println(obj.digitsNum(20));\n    }\n    \n  \n    public String digitsNum(int N) {\n        // Code here\n        StringBuilder sb = new StringBuilder();\n        for(int i = 0; i < N; i++) {\n            sb.append(\"0\");\n        }\n        \n        while(N > 9) {\n            N = N-9;\n            sb.append(\"9\");\n        }\n        sb.append(N);\n        \n        sb.reverse();\n        \n        return sb.toString();\n    }\n}\n"
  },
  {
    "path": "Solve-the-Sudoku - GFG/Solve-the-Sudoku.java",
    "content": "import java.util.*;\r\nimport java.io.*;\r\nimport java.lang.*;\r\n\r\nclass Driver_class\r\n{\r\n    public static void main(String args[])\r\n    {\r\n        \r\n        Scanner sc = new Scanner(System.in);\r\n        int t = sc.nextInt();\r\n        \r\n        while(t-- > 0)\r\n        {\r\n            int grid[][] = new int[9][9];\r\n            for(int i = 0; i < 9; i++)\r\n            {\r\n                for(int j = 0; j < 9; j++)\r\n                grid[i][j] = sc.nextInt();\r\n            }\r\n            \r\n            Solution ob = new Solution();\r\n            \r\n            if(ob.SolveSudoku(grid) == true)\r\n                ob.printGrid(grid);\r\n            else\r\n                System.out.print(\"NO solution exists\");\r\n            System.out.println();\r\n            \r\n        }\r\n    }\r\n}\r\n\r\nclass Solution\r\n{\r\n    static boolean isValid(int grid[][],int i, int j, int k){\r\n        for(int row = 0;row<9;row++){\r\n            if(grid[row][j]==k) return false;\r\n        }\r\n        for(int col = 0;col<9;col++){\r\n            if(grid[i][col]==k) return false;\r\n        }\r\n        int col = (j/3)*3;\r\n        int row = (i/3)*3;\r\n        for(int l = 0;l<3;l++){\r\n            for(int m = 0;m<3;m++){\r\n                if(grid[row+l][col+m]==k) return false;\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n    static boolean solve(int grid[][],int i,int j){\r\n        int ni = 0,nj = 0;\r\n        if(i==9){\r\n            return true;\r\n        }\r\n        if(j==8){\r\n            ni=i+1;\r\n            nj=0;\r\n        }else{\r\n            ni = i;\r\n            nj = j+1;\r\n        }\r\n        if(grid[i][j]!=0) return solve(grid,ni,nj);\r\n        \r\n        for(int k = 1;k<=9;k++){\r\n            if(isValid(grid,i,j,k)){\r\n                grid[i][j] = k;\r\n                if(solve(grid,ni,nj)){\r\n                    return true;\r\n                }\r\n                grid[i][j] = 0;\r\n            }\r\n        }\r\n        \r\n       return false;\r\n    }\r\n    static boolean SolveSudoku(int grid[][]){return solve(grid,0,0);}\r\n\r\n    static void printGrid (int grid[][])\r\n    {\r\n        for(int i = 0;i<9;i++){\r\n            for(int j = 0;j<9;j++){ System.out.print(grid[i][j]+\" \");} \r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Sort Binary Linked List.java",
    "content": "public class Solution {\n    public ListNode solve(ListNode A) {\n        ListNode head = A;\n        ListNode curr = A;\n        ListNode prev = null;\n        ListNode next = null;\n        while (curr != null){\n            next = curr.next;\n            if(curr.val == 0){\n                if(prev != null){\n                    prev.next = next;\n                    curr.next = head;\n                    head = curr;\n                }else {\n                    prev = curr;\n                }\n            }else {\n                prev = curr;\n            }\n            curr = next;\n        }\n        return head;\n    }\n}\n"
  },
  {
    "path": "Sort Even and Odd Indices Independently.java",
    "content": "class Solution {\n    public int[] sortEvenOdd(int[] nums) {\n        List<Integer> even=new ArrayList<>();;\n        List<Integer> odd=new ArrayList<>();;\n        for(int i=0;i<nums.length;i++){\n            if(i%2==0){\n                even.add(nums[i]);\n            }else{\n                odd.add(nums[i]);\n            }\n        }\n        Collections.sort(even);\n        Collections.sort(odd,Collections.reverseOrder());\n        int i=0;\n        int j=0;\n        int index=0;\n        while(i<even.size() && j<odd.size()){\n            nums[index]=even.get(i);\n            index++;\n            nums[index]=odd.get(j);\n            index++;\n            i++;\n            j++;\n        }\n        if(j==odd.size() && i<even.size()){\n            nums[index]=even.get(i);\n        }\n        return nums;\n    }\n}\n"
  },
  {
    "path": "Sort List.java",
    "content": "//Faster\nclass Solution {\n    public ListNode sortList(ListNode head) {\n        int len = 0;\n        ListNode h = head;\n        while (h != null) {\n            len++;\n            h = h.next;\n        }\n        \n        int[] tmp = new int[len];\n        \n        h = head;\n        for (int i = 0; i < len; i++) {\n            tmp[i] = h.val;\n            h = h.next;\n        }\n        \n        Arrays.sort(tmp);\n        \n        h = head;\n        for (int i = 0; i < len; i++) {\n            h.val = tmp[i];\n            h = h.next;\n        }\n        \n        return head;\n    }\n}\n\n//==============================================================\n//merge sort (iterative)\n\nclass Solution {\n    public ListNode sortList(ListNode head) {\n        if (head == null || head.next == null)\n            return head;\n        ListNode mid = getMid(head);\n        ListNode left = sortList(head);\n        ListNode right = sortList(mid);\n        return merge(left, right);\n    }\n\n    ListNode merge(ListNode list1, ListNode list2) {\n        ListNode dummyHead = new ListNode();\n        ListNode tail = dummyHead;\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        tail.next = (list1 != null) ? list1 : list2;\n        return dummyHead.next;\n    }\n\n    ListNode getMid(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}\n//===============================================================================\n//merge sort (recursive)\npublic class Solution {\n\n    public ListNode merge(ListNode A,ListNode B){\n        ListNode res=null;\n        if(A==null)\n            return B;\n        if(B==null)\n            return A;\n        if(A.val<=B.val){\n            res=A;\n            res.next=merge(A.next,B);\n        }else{\n            res=B;\n            res.next=merge(A,B.next);\n        }\n        return res;\n    }\n\n    public ListNode sortList(ListNode A) {\n        if(A==null || A.next==null)\n            return A;\n        ListNode middle=getMiddle(A);\n        ListNode nextOfMiddle=middle.next;\n        middle.next=null;\n        ListNode left=sortList(A);\n        ListNode right=sortList(nextOfMiddle);\n        ListNode ans=merge(left,right);\n        return ans;\n    }\n\n    public ListNode getMiddle(ListNode A){\n        if(A==null)\n            return A;\n        ListNode slow=A,fast=A;\n        while(fast.next!=null && fast.next.next!=null){\n            slow=slow.next;\n            fast=fast.next.next;\n        }\n        return slow;\n    }\n}\n"
  },
  {
    "path": "Sort by Set Bit Count.java",
    "content": "class Compute  \n{ \n    static void sortBySetBitCount(Integer arr[], int n)\n    { \n        // Your code goes here\n        Arrays.sort(arr, new Comparator<Integer>() {\n            @Override\n            public int compare(Integer o1, Integer o2) {\n                return countSetBits(o2)-countSetBits(o1);\n            }\n        });\n    }\n    static int countSetBits(int n)\n    {\n        int count = 0;\n        while (n > 0) {\n            count += n & 1;\n            n >>= 1;\n        }\n        return count;\n    }\n==========================================================================\n    class Compute  \n{ \n    static void sortBySetBitCount(Integer arr[], int n)\n    { \n        // Your code goes here\n        Arrays.sort(arr,(o1,o2)-> Integer.bitCount(o2)-Integer.bitCount(o1));\n    }\n}\n"
  },
  {
    "path": "Sorted Array To Balanced BST.java",
    "content": "public class Solution {\n    // DO NOT MODIFY THE ARGUMENTS WITH \"final\" PREFIX. IT IS READ ONLY\n    public TreeNode sortedArrayToBST(final int[] A) {\n        return makeTree(A,0,A.length-1);\n    }\n    public TreeNode makeTree(int[]a,int start,int end){\n        if(start>end)return null;\n        int mid=start+(end-start)/2;\n        TreeNode root=new TreeNode(a[mid]);\n        if(start==end)return root;\n        else{\n            root.left=makeTree(a,start,mid-1);\n            root.right=makeTree(a,mid+1,end);\n        }\n        return root;\n    }\n}\n"
  },
  {
    "path": "Sorted Insert Position.java",
    "content": "public class Solution {\n\tpublic int searchInsert(ArrayList<Integer> a, int b) {\n        int i=0;\n        int j=a.size();\n        while(i<j){\n            int mid=(i+j)/2;\n            if(a.get(mid)==b){\n                return mid;\n            }else if(a.get(mid)<b){\n                i=mid+1;\n            }else{\n                j=mid;\n            }\n        }\n        return i;\n\t}\n}\n"
  },
  {
    "path": "Sorted Link List to BST - GFG/README.md",
    "content": "# Sorted Link List to BST\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a Singly Linked List which has data members sorted in ascending order. Construct a&nbsp;Balanced Binary Search Tree&nbsp;which has same data members as the given Linked List.<br>\n<strong>Note: </strong>There might be nodes with same value.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nLinked List: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7\n<strong>Output:</strong>\n4 2 1 3 6 5 7\n<strong>Explanation :</strong>\nThe BST formed using elements of the \nlinked list is,\n        4\n      /   \\\n     2     6\n   /  \\   / \\\n  1   3  5   7  \nHence, preorder traversal of this \ntree is 4 2 1 3 6 5 7\n</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nLinked List : 1-&gt;2-&gt;3-&gt;4\n<strong>Ouput:</strong>\n3 2 1 4\n<strong>Exaplanation:</strong>\nThe BST formed using elements of the \nlinked list is,\n      3   \n    /  \\  \n   2    4 \n / \n1\nHence, the preorder traversal of this \ntree is 3 2 1 4\n</span></pre>\n\n<div><span style=\"font-size:18px\"><strong>Your task :</strong></span></div>\n\n<div><span style=\"font-size:18px\">You don't have to read input or print anything. Your task is to complete the function <strong>sortedListToBST()</strong>, which takes <strong>head</strong> of the linked list as an input parameter and returns the root of the BST created.</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N), N = number of Nodes<br>\n<strong>Expected Auxiliary Space:</strong> O(N), N = number of Nodes</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Constraints</strong>:</span></div>\n\n<div><span style=\"font-size:18px\">1 ≤ Number of Nodes ≤ 10<sup>6</sup></span></div>\n\n<div><span style=\"font-size:18px\">1 ≤ Value of each node ≤ 10<sup>6</sup></span></div>\n <p></p>\n            </div>"
  },
  {
    "path": "Special Matrix.java",
    "content": "class Solution{\n    int mod=1000000007;\n    public int FindWays(int n, int m, int[][] bl){\n        int[][]arr=new int[n+1][m+1];\n        for(int i=0;i<bl.length;i++){\n            int x=bl[i][0];\n            int y=bl[i][1];\n            arr[x][y]=-1;\n        }\n        if(arr[1][1]==-1 || arr[n][m]==-1){\n            return 0;\n        }\n        int[][]dp=new int[n+1][m+1];\n        dp[1][1]=1;\n        for(int i=1;i<=n;i++){\n            for(int j=1;j<=m;j++){\n                if(i!=1 || j!=1){\n                    if(arr[i][j]==-1){\n                        dp[i][j]=0;\n                    }else{\n                        int up=dp[i-1][j];\n                        int left=dp[i][j-1];\n                        dp[i][j]=up+left;\n                    }\n                }\n            }\n        }\n        return dp[n][m]%mod;\n    }\n}\n"
  },
  {
    "path": "Spidey Sense.java",
    "content": "class Solution{\n    \n    static int directions[][] = {{-1,0},{0,1},{1,0},{0,-1}};\n    \n    public static void add(char mat[][], int i, int j, boolean visited[][], Queue<int[]> q){\n        int n = mat.length;\n        int m = mat[0].length;\n        if(i<0 || i>=n || j<0 || j>=m || visited[i][j] || mat[i][j]=='W') return;\n        visited[i][j] = true;\n        q.offer(new int[]{i,j});\n    }\n    \n    public static int bfs(char mat[][], int i, int j){\n        int n = mat.length;\n        int m = mat[0].length;\n        boolean visited[][] = new boolean[n][m];\n        visited[i][j] = true;\n        Queue<int[]> q = new LinkedList<>();\n        q.offer(new int[]{i,j});\n        int min = 0;\n        while(!q.isEmpty()){\n            int len = q.size();\n            min++;\n            for(int k=0;k<len;k++){\n                int curr[] = q.poll();\n                if(mat[curr[0]][curr[1]]=='B') return min-1;\n                for(int dir[]: directions) add(mat,curr[0]+dir[0],curr[1]+dir[1],visited,q);\n            }\n        }\n        return -1;\n    }\n    \n    public static int[][] findDistance(char mat[][], int n,int m){\n        // Your code goes here\n        int arr[][] = new int[n][m];\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(mat[i][j]=='W') arr[i][j] = -1;\n                else if(mat[i][j]=='B') arr[i][j] = 0;\n                else arr[i][j] = bfs(mat,i,j);\n            }\n        }\n        return arr;\n    }\n}\n"
  },
  {
    "path": "Spiral Matrix.java",
    "content": "public class Solution {\n    public int[][] solve(int[] A, int B, int C) {\n        int res[][]=new int[B][C];\n        int top = 0, bottom = B-1, left = 0, right = C-1;\n        int val = 1,direction=1 , k = 0;\n        while(left <= right && top <= bottom){\n            if(direction == 1){   \n                for(int i=left;i<=right;i++)\n                    res[top][i] = A[k++];\n                top++;\n                direction=2;\n            }\n            else if(direction == 2){\n                for(int i = top;i<=bottom;i++)\n                    res[i][right] = A[k++];\n                right--;\n                direction = 3;\n            }\n            else if(direction == 3){\n                for(int i = right;i>=left;i--)\n                    res[bottom][i]=A[k++];\n                bottom--;\n                direction=4;\n            }\n            else if(direction == 4){\n                for(int i=bottom;i>=top;i--)\n                    res[i][left]=A[k++];\n                left++;\n                direction = 1;\n            }\n        }\n        return res;\n    }\n}\n"
  },
  {
    "path": "Spiral Order Matrix II.java",
    "content": "public class Solution {\n    public int[][] generateMatrix(int n) {\n        int[][] arr=new int[n][n];\n        for(int i=0;i<n;i++){\n            arr[0][i]=i+1;\n        }\n        int colBack=n-1;\n        int rowTop=1;\n        int colFront=0;\n        int rowBottom=n-1;\n        char dir='D';\n        while(true){\n            if(rowTop>rowBottom || colBack<colFront)break;\n            if(dir=='D'){\n                for(int i=rowTop;i<=rowBottom;i++){\n                    arr[i][colBack]=arr[i-1][colBack]+1;\n                }\n                dir='L';\n                colBack--;\n            }else if(dir=='L'){\n                for(int i=colBack;i>=colFront;i--){\n                    arr[rowBottom][i]=arr[rowBottom][i+1]+1;\n                }\n                dir='U';\n                rowBottom--;\n            }else if(dir=='U'){\n                for(int i=rowBottom;i>=rowTop;i--){\n                    arr[i][colFront]=arr[i+1][colFront]+1;\n                }\n                dir='R';\n                colFront++;\n            }else if(dir=='R'){\n                for(int i=colFront;i<=colBack;i++){\n                    arr[rowTop][i]=arr[rowTop][i-1]+1;\n                }\n                dir='D';\n                rowTop++;\n            }\n        }\n\n        return arr;\n    }\n}\n"
  },
  {
    "path": "Split_Array_Into_Consecutive_subsequence.java",
    "content": "\nclass Solution {\n    public boolean isPossible(int[] nums) {\n        HashMap<Integer,Integer> available = new HashMap<>();\n        for(int i:nums)\n            available.put(i,available.getOrDefault(i,0)+1);\n        HashMap<Integer,Integer> vacancyFor = new HashMap<>();\n        for(int i:nums)\n        {\n            int freq = available.get(i);\n            if(freq > 0)\n            {\n                if(vacancyFor.containsKey(i) && vacancyFor.get(i)>0)\n                {\n                    vacancyFor.put(i,vacancyFor.getOrDefault(i,0)-1);\n                    vacancyFor.put(i+1,vacancyFor.getOrDefault(i+1,0)+1);\n                    available.put(i,available.getOrDefault(i,0)-1);\n                }\n                else\n                {\n                    if(available.containsKey(i+1) && available.containsKey(i+2) && available.get(i+1)>0 && available.get(i+2)>0)\n                    {\n                        vacancyFor.put(i+3,vacancyFor.getOrDefault(i+3,0)+1);\n                        available.put(i,available.getOrDefault(i,0)-1);\n                        available.put(i+1,available.getOrDefault(i+1,0)-1);\n                        available.put(i+2,available.getOrDefault(i+2,0)-1);\n                    }\n                    else\n                        return false;\n                }\n            }\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "Square Root of Integer.java",
    "content": "public class Solution {\n    public int sqrt(int A) {\n        if (A == 0 || A == 1) return A;\n        if (A == 2 || A == 3) return 1;\n        int i=1;\n        int j=A/2;\n        int expect=0;\n        while(i<=j){\n            int m=i+(j-i)/2;\n\n            if(m<=A/m){\n                i=m+1;\n                expect=m;\n            }else{\n                j=m-1;\n            }\n        }\n        return expect;\n    }\n}\n"
  },
  {
    "path": "Stack Permutation med gfg sep7.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution{\npublic:\n    int isStackPermutation(int N,vector<int> &A,vector<int> &B){\n        // creating stack and a variable to traverse through 'B' variable\n        stack<int>st; int j=0;\n        \n        for(int i =0; i<N; i++){\n            // pushing/inserting into stack 1st\n            st.push(A[i]);\n            while(!st.empty()){\n                // checking if the inserted element is equal to B's element, if matched pop and increment else break\n                if(st.top()==B[j]){\n                    // pop until it is matching & incrementing j to match next B element\n                    j++; st.pop();\n                }\n                else break;\n            }\n        }\n        // if stack empty i.e all elements satisfies with B return true(1) \n        if(st.empty()) return 1;\n        // if any element left in the stack i.e !stack.empty return false \n        else return 0;\n    }\n};\n\nint main(){\n    \n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        vector<int> a(n),b(n);\n        for(int i=0;i<n;i++){\n            cin>>a[i];\n        }\n        for(int i=0;i<n;i++){\n            cin>>b[i];\n        }\n        Solution ob;\n        cout<<ob.isStackPermutation(n,a,b)<<endl;\n    }\n    \n    return 0;\n}"
  },
  {
    "path": "Stack Permutations [GFG POTD(07-09-22)].java",
    "content": "class Solution {\n    public static int isStackPermutation(int n, int[] ip, int[] op) {\n        // code here\n        int[]ans= new int [n];\n        Stack<Integer> s= new Stack<>();\n        int j=0,i=0;\n        for(int k=0;k<n*2;k++){\n            if(!s.isEmpty() && s.peek()==op[j]){\n               ans[j]=s.pop();\n               j++;\n            }\n            else if(!s.isEmpty() && s.peek()!=op[j] && i>=n){\n                return 0;\n            }\n            else{\n                s.push(ip[i]);\n                i++;\n            }\n            \n        }\n        if(Arrays.equals(ans,op)){\n            return 1;\n        }\n       return 0; \n    }\n}\n"
  },
  {
    "path": "Stack Permutations.java",
    "content": "class Solution {\n    public static int isStackPermutation(int n, int[] ip, int[] op) {\n        // code here\n        Stack<Integer> s=new Stack<>();\n        int i=0;\n        int j=0;\n        while(j<n){\n            while(i<n && (s.isEmpty() || s.peek()!=op[j])){\n                s.push(ip[i]);\n                i++;\n            }\n            while(!s.isEmpty() && s.peek()==op[j]){\n                s.pop();\n                j++;\n            }\n            if(i==n && !s.isEmpty() && s.peek()!=op[j])return 0;\n        }\n        return 1;\n    }\n}\n"
  },
  {
    "path": "Stack Permutations.py",
    "content": "def isStackPermutation(N, A, B):\n        arr = []\n        i = j = 0\n        while True:\n            if arr and arr[-1] == B[j]:\n                if j>=len(B): break\n                arr.pop()\n                j+=1\n            else:\n                if i>=len(A): break\n                arr.append(A[i])\n                i+=1\n        return 1 if len(arr) == 0 else 0\n"
  },
  {
    "path": "Step by Step.java",
    "content": "public class Solution {\n    public int solve(int A) {\n        A=Math.abs(A);\n        int i=0;\n        int sum=0;\n        while(sum<A){\n            i++;\n            sum+=i;\n        }\n        while((sum-A)%2!=0){\n            i++;\n            sum+=i;\n        }\n        return i;\n    }\n}\n"
  },
  {
    "path": "Stepping Numbers - GFG/README.md",
    "content": "# Stepping Numbers\n## Medium\n<div class=\"problems_problem_content__Xm_eO\"><p><span style=\"font-size:18px\">A number is called a stepping number if all adjacent digits have an absolute difference of 1, e.g. '321' is a Stepping Number while 421 is not. Given two integers<strong> n&nbsp;</strong>and <strong>m</strong>, find the count of all the stepping numbers in the range [n, m].<br>\n<br>\n<strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> n = 0, m = 21\n<strong>Output:</strong> 13\n<strong>Explanation: </strong>Stepping no's are 0 1 2 3 4 5\n6 7 8 9 10 12 21</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> n = 10, m = 15\n<strong>Output:</strong> 2\n<strong>Explanation: </strong>Stepping no's are 10, 12</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>steppingNumbers()</strong>&nbsp;which takes the integer <strong>n</strong>&nbsp;and integer <strong>m</strong>&nbsp;as input parameters and returns the number of stepping numbers in the range between <strong>n</strong> and <strong>m</strong>.<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(log(M))<br>\n<strong>Expected Auxiliary Space:</strong> O(SN) where SN is the number of stepping numbers in the range</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n0 ≤ N &lt; M ≤ 10</span><sup><span style=\"font-size:15px\">7</span></sup></p>\n</div>"
  },
  {
    "path": "Stepping Numbers - GFG/stepping-numbers.java",
    "content": "//{ Driver Code Starts\n//Initial Template for Java\n\n\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        \n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n            int  N = Integer.parseInt(input_line[0]);\n            int  M = Integer.parseInt(input_line[1]);\n            \n            Solution ob = new Solution();\n            int ans = ob.steppingNumbers(N, M);\n            System.out.println(ans);\n        }\n    }\n}\n\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    int steppingNumbers(int n, int m){\n        // code here\n        int ans=0;\n        if(n==0)ans++;\n        Queue<Integer> q=new LinkedList<>();\n        for(int i=1;i<=9;i++){\n            q.add(i);\n        }\n        while(q.size()>0){\n            int sz=q.size();\n            while(sz-->0){\n                int ele=q.remove();\n                if(ele>=n && ele<=m)ans++;\n                int lastDigit=ele%10;\n                if(lastDigit==9){\n                    int next=ele*10+8;\n                    if(next<=m)q.add(next);\n                }else if(lastDigit==0){\n                    int next=ele*10+1;\n                    if(next<=m)q.add(next);\n                }else{\n                    int smaller=ele*10+(lastDigit-1);\n                    if(smaller<=m)q.add(smaller);\n                    int greater=ele*10+(lastDigit+1);\n                    if(greater<=m)q.add(greater);\n                }\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Steps by Knight",
    "content": "class Solution\n{\n    public int minStepToReachTarget(int KnightPos[], int TargetPos[], int N)\n    {\n        boolean [][]vis = new boolean[N+1][N+1];\n        \n        Queue<int[]> q = new ArrayDeque<>();\n        q.add(KnightPos);\n        \n        vis[KnightPos[0]][KnightPos[1]] =true;\n        int step =0;\n        \n        int [][]dir ={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};\n        \n        while(q.size() > 0){\n            \n            int sz = q.size();\n                \n            while(sz-- >0 ){\n                int []pos = q.poll();\n                \n                if( pos[0] == TargetPos[0] && pos[1] == TargetPos[1] ){\n                    return step;\n                }\n                \n                for(int i=0 ; i < 8 ;i++){\n                    int r = pos[0] + dir[i][0];\n                    int c = pos[1] + dir[i][1];\n                    \n                    if( r > 0 && r <= N && c > 0 && c <= N && !vis[r][c] ){\n                        vis[r][c] =true;\n                        q.offer( new int[]{r ,c } );\n                    }\n                }\n                \n            }\n            step++;\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "Stock buy and sell - GFG/Stock buy and sell.cpp",
    "content": "// N = 7\n// A[] = { 100, 180, 260, 310, 40, 535, 695 }\n\n\n// This function finds the buy sell schedule for maximum profit\nvoid stockBuySell(int price[], int n) {\n    // code here\n    vector<vector<int>> v;\n    // int profit = 0;\n    for(int i=1;i<n;){\n        if(price[i] >= price[i-1]){\n            int j = i;\n            while(j < n and price[j] >= price[j-1]){\n                j++;\n            }\n            // profit = max(profit, (price[j-1] - price[i-1]));\n            v.push_back({i-1, j-1});\n            i = j;\n        }else i++;\n    }\n    // cout<<profit<<\"\\n\";\n    if(v.size() == 0) cout<<\"No Profit\";\n    else{\n        for(int i=0;i<v.size();i++){\n            cout<<\"(\"<<v[i][0]<<\" \"<<v[i][1]<<\") \";\n        }\n    }\n    cout<<\"\\n\";\n}\n"
  },
  {
    "path": "Stone Game IV.java",
    "content": "class Solution {\n    public boolean winnerSquareGame(int n) {\n        boolean[] dp = new boolean[n + 1];\n        for (int i = 0; i < n + 1; i++) {\n            for (int k = 1; k * k <= i; k++) {\n                if (dp[i - k * k] == false) {\n                    dp[i] = true;\n                    break;\n                }\n            }\n        }\n        return dp[n];\n    }\n}\n"
  },
  {
    "path": "String And Its Frequency.java",
    "content": "public class Solution {\n    public String solve(String A) {\n        StringBuilder sb=new StringBuilder();\n        int[]freq=new int[26];\n        for(char c:A.toCharArray()){\n            freq[c-'a']++;\n        }\n        for(int i=0;i<A.length();i++){\n            char ch=A.charAt(i);\n            if(freq[ch-'a']>0){\n                sb.append(ch);\n                sb.append(freq[ch-'a']);\n                freq[ch-'a']=0;\n            }\n        }\n        return sb.toString();\n    }\n}\n"
  },
  {
    "path": "String formation from substring - GFG/README.md",
    "content": "# String formation from substring\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string s, the task is to check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.&nbsp; </span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> s = \"ababab\"\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> It is contructed by \nappending \"ab\" 3 times</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> s = \"ababac\"\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> Not possible to construct</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>User Task:</strong><br>\nYour task is to complete the function <strong><code>isRepeat</code>()&nbsp;</strong>which takes a single string as input and returns 1 if possible to construct, otherwise 0. You do not need to take any input or print anything.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(|s|)<br>\n<strong>Expected Auxiliary Space:&nbsp;</strong>O(|s|)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= |s| &lt;= 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "String formation from substring - GFG/string-formation-from-substring.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            String input = read.readLine();\n            \n            Solution ob = new Solution();\n            int result = ob.isRepeat(input);\n            \n            System.out.println(result);\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    int isRepeat(String s) {\n        if(s.length()==1)return 0;\n        if(s.length()==2){\n            if(s.charAt(0)==s.charAt(1)) return 1;\n            return 0;\n        }\n        String t = s+s;\n        String ns = t.substring(2,t.length()-1);\n        if(ns.indexOf(s)!=-1)return 1;\n        return 0;\n    }\n}"
  },
  {
    "path": "String to Integer (atoi).java",
    "content": "class Solution {\n    public int myAtoi(String s) {\n        int sign=1,flagSign=0,n=s.length();\n        long ans=0;\n        for(int i=0;i<n;i++) {\n            if(s.charAt(i)=='-' && flagSign==0) {\n                sign=-1;\n                flagSign=1;\n            }\n            else if(s.charAt(i)=='+' && flagSign==0) {\n                flagSign=1;\n            }\n            else if(s.charAt(i)==' ' && flagSign==0) {\n                continue;\n            }\n            else if(s.charAt(i)>='0'&&s.charAt(i)<='9') {\n                ans=ans*10+(s.charAt(i)-'0');\n                if(ans*sign>=Integer.MAX_VALUE) {\n                    return Integer.MAX_VALUE;\n                }\n                else if(ans*sign<=Integer.MIN_VALUE) {\n                    return Integer.MIN_VALUE;\n                }\n                flagSign=1;\n            }\n            else break;\n        }\n        ans=ans*sign;\n        return (int)ans;\n    }\n}\n"
  },
  {
    "path": "Subarray Sum Equals K.java",
    "content": "public class Solution {\n    public int subarraySum(int[] nums, int k) {\n        int count = 0, sum = 0;\n        Map < Integer, Integer > map = new HashMap<>();\n        map.put(0, 1);\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}\n"
  },
  {
    "path": "Subarray with equal occurences!.java",
    "content": "public class Solution {\n    public int solve(int[] A, int B, int C) {\n        int ans=0;\n        for(int i=0;i<A.length;i++){\n            int cntB=0;\n            int cntC=0;\n            for(int j=i;j<A.length;j++){\n                if(A[j]==B){\n                    cntB++;\n                }else if(A[j]==C){\n                    cntC++;\n                }\n                if(cntB==cntC){\n                    ans++;\n                }\n            }\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "Subarray with given sum - GFG/Subarray with given sum.cpp",
    "content": "//{ Driver Code Starts\r\n#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\n\r\n// } Driver Code Ends\r\nclass Solution\r\n{\r\n    public:\r\n      vector<int> subarraySum(int arr[], int n, long long s)\r\n    {\r\n        vector<int> ans;\r\n        if(s==0)\r\n        {\r\n            ans.push_back(-1);\r\n            return ans;\r\n        }\r\n        int start=0;\r\n        int end=0;\r\n        long long sum=0;\r\n        while(end<n &&sum<s)\r\n        {\r\n            sum=sum+arr[end];\r\n            if(sum<s)\r\n            end++;\r\n        }\r\n        if(end==n)\r\n        {\r\n            ans.push_back(-1);\r\n            return ans;\r\n        }\r\n        if(sum==s)\r\n        {\r\n            ans.push_back(start+1);\r\n            ans.push_back(end+1);\r\n            return ans;\r\n        }\r\n        end++;\r\n        while(end<n)\r\n        {\r\n            while(sum>s)\r\n            {\r\n                sum=sum-arr[start];\r\n                start++;\r\n                                if(sum==s)\r\n                               {\r\n                                   ans.push_back(start+1);\r\n                                   ans.push_back(end);\r\n                                  return ans;\r\n                                }\r\n\r\n            }\r\n            while(end<n&&sum<s)\r\n            {\r\n                sum=sum+arr[end];\r\n                if(sum==s)\r\n                {\r\n                                ans.push_back(start+1);\r\n                                ans.push_back(end+1);\r\n                                return ans;\r\n                }\r\n                end++;\r\n            }\r\n        }\r\n        while(start<n&&sum>s)\r\n        {\r\n                            sum=sum-arr[start];\r\n                            start++;\r\n                                if(sum==s)\r\n                               {\r\n                                   ans.push_back(start+1);\r\n                                   ans.push_back(end);\r\n                                  return ans;\r\n                                }\r\n\r\n        }\r\n        ans.push_back(-1);\r\n        return ans;\r\n    }\r\n};\r\n\r\n//{ Driver Code Starts.\r\n\r\nint main()\r\n {\r\n    int t;\r\n    cin>>t;\r\n    while(t--)\r\n    {\r\n        int n;\r\n        long long s;\r\n        cin>>n>>s;\r\n        int arr[n];\r\n        const int mx = 1e9;\r\n        for(int i=0;i<n;i++)\r\n        {\r\n            cin>>arr[i];\r\n        }\r\n        Solution ob;\r\n        vector<int>res;\r\n        res = ob.subarraySum(arr, n, s);\r\n        \r\n        for(int i = 0;i<res.size();i++)\r\n            cout<<res[i]<<\" \";\r\n        cout<<endl;\r\n        \r\n    }\r\n\treturn 0;\r\n}\r\n// } Driver Code Ends"
  },
  {
    "path": "Subset.java",
    "content": "public class Solution {\n    \n    ArrayList<ArrayList<Integer>> res;\n    ArrayList<Integer> A;\n    int N;\n    \n\tpublic ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> A) {\n\t    ArrayList<Integer> temp;\n\t    res = new ArrayList<>();\n\t    temp = new ArrayList<>();\n\t    this.A = A;\n\t    N = A.size();\n\t    Collections.sort(A);\n\t    \n\t    subset(0, temp);\n\t    \n\t    Collections.sort(res, new Comparator<ArrayList<Integer>>() {\n\t        @Override\n\t        public int compare(ArrayList<Integer> a, ArrayList<Integer> b) {\n\t            int an = a.size();\n\t            int bn = b.size();\n\t            for (int i = 0; i < Math.min(an, bn); i++) {\n\t                int cmp = Integer.compare(a.get(i), b.get(i));\n\t                if (cmp != 0)\n\t                    return cmp;\n\t            }\n\t            return Integer.compare(a.size(), b.size());\n\t        }\n\t    });\n\t    \n\t    return res;\n\t    \n\t}\n\t\n\tprivate void subset(int index, ArrayList<Integer> arr) {\n\t    \n\t    if (index == N) {\n\t        res.add(new ArrayList<>(arr));\n\t        return;\n\t    }\n\t    \n\t    subset(index + 1, arr);\n\t    arr.add(A.get(index));\n\t    subset(index + 1, arr);\n\t    arr.remove(arr.size() - 1);\n\t    \n\t}\n\t\n\t\n}\n"
  },
  {
    "path": "Subsets II.java",
    "content": "public class Solution {\n    ArrayList<ArrayList<Integer>> ans;\n    public ArrayList<ArrayList<Integer>> subsetsWithDup(ArrayList<Integer> A) {\n        ans=new ArrayList<>();\n        ans.add(new ArrayList<>());\n        Collections.sort(A);\n        dfs(0,A,new ArrayList<>());\n        return ans;\n    }\n    public void dfs(int idx,ArrayList<Integer> a,ArrayList<Integer> curr){\n        if(idx==a.size())return;\n        for(int i=idx;i<a.size();i++){\n            curr.add(a.get(i));\n            if(!ans.contains(curr))ans.add(new ArrayList<>(curr));\n            dfs(i+1,a,curr);\n            curr.remove(curr.size()-1);\n        }\n    }\n}\n"
  },
  {
    "path": "Subsets with XOR value - GFG/README.md",
    "content": "# Subsets with XOR value\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:20px\">Given an array arr&nbsp;of N integers&nbsp;and an integer&nbsp;K, find the number of subsets of arr having XOR of elements as K.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 4\nk = 6\narr: 6 9 4 2</span><span style=\"font-size:18px\">\n<strong>Output:</strong>\n2\n<strong>Explanation:</strong>\nThe subsets are \n{4,2} and {6}</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 5\nK = 4\narr: </span><span style=\"font-size:18px\">1 2 3 4 5\n<strong>Output:</strong>\n4\n<strong>Explanation:</strong>\nThe subsets are {1, 5},\n{4}, {1, 2, 3, 4},\nand {2, 3, 5}</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>subsetXORâ€‹()</strong>&nbsp;which takes the array arr[], its size N and an integer K as input parameters&nbsp;and returns the number of subsets having xor as K</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity: </strong>O(N*M)<br>\n<strong>Expected Space Complexity: </strong>O(N*M)<br>\nNote: M = maximum value any XOR subset will acquire</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1&lt;=N&lt;=20<br>\n1&lt;=K&lt;=100<br>\n0&lt;=arr[i]&lt;=100</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Subsets with XOR value - GFG/subsets-with-xor-value.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n\nimport java.io.*;\nimport java.util.*;\n\n // } Driver Code Ends\n//User function Template for Java\n\nclass Solution{\n    static int subsetXOR(int arr[], int N, int K) { \n        int max_ele = arr[0]; \n        for (int i=1; i<N; i++) \n          if (arr[i] > max_ele) \n              max_ele = arr[i]; \n              \n        int m = 10*max_ele;\n            \n        int[][] dp = new int[N+1][m+1];\n        \n        dp[0][0] = 1;\n        \n        for(int i=1;i<=N;i++){\n            for(int j=0;j<=m;j++){\n                dp[i][j] += dp[i-1][j]; \n                if((j^arr[i-1])<=m){\n                    dp[i][j] += dp[i-1][j^arr[i-1]];\n                }\n            }\n        }\n        \n        return dp[N][K]; \n    } \n}\n\n// { Driver Code Starts.\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        Scanner s = new Scanner(System.in);\n        int t = s.nextInt();\n        while(t-- > 0)\n        {\n            int N = s.nextInt();\n            int K = s.nextInt();\n            int arr[] = new int[N];\n            for(int i =0;i<N;i++)\n            {\n                arr[i] =s.nextInt();\n            }\n            Solution ob = new Solution();\n            System.out.println(ob.subsetXOR(arr,N,K));\n        }\n    }\n}  // } Driver Code Ends"
  },
  {
    "path": "Subsets.java",
    "content": "class Solution {\n    public List<List<Integer>> subsets(int[] nums) {\n        List<List<Integer>> list = new ArrayList<>();\n        backtrack(list, new ArrayList<>(), nums, 0);\n        return list;\n    }\n\n    private void backtrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){\n        list.add(new ArrayList<>(tempList));\n        for(int i = start; i < nums.length; i++){\n            tempList.add(nums[i]);\n            backtrack(list, tempList, nums, i + 1);\n            tempList.remove(tempList.size() - 1);\n        }\n    }\n}\n"
  },
  {
    "path": "Sum Of k smallest elements in BST.java",
    "content": "class Tree {\n\n    public static void fun(Node root,ArrayList<Integer>aa){\n\n        if(root==null){\n\n            return ;\n\n        }\n\n        else{\n\n            fun(root.left,aa);\n\n            aa.add(root.data);\n\n            fun(root.right,aa);\n\n        }\n\n    }\n\n    int sum(Node root, int k) { \n\n        ArrayList<Integer>aa=new ArrayList<Integer>();\n\n        fun(root,aa);\n\n        int sum=0;\n\n        for(int i=0;i<k;i++){\n\n            sum=sum+aa.get(i);\n\n        }\n\n        return sum;\n\n        \n\n    } \n\n}\n\n\nFor More Information About Code\n\nhttps://yashboss116.blogspot.com/2022/09/sum-of-k-smallest-elements-in-bst-geeks.html\n\n\n\n"
  },
  {
    "path": "Sum Root to Leaf Numbers.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    int sum;\n    public void dfs(TreeNode a,int num){\n        if(a==null)return;\n        num=(num*10 + a.val)%1003;\n        if(a.left==null && a.right==null){\n            sum=(sum+num);\n            return;\n        }\n        dfs(a.left,num);\n        dfs(a.right,num);\n        return;\n    }\n    public int sumNumbers(TreeNode A) {\n        sum=0;\n        int curr=0;\n        dfs(A,curr);\n        return sum%1003;\n    }\n    \n}\n"
  },
  {
    "path": "Sum of 7's Multiple.java",
    "content": "public class Solution {\n    public long solve(int A, int B) {\n        long start=A;\n        long end=B;\n        while(start%7!=0)start++;\n        while(end%7!=0)end--;\n        if(start==end)return start;\n        long e=end/7;\n        long s=start/7;\n        return apSum(e)-apSum(s)+start;\n    }\n    public long apSum(long n){\n        return n*(14+((n-1)*7))/2;\n    }\n}\n"
  },
  {
    "path": "Sum of K smallest elements  in BST.cpp",
    "content": "void inorder(Node* node,int &k,int &sum)\n{\n    if(node==NULL)\n        return ;\n    //if(k==0)\n       //return;\n   inorder(node->left,k,sum);\n   if(k==0)\n       return;\n   sum+=node->data;\n   k--;\n   inorder(node->right,k,sum);\n}\n\nint sum(Node* root, int k) \n{ \n  \n    // Your code here\n    int sum=0;\n    inorder(root,k,sum);\n    return sum;\n    \n} \n"
  },
  {
    "path": "Sum of Root To Leaf Binary Numbers.java",
    "content": "Approach 1: Iterative\nTime: O(H)\nSpace: O(H)\n\nclass Solution {\n    public int sumRootToLeaf(TreeNode root) {\n        int rootToLeaf = 0, currNumber = 0;\n        Deque<Pair<TreeNode, Integer>> stack = new ArrayDeque();\n        stack.push(new Pair(root, 0));\n\n        while (!stack.isEmpty()) {\n          Pair<TreeNode, Integer> p = stack.pop();\n          root = p.getKey();\n          currNumber = p.getValue();\n\n          if (root != null) {\n            currNumber = (currNumber << 1) | root.val;\n            // if it's a leaf, update root-to-leaf sum\n            if (root.left == null && root.right == null) {\n              rootToLeaf += currNumber;\n            } else {\n              stack.push(new Pair(root.right, currNumber));\n              stack.push(new Pair(root.left, currNumber));\n            }\n          }\n        }\n        return rootToLeaf;\n    }\n}\n\n---------------------------------------------------------------------------------------\n\nApproach 2: Recursive\nTime: O(H)\nSpace: O(H)\n\nclass Solution {\n    public int sumRootToLeaf(TreeNode root) {\n        return pathSumRootToLeaf(root, 0);\n    }\n    \n    private int pathSumRootToLeaf(TreeNode root, int parentNodeSum){\n        if(root == null) return 0;\n        \n        parentNodeSum = 2 * parentNodeSum + root.val;\n        if(root.left == null && root.right == null){\n            return parentNodeSum;\n        }\n        \n        return pathSumRootToLeaf(root.left, parentNodeSum) + pathSumRootToLeaf(root.right, parentNodeSum);\n    }\n}\n\n---------------------------------------------------------------------------------------\n\nApproach 3: Morris approach(using predessesors)\nTime: O(n)\nSpace: O(1)\n\nclass Solution {\n    public int sumRootToLeaf(TreeNode root) {\n        int rootToLeaf = 0, currNumber = 0;\n        int steps;\n        TreeNode predecessor;\n\n        while (root != null) {\n            // If there is a left child,\n            // then compute the predecessor.\n            // If there is no link predecessor.right = root --> set it.\n            // If there is a link predecessor.right = root --> break it.\n            if (root.left != null) {\n                // Predecessor node is one step to the left\n                // and then to the right till you can.\n                predecessor = root.left;\n                steps = 1;\n                while (predecessor.right != null && predecessor.right != root) {\n                    predecessor = predecessor.right;\n                    ++steps;\n                }\n\n                // Set link predecessor.right = root\n                // and go to explore the left subtree\n                if (predecessor.right == null) {\n                    currNumber = (currNumber << 1) | root.val;\n                    predecessor.right = root;\n                    root = root.left;\n                }\n                // Break the link predecessor.right = root\n                // Once the link is broken,\n                // it's time to change subtree and go to the right\n                else {\n                    // If you're on the leaf, update the sum\n                    if (predecessor.left == null) {\n                        rootToLeaf += currNumber;\n                    }\n                    // This part of tree is explored, backtrack\n                    for(int i = 0; i < steps; ++i) {\n                        currNumber >>= 1;\n                    }\n                    predecessor.right = null;\n                    root = root.right;\n                }\n            }\n            // If there is no left child\n            // then just go right.\n            else {\n                currNumber = (currNumber << 1) | root.val;\n                // if you're on the leaf, update the sum\n                if (root.right == null) {\n                    rootToLeaf += currNumber;\n                }\n                root = root.right;\n            }\n        }\n        return rootToLeaf;\n    }\n}\n"
  },
  {
    "path": "Sum of elements between k1'th and k2'th smallest elements - GFG/README.md",
    "content": "# Sum of elements between k1'th and k2'th smallest elements\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-family:arial,helvetica,sans-serif\"><span style=\"font-size:18px\">Given an array <strong>A[]</strong>&nbsp;of <strong>N</strong>&nbsp;positive&nbsp;integers and two positive integers <strong>K<sub>1</sub></strong> and <strong>K<sub>2</sub></strong>. Find the sum of all elements between K<sub>1</sub><sup>th</sup> and&nbsp;K<sub>2</sub><sup>th</sup> smallest elements of the array.&nbsp;</span></span><span style=\"font-size:18px\">It may be assumed that (1 &lt;= k1 &lt; k2 &lt;= n).</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-family:arial,helvetica,sans-serif\"><span style=\"font-size:18px\"><strong>Example 1:</strong></span></span></p>\n\n<pre><span style=\"font-family:arial,helvetica,sans-serif\"><span style=\"font-size:18px\"><strong>Input:</strong></span><span style=\"font-size:18px\">\nN  = 7\nA[] = {20, 8, 22, 4, 12, 10, 14}\nK1 = 3, K2 = 6\n<strong>Output:</strong></span>\n<span style=\"font-size:18px\">26\n<strong>Explanation:</strong></span><span style=\"font-size:18px\">\n3rd smallest element is 10\n6th smallest element is 20\nSum of all element between\nK1 &amp; K2 is 12 + 14 = 26</span></span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-family:arial,helvetica,sans-serif\"><span style=\"font-size:18px\"><strong>Example 2:</strong></span></span></p>\n\n<pre><span style=\"font-family:arial,helvetica,sans-serif\"><span style=\"font-size:18px\"><strong>Input</strong>\nN = 6\nA[] = {10, 2, 50, 12, 48, 13}\nK1= 2, K2 = 6\n<strong>Output:</strong></span><span style=\"font-size:18px\">\n73</span></span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-family:arial,helvetica,sans-serif\"><span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>sumBetweenTwoKth()</strong>&nbsp;which takes the array <strong>A[]</strong>, its size <strong>N</strong><strong> </strong>and two integers <strong>K1</strong> and <strong>K2</strong> as inputs and returns the sum of all the elements between K<sub>1</sub><sup>th</sup> and K<sub>2</sub><sup>th</sup> smallest elements.</span></span><br>\n&nbsp;</p>\n\n<p><span style=\"font-family:arial,helvetica,sans-serif\"><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N. log(N))<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span></span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-family:arial,helvetica,sans-serif\"><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n1 ≤ K<sub>1</sub>, K<sub>2</sub> ≤ 10<sup>9</sup></span></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Sum of elements between k1'th and k2'th smallest elements - GFG/sum-of-elements-between-k1th-and-k2th-smallest-elements.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG {\n\tpublic static void main(String[] args) throws IOException\n\t{\n\t        BufferedReader br =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t =\n            Integer.parseInt(br.readLine().trim());\n        while(t-->0)\n        {\n            long n = Long.parseLong(br.readLine().trim());\n            long a[] = new long[(int)n];\n            String inputLine[] = br.readLine().trim().split(\" \");\n            for (int i = 0; i < n; i++) {\n                a[i] = Long.parseLong(inputLine[i]);\n            }\n            \n            StringTokenizer stt = new StringTokenizer(br.readLine());\n            long k1 = Long.parseLong(stt.nextToken());\n            long k2 = Long.parseLong(stt.nextToken());\n            \n            Solution obj = new Solution();\n            System.out.println( obj.sumBetweenTwoKth(a, n, k1, k2) );\n            \n        }\n\t}\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution { \n    public static long sumBetweenTwoKth(long A[], long N, long K1, long K2)\n    {\n        // Your code goes here\n        Arrays.sort(A);\n        long ans = 0;\n        for(long i=K1;i<K2-1;i++)\n            ans+=A[(int)i];\n        return ans;\n    }\n    \n}"
  },
  {
    "path": "Sum of k smallest elements in BST.cpp",
    "content": "// Function to find ceil of a given input in BST. If input is more \n// than the max key in BST, return -1 \nint sum(Node* root, int k) \n{ \n    // Your code here\n    int ans = 0;\n    \n    if(!root)\n        return ans;\n    \n    Node* cur = root;\n    stack<Node*> S;\n    \n    while((!S.empty() or cur) and k--)\n    {\n        while(cur)\n        {\n            S.push(cur);\n            cur = cur->left;\n        }\n        \n        cur = S.top();\n        S.pop();\n        \n        ans += cur->data;\n        \n        cur = cur->right;\n    }\n    \n    return ans;\n} \n"
  },
  {
    "path": "Sum of k smallest elements in BST.java",
    "content": "\nclass Tree {\n    int sum;\n    int cnt;\n    int sum(Node root, int k) { \n        sum=0;\n        cnt=0;\n        dfs(root,k);\n        return sum;\n        // Code here\n    } \n    void dfs(Node root,int k){\n        if(root==null)return;\n        dfs(root.left,k);\n        if(cnt<k){\n            sum+=root.data;\n            cnt++;\n        }\n        if(cnt<k){\n            dfs(root.right,k);\n        }\n    }\n}\n"
  },
  {
    "path": "Sum of nodes within k distance from target - GFG/README.md",
    "content": "# Sum of nodes within k distance from target\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\"><strong>Note: This&nbsp;<a href=\"http://practice.geeksforgeeks.org/problem-of-the-day\" target=\"_blank\">POTD</a>&nbsp;is a part of&nbsp;<a href=\"https://practice.geeksforgeeks.org/summer-carnival-2022?utm_source=potd&amp;utm_medium=problempage&amp;utm_campaign=gsc22\" target=\"_blank\">Geek Summer Carnival</a>. Solve all POTD consecutively from 5th to 10th April and get a chance to win exclusive discount vouchers on our GfG courses.</strong></span></p>\n\n<hr>\n<p><span style=\"font-size:18px\">Geek is at the geek summer carnival. To unlock discounts on exclusive courses he is given a card with a binary tree, a target node and a positive integer k on it.&nbsp;<br>\nHe needs to find the sum of all nodes within a max distance k from target node such that the target node is included in sum.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:</span></strong>\n<span style=\"font-size:18px\">target = 9 \nk = 1\nBinary Tree = \n            1\n           /  \\\n          2    9\n        /     /  \\\n       4     5    7\n      /  \\       /  \\\n     8    19    20   11\n    /   /   \\\n  30   40   50\n</span>\n<span style=\"font-size:18px\"><strong>Output: </strong>22</span>\n\n<span style=\"font-size:18px\"><strong>Explanation: </strong>\nNodes within distance 1 from 9 \n9 + 5 + 7 + 1 = 22</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:</span></strong>\n<span style=\"font-size:18px\">target = 40 \nk = 2\nBinary Tree = \n            1\n           /  \\\n          2    9\n        /     /  \\\n       4     5    7\n      /  \\       /  \\\n     8    19    20   11\n    /   /   \\\n  30   40   50</span>\n<span style=\"font-size:18px\">\n<strong>Output: </strong>113</span>\n\n<span style=\"font-size:18px\"><strong>Explanation:</strong>\nNodes within distance 2 from 40,\n40 + 19 + 50 + 4 = 113\n</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Complete the function <strong>sum_at_distK()</strong> that takes the root of the given binary tree, target and k as input parameters and return the required sum.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected time complexity:</strong> O(n)<br>\n<strong>Expected space complexity: </strong>O(n)</span><br>\n<br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= number of nodes &lt;= 1000<br>\n1 &lt;= data in nodes,target &lt;= 10000<br>\n1 &lt;= k &lt;= 20</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Sum of nodes within k distance from target - GFG/sum-of-nodes-within-k-distance-from-target.java",
    "content": "// { Driver Code Starts\nimport java.util.LinkedList; \nimport java.util.Queue; \nimport java.io.*;\nimport java.util.*;\n\nclass Node{\n    int data;\n    Node left;\n    Node right;\n    Node(int data){\n        this.data = data;\n        left=null;\n        right=null;\n    }\n}\n\nclass GfG {\n    \n    static Node buildTree(String str){\n        \n        if(str.length()==0 || str.charAt(0)=='N'){\n            return null;\n        }\n        \n        String ip[] = str.split(\" \");\n        // Create the root of the tree\n        Node root = new Node(Integer.parseInt(ip[0]));\n        // Push the root to the queue\n        \n        Queue<Node> queue = new LinkedList<>(); \n        \n        queue.add(root);\n        // Starting from the second element\n        \n        int i = 1;\n        while(queue.size()>0 && i < ip.length) {\n            \n            // Get and remove the front of the queue\n            Node currNode = queue.peek();\n            queue.remove();\n                \n            // Get the current node's value from the string\n            String currVal = ip[i];\n                \n            // If the left child is not null\n            if(!currVal.equals(\"N\")) {\n                    \n                // Create the left child for the current node\n                currNode.left = new Node(Integer.parseInt(currVal));\n                // Push it to the queue\n                queue.add(currNode.left);\n            }\n                \n            // For the right child\n            i++;\n            if(i >= ip.length)\n                break;\n                \n            currVal = ip[i];\n                \n            // If the right child is not null\n            if(!currVal.equals(\"N\")) {\n                    \n                // Create the right child for the current node\n                currNode.right = new Node(Integer.parseInt(currVal));\n                    \n                // Push it to the queue\n                queue.add(currNode.right);\n            }\n            i++;\n        }\n        \n        return root;\n    }\n    \n\tpublic static void main (String[] args) throws IOException{\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        \n        int t=Integer.parseInt(br.readLine());\n        \n        while(t > 0){\n            String line = br.readLine().trim();\n            Node root = buildTree(line);\n            \n            line = br.readLine().trim();\n            String target_k[] = line.split(\" \");\n            int target = Integer.parseInt(target_k[0]);\n            int k = Integer.parseInt(target_k[1]);\n            \n            solver x = new solver();\n            System.out.println( x.sum_at_distK(root, target, k) );\n            t--;\n        }\n    }\n}\n\n// } Driver Code Ends\n\n\n/*\n// node structure:\n\nclass Node{\n    int data;\n    Node left;\n    Node right;\n    Node(int data){\n        this.data = data;\n        left=null;\n        right=null;\n    }\n}\n\n*/\n\nclass solver{\n    static Map<Node,Node> map=new HashMap<>();\n    static Node tar;\n    static int n;\n    static int sum_at_distK(Node root, int target, int k){\n        n=target;\n        Node copy=root;\n        addAll(copy);\n        Set<Integer> set=new HashSet<>();\n        bfs(tar,set,0,k);\n        int sum=0;\n        for(int i:set){\n            sum+=i;\n        }\n        return sum;\n    }\n    static void bfs(Node curr,Set<Integer>set,int dis,int k){\n        if(curr==null)return;\n        if(dis>k)return;\n        if(set.contains(curr.data))return;\n        set.add(curr.data);\n        bfs(curr.left,set,dis+1,k);\n        bfs(curr.right,set,dis+1,k);\n        bfs(map.get(curr),set,dis+1,k);\n    }\n    static void addAll(Node root){\n        if(root==null)return;\n        if(root.data==n)tar=root;\n        if(root.left!=null){\n            map.put(root.left,root);\n            addAll(root.left);\n        }\n        if(root.right!=null){\n            map.put(root.right,root);\n            addAll(root.right);\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sum of two large numbers.cpp",
    "content": "class Solution {\n  public:\n    string findSum(string X, string Y) {\n        // Your code goes here\n        string ans = \"\";\n        \n        int n = X.length()-1, m = Y.length()-1, rem = 0;\n        \n        while(n >= 0 and m >= 0)\n        {\n            int cur = (X[n--]-'0') + (Y[m--]-'0') + rem;\n            rem = cur/10;\n            cur = cur%10;\n            \n            ans.push_back('0'+cur);\n        }\n        \n        while(n >= 0)\n        {\n            int cur = (X[n--]-'0') + rem;\n            rem = cur/10;\n            cur = cur%10;\n            \n            ans.push_back('0'+cur);\n        }\n        \n        while(m >= 0)\n        {\n            int cur = (Y[m--]-'0') + rem;\n            rem = cur/10;\n            cur = cur%10;\n            \n            ans.push_back('0'+cur);\n        }\n        \n        if(rem)\n        ans.push_back('0'+rem);\n        \n        while(ans.back() == '0')\n        ans.pop_back();\n        \n        if(ans.empty())\n        return \"0\";\n        \n        reverse(ans.begin(), ans.end());\n        \n        return ans;\n    }\n};\n\n// Used almost same approach\n// class Solution {\n//   public:\n//     string findSum(string X, string Y) {\n        \n//         int i = X.length()-1, j = Y.length()-1;\n        \n//         string ans = \"\";\n//         int c = 0;\n//         while(i >= 0 || j >= 0 || c != 0){\n//             int val1 = 0, val2 = 0;\n//             if(i >= 0) val1 = X[i] - 48;\n//             if(j >= 0) val2 = Y[j] - 48;\n//             int sum = val1+val2+c;\n            \n//             int rem = sum % 10;\n//             ans.push_back(char(rem+48));\n//             c = sum / 10;\n//             if(i>=0) i--;\n//             if(j>=0) j--;\n//         }\n//         reverse(ans.begin(), ans.end());\n        \n//         int idx = 0;\n//         while(idx < ans.size()-1){\n//             if(ans[idx] != '0')\n//                 break;\n//             idx++;\n//         }\n//         ans.erase(0,idx);\n//         return ans;\n//     }\n// };\n"
  },
  {
    "path": "Sum of two large numbers.java",
    "content": "class Solution {\n    String findSum(String X, String Y) {\n        // code here\n        StringBuilder a=new StringBuilder(X);\n        StringBuilder b=new StringBuilder(Y);\n        StringBuilder ans=new StringBuilder();\n        \n        int carry=0;\n        while(a.length()>0 || b.length()>0){\n            int first=a.length()>0?a.charAt(a.length()-1)-'0':0;\n            int second=b.length()>0?b.charAt(b.length()-1)-'0':0;\n            int sum=first+second+carry;\n            if(sum>9){\n                sum-=10;\n                carry=1;\n            }else{\n                carry=0;\n            }\n            ans.insert(0,sum);\n            if(a.length()>0)a.setLength(a.length()-1);\n            if(b.length()>0)b.setLength(b.length()-1);\n        }\n        if(carry==1){\n            ans.insert(0,1);\n        }\n        //000000\n        for(int i=0;i<ans.length();i++){\n            if(ans.charAt(i)>'0'){\n                return ans.substring(i);\n            }\n        }\n        return \"0\";\n    }\n}\n"
  },
  {
    "path": "Sum of two numbers without using arithmetic operators - GFG/README.md",
    "content": "# Sum of two numbers without using arithmetic operators\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two integers a and b. Find the sum of two numbers<strong> without using&nbsp;arithmetic operators</strong>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>a = 5, b = 3\n<strong>Output:</strong> 8\n<strong>Explanation :</strong>\n5 + 3 = 8</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\na = 10, b = 30\n<strong>Output:</strong> 40\n<strong>Explanation:</strong>\n10 + 30 = 40</span></pre>\n\n<div><span style=\"font-size:18px\"><strong>Your task:</strong></span></div>\n\n<div><span style=\"font-size:18px\">You don't need to read input or print anything. Your task is to complete the function sum() which takes two integers a and b as input and returns the sum of a and b, which is calculated without using any arithmetic operator.</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Time Complexity :</strong> O(max(number of bits in 'a', number of bits in 'b'))</span></div>\n\n<div><span style=\"font-size:18px\"><strong>Expected Auxiliary Space : </strong>O(1)</span></div>\n\n<div>&nbsp;</div>\n\n<div><span style=\"font-size:18px\"><strong>Constraints:</strong></span></div>\n\n<div><span style=\"font-size:18px\">1&lt;=a, b&lt;=10^8</span></div>\n <p></p>\n            </div>"
  },
  {
    "path": "Sum of two numbers without using arithmetic operators - GFG/sum-of-two-numbers-without-using-arithmetic-operators.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*; \nimport java.math.BigInteger;\n\nclass GFG\n{\n\tpublic static void main(String[] args) throws NumberFormatException, IOException \n\t{\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\tint t = Integer.parseInt(br.readLine());\n\t\twhile(t>0)\n\t\t{\n\t\t    String S[] = br.readLine().split(\" \");\n            \n            int a = Integer.parseInt(S[0]);\n            int b = Integer.parseInt(S[1]);\n\t\t\tSolution obj = new Solution();\n\t\t\tSystem.out.println(obj.sum(a,b));\n            t--;\n\t\t}\n\t}\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    int sum(int a , int b){\n        while(b!=0){\n            int ans=(a^b);\n            int carry=(a&b)<<1;\n            a=ans;\n            b=carry;\n        }\n        return a;\n    }\n}"
  },
  {
    "path": "Summary Ranges.java",
    "content": "class Solution {\n    public List<String> summaryRanges(int[] nums) {\n        List<String> res = new ArrayList<>();\n        StringBuilder buf = new StringBuilder();\n        for(int i = 0; i < nums.length; i++)\n        {\n            buf.setLength(0);\n            int index = i;\n            while(index < nums.length-1 && nums[index]+1 == nums[index+1]){\n                index++;\n            }\n            if(index == i){\n                buf.append(\"\");\n                buf.append(nums[i]);\n            }else{\n                buf.append(nums[i]);\n                buf.append(\"->\");\n                buf.append(nums[index]);\n            }\n            res.add(buf.toString());\n            i = index;\n        }\n        return res;\n    }\n}\n"
  },
  {
    "path": "Super Primes - GFG/README.md",
    "content": "# Super Primes\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:20px\">A prime number is Super Prime if it is a sum of two primes. Find all the Super Primes upto <strong>N</strong></span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 5\n<strong>Output:</strong> 1\n<strong>Explanation: </strong>5 = 2 + 3, 5 is the\nonly super prime</span>\n\n</pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nN = 10 \n<strong>Output:</strong> 2\n<strong>Explanation: </strong>5 and 7 are super primes</span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function <strong>superPrimes()</strong>&nbsp;which takes the <strong>N </strong>as input and returns the count of super primes.</span><br>\n<br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(Nlog(logN))<br>\n<strong>Expected Auxiliary Space:</strong> O(N)</span><br>\n<br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ <strong>N</strong> ≤ 10<sup>5</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Super Primes - GFG/super-primes.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG {\n    public static void main(String args[]) throws IOException {\n        BufferedReader read =\n            new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while (t-- > 0) {\n            int n = Integer.parseInt(read.readLine());\n            \n            Solution ob = new Solution();\n            System.out.println(ob.superPrimes(n));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution {\n    int superPrimes(int n) {\n        boolean [] primes=new boolean[n+1];\n        Arrays.fill(primes,true);\n        \n        //performing sieve\n        for(int i=2;i<=Math.sqrt(n);i++){\n            if(primes[i]==true){\n                for(int j=i*i;j<=n;j+=i){\n                    primes[j]=false;\n                }\n            }\n        }\n        int count=0;\n        for(int i=5;i<=n;i++){\n            if(primes[i] && primes[i-2]){\n                count++;\n            }\n        }\n        return count;\n    }\n}"
  },
  {
    "path": "Swap Bits.java",
    "content": "public class Solution {\n    public int solve(int n, int p, int q) {\n        if ((((n & (1 << p-1)) >> p-1) ^ ((n & (1 << q-1)) >> q-1))!=0){\nn ^= (1 << p-1);\nn ^= (1 << q-1);\n}\n\n\nreturn n ;\n\n    }\n}\n"
  },
  {
    "path": "Swap Kth nodes from ends - GFG/README.md",
    "content": "# Swap Kth nodes from ends\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a singly linked list of size N, and an integer K.&nbsp;You need to swap the K<sup>th</sup>&nbsp;node from the beginning and K<sup>th</sup> node from the end of the linked list. Swap the nodes through the links. Do&nbsp;not change&nbsp;the content of the nodes.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 4,  K = 1\nvalue[] = {1,2,3,4}\n<strong>Output: </strong>1<strong>\nExplanation: </strong>Here K = 1, hence after\nswapping the 1st node from the beginning\nand end thenew list will be 4 2 3 1.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 5,  K = 7\nvalue[] = {1,2,3,4,5}\n<strong>Output: </strong>1<strong>\nExplanation: </strong>K &gt; N. Swapping is invalid. \nReturn the head node as it is.</span>\n</pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong>&nbsp;<br>\nYou do not need to read input or print anything. The task is to complete the function&nbsp;<strong>swapkthnode</strong>(), which has takes head of link list, N and K as input parameters<strong>&nbsp;</strong>and&nbsp;returns the&nbsp;new head.<br>\n<strong>The generated output will be 1 if you are able to complete your task.&nbsp;</strong></span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity</strong>: O(n)<br>\n<strong>Expected Auxillary space Complexity:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 &lt;= N &lt;= 10<sup>3</sup></span><br>\n<span style=\"font-size:18px\">1 &lt;= K &lt;= 10<sup>3</sup></span></p>\n\n<p>&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Swap Kth nodes from ends - GFG/swap-kth-nodes-from-ends.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass Node\n{\n    int data;\n    Node next;\n    \n    Node(int data)\n    {\n        this.data = data;\n        next = null;\n    }\n}\n\nclass LinkedList\n{\n    static  Node head;  \n    static  Node lastNode;\n    \n    public static void addToTheLast(Node node)\n    {\n\n        if (head == null)\n        {\n            head = node;\n            lastNode = node;\n        }\n        else\n        {\n            Node temp = head;\n            lastNode.next = node;\n            lastNode = node;\n        }\n    }\n    \n    public static void main(String args[])\n    {\n        Scanner sc=  new Scanner(System.in);\n        int t = sc.nextInt();\n        \n        while(t-- > 0)\n        {\n            int n, K;\n            n = sc.nextInt();\n            K = sc.nextInt();\n            \n            Node head = null;\n            int val = sc.nextInt();\n            head = new Node(val);\n            addToTheLast(head);\n            \n            for(int i = 1; i< n; i++)\n            {\n                val = sc.nextInt();\n                addToTheLast(new Node(val));\n            }\n            \n            Node before[] = new Node[n];\n            addressstore(before, head);\n            GFG obj = new GFG();\n            \n            head = obj.swapkthnode(head, n, K);\n        \n           Node after[] = new Node[n];\n          addressstore(after, head);\n        \n        if(check(before, after, n, K) == true)\n            System.out.println(\"1\");\n        else\n            System.out.println(\"0\");\n        \n        }\n    }\n    \n    static boolean check(Node before[], Node after[], int num, int K)\n    {\n          if(K > num)\n           return true;\n           \n           return (before[K-1] == after[num - K]) && (before[num-K] == after[K-1]);\n              \n       \n    }\n    \n    static void addressstore(Node arr[], Node head)\n  {\n      Node temp = head;\n      int i = 0;\n      while(temp != null){\n        arr[i] = temp;\n        i++;\n        temp = temp.next;\n    }\n}\n    \n}// } Driver Code Ends\n\n\n//User function Template for Java\n\n\n/* Linked List Node class\n   class Node  {\n     int data;\n     Node next;\n     Node(int data)\n     {\n         this.data = data;\n         next = null;\n     }\n  }\n*/\nclass GFG{\n    //Function to swap Kth node from beginning and end in a linked list.\n    Node swapkthnode(Node head, int num, int k){\n        // your code here\n        if (head == null)return head;\n        if (k > num)return head;\n        // begining node will be at k\n        // end node will be at n - k + 1\n        Node x = head;\n        Node prevX = null;\n        Node y = head;\n        Node prevY = null;\n        for (int i = 1; i < k; i++) {\n            prevX = x;\n            x = x.next;\n        }\n        for (int i = 1; i < num - k + 1; i++) {\n            prevY = y;\n            y = y.next;\n        }\n        \n        if (prevX != null) {\n            prevX.next = y;\n        }\n        if (prevY != null) {\n            prevY.next = x;\n        }\n        Node temp = x.next;\n        x.next = y.next;\n        y.next = temp;\n        if (k == 1) {\n            head = y;\n        }\n        if (k == num) {\n            head = x;\n        }\n        return head;\n    }\n}"
  },
  {
    "path": "Swap Nodes in Pairs.java",
    "content": "class Solution {\n    public ListNode swapPairs(ListNode head) {\n        if(head==null)return null;\n        if(head.next==null)return head;\n        ListNode rec=swapPairs(head.next.next);\n        ListNode sec=head.next;\n        sec.next=head;\n        head.next=rec;\n        return sec;\n    }\n}\n"
  },
  {
    "path": "Swap bits - GFG/README.md",
    "content": "# Swap bits\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a number X and two positions (from right side) in binary representation of x, write a program that swaps N bits at given two positions and returns the result.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input</strong>:\nX = 47\nP1 = 1\nP2 = 5\nN = 3\n<strong>Output:</strong>&nbsp;227\n<strong>Explanation</strong>:\nThe 3 bits starting from the second bit \n(from the right side) are swapped with 3 bits\nstarting from 6th position (from the right side) </span></pre>\n\n<pre><span style=\"font-size:18px\">X = 47 (</span><span style=\"font-size:18px\">00101111)\n[001]0[111]1\nANS = [111]0[001]1\nANS = 227 (</span><span style=\"font-size:18px\">11100011)\nHence, the result is 227.  \n</span></pre>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nX = 28\nP1 = 0\nP2 = 3\nN = 2\n<strong>Output:&nbsp;</strong>7</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:&nbsp;&nbsp;</strong><br>\nYou don't need to read input or print anything. Your task is to complete the function&nbsp;<strong>swapBits()</strong>&nbsp;which takes the integer X, integer P1, integer P2, and&nbsp;integer&nbsp;N<strong>&nbsp;</strong>as input parameters and returns the new integer after swapping.&nbsp;<br>\n<br>\n<strong>Expected Time Complexity:</strong> O(1)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span><br>\n&nbsp;</p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong></span><br>\n<span style=\"font-size:18px\">1 ≤ X ≤ 200<br>\n0 ≤ P1 &lt; P2&nbsp;≤ 11<br>\n1 ≤ N ≤ 5</span><br>\n<br>\n&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Swap bits - GFG/swap-bits.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG\n{\n    public static void main(String args[])throws IOException\n    {\n        \n        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(read.readLine());\n        while(t-- > 0)\n        {\n            String input_line[] = read.readLine().trim().split(\"\\\\s+\");\n            int X = Integer.parseInt(input_line[0]);\n            int P1 = Integer.parseInt(input_line[1]);\n            int P2 = Integer.parseInt(input_line[2]);\n            int N = Integer.parseInt(input_line[3]);\n            \n            Solution ob = new Solution();\n            System.out.println(ob.swapBits(X, P1, P2, N));\n        }\n    }\n}\n\n\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    \n    int swapBits(int x, int p1, int p2, int n){\n        int  mask1= (x >> p1) & ((1 << n) - 1);\n        int  mask2 = (x >> p2) & ((1 << n) - 1);\n        int xor = ( mask1^ mask2);\n        xor = (xor << p1) | (xor << p2);\n        int res = x ^ xor;\n        \n        return res;\n    }\n}"
  },
  {
    "path": "Symmetric Binary Tree.java",
    "content": "public class Solution {\n    public int isSymmetric(TreeNode A) {\n        if( isMirrorUtil(A, A)){\n            return 1;\n        }\n        return 0;\n    }\n    public static boolean isMirrorUtil(TreeNode root1, TreeNode  root2){\n        if(root1 == null && root2 == null){\n            return true;\n        }\n        if(root1 != null && root2!= null && root1.val == root2.val){\n            return (isMirrorUtil(root1.left, root2.right) \n                &&  isMirrorUtil(root1.right, root2.left));\n            }\n        return false;\n    }\n}\n"
  },
  {
    "path": "The Bit Game easy s24.cpp",
    "content": "#include<bits/stdc++.h> \nusing namespace std; \nclass Solution{   \npublic:\n    int swapBitGame(long long N){\n        // code here \n        int win=0, swap=0;\n        while(N>0){\n            if((N&1)==1 && swap>0) win^=swap;\n            if((N&1)==0) swap++;\n            N>>=1;\n        }\n        return win>0? 1: 2;\n    }\n};\n\nint main() \n{ \n    int t;\n    cin>>t;\n    while(t--)\n    {\n        long long N;\n        cin >> N;\n        Solution ob;\n        cout << ob.swapBitGame(N) << endl;\n    }\n    return 0; \n}"
  },
  {
    "path": "The bit Game.cpp",
    "content": "class Solution{\npublic:\n    int swapBitGame(long long N){\n     int cnt=0;\n     while(N>0){\n         if((N&1)==1){\n             cnt++;\n         }\n         N>>=1;\n     }\n     return cnt%2==0?2:1;\n     }\n};\n"
  },
  {
    "path": "Theft at World Bank - GFG/README.md",
    "content": "# Theft at World Bank\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">The worlds most successful thief Albert Spaggiari was planning for his next heist on the world bank. He decides to carry a sack with him, which can carry a maximum weight&nbsp;of <strong>C</strong> kgs. Inside the world bank there were <strong>N</strong>&nbsp;large blocks of gold. All the blocks have some profit value associated with them<em> i.e.</em> if he steals <strong>i<sup>th</sup></strong> block of weight <strong>w[i]</strong> then he will have <strong>p[i] </strong>profit. As blocks were heavy he decided to steal some part of them by cutting them&nbsp;with his cutter.<br>\nThe thief does not like symmetry, hence, he wishes to not take blocks or parts of them whose weight is a perfect square. Now, you need to find out the maximum profit that he can earn given that he can only carry blocks of gold in his sack.&nbsp;<br>\n<strong>Note</strong>: The answer should be precise upto 3 decimal places.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1 :</strong></span></p>\n\n<pre><span style=\"font-size:18px\">N = 3, C = 10\nw[] = {4, 5, 7}\np[] = {8, 5, 4)\n<strong>Output: </strong>\n7.857\n<strong>Explanation: </strong>As first blocks weight is 4\nwhich is a perfect square, he will not use \nthis block. Now with the remaining blocks \nthe most optimal way is to use 2<sup>nd</sup> block \ncompletely and cut 5kg piece from the 3<sup>rd</sup> \nblock to get a total profit of 5 + 2.857 \n= 7.857</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anything. Your task is to complete the function&nbsp;<strong>maximumProfit()</strong>&nbsp;which takes N, C, w[ ] and p[ ]&nbsp;as input parameters and returns the maximum profit thief can achieve with precision&nbsp;upto 3 decimal places.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(N * LogN)<br>\n<strong>Expected Space Complexity :&nbsp;</strong>O(N)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤&nbsp;10<sup>3</sup><br>\n1&nbsp;≤&nbsp;C ≤&nbsp;10<sup>18</sup><br>\n1 ≤&nbsp;W<sub>i&nbsp;</sub>≤&nbsp;10<sup>9</sup><br>\n1 ≤&nbsp;P<sub>i&nbsp;</sub>≤&nbsp;10<sup>9</sup></span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Theft at World Bank - GFG/theft-at-world-bank.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            String s1 = br.readLine().trim();\n            String []S1 = s1.split(\" \");\n            int n = Integer.parseInt(S1[0]);\n            long C = Long.parseLong(S1[1]);\n            String s2 = br.readLine().trim();\n            String []S2 = s2.split(\" \");\n            long [] w = new long[n];\n            long [] p = new long[n];\n            for(int i = 0; i < n; i++){\n                w[i] = Long.parseLong(S2[2*i]);\n                p[i] = Long.parseLong(S2[(2*i)+1]);\n            }\n            Solution ob = new Solution();\n            double ans = ob.maximumProfit(n, C, w, p);\n            String a1 = String.format(\"%.3f\",ans);\n            System.out.println(a1);\n        }\n    }\n}\n// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Pair{\n    long weight;\n    long profit;\n    double ratio;\n    Pair(long weight, long profit, double ratio){\n        this.weight=weight;\n        this.profit=profit;\n        this.ratio=ratio;\n    }\n}\nclass Solution\n{\n    public boolean isPerfect(long num){\n        long sq=(long)Math.sqrt(num);\n        return sq*sq==num;\n    }\n    public double maximumProfit(int n, long c, long w[], long p[])\n    {\n        Pair[] item=new Pair[n];\n        for(int i=0;i<n;i++){\n            item[i]=new Pair(w[i],p[i],(double)p[i]/(double)w[i]);\n        }\n        Arrays.sort(item, (a,b)->Double.compare(b.ratio, a.ratio));\n        double total=0;\n        int i=0;\n        while(c>0){\n            if(!isPerfect(item[i].weight)){\n                long wgt=Math.min(c, item[i].weight);\n                total+=(double)(wgt)*item[i].ratio;\n                c-=wgt;\n            }\n            i++;\n        }\n        return total;\n    }\n}"
  },
  {
    "path": "Topo_sort.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nvoid funct(vector<int> adj[],vector<int> &vis,stack<int>&st,int node){\n    vis[node]=1;\n    for(auto it:adj[node]){\n        if(!vis[it]){\n            funct(adj,vis,st,it);\n        }\n    }\n    st.push(node);\n}\n\nvoid topo(int n, vector<int> adj[]){\n    stack<int> st;\n    vector<int> vis(n,0);\n    for(int i =0;i<n;i++){\n        if(!vis[i]){\n            funct(adj,vis,st,i);\n        }\n    }\n    vector<int> v;\n    while(!st.empty()){\n        v.push_back(st.top());\n        st.pop();\n    }\n    for(int i =0;i< v.size();i++){\n        cout<<v[i]<<\" \";\n    }\n    cout<<endl;\n}\n\nint main(){\n    int m,n;\n    cin>>m>>n;\n    vector<int> adj[m];\n    for(int i =0;i<n;i++){\n        int x,y;\n        cin>>x>>y;\n        adj[x].push_back(y);\n    }\n    topo(m,adj);\n    return 0;\n}\n"
  },
  {
    "path": "Total Moves For Bishop!.java",
    "content": "public class Solution {\n    public int solve(int A, int B) {\n        int topLeft=Math.min(A-1,B-1);\n        int topRight=Math.min(A-1,8-B);\n        int botLeft=Math.min(8-A,B-1);\n        int botRight=Math.min(8-A,8-B);\n        return topLeft+topRight+botLeft+botRight;\n    }\n}\n"
  },
  {
    "path": "Towers_CSES.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n#define ll long long\nvoid solve(){\n    int n;\n    cin>>n;\n    multiset<int>set;\n    for(int i = 0; i<n; i++){\n        int x;\n        cin>>x;\n        auto it = set.upper_bound(x);\n        if(it == set.end()){\n            set.insert(x);\n        }\n        else{\n            set.erase(it);\n            set.insert(x);\n        }\n    }\n    cout<<set.size()<<endl;\n    return;\n}\nint main()\n{\n    solve();\n    return 0;\n}\n"
  },
  {
    "path": "Trailing Zeroes.java",
    "content": "public class Solution {\n    public int solve(int A) {\n        return (int) (Math.log(A&~(A-1))/Math.log(2));\n    }\n}\n"
  },
  {
    "path": "Transfiguration.java",
    "content": "class Solution\n{\n    int transfigure (String A, String B)\n    {\n    \t// Your code goes here.\n    \tif(A.length()!=B.length())\n            return -1;  \n            \n        int sum=0;\n        for(int i=0;i<A.length();i++){\n            sum=sum+A.charAt(i);\n            sum=sum-B.charAt(i);\n        }\n        if(sum!=0)\n            return -1;\n            \n        int n1=A.length()-1;\n        int n2=B.length()-1;\n        int res=0;\n    \t while(n1>=0 && n2>=0){\n            if(A.charAt(n1)==B.charAt(n2)){\n                n1--;\n                n2--;\n            }else{\n                n1--;\n                res++;\n            }\n        }\n        return res;\n    }\n}\n"
  },
  {
    "path": "Transform String - GFG/README.md",
    "content": "# Transform String\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given two strings A and B. Find the minimum number of steps required to transform string A into string B. The only allowed operation for the transformation is selecting a character from string A and inserting it in the beginning of string A.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nA = \"abd\"\nB = \"bad\"\n<strong>Output:</strong> 1\n<strong>Explanation: </strong>The conversion can take place in\n1 operation: Pick 'b' and place it at the front.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nA = \"GeeksForGeeks\"\nB = \"ForGeeksGeeks\"\n<strong>Output: </strong>3\n<strong>Explanation:</strong> The conversion can take\nplace in 3 operations:\nPick 'r' and place it at the front.\nA = \"rGeeksFoGeeks\"\nPick 'o' and place it at the front.\nA = \"orGeeksFGeeks\"\nPick 'F' and place it at the front.\nA = \"ForGeeksGeeks\"</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:&nbsp; </strong><br>\nYou dont need to read input or print anything. Complete the function<strong> transform()</strong> which takes two strings A and B as input parameters and returns the minimum number of steps required to transform A into B. If transformation is not possible return -1.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity: </strong>O(N) where N is max(length of A,&nbsp;length of B)&nbsp;<br>\n<strong>Expected Auxiliary Space: </strong>O(1) &nbsp;</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1&lt;= A.length(), B.length()&nbsp;&lt;= 10<sup>4</sup></span></p>\n\n<p>&nbsp;</p>\n <p></p>\n            </div>"
  },
  {
    "path": "Tree Path Sum.java",
    "content": "public class Solution {\n    public int hasPathSum(TreeNode A, int B) {\n        if(A==null) return 0;\n        if(A.val==B && A.left==null && A.right==null) return 1;\n        if(hasPathSum(A.left,B-A.val)==1) return 1;\n        return hasPathSum(A.right,B-A.val);\n    }\n}\n"
  },
  {
    "path": "Triangle and Square - GFG/README.md",
    "content": "# Triangle and Square\n## Easy \n<div class=\"problem-statement\">\n                <p><a onclick=\"gtagHelperFunction('clickopen','salesevent_gsc_problemspage_promobanner')\" href=\"https://practice.geeksforgeeks.org/summer-carnival-2022?utm_source=practiceproblems&amp;utm_medium=problemspromobanner&amp;utm_campaign=gsc22\" target=\"_blank\"></a></p><div style=\"margin: 14px 0px !important;\" class=\"row\"><a onclick=\"gtagHelperFunction('clickopen','salesevent_gsc_problemspage_promobanner')\" href=\"https://practice.geeksforgeeks.org/summer-carnival-2022?utm_source=practiceproblems&amp;utm_medium=problemspromobanner&amp;utm_campaign=gsc22\" target=\"_blank\">             <div class=\"col-md-12\" style=\"cursor:pointer;background: #EFF8F3 0% 0% no-repeat padding-box; display: flex; align-items: center; position:                 relative; padding: 1.5%; border-radius: 10px; display: inline-block; text-align: center; font-weight: 600; color: #333\"> <img src=\"https://media.geeksforgeeks.org/img-practice/gcs2022thumbnail-1649059370.png\" alt=\"Lamp\" width=\"46\" height=\"40\" style=\"background: transparent 0% 0% no-repeat padding-box;opacity: 1; margin: 0 16px;\" class=\"img-responsive\"> Geeks Summer Carnival is LIVE NOW &nbsp; <i class=\"fa fa-external-link\" aria-hidden=\"true\"></i> </div></a></div><p><strong><span style=\"font-size:18px\">Note: This <a href=\"http://practice.geeksforgeeks.org/problem-of-the-day\" target=\"_blank\">POTD</a>&nbsp;is a part of&nbsp;<a href=\"https://practice.geeksforgeeks.org/summer-carnival-2022?utm_source=potd&amp;utm_medium=problempage&amp;utm_campaign=gsc22\" target=\"_blank\">Geek Summer Carnival</a>. Solve all POTD consecutively from 5th to 10th April and get a chance to win exclusive discount vouchers on our GfG courses.</span></strong></p>\n\n<hr>\n<p><span style=\"font-size:18px\">Geek has a ticket to the Geek Summer Carnival. The ticket has a positive integer <strong>B </strong>written on it. <strong>B </strong>denotes the base of a right-angled <strong>isosceles </strong>triangle.&nbsp;<br>\nGeek can avail discounts on <strong>X </strong>courses in the carnival.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>X </strong>is the <strong>maximum </strong>number of squares of size <strong>2x2 </strong>units that can fit in the given right-angled isosceles triangle.&nbsp;<br>\nFind <strong>X</strong>.&nbsp;</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nB = 8\n<strong>Output:</strong>\n6 \n<strong>Explanation: \n</strong></span><img alt=\"\" src=\"https://media.geeksforgeeks.org/img-practice/ScreenShot2022-04-01at2-1648805313.png\" style=\"height:224px; width:300px\" class=\"img-responsive\">\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong>\nB = 2\n<strong>Output:</strong>\n0</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read input or print anything. Complete the function <strong>countSquare()</strong> that takes integer b as input parameter and returns the number of possible squares that can fit into the isosceles triangle.&nbsp;</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(1)<br>\n<strong>Expected Auxiliary Space:</strong> O(1)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 &lt;= B &lt;= 1000</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Triangle and Square - GFG/triangle-and-square.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\nimport java.util.*;\nimport java.io.*;\nimport java.lang.*;\n\nclass GFG{\n\tpublic static void main(String [] args) throws IOException{\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\t\tint test = Integer.parseInt(br.readLine());\n\t\twhile(test-- > 0) {\n\t\t\tint B = Integer.parseInt(br.readLine());\n\t\t\tSolution obj = new Solution();\n\t\t\tint count = obj.countSquare(B);\n\t\t\tSystem.out.println(count);\n\t\t}\n\t}\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n\tint countSquare(int B){\n\t\t//Write your code here\n\t\tB-=2;\n\t\tB/=2;\n\t\treturn B*(B+1)/2;\n\t}\n}"
  },
  {
    "path": "Tricky Subset Problem - GFG/README.md",
    "content": "# Tricky Subset Problem\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">N children are made to stand in a queue. Each of them is given a number A[i]. The teacher writes a number S on a page and passes it to the first child. Each child must add all the numbers they see on the page along with their own number, write the sum on the paper and pass it to the next person.&nbsp;<br>\nIn the end, the teacher must determine if X can be formed by adding some of the numbers from the series of numbers written on the paper.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>\nS = 1, N = 4, X = 7\nA = {1, 2, 4, 2}\n<strong>Output:</strong> yes\n<strong>Explaination:</strong> The final sequence of \nnumbers on the paper is 1, 2, 5, 12, 22. \nUsing 2 and 5 we can form 7. </span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>\nS = 100, N = 2, X = 500\nA = {51, 88}\n<strong>Output: </strong>no\n<strong>Explaination:</strong> The final sequence of \nnumbers on the paper is 100, 151, 339. \nUsing these numbers we cannot form 500.</span></pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>isPossible() </strong>which takes S, N, X and array A as input parameters and returns 1 if there is a subset which adds to this sum. Otherwise returns 0.</span></p>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Expected Time Complexity: </strong>O(N)<br>\n<strong>Expected Auxiliary Space: </strong>O(N)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n1 ≤ S, A<sub>i</sub>&nbsp;, X ≤ 10<sup>18</sup>&nbsp;&nbsp;</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Tricky Subset Problem - GFG/tricky-subset-problem.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            String a[] = in.readLine().trim().split(\"\\\\s+\");\n            long S = Long.parseLong(a[0]);\n            int N = Integer.parseInt(a[1]);\n            long X = Long.parseLong(a[2]);\n            String a1[] = in.readLine().trim().split(\"\\\\s+\");\n            long A[] = new long[N];\n            for(int i = 0;i < N;i++)\n                A[i] = Long.parseLong(a1[i]);\n            \n            Solution ob = new Solution();\n            if(ob.isPossible(S, N, X, A) == 1)\n                System.out.println(\"yes\");\n            else\n                System.out.println(\"no\");\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static int isPossible(long S, int N, long X, long A[])\n    {\n        int i=0;\n        long s=S;\n        for(i=0;i<N;i++){\n            A[i]+=s;\n            s+=A[i];\n            if(s>X){\n                break;\n            }\n        }\n        if(s==X)return 1;\n        while(X>=0 && i>=0){\n            if(X>=A[i])X-=A[i];\n            if(X==0 || X-S==0)return 1;\n            i--;\n        }\n        return 0;\n    }\n}"
  },
  {
    "path": "Two Sum.java",
    "content": "class Solution {\n    public int[] twoSum(int[] nums, int target) {\n        int i;\n        int j;\n        for (i=1;i<nums.length;i++)\n        {\n            for (j=i;j<nums.length;j++)\n            {\n                if (nums[j-i]+nums[j]==target)\n                {\n                    return new int[]{j-i,j};\n                }\n            }\n        }\n        return new int[]{-1,-1};\n    }\n}\n"
  },
  {
    "path": "Two Sum.py",
    "content": "class Solution:\n    def twoSum(self, nums: List[int], target: int) -> List[int]:\n        \n        \n        lookup_dict = {}\n        \n        for position, number in enumerate(nums):\n            \n            if target - number in lookup_dict:\n                return lookup_dict[target-number], position\n            \n            else:\n                lookup_dict[number] = position\n"
  },
  {
    "path": "UTF-8-Validation med lc.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n// TC : O(N) where N is the number of elements in data\n// SC: O(1) \nclass Solution {\npublic:\n    bool validUtf8(vector<int>& data) {\n        int remaining = 0;\n        for (auto& x : data) {\n            if (remaining == 0) {\n                if ((x >> 5) == 0b110) {\n                    remaining = 1;\n                } else if ((x >> 4) == 0b1110) {\n                     remaining = 2;\n                } else if ((x >> 3) == 0b11110) {\n                    remaining = 3;\n                } else if ((x >> 7) != 0) {\n                    return false;\n                }\n            } else {\n                if ((x >> 6) != 0b10) return false;\n                else remaining--;\n            }\n        }\n        return remaining == 0;\n    }\n};\n"
  },
  {
    "path": "Union-Find - GFG/README.md",
    "content": "# Union-Find\n## Easy \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">This problem is to implement disjoint set union. There will be 2 incomplete functions namely union and find. You have to complete these functions.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Union:</strong> Join two subsets into a single set.<br>\n<strong>isConnected:</strong> Determine which subset a particular element is in. This can be used for determining if two elements are in same subset.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 5\nq = 4\nQueries = \nUnion(1,3)\nisConnected(1,2)\nUnion(1,5)\nisConnected(3,5)\n<strong>Output:\n</strong>0\n1<strong>\nExplanation: </strong>Initially all nodes 1 2 3 4 5\nare not connected.&nbsp;\nAfter <strong>Union(1,3)</strong>, node 1 and 3 will be\nconnected.\nWhen we do <strong>isConnected(</strong><strong>1,2)</strong>,&nbsp; as node 1\nand 2&nbsp;are not connected it will return 0.\nAfter <strong>Union(1,5)</strong>, node 1 and 5&nbsp;will be\nconnected.\nWhen we do <strong>isConnected(3,5</strong><strong>)</strong>,&nbsp; as node\n1 and 3&nbsp;are&nbsp;connected, and node 1 and 5\nare connected, hence 3 and 5 are\nconnected.&nbsp;Thus it will return 1.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:\n</strong>N = 5\nq = 4\nQueries = \nUnion(1,4)\nUnion(1,5)\nisConnected(2,3)\nUnion(3,4)\n<strong>Output: </strong>0</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong></span></p>\n\n<p><span style=\"font-size:18px\">You have to complete the function <strong>union_() </strong>which merges the node1 and node2. You will also have to complete the function <strong>isConnected() </strong>which will return whether the two nodes are connected.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Note:&nbsp;</span></strong><span style=\"font-size:18px\">Both function will contain two arrays&nbsp;<strong>par[] and ranks1[]&nbsp;</strong>along with two nodes. Initially&nbsp;<strong>par[i] = i </strong>and <strong>rank1[i] = 1&nbsp;</strong></span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(N + Q).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(1).</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:&nbsp;</strong><br>\n1 &lt;= N &lt;= 10<sup>5</sup><br>\n1&lt;= Q &lt;= 10<sup>5</sup><br>\n1 &lt;= node1, node2 &lt;= N</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Union-Find - GFG/union-find.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\n\npublic class GFG {\n    public static void main(String[] args) throws IOException {\n        \n        //using BufferedReader to take input\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        \n        //taking total testcases\n        int t = Integer.parseInt(br.readLine());\n\n        while(t-- > 0){\n            \n            //taking total number of elements\n            int n = Integer.parseInt(br.readLine());\n            \n            int par[] = new int[n+1];\n            int rank[] = new int[n+1];\n            \n            //initializing the parent and\n            //the rank array\n            for(int i = 1; i<=n; ++i){\n                par[i] = i;\n                rank[i] = 1;\n            }\n            int a = 0, b = 0;\n            char c = '0';\n            \n            //taking number of queries\n            int query = Integer.parseInt(br.readLine());\n            \n            Boolean output = false;\n            while(query-- >0){\n                String str[] = br.readLine().trim().split(\" \");\n                c = str[0].charAt(0);\n                a = Integer.parseInt(str[1]);\n                b = Integer.parseInt(str[2]);\n\n                //if query type is 'U'\n                //then calling union_ method\n                if(c == 'U'){\n                    new Solution().union_(a, b, par, rank);\n                }\n                else{//else calling isConnected() method\n                    output = new Solution().isConnected(a, b, par, rank);\n                    if(output == true)\n                        System.out.println(\"1\");\n                    else\n                        System.out.println(\"0\");\n                }\n            }\n\n\n\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\n\nclass Solution\n{\n    public int findPar(int node,int par[]){\n        if(node==par[node])return node;\n        return par[node]=findPar(par[node],par);\n    }\n    //Function to merge two nodes a and b.\n    public void union_(int a, int b, int par[], int rank[])\n    {\n        a=findPar(a,par);\n        b=findPar(b,par);\n        if(rank[a]<rank[b]){\n            par[a]=b;\n        }else if(rank[b]<rank[a]){\n            par[b]=a;\n        }else{\n            par[b]=a;\n            rank[a]++;\n        }\n    }\n\n    //Function to check whether 2 nodes are connected or not.\n    public Boolean isConnected(int a, int b, int par[], int rank[])\n    {\n        return findPar(a,par)==findPar(b,par);\n    }\n\n}"
  },
  {
    "path": "Unique Subsets - GFG/README.md",
    "content": "# Unique Subsets\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given an array <strong>arr[]</strong><strong> </strong>of integers&nbsp;of size <strong>N</strong> that might contain <strong>duplicates</strong>, the task is to find all possible unique subsets.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Note:</strong> Each subset should be sorted.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>N = 3, arr[] = {2,1,2}\n<strong>Output:</strong>(),(1),(1 2),(1 2 2),(2),(2 2)</span>\n<span style=\"font-size:18px\"><strong>Explanation: </strong>\nAll possible subsets = (),(2),(1),(1,2),(2),(2,2),(2,1),(2,1,2)\nAfter Sorting each subset = (),(2),(1),(1,2),(2),(2,2),(1,2),(1,2,2) \nUnique Susbsets in Lexicographical order = (),(1),(1,2),(1,2,2),(2),(2,2)</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>N = 4, arr[] = {1,2,3,3}\n<strong>Output: </strong>(),(1),(1 2),(1 2 3)\n(1 2 3 3),(1 3),(1 3 3),(2),(2 3)\n(2 3 3),(3),(3 3)</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYour task is to complete the function <strong>AllSubsets()</strong>&nbsp;which takes the array <strong>arr[]</strong> and <strong>N</strong> as input parameters and returns list of&nbsp;all possible unique subsets in lexicographical order.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong>&nbsp;O(2<sup>N</sup>).<br>\n<strong>Expected Auxiliary Space:</strong>&nbsp;O(2<sup>N</sup>&nbsp;* X), X = Length of each subset.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 12</span><br>\n<span style=\"font-size:18px\">1 ≤ arr[i] ≤ 9</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Unique Subsets - GFG/unique-subsets.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass GFG {\n    \n    \n\tpublic static void main (String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n\t\tint testCases = sc.nextInt();\n\t\tfor(int t=0;t<testCases;t++){\n\t\t    int n = sc.nextInt();\n\t\t    int arr[] = new int[n];\n\t\t    for(int i=0;i<n;i++){\n\t\t        arr[i] = sc.nextInt();\n\t\t    }\n\t\t    Arrays.sort(arr);\n\t\t    System.out.print(\"()\");\n\t\t    ArrayList <ArrayList<Integer>> res = new solve().AllSubsets(arr,n);\n\t\t    for (int i = 0; i < res.size (); i++)\n\t\t    {\n\t\t        System.out.print (\"(\");\n\t\t        for (int j = 0; j < res.get(i).size (); j++)\n\t\t        {\n\t\t            if (j != res.get(i).size()-1)\n\t\t                System.out.print ((res.get(i)).get(j) + \" \");\n\t\t            else\n\t\t                System.out.print ((res.get(i)).get(j));\n\t\t        }\n\t\t        System.out.print (\")\");\n\t\t      \n\t\t    }\n\t\t    System.out.println();\n\t\t}\n\t}\n}// } Driver Code Ends\n\n\nclass solve{\n    public static ArrayList <ArrayList <Integer>> AllSubsets(int arr[], int n){\n        Arrays.sort(arr);\n        ArrayList<ArrayList<Integer>> ans= new ArrayList<>();\n        ArrayList<Integer> al=new ArrayList<>();\n        check(arr,n,0,ans,al);\n        ans.remove(0);\n        return ans;\n    }\n   \n    public static void check(int arr[], int n,int index,ArrayList<ArrayList<Integer>> ans,ArrayList<Integer> al){\n        if(!ans.contains(al))ans.add(al);\n        if(index==n) return;\n        ArrayList<Integer> temp=new ArrayList<>(al);\n        temp.add(arr[index]);\n        check(arr,n,index+1,ans,temp);\n        check(arr,n,index+1,ans,al);\n    }\n\n\n}\n"
  },
  {
    "path": "Unit Area of largest region of 1's.cpp",
    "content": "class Solution\n{\n    public:\n    //Function to find unit area of the largest region of 1s.\n    void solve(vector<vector<int>> &grid , int i , int j , int n , int m , int &cnt)\n    {\n        if(i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 0)\n            return;\n            \n        cnt+=1;\n        grid[i][j] = 0;\n      \n        // 8 directions\n        solve(grid,i-1,j,n,m ,cnt);\n        solve(grid,i+1,j,n,m ,cnt);\n        solve(grid,i,j-1,n,m ,cnt);\n        solve(grid,i,j+1,n,m ,cnt);\n        solve(grid,i-1,j-1,n,m ,cnt);\n        solve(grid,i-1,j+1,n,m ,cnt);\n        solve(grid,i+1,j-1,n,m ,cnt);\n        solve(grid,i+1,j+1,n,m ,cnt);\n    }\n  \n    int findMaxArea(vector<vector<int>>& grid) \n    {\n        int ans = 0;\n        int n = grid.size() , m = grid[0].size();\n        for(int i = 0;i<n;i++)\n        {\n            for(int j = 0;j<m;j++)\n            {\n                if(grid[i][j] == 1)\n                {\n                    int cnt = 0;\n                    solve(grid , i , j , n , m , cnt);\n                    ans = max(ans , cnt);\n                }\n            }\n        }\n        \n        return ans;\n        // Code here\n    }\n};\n\n// class Solution\n// {\n//     public:\n    \n//     int n, m;\n//     int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};\n//     int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};\n    \n//     // Function to count the area of adjacent elements\n//     int countArea(vector<vector<int>>& grid, int i, int j)\n//     {\n//         if(i < 0 or i >= n or j < 0 or j >= m or grid[i][j] == 0)\n//         return 0;\n        \n//         int ans = 1;\n//         grid[i][j] = 0;\n        \n//         for(int d=0; d<8; d++)\n//             ans += countArea(grid, i+dx[d], j+dy[d]);\n            \n//         return ans;\n//     }\n    \n//     //Function to find unit area of the largest region of 1s.\n//     int findMaxArea(vector<vector<int>>& grid) {\n//         // Code here\n//         n = grid.size();\n//         m = grid[0].size();\n        \n//         int ans = 0;\n        \n//         for(int i=0; i<n; i++)\n//         {\n//             for(int j=0; j<m; j++)\n//             {\n//                 if(grid[i][j] == 1)\n//                 ans = max(ans, countArea(grid, i, j));\n//             }\n//         }\n        \n//         return ans;\n//     }\n// };\n"
  },
  {
    "path": "Unit Area of largest region of 1's.java",
    "content": "class Solution\n{\n    //Function to find unit area of the largest region of 1s.\n    public int findMaxArea(int[][] grid)\n    {\n        // Code here\n        int ans=0;\n        boolean[][]vis=new boolean[grid.length][grid[0].length];\n        for(int i=0;i<grid.length;i++){\n            for(int j=0;j<grid[0].length;j++){\n                if(!vis[i][j] && grid[i][j]==1){\n                    ans=Math.max(ans,dfs(grid,i,j,vis));\n                }\n            }\n        }\n        return ans;\n    }\n    int dfs(int[][]grid,int i,int j,boolean[][]vis){\n        if(!valid(grid,i,j,vis))return 0;\n        vis[i][j]=true;\n        int ans=1;\n        ans+=dfs(grid,i+1,j,vis);\n        ans+=dfs(grid,i-1,j,vis);\n        ans+=dfs(grid,i,j+1,vis);\n        ans+=dfs(grid,i,j-1,vis);\n        ans+=dfs(grid,i+1,j+1,vis);\n        ans+=dfs(grid,i+1,j-1,vis);\n        ans+=dfs(grid,i-1,j+1,vis);\n        ans+=dfs(grid,i-1,j-1,vis);\n        return ans;\n    }\n    boolean valid(int[][]grid,int i,int j,boolean[][]vis){\n        if(i<0 || j<0 || i==grid.length || j==grid[0].length\n        || grid[i][j]==0 || vis[i][j])return false;\n        return true;\n    }\n}\n\n//Approach-2\n\nclass Solution\n{\n    int count;\n    static boolean isSafe(int[][] grid,int row,int col,boolean[][] visited,int ROW,int COL)\n    {\n        if(row<0 || col<0 || row>=ROW || col>=COL || visited[row][col] || grid[row][col]==0)\n            return false;\n        return true;    \n    }\n\n    \n    void DFS(int[][] grid,int row,int col,boolean[][] visited,int ROW,int COL)\n    {\n        int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 };\n        int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 };\n\n        visited[row][col] = true;\n\n        for (int k = 0; k < 8; k++) \n        {\n            if (isSafe(grid, row + x[k], col + y[k],visited, ROW, COL)) \n            {\n                count++;\n                DFS(grid, row + x[k], col + y[k],visited, ROW, COL);\n            }\n        }\n    }\n    \n    public int findMaxArea(int[][] grid)\n    {\n        int ROW = grid.length;\n        int COL = grid[0].length;\n        \n        boolean[][] visited = new boolean[ROW][COL];\n\n        int result = 0;\n      \n        for (int i = 0; i < ROW; i++) \n        {\n            for (int j = 0; j < COL; j++) \n            {\n                \n                if (grid[i][j] == 1 && !visited[i][j]) \n                {\n                    count = 1;\n                    DFS(grid, i, j, visited, ROW, COL);\n\n                    result = Math.max(result, count);\n                }\n            }\n        }\n        return result;\n    }\n}\n\n    \n   \n"
  },
  {
    "path": "Valid Binary Search Tree.java",
    "content": "public class Solution {\n    int check(TreeNode a,int min,int max){\n        if(a==null)return 1;\n        if(a.val<min || a.val>max)return 0;\n        return check(a.left,min,a.val-1)& check(a.right,a.val+1,max);\n    }\n    public int isValidBST(TreeNode root) {\n        return check(root,Integer.MIN_VALUE,Integer.MAX_VALUE);\n    }\n}\n"
  },
  {
    "path": "Valid Mountain Array.java",
    "content": "class Solution {\n    public boolean validMountainArray(int[] A) {\n        int N = A.length;\n        int i = 0;\n\n        // walk up\n        while (i+1 < N && A[i] < A[i+1])\n            i++;\n\n        // peak can't be first or last\n        if (i == 0 || i == N-1)\n            return false;\n\n        // walk down\n        while (i+1 < N && A[i] > A[i+1])\n            i++;\n\n        return i == N-1;\n    }\n}\n"
  },
  {
    "path": "Valid Parentheses.java",
    "content": "class Solution {\n    public boolean isValid(String s) {\n\t\tchar[] stack = new char[s.length()];\n\t\tint head = 0;\n\t\tfor(char c : s.toCharArray()) {\n\t\t\tswitch(c) {\n\t\t\t\tcase '{':\n\t\t\t\tcase '[':\n\t\t\t\tcase '(':\n\t\t\t\t\tstack[head++] = c;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '}':\n\t\t\t\t\tif(head == 0 || stack[--head] != '{') return false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase ')':\n\t\t\t\t\tif(head == 0 || stack[--head] != '(') return false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase ']':\n\t\t\t\t\tif(head == 0 || stack[--head] != '[') return false;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn head == 0;\n    }\n}\n"
  },
  {
    "path": "Valid Password.java",
    "content": "public class Solution {\n    public int solve(String A) {\n        if(A.length()<8 || A.length()>15)return 0;\n        boolean num=false;\n        boolean lower=false;\n        boolean upper=false;\n        boolean spcl=false;\n        for(int i=0;i<A.length();i++){\n            char ch=A.charAt(i);\n            if(ch>='0' && ch<='9')num=true;\n            if(ch>='a' && ch<='z')lower=true;\n            if(ch>='A' && ch<='Z')upper=true;\n            if(ch=='@' || ch=='#' || ch=='%'||ch=='&'||ch=='!'||ch=='$'||ch=='*')spcl=true;\n        }\n        return num && lower && upper && spcl?1:0;\n    }\n}\n"
  },
  {
    "path": "Validate Stack Sequences.java",
    "content": "class Solution {\n    public boolean validateStackSequences(int[] a, int[] b) {\n        Deque<Integer> st=new ArrayDeque<>();\n        int i=0;\n        int j=0;\n        st.push(a[i]);\n        i++;\n        while(i<a.length || j<b.length){\n            if(st.peek()!=null){\n                while(st.peek()!=b[j] && i<a.length){\n                    st.push(a[i]);\n                    i++;\n                }\n                if(st.peek()==b[j]){\n                    st.pop();\n                    j++;\n                }else{\n                    return false;   \n                }\n            }else{\n                st.push(a[i]);\n                i++;\n            }\n        }\n        return true;\n    }\n}\n//=============================================\nclass Solution {\n    public boolean validateStackSequences(int[] arr, int[] pop) {\n       \n        int n=arr.length;\n         if(n==0)\n            return true;\n        int j=0;\n        int i=-1;\n        for(int e:arr)\n        {\n                arr[++i]=e;\n                while(i>=0&&arr[i]==pop[j])\n                {\n                    i--;\n                    j++;\n                }\n        }\n        if(i==-1&&j==n)\n            return true;\n        return false;\n            \n    }\n}\n"
  },
  {
    "path": "Verify Prime.java",
    "content": "static boolean prime(int n)\n{\n        // Corner cases\n        if (n <= 1)\n            return false;\n        if (n <= 3)\n            return true;\n  \n        // This is checked so that we can skip\n        // middle five numbers in below loop\n        if (n % 2 == 0 || n % 3 == 0)\n            return false;\n            \n        for (int i = 5; i * i <= n; i += 6)\n            if (n % i == 0 || n % (i + 2) == 0)\n                return false;\n  \n        return true;\n}\n"
  },
  {
    "path": "Vertical Sum of a Binary Tree.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    int min;\n    int max;\n    public ArrayList<Integer> verticalSum(TreeNode A) {\n        min=Integer.MAX_VALUE;\n        max=Integer.MIN_VALUE;\n        ArrayList<Integer> arr=new ArrayList<>();\n        Map<Integer,Integer> map=new HashMap<>();\n        dfs(A,map,0);\n        while(min<=max){\n            arr.add(map.get(min));\n            min++;\n        }\n        return arr;\n    }\n    public void dfs(TreeNode a,Map<Integer,Integer> map,int curr){\n        if(a==null)return;\n        map.put(curr,map.getOrDefault(curr,0)+a.val);\n        min=Math.min(min,curr);\n        max=Math.max(max,curr);\n        dfs(a.left,map,curr-1);\n        dfs(a.right,map,curr+1);\n    }\n}\n"
  },
  {
    "path": "Villain Con - GFG/README.md",
    "content": "# Villain Con\n## Medium \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">The minions are very elitist in nature. If minion x admires minion y, then y thinks too highly of himself and does not admire x back. Also, if x admires y, x also admires everyone that y admires.<br>\nAll the&nbsp;minions are going to be present at the Villain Con. They want&nbsp;to make sure that they do not dress in the&nbsp;same color as someone who admires them.&nbsp;<br>\nThere are <strong>N</strong> minions and <strong>M</strong> relations between them. The relations are given in a 2D array <strong>mat</strong>. Each relation is given in x<sub>i</sub>&nbsp;, y<sub>i</sub>&nbsp;format where y<sub>i</sub>&nbsp;admires x<sub>i. </sub>Find the minimum number of different colours that the minions will be dressing in.&nbsp;</span></p>\n\n<p>&nbsp;</p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> \nN = 5, M = 6\nmat = {{1, 3}, \n&nbsp;      {2, 3}, \n&nbsp;      {3, 4}, \n&nbsp;      {1, 4}, \n&nbsp;      {2, 5}, \n&nbsp;      {3, 5}}\n<strong>Output:</strong> 3\n<strong>Explaination:\n</strong>If we assign red colour to 1 and 2,\ngreen colour to 3, and blue colour to 4 and 5, then\nevery minion will have different coloured dresses\nfrom the one who admires them.</span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><strong><span style=\"font-size:18px\">Input:\n</span></strong><span style=\"font-size:18px\">N = 3, M = 2\nmat = {{1,3},{2,3}}</span><strong><span style=\"font-size:18px\">\nOutput:\n</span></strong><span style=\"font-size:18px\">2</span><strong><span style=\"font-size:18px\">\nExplanation:\n</span></strong><span style=\"font-size:18px\">If we assign red colour to 1 and 2, and green colour to 3, then the condition is satisfied.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>minColour()</strong> which takes N, M and mat[][] as input parameters and returns the minimum number of colours required.</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N+M)<br>\n<strong>Expected Auxiliary Space:</strong> O(N+M)</span></p>\n\n<p>&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ N ≤ 10<sup>5</sup><br>\n1 ≤ M ≤ 2*10<sup>5</sup>&nbsp;&nbsp;<br>\n1 ≤ x<sub>i</sub> , y<sub>i</sub> ≤ N</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Villain Con - GFG/villain-con.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0) {\n            String a[] = in.readLine().trim().split(\"\\\\s+\");\n            int N = Integer.parseInt(a[0]);\n            int M = Integer.parseInt(a[1]);\n            int mat[][] = new int[M][2];\n            for(int i = 0;i < M;i++){\n                String a1[] = in.readLine().trim().split(\"\\\\s+\");\n                mat[i][0] = Integer.parseInt(a1[0]);\n                mat[i][1] = Integer.parseInt(a1[1]);\n            }\n            \n            Solution ob = new Solution();\n            System.out.println(ob.minColour(N, M, mat));\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static int minColour(int N, int M, int mat[][]) {\n        Queue<Integer> q = new LinkedList<>();\n        int[] indegree = new int[N+1];\n        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n        for(int i=0;i<=N;i++){\n            adj.add(new ArrayList<>());\n        }\n        for(int[] row : mat){\n            indegree[row[0]]++;\n            adj.get(row[1]).add(row[0]);\n        }\n        \n        for(int i=0;i<=N;i++){\n            if(indegree[i] == 0){\n                q.offer(i);\n            }\n        }\n        \n        \n        int count = 0;\n        \n        \n        while(!q.isEmpty()){\n            count++;\n            int size = q.size();\n            while(size-->0){\n                int currVertex = q.poll();\n                for(int neighbor : adj.get(currVertex)){\n                    if(indegree[neighbor] == 1){\n                        q.offer(neighbor);\n                    }\n                    indegree[neighbor]--;\n                }\n            }\n        }\n        \n        return count;\n    }\n}"
  },
  {
    "path": "Vowel and Consonant Substrings!.java",
    "content": "public class Solution {\n    int mod=1000000007;\n    public int solve(String A) {\n        int ans=0;\n        int con=0;\n        int vow=0;\n        for(int i=A.length()-1;i>=0;i--){\n            char c=A.charAt(i);\n            if(vowel(c)){\n                vow++;\n                ans+=con;\n            }else{\n                con++;\n                ans+=vow;\n            }\n            ans%=mod;\n        }\n        return ans;\n    }\n    public boolean vowel(char c){\n        if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u'){\n            return true;\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "Wave Array.java",
    "content": "public class Solution {\n    public ArrayList<Integer> wave(ArrayList<Integer> arr) {\n        Collections.sort(arr);\n        int i=0;\n        while(i+1<arr.size()){\n            int first=i;\n            int second=i+1;\n            Collections.swap(arr,first,second);\n            i+=2;\n        }\n        return arr;\n    }\n}\n"
  },
  {
    "path": "Ways to Decode.java",
    "content": "public class Solution {\n    int mod=1000000007;\n    public int numDecodings(String s) {\n        int n = s.length();\n        int[]dp=new int[n+1];\n        dp[0] = 1;\n        dp[1] = s.charAt(0) == '0' ? 0 : 1;\n        for(int i=2; i<=n; i++) {\n            int ways = 0;\n            String dig = s.substring(i-1,i);\n            if(Integer.parseInt(dig) > 0) {\n                ways += dp[i-1];\n                ways %= mod;\n            }\n            dig = s.substring(i-2, i);\n            if(Integer.parseInt(dig) >= 10 && Integer.parseInt(dig) <= 26) {\n                ways += dp[i-2];\n                ways %= mod;\n            }\n            dp[i] = ways;\n        }\n        return dp[n];\n    }\n}\n"
  },
  {
    "path": "Window String.java",
    "content": "public class Solution {\n    public String minWindow(String A, String B) {\n        int want=B.length();\n        int count=0;\n        StringBuilder sb=new StringBuilder();\n        String ans=null;\n        Map<Character,Integer> map=new HashMap<>();\n        Map<Character,Integer> curr=new HashMap<>();\n        for(char c:B.toCharArray()){\n            map.put(c,map.getOrDefault(c,0)+1);\n        }\n        \n        int i=0;\n        int j=0;\n        while(j<A.length()){\n            if(count==want){\n                if(ans==null || ans.length()>sb.length()){\n                    ans=sb.toString();\n                }\n                char c=A.charAt(j);\n                sb.deleteCharAt(0);\n                curr.put(c,curr.get(c)-1);\n                if(!map.containsKey(c)){\n                    j++;\n                    continue;\n                }\n                if(curr.get(c)<map.get(c)){\n                    count--;\n                }\n                j++;\n            }else{\n                if(i==A.length())break;\n                char c=A.charAt(i);\n                sb.append(c);\n                curr.put(c,curr.getOrDefault(c,0)+1);\n                if(!map.containsKey(c)){\n                    i++;\n                    continue;\n                }\n                if(curr.get(c)<=map.get(c)){\n                    count++;\n                }\n                i++;\n            }\n        }\n        return ans==null?\"\":ans;\n    }\n}\n"
  },
  {
    "path": "Word Break - Part 2 - GFG/README.md",
    "content": "# Word Break - Part 2\n## Hard \n<div class=\"problem-statement\">\n                <p></p><p><span style=\"font-size:18px\">Given a string <strong>s</strong> and a dictionary of words <strong>dict</strong> of length <strong>n</strong><strong>,</strong> add spaces in <strong>s</strong> to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences.</span></p>\n\n<p><span style=\"font-size:18px\">Follow examples for better understanding.</span></p>\n\n<p><strong><span style=\"font-size:18px\">Example 1:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> s = \"catsanddog\", n = 5 \ndict = {\"cats\", \"cat\", \"and\", \"sand\", \"dog\"}\n<strong>Output:</strong> (cats and dog)(cat sand dog)\n<strong>Explanation:</strong> All the words in the given \nsentences are present in the dictionary.</span></pre>\n\n<p><strong><span style=\"font-size:18px\">Example 2:</span></strong></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input:</strong> s = \"catsandog\", n = 5\ndict = {\"cats\", \"cat\", \"and\", \"sand\", \"dog\"}\n<strong>Output:</strong> Empty\n<strong>Explanation:</strong> There is no possible breaking \nof the string s where all the words are present \nin dict.</span></pre>\n\n<p><span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou do not need to read input or print anything. Your task is to complete the function <strong>wordBreak()</strong> which takes <strong>n</strong>, <strong>dict</strong> and <strong>s</strong> as input parameters and returns a list of possible sentences. If no sentence is possible it returns an empty list.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:</strong> O(N<sup>2</sup>*n) where N = |s|<br>\n<strong>Expected Auxiliary Space:</strong> O(N<sup>2</sup>)</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ n ≤ 20<br>\n1 ≤ dict[i] ≤ 15<br>\n1 ≤ |s| ≤ 500&nbsp;</span></p>\n <p></p>\n            </div>"
  },
  {
    "path": "Word Break - Part 2 - GFG/word-break-part-2.java",
    "content": "// { Driver Code Starts\n//Initial Template for Java\n\nimport java.io.*;\nimport java.util.*;\nimport java.util.stream.*;\n\nclass GFG{\n    public static void main(String args[])throws IOException\n    {\n        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n        int t = Integer.parseInt(in.readLine());\n        while(t-- > 0){\n            int n = Integer.parseInt(in.readLine());\n            String arr[] = in.readLine().trim().split(\"\\\\s+\");\n            List<String> dict = new ArrayList<String>();\n            for(int i = 0;i < n;i++)\n                dict.add(arr[i]);\n            String s = in.readLine();\n            \n            Solution ob = new Solution();\n            List<String> ans = new ArrayList<String>();\n            ans = ob.wordBreak(n, dict, s);\n            if(ans.size() == 0)\n                System.out.println(\"Empty\");\n            else{\n                List<String> sol = ans.stream().sorted().collect(Collectors.toList());\n                for(int i = 0;i < sol.size();i++)\n                    System.out.print(\"(\"+sol.get(i)+\")\");\n                System.out.println();\n            }\n        }\n    }\n}// } Driver Code Ends\n\n\n//User function Template for Java\n\nclass Solution{\n    static List<String> wordBreak(int n, List<String> dict, String s)\n    {\n        // code here\n        List<String> ans=new ArrayList<>();\n        dfs(dict,s,\"\",ans);\n        return ans;\n    }\n    static void dfs(List<String> dict,String s,String sentence,List<String> ans){\n        if(s.length()==0){\n            ans.add(sentence.substring(0,sentence.length()-1));\n        }\n        \n        for(int i=0;i<s.length();i++){\n            String word=s.substring(0,i+1);\n            if(dict.contains(word)){\n                String temp=s.substring(i+1);\n                dfs(dict,temp,sentence+word+\" \",ans);\n            }\n        }\n    }\n}"
  },
  {
    "path": "Word Break II.cpp",
    "content": "class Solution {\npublic:\n    vector<string>ans;\n    void backTrack(int i, string &s, string t, vector<string>& wordDict){\n        if(i == s.size()){\n            t.pop_back();\n            ans.push_back(t);\n            return;\n        }\n        for(auto &w : wordDict){\n            int n = w.size();\n            string str = s.substr(i, n);\n            \n            if(w == str){\n                backTrack(i + n, s, t + str + \" \", wordDict);\n            }\n        }\n    }\n    vector<string> wordBreak(string s, vector<string>& wordDict) {\n        backTrack(0, s, \"\", wordDict);\n        return ans;\n    }\n};\n"
  },
  {
    "path": "Word Break II.java",
    "content": "public class Solution {\n    ArrayList<ArrayList<String>> dp;\n    public ArrayList<String> wordBreak(String A,  ArrayList<String> B) {\n        dp = new ArrayList<>();\n        for(int i = 0;i<A.length();i++){\n            dp.add(new ArrayList<String>());\n        }\n        Set<String> set = new HashSet<>();\n        for(String str:B){\n            set.add(str);\n        }\n        return wordBreak(A,set,0);\n    }\n    public ArrayList<String> wordBreak(String A, Set<String> set, int i) {\n        if(i==A.length()){\n            return new ArrayList<String>();\n        }\n        if(dp.get(i).size()!=0)\n            return dp.get(i);\n        ArrayList<String> ans = new ArrayList<>();\n        for(int j = i+1;j<=A.length();j++){\n            if(set.contains(A.substring(i,j))){\n                ArrayList<String> buf = wordBreak(A,set,j);\n                for(String a: buf){\n                    ans.add(A.substring(i,j)+\" \"+a);\n                }\n                if(j==A.length()){\n                    ans.add(A.substring(i));\n                }\n            }\n        }\n        dp.set(i,ans);\n        return ans;\n    }\n}\n\n"
  },
  {
    "path": "Word Break.java",
    "content": "public class Solution {\n    public int wordBreak(String A, String[] B) {\n        Set<String> set = new HashSet<>();\n        for (String s : B) {\n            set.add(s);\n        }\n        Boolean[] dp = new Boolean[A.length()];\n        return wordBreak(A, set, 0, dp);\n    }\n    \n    private int wordBreak(String s, Set<String> set, int start, Boolean[] dp) {\n        if (start == s.length()) {\n            return 1;\n        }\n        if (dp[start] != null) return dp[start] ? 1 : 0;\n        \n        int ans = 0;\n        for (int end = start + 1; end <= s.length(); end++) {\n            if (set.contains(s.substring(start, end)) && wordBreak(s, set, end, dp) == 1) {\n                ans = 1;\n                break;\n            }\n        }\n        \n        dp[start] = ans == 1;\n        return ans;\n    }\n}\n\n"
  },
  {
    "path": "Word Count.py",
    "content": "class Solution:\n    # @param A : string\n    # @return an integer\n    def solve(self, A):\n        list1=A.split(' ')\n        i=0\n        k=len(list1)\n        while i<k:\n            if(list1[i]==''):\n                list1.pop(i)\n                k=len(list1)\n            else:\n                i=i+1\n        return k\n"
  },
  {
    "path": "Word Ladder I.cpp",
    "content": "class Solution {\npublic:\nint count(string a, string b){\n    if(a.length()!=b.length()) return -1;\n    \n    int cnt = 0;\n    for(int i=0;i<a.length();i++){\n        if(a[i]!=b[i]) cnt++;\n    }\n    return cnt;\n}\n    int wordLadderLength(string startWord, string targetWord, vector<string>& wordList) {\n        if(startWord==targetWord){\n            for(int i=0;i<wordList.size();i++){\n                if(wordList[i]==targetWord) return 1;\n            }\n        }\n        \n        queue<pair<string,int>> st;\n        st.push({startWord, 1});\n        set<string> sr;\n        \n        while(!st.empty()){\n            auto tp = st.front();\n            sr.insert(tp.first);\n            if(tp.first==targetWord) return tp.second;\n            st.pop();\n            \n            for(int i=0; i<wordList.size();i++){\n                if(sr.find(wordList[i])==sr.end() && count(wordList[i], tp.first)==1){\n                    st.push({wordList[i], tp.second+1});\n                }\n            }\n        }\n        \n        return 0;\n    }\n};\n"
  },
  {
    "path": "Word Ladder II.py",
    "content": "class Solution:\n    def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n            #generate\n        Nei = defaultdict(list)\n        for word in wordList:\n            for i in range(len(word)):\n                pattern = word[:i]+'*'+word[i+1:]\n                Nei[pattern].append(word)     \n        \n        #breadth first search + generate parent dictionary with path length limit\n        seen = {beginWord:0}\n        q = deque([(beginWord,0)])\n        minDist = float(\"inf\")\n        Parent = defaultdict(set)\n        while q:        \n            for _ in range(len(q)):\n                pre,dis = q.popleft()\n                for i in range(len(pre)):\n                    pattern = pre[:i] + \"*\" + pre[i+1:]\n                    for neighbor in Nei[pattern]:\n                        if neighbor not in seen or (seen[neighbor] == dis + 1 and seen[neighbor] <= minDist):\n                            if neighbor == endWord: \n                                minDist = dis + 1\n                            Parent[neighbor].add(pre)\n                            if neighbor not in seen:   \n                                q.append((neighbor,dis+1))\n                                seen[neighbor] = dis + 1\n\t\t\t\t\t\t\t\t\n        #generate path from parent dictionary\n        def makeList(cur,Path):\n            if cur == beginWord:\n                res.append(Path)\n            else:\n                for parent in Parent[cur]:\n                    makeList(parent,[parent] + Path)\n        res = []\n        makeList(endWord,[endWord])\n        \n        #return results\n        return res\n        \n"
  },
  {
    "path": "Word Ladder.java",
    "content": "class Solution {\n   public int ladderLength(String beginWord, String endWord, List<String> wordList) {\n        if (wordList == null || wordList.size() == 0) return 0;\n        //Hashset benefits: deduplication is also completed\n        //start end\n        HashSet<String> start = new HashSet<>();\n        //end\n        HashSet<String> end = new HashSet<>();\n        //dictionary of all strings\n        HashSet<String> dic = new HashSet<>(wordList);\n        start.add(beginWord);\n        end.add(endWord);\n        if (!dic.contains(endWord)) return 0;\n        //After going through the above series of judgments, when you get here, if there is a path, the minimum is 2, so start with 2\n        return bfs(start, end, dic, 2);\n\n    }\n\n    public int bfs(HashSet<String> st, HashSet<String> ed, HashSet<String> dic, int l) {\n        //When searching with two ends, if any segment is \"broken\", that is to say, there is no path that can be connected, it will return 0 directly.\n        if (st.size() == 0) return 0;\n        if (st.size() > ed.size()) {//Double-ended search, in order to optimize the time, always use less to find more. For example, if 1000 are inserted at the beginning, but only 3 at the end, it is definitely better to start from the less end.\n            return bfs(ed, st, dic, l);\n        }\n        //Marking behavior of BFS, i.e. used not reused\n        dic.removeAll(st);\n        //Collect next level proximity points\n        HashSet<String> next = new HashSet<>();\n        for (String s : st) {\n            char[] arr = s.toCharArray();\n            for (int i = 0; i < arr.length; i++) {\n                char tmp = arr[i];\n                //Variety\n                for (char c = 'a'; c <= 'z'; c++) {\n                    if (tmp == c) continue;\n                    arr[i] = c;\n                    String nstr = new String(arr);\n                    if (dic.contains(nstr)) {\n                        if (ed.contains(nstr)) return l;\n                        else next.add(nstr);\n                    }\n                }\n                //Variety\n                arr[i] = tmp;\n            }\n        }\n        return bfs(next, ed, dic, l + 1);\n    }\n}\n"
  },
  {
    "path": "Word Pattern.java",
    "content": "class Solution {\n    public boolean wordPattern(String pattern, String s) {\n        String[] words = s.split(\" \");\n        Map<Character,String> wordMap = new HashMap<>();\n        Map<String, Character> charMap = new HashMap<>();\n        if(pattern.length()!=words.length){\n            return false;\n        }\n        for(int i= 0;i<pattern.length();i++){\n            if(wordMap.containsKey(pattern.charAt(i)) && words[i].equals(wordMap.get(pattern.charAt(i)))){\n                continue;\n            } else if(!wordMap.containsKey(pattern.charAt(i))){\n                if(wordMap.containsValue(words[i])){\n                    return false;\n                }\n                wordMap.put(pattern.charAt(i), words[i]);\n            } else if(wordMap.containsKey(pattern.charAt(i)) && !words[i].equals(wordMap.get(pattern.charAt(i)))){\n                return false;\n            }\n        }\n        return true;\n    }\n}\n"
  },
  {
    "path": "Word Wrap - GFG/README.md",
    "content": "# Word Wrap\n## Medium \n<div class=\"problem-statement\">\n                <p></p><div class=\"row bottom\">\n<div class=\"col-xs-12 textAlign\">\n<div class=\"modifiedAnswer\">\n<p><span style=\"font-size:18px\">Given an array <strong>nums[]</strong> of size <strong>n</strong>, where&nbsp;<strong>nums[i]</strong>&nbsp;denotes the number of characters in one word.</span><span style=\"font-size:18px\">&nbsp;Let <strong>K</strong>&nbsp;be the&nbsp;limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly.<br>\nAssume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces include spaces put at the end of every line <strong>except the last one</strong>.&nbsp;</span></p>\n\n<p><span style=\"font-size:18px\">You have&nbsp;to <strong>minimize </strong>the following total cost where <strong>total cost </strong>= Sum of cost of all lines, where cost of line is = (Number of extra spaces in the line)<sup>2</sup>.</span></p>\n\n<p><span style=\"font-size:18px\"><strong>Example 1:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>nums = {3,2,2,5}, k = 6\n<strong>Output: </strong>10\n<strong>Explanation</strong>: Given a line can have 6\ncharacters,\nLine number 1: From word no. 1 to 1\nLine number 2: From word no. 2 to 3\nLine number 3: From word no. 4 to 4\nSo total cost = (6-3)<sup>2</sup> + (6-2-2-1)<sup>2</sup> = 3<sup>2</sup>+1<sup>2</sup> = 10.\nAs in the first line word length = 3 thus\nextra spaces = 6 - 3 = 3 and in the second line\nthere are two word of length 2 and there already\n1 space between two word thus extra spaces\n= 6 - 2 -2 -1 = 1. As mentioned in the problem\ndescription there will be no extra spaces in\nthe last line. Placing first and second word\nin first line and third word on second line\nwould take a cost of 0<sup>2</sup> + 4<sup>2</sup> = 16 (zero spaces\non first line and 6-2 = 4 spaces on second),\nwhich isn't the minimum possible cost.</span>\n</pre>\n\n<p><span style=\"font-size:18px\"><strong>Example 2:</strong></span></p>\n\n<pre><span style=\"font-size:18px\"><strong>Input: </strong>nums = {3,2,2}, k = 4\n<strong>Output: </strong>5\n<strong>Explanation: </strong>Given a line can have 4 \ncharacters,\nLine number 1: From word no. 1 to 1\nLine number 2: From word no. 2 to 2\nLine number 3: From word no. 3 to 3\nSame explaination as above total cost\n= (4 - 3)<sup>2</sup> + (4 - 2)<sup>2</sup> = 5<strong>.</strong></span>\n</pre>\n\n<p><br>\n<span style=\"font-size:18px\"><strong>Your Task:</strong><br>\nYou don't need to read or print anyhting. Your task is to complete the function&nbsp;<strong>solveWordWrap()&nbsp;</strong>which takes nums and k as input paramater and returns the minimized total cost.</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Expected Time Complexity:&nbsp;</strong>O(n<sup>2</sup>)<br>\n<strong>Expected Space Complexity:&nbsp;</strong>O(n)</span><br>\n&nbsp;</p>\n\n<p><span style=\"font-size:18px\"><strong>Constraints:</strong><br>\n1 ≤ n ≤ 500<br>\n1 ≤ nums[i] ≤ 1000<br>\nmax(nums[i]) ≤ k ≤ 2000</span></p>\n</div>\n</div>\n</div>\n <p></p>\n            </div>"
  },
  {
    "path": "Word Wrap - GFG/word-wrap.java",
    "content": "// { Driver Code Starts\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG\n{\n    public static void main(String[] args) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        int T = Integer.parseInt(br.readLine().trim());\n        while(T-->0)\n        {\n            int n = Integer.parseInt(br.readLine().trim());\n            int[] nums = new int[n];\n            String[] S = br.readLine().trim().split(\" \");\n            for(int i = 0; i < n; i++)\n                nums[i]  =Integer.parseInt(S[i]);\n            int k = Integer.parseInt(br.readLine().trim());\n            Solution obj = new Solution();\n            System.out.println(obj.solveWordWrap(nums, k));\n        }\n    }\n}\n// } Driver Code Ends\n\n\nclass Solution{\n    public int solveWordWrap (int[] nums, int k){\n        return solveWordWrapRec(nums, k, 0, new HashMap<>());\n    }\n    \n    public int solveWordWrapRec (int[] nums, int k, int idx, Map<Integer, Integer> cache){\n        if(idx >= (nums.length-1)){\n           return 0;\n        }\n       \n        Integer value = cache.get(idx);\n        if(value != null) return value;\n       \n        int cost = Integer.MAX_VALUE;\n        int used = 0;\n       \n        for(int i=idx; i<nums.length; i++){\n            if(used+nums[i] > k) break;\n            \n            if(i+1 < nums.length){\n                cost = Math.min(cost, solveWordWrapRec(nums, k, i+1, cache) + getCost(nums, idx, i, k));\n            }else{\n                cost = Math.min(cost, getCost(nums, idx, i, k));\n            }\n            used += nums[i] + 1;\n        }\n        value = cost;\n        cache.put(idx, value);\n        \n        return value;\n    }\n    \n    private int getCost(int[] nums, int from, int to, int k){\n        if(to == nums.length-1) return 0;\n        int used = 0;\n        \n        for(int i=from; i<=to; i++){\n            if(used > 0) used++;\n            used += nums[i];    \n        }\n        \n        return (k-used)*(k-used);\n    }\n}"
  },
  {
    "path": "X Total Shapes.java",
    "content": "\nclass Solution\n{\n    //Function to find the number of 'X' total shapes.\n    public int xShape(char[][] grid)\n    {\n        // code here\n        int ans=0;\n        int n=grid.length;\n        int m=grid[0].length;\n        boolean[][] vis=new boolean[n][m];\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(grid[i][j]=='X' && vis[i][j]==false){\n                    ans++;\n                    dfs(grid,i,j,vis);\n                }\n            }\n        }\n        return ans;\n    }\n    void dfs(char[][]grid,int i,int j,boolean[][]vis){\n        if(grid[i][j]!='X')return;\n        if(vis[i][j])return;\n        vis[i][j]=true;\n        if(i>0){\n            dfs(grid,i-1,j,vis);\n        }\n        if(i<grid.length-1){\n            dfs(grid,i+1,j,vis);\n        }\n        if(j>0){\n            dfs(grid,i,j-1,vis);\n        }\n        if(j<grid[0].length-1){\n            dfs(grid,i,j+1,vis);\n        }\n    }\n}\n"
  },
  {
    "path": "XOR Game.java",
    "content": "class Solution{\n    static int xorCal(int k){\n        // code here\n        // if (k == 1)return 2;\n        // int a = k >> 1;\n        // int b = a ^ k;\n        // return Math.abs(a - b) == 1? Math.min(a,b): -1;\n        if (k % 2 == 0)\n            return -1;\n            \n        if ((k & (k+1)) != 0)\n            return -1;\n            \n        if (k == 1)\n            return 2;\n        \n        return k>>1;\n    }\n}\n"
  },
  {
    "path": "XOR-ing the Subarrays!.java",
    "content": "public class Solution {\n    public int solve(int[] A) {\n        int ans=0;\n        if(A.length%2==0)return ans;\n        for(int i=0;i<A.length;i+=2){\n            ans=ans^A[i];\n        }\n        return ans;\n    }\n}\n"
  },
  {
    "path": "ZigZag Level Order Traversal BT.java",
    "content": "/**\n * Definition for binary tree\n * class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) {\n *      val = x;\n *      left=null;\n *      right=null;\n *     }\n * }\n */\npublic class Solution {\n    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {\n        ArrayList<ArrayList<Integer>> res = new ArrayList<>();\n        if(root==null)\n            return res;\n        Queue<TreeNode> q = new LinkedList<>();\n        q.offer(root);\n        \n        int p=0;\n        \n        while(!q.isEmpty())\n        {\n            int l = q.size();\n            List<Integer> level = new ArrayList<>();\n            for(int i=0;i<l;i++)\n            {\n                TreeNode curr = q.poll();\n                level.add(curr.val);\n                if(curr.left!=null)\n                    q.offer(curr.left);\n                if(curr.right!=null)\n                    q.offer(curr.right);\n            }\n            if(p%2!=0)\n                Collections.reverse(level);\n            \n            res.add(new ArrayList<Integer>(level));\n            p++;\n        }\n        return res;\n    }\n}\n\n"
  },
  {
    "path": "Zigzag String.java",
    "content": "public class Solution {\n    public String convert(String input, int num) {\n        if(num<=1){\n            return input;\n        }\n        StringBuilder result = new StringBuilder();\n        List<StringBuilder> list = new ArrayList<>();\n        for (int i = 0; i < num; i++) {\n          list.add(new StringBuilder());\n        }\n        boolean l2r = true;\n        int i = 0;\n        int size = input.length();\n        int ptr = 0;\n        while (i < size) {\n          if (l2r) {\n            while (ptr < num && i < size) {\n              list.get(ptr).append(input.charAt(i));\n              i++;\n              ptr++;\n            }\n            ptr -= 2;\n            l2r = false;\n          } else {\n            while (ptr >= 0 && i < size) {\n              list.get(ptr).append(input.charAt(i));\n              i++;\n              ptr--;\n            }\n            ptr = 1;\n            l2r = true;\n          }\n        }\n        for (StringBuilder temp : list) {\n          result.append(temp);\n        }\n        return result.toString();\n      }\n    \n}\n\n"
  },
  {
    "path": "alternate positive and negative.cpp",
    "content": "\tvoid rearrange(int arr[], int n) {\n    // code here\n    vector <int> A;\n    vector <int> B;\n    for (int i=0; i<n; i++){\n        if (arr[i] < 0){\n            A.push_back(arr[i]);\n        }else{\n            B.push_back(arr[i]);\n        }\n    }\n    int i=0;\n    int j=0;\n    int k=0;\n    \n    while(i<A.size() && j<B.size()){\n        if(k%2 == 0){\n            arr[k++] = B[j++];\n        }else{\n            arr[k++] = A[i++];\n        }\n    }while(i<A.size()){\n        arr[k++] = A[i++];\n    }while(j<B.size()){\n        arr[k++] = B[j++];\n    }\n}\n"
  },
  {
    "path": "check if array is sorted and rotated/check-if-array-is-rotated-and-sorted.cpp",
    "content": "class Solution {\npublic:\n    bool check(vector<int>& nums) {\n        \n        int size = nums.size();\n        int count = 0;\n\n        for(int x=0; x<size; x++)\n        {   \n            if(nums[x] > nums[(x+1)%size])\n                count ++;\n        }\n        return (count <= 1);\n        \n        // in case of sorted and rotated array the count is 1 and in case of only sorted array the count is 0\n        // in case of non-sorted and non-rotated array the count is greater than 1 so false.\n    }\n};\n"
  },
  {
    "path": "depth first search.cpp",
    "content": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nvoid dfs(vector<int>* adj,int node,vector<int>& visited)\n{\n    visited[node]=1;\n    cout<<node<<\" \";\n    for(auto it:adj[node])\n    {\n        if(!visited[it])\n        dfs(adj,node,visited);\n    }\n    \n    return ;\n}\n\nint main()\n{\n    //taking input\n    int n,e;\n    cin>>n>>e; // n is number of vertix\n               // e is number of edges\n    \n    vector<int> adj[n];\n    while(e--)\n    {\n        int u,v;\n        cin>>u>>v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    vector<int> visited(n,0);\n    for(int i=0;i<n;i++)\n    {\n        if(!visited[i])\n        dfs(adj,i,visited);\n    }\n    \n    return 0;\n}"
  },
  {
    "path": "rotate-array/rotate-array.cpp",
    "content": "class Solution {\npublic:\n    void rotate(vector<int>& nums, int k) {        \n        // eg 1 2 3 4 5 6 7\n        k %= nums.size();\n        reverse(nums.begin(), nums.end()); // reverse full 7 6 5 4 3 2 1\n        reverse(nums.begin(), nums.begin()+k); // reverse till first k 5 6 7 4 3 2 1\n        reverse(nums.begin()+k, nums.end()); // reverse till end from k 5 6 7 1 2 3 4        \n    }\n};\n"
  },
  {
    "path": "sorting-characters-by-frequency/sorting-characters-by-frequency.cpp",
    "content": "bool compare(const string& a, const string &b){\n        return a.length() > b.length();\n}\nclass Solution {\npublic:    \n    string frequencySort(string s) {\n        \n        // 1.\n        // unordered_map<char, int> mp;\n        // for(int i=0;i<s.size();i++){\n        //     mp[s[i]]++;\n        // }\n        // string ans=\"\";\n        // while(mp.size() > 0){\n        //     int maxFre = -1;\n        //     char ch;\n        //     for(auto it : mp){\n        //         if(maxFre < it.second){\n        //             maxFre = it.second;\n        //             ch = it.first;\n        //         }\n        //     }\n        //     mp.erase(ch);\n        //     for(int i=0;i<maxFre;i++){\n        //         ans += ch;\n        //     }\n        // }\n        // return ans;\n        \n        \n        // 2.\n        vector<string> freq(100,\"\");\n        for (char a : s) freq[a-'0'] += a;\n        sort(freq.begin(), freq.end(), compare);\n        s = \"\";\n        for (string str : freq) s += str;\n        return s;\n        // what it does is it is appending the string at the position of characters based on their indexes in alphabet order\n            // like for tree it storing like for position 4(0-based indexing) ee, 19 - t and 17 - r\n            // and then sorting based on length of strings.        \n        \n    }\n};\n"
  },
  {
    "path": "split array into consecutive subsequences/split-array-into-consecutive-subsequences.cpp",
    "content": "class Solution {\npublic:\n    bool isPossible(vector<int>& nums) {\n        int n = nums.size();                \n        unordered_map<int, int>m, m1;        \n        // to store the frequency of each element\n        for(int i=0;i<n;i++) m[nums[i]]++;       \n        // iterate over nums\n        for(auto it:nums){\n            if(m[it] == 0) continue; // step 1. earlier explained\n            m[it]--;// step 2. reduce the freq of element\n            if(m1[it-1]>0){// step 3. earlier explained\n                m1[it-1]--;\n                m1[it]++;\n            }else if(m[it+1] != 0 and m[it+2] != 0){ // step 4. --> if(next 2 consecutive elements present in the map) like if it == 1 then if 2 and 3 is present in the map or not if not then false else reduce their freq and store the last element's freq in second map\n                m[it+1]--;\n                m[it+2]--;\n                m1[it+2]++;\n            }\n            // if for test case 1 2 3 3 4 4 5 5 answer is true but our algo return false when reached to 4 so to overcome it we are using m1 and doing step 3, like if for 4 if 3 is present in m1 then add 4 also to one of the subsequence.\n            // https://youtu.be/Gmc-4Dpzw2g -- video for reference\n            else{\n                return false;\n            }\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "string-to-integer(atoi)/string-to-integer(atoi).cpp",
    "content": "#include<bits/stdc++.h>\nclass Solution {\npublic:\n    int myAtoi(string str) {\n        long long res = 0;\n        int i=0, len = str.length();\n        bool neg = false;\n        while(str[i]==' ') i++; // skip all the spaces in starting\n        if(str[i]=='+') i++; // skip + in starting\n        else if(str[i]=='-') {i++; neg=true;} // skip - in starting\n\n        while(str[i]>='0' && str[i]<='9'){\n            res = res*10 + (str[i]-'0');\n            if(res>=INT_MAX && !neg) {res = INT_MAX; break;}\n            else if(res>INT_MAX && neg) {res = INT_MIN; break;}\n            i++;\n        }\n\n        if (neg) res *= -1;\n        return (int)res;\n    }\n};\n"
  },
  {
    "path": "sum of k smallest elements in  BST.cpp",
    "content": "void inorder(Node* node,vector<int> &ans)\n{\n    if(node==NULL)\n        return ;\n   inorder(node->left,ans);\n   ans.push_back(node->data);\n   inorder(node->right,ans);\n}\n\nint sum(Node* root, int k) \n{ \n  \n    // Your code here\n    int sum=0;\n    vector<int> ans;\n    inorder(root,ans);\n    int cnt=0;\n    for(int i=0;i <ans.size();i++)\n    {\n        if(cnt==k)\n           break;\n        else   \n           sum+=ans[i];\n        cnt++;\n    }\n    return sum;\n    \n} \n\n"
  },
  {
    "path": "valid parenthesis.java",
    "content": "class Solution {\n    public boolean isValid(String s) {\n        if(s.length() % 2 != 0){\n            return false;  \n        }\n        \n        Stack<Character> stack = new Stack();\n        for(char c: s.toCharArray()){\n            if(c == '(' || c == '[' || c == '{'){ \n                stack.push(c);\n            }\n            else if(c == ')' && !stack.isEmpty() && stack.peek() == '(' ){ \n                stack.pop();\n            }\n            else if(c == ']' && !stack.isEmpty() && stack.peek() == '[') {\n                stack.pop();\n            }\n            else if(c == '}' && !stack.isEmpty() && stack.peek() == '{') {\n                stack.pop();\n            }\n            else{\n                return false; \n            }  \n        }\n        return stack.isEmpty(); \n    }\n}\n"
  }
]