├── .gitignore ├── .vscode └── settings.json ├── 0134-gas-station ├── 0134-gas-station.java └── README.md ├── 0144-binary-tree-preorder-traversal ├── 0144-binary-tree-preorder-traversal.java └── README.md ├── 0290-word-pattern ├── 0290-word-pattern.java └── NOTES.md ├── 0421-maximum-xor-of-two-numbers-in-an-array ├── 0421-maximum-xor-of-two-numbers-in-an-array.java └── README.md ├── 0452-minimum-number-of-arrows-to-burst-balloons ├── 0452-minimum-number-of-arrows-to-burst-balloons.java └── README.md ├── 0520-detect-capital ├── 0520-detect-capital.java └── README.md ├── 0583-delete-operation-for-two-strings ├── 0583-delete-operation-for-two-strings.java └── README.md ├── 0820-short-encoding-of-words ├── 0820-short-encoding-of-words.java └── README.md ├── 0852-peak-index-in-a-mountain-array ├── 0852-peak-index-in-a-mountain-array.java └── README.md ├── 0944-delete-columns-to-make-sorted ├── 0944-delete-columns-to-make-sorted.java └── README.md ├── 1669-merge-in-between-linked-lists ├── 1669-merge-in-between-linked-lists.java └── README.md ├── 1833-maximum-ice-cream-bars ├── 1833-maximum-ice-cream-bars.java └── README.md ├── 2244-minimum-rounds-to-complete-all-tasks ├── 2244-minimum-rounds-to-complete-all-tasks.java └── README.md ├── 2349-design-a-number-container-system ├── 2349-design-a-number-container-system.java └── README.md ├── c++ ├── 100.same-tree.cpp ├── 103.binary-tree-zigzag-level-order-traversal.cpp ├── 105.construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── 106.construct-binary-tree-from-inorder-and-postorder-traversal.cpp ├── 108.convert-sorted-array-to-binary-search-tree.cpp ├── 110.balanced-binary-tree.cpp ├── 114.flatten-binary-tree-to-linked-list.cpp ├── 121.best-time-to-buy-and-sell-stock.cpp ├── 122.best-time-to-buy-and-sell-stock-ii.cpp ├── 129.sum-root-to-leaf-numbers.cpp ├── 15.3-sum.cpp ├── 153.find-minimum-in-rotated-sorted-array.cpp ├── 16.3-sum-closest.cpp ├── 162.find-peak-element.cpp ├── 17.letter-combinations-of-a-phone-number.cpp ├── 18.4-sum.cpp ├── 19.remove-nth-node-from-end-of-list.cpp ├── 1943.Describe the Painting.cpp ├── 22.generate-parentheses.cpp ├── 239.sliding-window-maximum.cpp ├── 283.move-zeroes.cpp ├── 29.divide-two-integers.cpp ├── 309.best-time-to-buy-and-sell-stock-with-cooldown.cpp ├── 31.next-permutation.cpp ├── 33.search-in-rotated-sorted-array.cpp ├── 34.find-first-and-last-position-of-element-in-sorted-array.cpp ├── 343.integer-break.cpp ├── 35.search-insert-position.cpp ├── 36.valid-sudoku.cpp ├── 376.wiggle-subsequence.cpp ├── 395.longest-substring-with-at-least-k-repeating-characters.cpp ├── 413.arithmetic-slices.cpp ├── 486.predict-the-winner.cpp ├── 494.target-sum.cpp ├── 51.n-queens.cpp ├── 53.maximum-subarray.cpp ├── 543.diameter-of-binary-tree.cpp ├── 6.zig-zag-conversion.cpp ├── 617.merge-two-binary-trees.cpp ├── 62.unique-paths.cpp ├── 63.unique-paths-ii.cpp ├── 64.minimum-path-sum.cpp ├── 652.find-duplicate-subtrees.cpp ├── 69.sqrt-x.cpp ├── 70.climbing-stairs.cpp ├── 714.best-time-to-buy-and-sell-stock-with-transaction-fee.cpp ├── 74.search-a-2-d-matrix.cpp ├── 76.minimum-window-substring.cpp ├── 79.word-search.cpp ├── 795.number-of-subarrays-with-bounded-maximum.cpp ├── 8.string-to-integer-atoi.cpp ├── 81.search-in-rotated-sorted-array-ii.cpp ├── 839.similar-string-groups.cpp ├── 88.merge-sorted-array.cpp ├── 889.construct-binary-tree-from-preorder-and-postorder-traversal.cpp ├── 95.unique-binary-search-trees-ii.cpp ├── 96.unique-binary-search-trees.cpp ├── 978.longest-turbulent-subarray.cpp ├── 98.validate-binary-search-tree.cpp └── 993.cousins-in-binary-tree.cpp └── java ├── 1.two-sum.java ├── 101.symmetric-tree.java ├── 104.maximum-depth-of-binary-tree.java ├── 1137.n-th-tribonacci-number.java ├── 116.populating-next-right-pointers-in-each-node.java ├── 118.pascals-triangle.java ├── 121.best-time-to-buy-and-sell-stock.java ├── 1288.remove-covered-intervals.java ├── 136.single-number.java ├── 151.reverse-words-in-a-string.java ├── 167.two-sum-ii-input-array-is-sorted.java ├── 169.majority-element.java ├── 189.rotate-array.java ├── 19.remove-nth-node-from-end-of-list.java ├── 198.house-robber.java ├── 206.reverse-linked-list.java ├── 213.house-robber-ii.java ├── 217.contains-duplicate.java ├── 23.merge-k-sorted-lists.java ├── 231.power-of-two.java ├── 24.swap-nodes-in-pairs.java ├── 258.add-digits.java ├── 278.first-bad-version.java ├── 283.move-zeroes.java ├── 287.find-the-duplicate-number.java ├── 326.power-of-three.java ├── 344.reverse-string.java ├── 349.intersection-of-two-arrays.java ├── 35.search-insert-position.java ├── 350.intersection-of-two-arrays-ii.java ├── 389.find-the-difference.java ├── 39.combination-sum.java ├── 438.find-all-anagrams-in-a-string.java ├── 45.jump-game-ii.java ├── 454.4-sum-ii.java ├── 496.next-greater-element-i.java ├── 509.fibonacci-number.java ├── 525.contiguous-array.java ├── 53.maximum-subarray.java ├── 532.k-diff-pairs-in-an-array.java ├── 55.jump-game.java ├── 557.reverse-words-in-a-string-iii.java ├── 566.reshape-the-matrix.java ├── 567.permutation-in-string.java ├── 695.max-area-of-island.java ├── 70.climbing-stairs.java ├── 704.binary-search.java ├── 733.flood-fill.java ├── 740.delete-and-earn.java ├── 746.min-cost-climbing-stairs.java ├── 78.subsets.java ├── 80.remove-duplicates-from-sorted-array-ii.java ├── 869.reordered-power-of-2.java ├── 876.middle-of-the-linked-list.java ├── 88.merge-sorted-array.java ├── 92.reverse-linked-list-ii.java └── 977.squares-of-a-sorted-array.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | *.class -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "emmet.triggerExpansionOnTab": true, 3 | "files.associations": { 4 | "any": "cpp", 5 | "array": "cpp", 6 | "atomic": "cpp", 7 | "bit": "cpp", 8 | "*.tcc": "cpp", 9 | "bitset": "cpp", 10 | "cctype": "cpp", 11 | "cfenv": "cpp", 12 | "charconv": "cpp", 13 | "chrono": "cpp", 14 | "cinttypes": "cpp", 15 | "clocale": "cpp", 16 | "cmath": "cpp", 17 | "codecvt": "cpp", 18 | "complex": "cpp", 19 | "condition_variable": "cpp", 20 | "csetjmp": "cpp", 21 | "csignal": "cpp", 22 | "cstdarg": "cpp", 23 | "cstddef": "cpp", 24 | "cstdint": "cpp", 25 | "cstdio": "cpp", 26 | "cstdlib": "cpp", 27 | "cstring": "cpp", 28 | "ctime": "cpp", 29 | "cuchar": "cpp", 30 | "cwchar": "cpp", 31 | "cwctype": "cpp", 32 | "deque": "cpp", 33 | "forward_list": "cpp", 34 | "list": "cpp", 35 | "map": "cpp", 36 | "set": "cpp", 37 | "unordered_map": "cpp", 38 | "unordered_set": "cpp", 39 | "vector": "cpp", 40 | "exception": "cpp", 41 | "algorithm": "cpp", 42 | "functional": "cpp", 43 | "iterator": "cpp", 44 | "memory": "cpp", 45 | "memory_resource": "cpp", 46 | "numeric": "cpp", 47 | "optional": "cpp", 48 | "random": "cpp", 49 | "ratio": "cpp", 50 | "regex": "cpp", 51 | "string": "cpp", 52 | "string_view": "cpp", 53 | "system_error": "cpp", 54 | "tuple": "cpp", 55 | "type_traits": "cpp", 56 | "utility": "cpp", 57 | "fstream": "cpp", 58 | "future": "cpp", 59 | "initializer_list": "cpp", 60 | "iomanip": "cpp", 61 | "iosfwd": "cpp", 62 | "iostream": "cpp", 63 | "istream": "cpp", 64 | "limits": "cpp", 65 | "mutex": "cpp", 66 | "new": "cpp", 67 | "ostream": "cpp", 68 | "scoped_allocator": "cpp", 69 | "shared_mutex": "cpp", 70 | "sstream": "cpp", 71 | "stdexcept": "cpp", 72 | "streambuf": "cpp", 73 | "thread": "cpp", 74 | "typeindex": "cpp", 75 | "typeinfo": "cpp", 76 | "valarray": "cpp", 77 | "variant": "cpp", 78 | "stdio.h": "c" 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /0134-gas-station/0134-gas-station.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int canCompleteCircuit(int[] gas, int[] cost) { 3 | // Initialize totalGas and totalCost to 0 4 | int totalGas = 0, totalCost = 0; 5 | // Iterate through all the gas stations 6 | for(int i = 0 ; i134. Gas Station

Medium


Gas Station - There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. 2 | 3 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. 4 | 5 | Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique 6 | 7 |   8 | 9 | Example 1: 10 | 11 | 12 | Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] 13 | Output: 3 14 | Explanation: 15 | Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 16 | Travel to station 4. Your tank = 4 - 1 + 5 = 8 17 | Travel to station 0. Your tank = 8 - 2 + 1 = 7 18 | Travel to station 1. Your tank = 7 - 3 + 2 = 6 19 | Travel to station 2. Your tank = 6 - 4 + 3 = 5 20 | Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. 21 | Therefore, return 3 as the starting index. 22 | 23 | 24 | Example 2: 25 | 26 | 27 | Input: gas = [2,3,4], cost = [3,4,3] 28 | Output: -1 29 | Explanation: 30 | You can't start at station 0 or 1, as there is not enough gas to travel to the next station. 31 | Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 32 | Travel to station 0. Your tank = 4 - 3 + 2 = 3 33 | Travel to station 1. Your tank = 3 - 3 + 3 = 3 34 | You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. 35 | Therefore, you can't travel around the circuit once no matter where you start. 36 | 37 | 38 |   39 | 40 | Constraints: 41 | 42 | * n == gas.length == cost.length 43 | * 1 <= n <= 105 44 | * 0 <= gas[i], cost[i] <= 104 -------------------------------------------------------------------------------- /0144-binary-tree-preorder-traversal/0144-binary-tree-preorder-traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | 18 | private void preorder(TreeNode root, List arr) { 19 | if(root == null) return; 20 | arr.add(root.val); 21 | preorder(root.left, arr); 22 | preorder(root.right, arr); 23 | } 24 | 25 | public List preorderTraversal(TreeNode root) { 26 | List arr = new ArrayList<>(); 27 | preorder(root, arr); 28 | return arr; 29 | } 30 | } -------------------------------------------------------------------------------- /0144-binary-tree-preorder-traversal/README.md: -------------------------------------------------------------------------------- 1 |

144. Binary Tree Preorder Traversal

Easy


Binary Tree Preorder Traversal - Given the root of a binary tree, return the preorder traversal of its nodes' values. 2 | 3 |   4 | 5 | Example 1: 6 | 7 | [https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg] 8 | 9 | 10 | Input: root = [1,null,2,3] 11 | Output: [1,2,3] 12 | 13 | 14 | Example 2: 15 | 16 | 17 | Input: root = [] 18 | Output: [] 19 | 20 | 21 | Example 3: 22 | 23 | 24 | Input: root = [1] 25 | Output: [1] 26 | 27 | 28 |   29 | 30 | Constraints: 31 | 32 | * The number of nodes in the tree is in the range [0, 100]. 33 | * -100 <= Node.val <= 100 34 | 35 |   36 | 37 | Follow up: Recursive solution is trivial, could you do it iteratively? -------------------------------------------------------------------------------- /0290-word-pattern/0290-word-pattern.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean wordPattern(String pattern, String s) { 3 | Map map = new HashMap<>(); 4 | Map revMap = new HashMap<>(); 5 | String[] arr = s.split(" "); 6 | if(arr.length != pattern.length()) return false; 7 | for(int i = 0; i < pattern.length(); i++) { 8 | if(!map.containsKey(pattern.charAt(i))) { 9 | if(revMap.containsKey(arr[i])) return false; 10 | map.put(pattern.charAt(i), arr[i]); 11 | revMap.put(arr[i], pattern.charAt(i)); 12 | } else { 13 | if(!map.get(pattern.charAt(i)).equals(arr[i])) { 14 | return false; 15 | } 16 | } 17 | } 18 | return true; 19 | } 20 | } -------------------------------------------------------------------------------- /0290-word-pattern/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /0421-maximum-xor-of-two-numbers-in-an-array/0421-maximum-xor-of-two-numbers-in-an-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /** 3 | First, a trie is built using the bits of the numbers from MSB to LSB. 4 | After that, for each element num in the array, an element is searched in the trie which has the maximum (num ^ trieElement) 5 | To do this, a number is built using the opposite bits of the (num) since xor of opposite bits result in 1. If opposite bit is not present in the trie for any ith bit, the same bit is taken. 6 | */ 7 | public int findMaximumXOR(int[] nums) { 8 | TrieNode root = new TrieNode(); 9 | 10 | // Build Trie 11 | for(int num : nums) { 12 | TrieNode curr = root; 13 | for(int i = 31; i >= 0; i--) { 14 | int bit = (num >> i) & 1; 15 | if(curr.children[bit] == null) { 16 | curr.children[bit] = new TrieNode(); 17 | } 18 | curr = curr.children[bit]; 19 | } 20 | } 21 | 22 | int ans = 0; 23 | for(int num : nums) { 24 | TrieNode curr = root; 25 | int res = 0; 26 | for(int i = 31; i >= 0; i--) { 27 | int bit = (num >> i) & 1; // get the ith bit of num 28 | int targetBit = 1 - bit; // get the opposite bit to maximize the xor result 29 | if(curr.children[targetBit] != null) { 30 | curr = curr.children[targetBit]; // go with opposite bit if found 31 | res = res | (1 << i); // mark the ith bit of res as 1 since ith bit of num and ith bit of searched element is different and xor will give 1 32 | } else { 33 | curr = curr.children[bit]; // if opposite bit not found, then go with same bit 34 | } 35 | } 36 | ans = Math.max(ans, res); // res is the maximum possible result for any arr[j] ^ num. no need to xor here since the bits are already set at line 31 -> res = res | (1 << i); 37 | } 38 | return ans; 39 | } 40 | } 41 | 42 | class TrieNode { 43 | TrieNode[] children; 44 | 45 | TrieNode() { 46 | this.children = new TrieNode[2]; 47 | } 48 | } -------------------------------------------------------------------------------- /0421-maximum-xor-of-two-numbers-in-an-array/README.md: -------------------------------------------------------------------------------- 1 |

421. Maximum XOR of Two Numbers in an Array

Medium


Maximum XOR of Two Numbers in an Array - Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n. 2 | 3 |   4 | 5 | Example 1: 6 | 7 | 8 | Input: nums = [3,10,5,25,2,8] 9 | Output: 28 10 | Explanation: The maximum result is 5 XOR 25 = 28. 11 | 12 | 13 | Example 2: 14 | 15 | 16 | Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70] 17 | Output: 127 18 | 19 | 20 |   21 | 22 | Constraints: 23 | 24 | * 1 <= nums.length <= 2 * 105 25 | * 0 <= nums[i] <= 231 - 1 -------------------------------------------------------------------------------- /0452-minimum-number-of-arrows-to-burst-balloons/0452-minimum-number-of-arrows-to-burst-balloons.java: -------------------------------------------------------------------------------- 1 | /** 2 | 1. Sort the array by their 0th position 3 | 2. Find common sections between adjacent elements and store in an arr 4 | 3. If common section is not found between current element and last element in arr, insert the current element to arr 5 | 4. If common section is found, update the last element in arr with the new common section 6 | */ 7 | 8 | class Solution { 9 | public int findMinArrowShots(int[][] points) { 10 | List arr = new ArrayList<>(); 11 | Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0])); // For points: [[-2147483646,-2147483645],[2147483646,2147483647]], a[0] - b[0] is so large that it won't fit in an integer. Thus Integer.compare(a[0], b[0]) is used instead 12 | arr.add(points[0]); 13 | for(int i = 1; i < points.length; i++) { 14 | int[] prev = arr.get(arr.size() - 1); 15 | int[] curr = points[i]; 16 | if(curr[0] > prev[1]) { 17 | arr.add(curr); 18 | continue; 19 | } 20 | int[] newCurr = new int[]{curr[0], Math.min(prev[1], curr[1])}; 21 | arr.set(arr.size() - 1, newCurr); 22 | } 23 | return arr.size(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /0452-minimum-number-of-arrows-to-burst-balloons/README.md: -------------------------------------------------------------------------------- 1 |

452. Minimum Number of Arrows to Burst Balloons

Medium


Minimum Number of Arrows to Burst Balloons - There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. 2 | 3 | Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. 4 | 5 | Given the array points, return the minimum number of arrows that must be shot to burst all balloons. 6 | 7 |   8 | 9 | Example 1: 10 | 11 | 12 | Input: points = [[10,16],[2,8],[1,6],[7,12]] 13 | Output: 2 14 | Explanation: The balloons can be burst by 2 arrows: 15 | - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. 16 | - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. 17 | 18 | 19 | Example 2: 20 | 21 | 22 | Input: points = [[1,2],[3,4],[5,6],[7,8]] 23 | Output: 4 24 | Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows. 25 | 26 | 27 | Example 3: 28 | 29 | 30 | Input: points = [[1,2],[2,3],[3,4],[4,5]] 31 | Output: 2 32 | Explanation: The balloons can be burst by 2 arrows: 33 | - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. 34 | - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. 35 | 36 | 37 |   38 | 39 | Constraints: 40 | 41 | * 1 <= points.length <= 105 42 | * points[i].length == 2 43 | * -231 <= xstart < xend <= 231 - 1 -------------------------------------------------------------------------------- /0520-detect-capital/0520-detect-capital.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean detectCapitalUse(String word) { 3 | int uppercaseCount = 0; 4 | for(int i = 0; i < word.length(); i++) { 5 | if(Character.isUpperCase(word.charAt(i))) { 6 | uppercaseCount++; 7 | } 8 | } 9 | return uppercaseCount == 0 || uppercaseCount == word.length() || (uppercaseCount == 1 && Character.isUpperCase(word.charAt(0))); 10 | } 11 | } -------------------------------------------------------------------------------- /0520-detect-capital/README.md: -------------------------------------------------------------------------------- 1 |

520. Detect Capital

Easy


Detect Capital - We define the usage of capitals in a word to be right when one of the following cases holds: 2 | 3 | * All letters in this word are capitals, like "USA". 4 | * All letters in this word are not capitals, like "leetcode". 5 | * Only the first letter in this word is capital, like "Google". 6 | 7 | Given a string word, return true if the usage of capitals in it is right. 8 | 9 |   10 | 11 | Example 1: 12 | 13 | Input: word = "USA" 14 | Output: true 15 | 16 | 17 | Example 2: 18 | 19 | Input: word = "FlaG" 20 | Output: false 21 | 22 | 23 |   24 | 25 | Constraints: 26 | 27 | * 1 <= word.length <= 100 28 | * word consists of lowercase and uppercase English letters. -------------------------------------------------------------------------------- /0583-delete-operation-for-two-strings/0583-delete-operation-for-two-strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | private int solve(int n, int m, String s, String t, int[][] dp) { 4 | if(n == 0) return m; 5 | if(m == 0) return n; 6 | 7 | if(dp[n][m] != -1) return dp[n][m]; 8 | 9 | if(s.charAt(n - 1) == t.charAt(m - 1)) { 10 | dp[n][m] = solve(n - 1, m - 1, s, t, dp); 11 | return dp[n][m]; 12 | } 13 | 14 | dp[n][m] = 1 + Math.min(solve(n - 1, m, s, t, dp), solve(n, m - 1, s, t, dp)); 15 | return dp[n][m]; 16 | } 17 | 18 | public int minDistance(String word1, String word2) { 19 | int[][] dp = new int[word1.length()+1][word2.length()+1]; 20 | for(int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1); 21 | int ans = solve(word1.length(), word2.length(), word1, word2, dp); 22 | return ans; 23 | } 24 | } -------------------------------------------------------------------------------- /0583-delete-operation-for-two-strings/README.md: -------------------------------------------------------------------------------- 1 |

583. Delete Operation for Two Strings

Medium


Delete Operation for Two Strings - Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. 2 | 3 | In one step, you can delete exactly one character in either string. 4 | 5 |   6 | 7 | Example 1: 8 | 9 | 10 | Input: word1 = "sea", word2 = "eat" 11 | Output: 2 12 | Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". 13 | 14 | 15 | Example 2: 16 | 17 | 18 | Input: word1 = "leetcode", word2 = "etco" 19 | Output: 4 20 | 21 | 22 |   23 | 24 | Constraints: 25 | 26 | * 1 <= word1.length, word2.length <= 500 27 | * word1 and word2 consist of only lowercase English letters. -------------------------------------------------------------------------------- /0820-short-encoding-of-words/0820-short-encoding-of-words.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumLengthEncoding(String[] words) { 3 | Set set = new HashSet<>(); 4 | Arrays.sort(words, (a, b) -> b.length() - a.length()); 5 | int ans = 0; 6 | for(String word : words) { 7 | if(!set.contains(word)) { 8 | for(int i = 0; i < word.length(); i++) { 9 | set.add(word.substring(i)); 10 | } 11 | ans += word.length() + 1; 12 | } 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /0820-short-encoding-of-words/README.md: -------------------------------------------------------------------------------- 1 |

820. Short Encoding of Words

Medium


Short Encoding of Words - A valid encoding of an array of words is any reference string s and array of indices indices such that: 2 | 3 | * words.length == indices.length 4 | * The reference string s ends with the '#' character. 5 | * For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i]. 6 | 7 | Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words. 8 | 9 |   10 | 11 | Example 1: 12 | 13 | 14 | Input: words = ["time", "me", "bell"] 15 | Output: 10 16 | Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5]. 17 | words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#" 18 | words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#" 19 | words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#" 20 | 21 | 22 | Example 2: 23 | 24 | 25 | Input: words = ["t"] 26 | Output: 2 27 | Explanation: A valid encoding would be s = "t#" and indices = [0]. 28 | 29 | 30 |   31 | 32 | Constraints: 33 | 34 | * 1 <= words.length <= 2000 35 | * 1 <= words[i].length <= 7 36 | * words[i] consists of only lowercase letters. -------------------------------------------------------------------------------- /0852-peak-index-in-a-mountain-array/0852-peak-index-in-a-mountain-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int peakIndexInMountainArray(int[] arr) { 3 | int low = 0; 4 | int high = arr.length - 1; 5 | while(low < high) { 6 | int mid = low + (high - low) / 2; 7 | if(mid == 0 || mid == arr.length - 1) return 0; 8 | if(arr[mid + 1] < arr[mid] && arr[mid - 1] < arr[mid]) return mid; 9 | if(arr[mid - 1]< arr[mid] && arr[mid] < arr[mid + 1]) { 10 | low = mid; 11 | } else if(arr[mid - 1] > arr[mid] && arr[mid] > arr[mid + 1]) { 12 | high = mid; 13 | } 14 | } 15 | return -1; 16 | } 17 | } -------------------------------------------------------------------------------- /0852-peak-index-in-a-mountain-array/README.md: -------------------------------------------------------------------------------- 1 |

852. Peak Index in a Mountain Array

Medium


Peak Index in a Mountain Array - An array arr a mountain if the following properties hold: 2 | 3 | * arr.length >= 3 4 | * There exists some i with 0 < i < arr.length - 1 such that: 5 | * arr[0] < arr[1] < ... < arr[i - 1] < arr[i] 6 | * arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 7 | 8 | Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. 9 | 10 | You must solve it in O(log(arr.length)) time complexity. 11 | 12 |   13 | 14 | Example 1: 15 | 16 | 17 | Input: arr = [0,1,0] 18 | Output: 1 19 | 20 | 21 | Example 2: 22 | 23 | 24 | Input: arr = [0,2,1,0] 25 | Output: 1 26 | 27 | 28 | Example 3: 29 | 30 | 31 | Input: arr = [0,10,5,2] 32 | Output: 1 33 | 34 | 35 |   36 | 37 | Constraints: 38 | 39 | * 3 <= arr.length <= 105 40 | * 0 <= arr[i] <= 106 41 | * arr is guaranteed to be a mountain array. -------------------------------------------------------------------------------- /0944-delete-columns-to-make-sorted/0944-delete-columns-to-make-sorted.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDeletionSize(String[] strs) { 3 | int ans = 0, n = strs.length, m = strs[0].length(); 4 | for(int i = 0; i < m; i++) { 5 | for(int j = 1; j < n; j++) { 6 | String curr = strs[j]; 7 | String prev = strs[j - 1]; 8 | if(curr.charAt(i) < prev.charAt(i)) { 9 | ans++; 10 | break; 11 | } 12 | } 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /0944-delete-columns-to-make-sorted/README.md: -------------------------------------------------------------------------------- 1 |

944. Delete Columns to Make Sorted

Easy


Delete Columns to Make Sorted - You are given an array of n strings strs, all of the same length. 2 | 3 | The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as: 4 | 5 | 6 | abc 7 | bce 8 | cae 9 | 10 | 11 | You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1. 12 | 13 | Return the number of columns that you will delete. 14 | 15 |   16 | 17 | Example 1: 18 | 19 | 20 | Input: strs = ["cba","daf","ghi"] 21 | Output: 1 22 | Explanation: The grid looks as follows: 23 | cba 24 | daf 25 | ghi 26 | Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. 27 | 28 | 29 | Example 2: 30 | 31 | 32 | Input: strs = ["a","b"] 33 | Output: 0 34 | Explanation: The grid looks as follows: 35 | a 36 | b 37 | Column 0 is the only column and is sorted, so you will not delete any columns. 38 | 39 | 40 | Example 3: 41 | 42 | 43 | Input: strs = ["zyx","wvu","tsr"] 44 | Output: 3 45 | Explanation: The grid looks as follows: 46 | zyx 47 | wvu 48 | tsr 49 | All 3 columns are not sorted, so you will delete all 3. 50 | 51 | 52 |   53 | 54 | Constraints: 55 | 56 | * n == strs.length 57 | * 1 <= n <= 100 58 | * 1 <= strs[i].length <= 1000 59 | * strs[i] consists of lowercase English letters. -------------------------------------------------------------------------------- /1669-merge-in-between-linked-lists/1669-merge-in-between-linked-lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { 13 | int i = 0; 14 | ListNode nodeAMinus1 = list1, nodeBPlus1 = list1; 15 | while(i < a - 1) { 16 | nodeAMinus1 = nodeAMinus1.next; 17 | i++; 18 | } 19 | i = 0; 20 | while(i < b + 1) { 21 | nodeBPlus1 = nodeBPlus1.next; 22 | i++; 23 | } 24 | nodeAMinus1.next = list2; 25 | ListNode list2EndNode = list2; 26 | while(list2EndNode.next != null) { 27 | list2EndNode = list2EndNode.next; 28 | } 29 | list2EndNode.next = nodeBPlus1; 30 | return list1; 31 | } 32 | } -------------------------------------------------------------------------------- /1669-merge-in-between-linked-lists/README.md: -------------------------------------------------------------------------------- 1 |

1669. Merge In Between Linked Lists

Medium


Merge In Between Linked Lists - You are given two linked lists: list1 and list2 of sizes n and m respectively. 2 | 3 | Remove list1's nodes from the ath node to the bth node, and put list2 in their place. 4 | 5 | The blue edges and nodes in the following figure indicate the result: 6 | 7 | [https://assets.leetcode.com/uploads/2020/11/05/fig1.png] 8 | 9 | Build the result list and return its head. 10 | 11 |   12 | 13 | Example 1: 14 | 15 | [https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex1.png] 16 | 17 | 18 | Input: list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] 19 | Output: [0,1,2,1000000,1000001,1000002,5] 20 | Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. 21 | 22 | 23 | Example 2: 24 | 25 | [https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex2.png] 26 | 27 | 28 | Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] 29 | Output: [0,1,1000000,1000001,1000002,1000003,1000004,6] 30 | Explanation: The blue edges and nodes in the above figure indicate the result. 31 | 32 | 33 |   34 | 35 | Constraints: 36 | 37 | * 3 <= list1.length <= 104 38 | * 1 <= a <= b < list1.length - 1 39 | * 1 <= list2.length <= 104 -------------------------------------------------------------------------------- /1833-maximum-ice-cream-bars/1833-maximum-ice-cream-bars.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxIceCream(int[] costs, int coins) { 3 | Arrays.sort(costs); 4 | int ans = 0; 5 | for(int c : costs) { 6 | if(c <= coins) { 7 | coins -= c; 8 | ans++; 9 | } else { 10 | break; 11 | } 12 | } 13 | return ans; 14 | } 15 | } -------------------------------------------------------------------------------- /1833-maximum-ice-cream-bars/README.md: -------------------------------------------------------------------------------- 1 |

1833. Maximum Ice Cream Bars

Medium


Maximum Ice Cream Bars - It is a sweltering summer day, and a boy wants to buy some ice cream bars. 2 | 3 | At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.  4 | 5 | Return the maximum number of ice cream bars the boy can buy with coins coins. 6 | 7 | Note: The boy can buy the ice cream bars in any order. 8 | 9 |   10 | 11 | Example 1: 12 | 13 | 14 | Input: costs = [1,3,2,4,1], coins = 7 15 | Output: 4 16 | Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. 17 | 18 | 19 | Example 2: 20 | 21 | 22 | Input: costs = [10,6,8,7,7,8], coins = 5 23 | Output: 0 24 | Explanation: The boy cannot afford any of the ice cream bars. 25 | 26 | 27 | Example 3: 28 | 29 | 30 | Input: costs = [1,6,3,1,2,5], coins = 20 31 | Output: 6 32 | Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. 33 | 34 | 35 |   36 | 37 | Constraints: 38 | 39 | * costs.length == n 40 | * 1 <= n <= 105 41 | * 1 <= costs[i] <= 105 42 | * 1 <= coins <= 108 -------------------------------------------------------------------------------- /2244-minimum-rounds-to-complete-all-tasks/2244-minimum-rounds-to-complete-all-tasks.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumRounds(int[] tasks) { 3 | Map map = new HashMap<>(); 4 | for(int difficulty : tasks) { 5 | map.put(difficulty, map.getOrDefault(difficulty, 0) + 1); 6 | } 7 | int ans = 0; 8 | for(int count : map.values()) { 9 | if(count < 2) return -1; 10 | if(count % 3 == 0) ans += count / 3; // Best case: Example - 15 11 | if(count % 3 == 1) ans += count / 3 - 1 + 2; // Example - 16, then 16 = (3 * 5 - 3) + (2 * 2) 12 | if(count % 3 == 2) ans += count / 3 + 1; // Example - 17, then 17 = (3 * 5) + 2 13 | } 14 | return ans; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /2244-minimum-rounds-to-complete-all-tasks/README.md: -------------------------------------------------------------------------------- 1 |

2244. Minimum Rounds to Complete All Tasks

Medium


Minimum Rounds to Complete All Tasks - You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. 2 | 3 | Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks. 4 | 5 |   6 | 7 | Example 1: 8 | 9 | 10 | Input: tasks = [2,2,3,3,2,4,4,4,4,4] 11 | Output: 4 12 | Explanation: To complete all the tasks, a possible plan is: 13 | - In the first round, you complete 3 tasks of difficulty level 2. 14 | - In the second round, you complete 2 tasks of difficulty level 3. 15 | - In the third round, you complete 3 tasks of difficulty level 4. 16 | - In the fourth round, you complete 2 tasks of difficulty level 4. 17 | It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4. 18 | 19 | 20 | Example 2: 21 | 22 | 23 | Input: tasks = [2,3,3] 24 | Output: -1 25 | Explanation: 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. 26 | 27 | 28 |   29 | 30 | Constraints: 31 | 32 | * 1 <= tasks.length <= 105 33 | * 1 <= tasks[i] <= 109 -------------------------------------------------------------------------------- /2349-design-a-number-container-system/2349-design-a-number-container-system.java: -------------------------------------------------------------------------------- 1 | class NumberContainers { 2 | 3 | HashMap> map; 4 | HashMap mm; 5 | 6 | public NumberContainers() { 7 | this.map = new HashMap<>(); 8 | this.mm = new HashMap<>(); 9 | } 10 | 11 | public void change(int index, int number) { 12 | if(mm.containsKey(index)) { 13 | int oldNumber = mm.get(index); 14 | map.get(oldNumber).remove(index); 15 | if(map.get(oldNumber).size() == 0) map.remove(oldNumber); 16 | } 17 | map.putIfAbsent(number,new TreeSet<>()); 18 | map.get(number).add(index); 19 | mm.put(index,number); 20 | } 21 | 22 | public int find(int number) { 23 | if(!map.containsKey(number)) return -1; 24 | return map.get(number).first(); 25 | } 26 | } 27 | 28 | 29 | /** 30 | * Your NumberContainers object will be instantiated and called as such: 31 | * NumberContainers obj = new NumberContainers(); 32 | * obj.change(index,number); 33 | * int param_2 = obj.find(number); 34 | */ -------------------------------------------------------------------------------- /2349-design-a-number-container-system/README.md: -------------------------------------------------------------------------------- 1 |

2349. Design a Number Container System

Medium


Design a Number Container System - Design a number container system that can do the following: 2 | 3 | * Insert or Replace a number at the given index in the system. 4 | * Return the smallest index for the given number in the system. 5 | 6 | Implement the NumberContainers class: 7 | 8 | * NumberContainers() Initializes the number container system. 9 | * void change(int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it. 10 | * int find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system. 11 | 12 |   13 | 14 | Example 1: 15 | 16 | 17 | Input 18 | ["NumberContainers", "find", "change", "change", "change", "change", "find", "change", "find"] 19 | [[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]] 20 | Output 21 | [null, -1, null, null, null, null, 1, null, 2] 22 | 23 | Explanation 24 | NumberContainers nc = new NumberContainers(); 25 | nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1. 26 | nc.change(2, 10); // Your container at index 2 will be filled with number 10. 27 | nc.change(1, 10); // Your container at index 1 will be filled with number 10. 28 | nc.change(3, 10); // Your container at index 3 will be filled with number 10. 29 | nc.change(5, 10); // Your container at index 5 will be filled with number 10. 30 | nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1. 31 | nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. 32 | nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2. 33 | 34 | 35 |   36 | 37 | Constraints: 38 | 39 | * 1 <= index, number <= 109 40 | * At most 105 calls will be made in total to change and find. -------------------------------------------------------------------------------- /c++/100.same-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=100 lang=cpp 3 | * 4 | * [100] Same Tree 5 | */ 6 | 7 | // @lc code=start 8 | 9 | struct TreeNode { 10 | int val; 11 | TreeNode *left; 12 | TreeNode *right; 13 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 14 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 15 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 16 | }; 17 | 18 | class Solution { 19 | public: 20 | bool isSameTree(TreeNode *p, TreeNode *q) { 21 | if (!p && !q) return true; 22 | if (!p || !q) return false; 23 | if (p->val != q->val) return false; 24 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 25 | } 26 | }; 27 | // @lc code=end 28 | -------------------------------------------------------------------------------- /c++/103.binary-tree-zigzag-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=103 lang=cpp 6 | * 7 | * [103] Binary Tree Zigzag Level Order Traversal 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | vector> zigzagLevelOrder(TreeNode *root) { 24 | if (!root) return {}; 25 | vector> res; 26 | queue q; 27 | int level = 0; // If we don't consider the 'level' variable and keep adding values in left -> right order, then this program would become level order traversal. 28 | q.push(root); 29 | while (!q.empty()) { 30 | int n = q.size(); 31 | vector v(n); 32 | // On every iteration in the while loop, we traverse the current level (using the for loop) and add elements of the next level to the queue. 33 | for (int i = 0; i < n; i++) { 34 | TreeNode *curr = q.front(); 35 | q.pop(); 36 | if (level % 2 == 0) { 37 | v[i] = curr->val; 38 | } else { 39 | v[n - i - 1] = curr->val; 40 | } 41 | if (curr->left) q.push(curr->left); 42 | if (curr->right) q.push(curr->right); 43 | } 44 | res.push_back(v); 45 | level = !level; 46 | } 47 | return res; 48 | } 49 | }; 50 | // @lc code=end 51 | -------------------------------------------------------------------------------- /c++/105.construct-binary-tree-from-preorder-and-inorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=105 lang=cpp 6 | * 7 | * [105] Construct Binary Tree from Preorder and Inorder Traversal 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | TreeNode *recurse(int preStart, int inStart, int inEnd, vector &preorder, vector &inorder) { 24 | if (preStart >= preorder.size() || inStart > inEnd) return NULL; 25 | 26 | int i = find(inorder.begin(), inorder.end(), preorder[preStart]) - inorder.begin(); 27 | TreeNode *root = new TreeNode(preorder[preStart]); 28 | root->left = recurse(preStart + 1, inStart, i - 1, preorder, inorder); 29 | int elemCnt = i - inStart; // Element count in left subtree of i in inorder array 30 | // preStart + elemCnt + 1 gives the right child of i 31 | root->right = recurse(preStart + elemCnt + 1, i + 1, inEnd, preorder, inorder); 32 | return root; 33 | } 34 | TreeNode *buildTree(vector &preorder, vector &inorder) { 35 | TreeNode *root = recurse(0, 0, inorder.size() - 1, preorder, inorder); 36 | return root; 37 | } 38 | }; 39 | // @lc code=end 40 | -------------------------------------------------------------------------------- /c++/106.construct-binary-tree-from-inorder-and-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=106 lang=cpp 6 | * 7 | * [106] Construct Binary Tree from Inorder and Postorder Traversal 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | TreeNode *recurse(int postStart, int inStart, int inEnd, vector &inorder, vector &postorder) { 22 | if (postStart < 0 || inStart > inEnd) return NULL; 23 | 24 | TreeNode *root = new TreeNode(postorder[postStart]); 25 | int i = find(inorder.begin(), inorder.end(), root->val) - inorder.begin(); 26 | root->right = recurse(postStart - 1, i + 1, inEnd, inorder, postorder); 27 | root->left = recurse(postStart - (inEnd - i) - 1, inStart, i - 1, inorder, postorder); 28 | return root; 29 | } 30 | 31 | class Solution { 32 | public: 33 | TreeNode *buildTree(vector &inorder, vector &postorder) { 34 | TreeNode *root = recurse(postorder.size() - 1, 0, inorder.size() - 1, inorder, postorder); 35 | return root; 36 | } 37 | }; 38 | // @lc code=end 39 | -------------------------------------------------------------------------------- /c++/108.convert-sorted-array-to-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=108 lang=cpp 6 | * 7 | * [108] Convert Sorted Array to Binary Search Tree 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | TreeNode *buildTree(vector &nums, int l, int r) { 24 | if (l > r) return nullptr; 25 | int mid = l + (r - l) / 2; 26 | TreeNode *node = new TreeNode(nums[mid]); 27 | node->left = buildTree(nums, l, mid - 1); 28 | node->right = buildTree(nums, mid + 1, r); 29 | return node; 30 | } 31 | TreeNode *sortedArrayToBST(vector &nums) { 32 | TreeNode *node = buildTree(nums, 0, nums.size() - 1); 33 | return node; 34 | } 35 | }; 36 | // @lc code=end 37 | -------------------------------------------------------------------------------- /c++/110.balanced-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=110 lang=cpp 6 | * 7 | * [110] Balanced Binary Tree 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | int recurse(TreeNode *root) { 24 | if (!root) return 0; 25 | int l = recurse(root->left); 26 | int r = recurse(root->right); 27 | if (l == -1 || r == -1 || abs(l - r) > 1) return -1; 28 | return 1 + max(l, r); 29 | } 30 | bool isBalanced(TreeNode *root) { 31 | return recurse(root) != -1; 32 | } 33 | }; 34 | // @lc code=end 35 | -------------------------------------------------------------------------------- /c++/114.flatten-binary-tree-to-linked-list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=114 lang=cpp 6 | * 7 | * [114] Flatten Binary Tree to Linked List 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | void flatten(TreeNode *root) { 24 | if (!root) return; 25 | TreeNode *curr = root; 26 | while (curr) { 27 | if (curr->left) { 28 | TreeNode *lcurr = curr->left; 29 | while (lcurr->right) lcurr = lcurr->right; 30 | // We go to the rightmost node of the left subtree (x) and join the curr's right subtree (y) to x (x->right = y) 31 | // Why rightmost node of left subtree? Because it is the last node in the preorder traversal of the subtree and we are supposed to move to curr's right next. 32 | lcurr->right = curr->right; 33 | curr->right = curr->left; // According to preorder traversal: curr's left should be next to curr in the linked list 34 | curr->left = nullptr; // Making curr's left NULL according to the question's rules 35 | } 36 | curr = curr->right; // proceeding to the next right element which is actually curr's left now 37 | } 38 | } 39 | }; 40 | // @lc code=end 41 | -------------------------------------------------------------------------------- /c++/121.best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=121 lang=cpp 6 | * 7 | * [121] Best Time to Buy and Sell Stock 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int maxProfit(vector& prices) { 14 | int n = prices.size(); 15 | vector maxarr(n), minarr(n); 16 | minarr[0] = prices[0], maxarr[n - 1] = prices[n - 1]; 17 | int minval = prices[0], maxval = prices[n - 1]; 18 | for (int i = 1; i < n; i++) { 19 | if (prices[i] < minval) { 20 | minval = prices[i]; 21 | minarr[i] = minval; 22 | } else { 23 | minarr[i] = minarr[i - 1]; 24 | } 25 | } 26 | for (int i = n - 2; i >= 0; i--) { 27 | if (prices[i] > maxval) { 28 | maxval = prices[i]; 29 | maxarr[i] = maxval; 30 | } else { 31 | maxarr[i] = maxarr[i + 1]; 32 | } 33 | } 34 | int ans = INT_MIN; 35 | for (int i = 0; i < n; i++) { 36 | ans = max(ans, maxarr[i] - minarr[i]); 37 | } 38 | return ans; 39 | } 40 | }; 41 | // @lc code=end 42 | -------------------------------------------------------------------------------- /c++/122.best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=122 lang=cpp 6 | * 7 | * [122] Best Time to Buy and Sell Stock II 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int maxProfit(vector& arr) { 14 | int ans = 0, minval = INT_MAX, n = arr.size(); 15 | for (int i = 0; i < n; i++) { 16 | if (arr[i] >= minval) ans += arr[i] - minval; 17 | minval = arr[i]; 18 | } 19 | return ans; 20 | } 21 | }; 22 | // @lc code=end 23 | -------------------------------------------------------------------------------- /c++/129.sum-root-to-leaf-numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=129 lang=cpp 6 | * 7 | * [129] Sum Root to Leaf Numbers 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | vector recurse(TreeNode *root) { 24 | if (root == NULL) return {}; 25 | vector res; 26 | if (!root->left && !root->right) { 27 | res.push_back(to_string(root->val)); 28 | } 29 | if (root->left) { 30 | vector l = recurse(root->left); 31 | for (string s : l) { 32 | res.push_back(to_string(root->val) + s); 33 | } 34 | } 35 | if (root->right) { 36 | vector r = recurse(root->right); 37 | for (string s : r) { 38 | res.push_back(to_string(root->val) + s); 39 | } 40 | } 41 | return res; 42 | } 43 | int sumNumbers(TreeNode *root) { 44 | vector res = recurse(root); 45 | int ans = 0; 46 | for (string s : res) { 47 | ans += stoi(s); 48 | } 49 | return ans; 50 | } 51 | }; 52 | // @lc code=end 53 | -------------------------------------------------------------------------------- /c++/15.3-sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=15 lang=cpp 6 | * 7 | * [15] 3Sum 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | vector> threeSum(vector& nums) { 14 | vector> res; 15 | set> s; 16 | int n = nums.size(); 17 | int i = 0, j = 1, k = n - 1; 18 | sort(nums.begin(), nums.end()); 19 | while (i < n - 2) { 20 | j = i + 1, k = n - 1; 21 | while (j < k) { 22 | int sum = nums[i] + nums[j] + nums[k]; 23 | if (sum == 0) { 24 | s.insert({nums[i], nums[j], nums[k]}); 25 | } 26 | if (sum < 0) 27 | j += 1; 28 | else 29 | k -= 1; 30 | } 31 | i += 1; 32 | } 33 | for (auto it : s) res.push_back(it); 34 | return res; 35 | } 36 | }; 37 | // @lc code=end 38 | -------------------------------------------------------------------------------- /c++/153.find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=153 lang=cpp 6 | * 7 | * [153] Find Minimum in Rotated Sorted Array 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int findMin(vector& nums) { 14 | int l = 0, r = nums.size() - 1, ans = 0; 15 | while (l < r) { 16 | int mid = l + (r - l) / 2; 17 | if (nums[mid] > nums[r]) { 18 | l = mid + 1; 19 | } else { 20 | r = mid; 21 | } 22 | } 23 | return nums[l]; 24 | } 25 | }; 26 | // @lc code=end 27 | -------------------------------------------------------------------------------- /c++/16.3-sum-closest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=16 lang=cpp 6 | * 7 | * [16] 3Sum Closest 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int threeSumClosest(vector& nums, int target) { 14 | int n = nums.size(); 15 | int i = 0, j = 1, k = n - 1, closestVal = 999999; 16 | sort(nums.begin(), nums.end()); 17 | while (i < n - 2) { 18 | j = i + 1; 19 | k = n - 1; 20 | while (j < k) { 21 | int sum = nums[i] + nums[j] + nums[k]; 22 | if (sum == target) { 23 | closestVal = target; 24 | break; 25 | } else if (sum < target) { 26 | if (target - sum < abs(target - closestVal)) { 27 | closestVal = sum; 28 | } 29 | j += 1; 30 | } else { 31 | if (sum - target < abs(closestVal - target)) { 32 | closestVal = sum; 33 | } 34 | k -= 1; 35 | } 36 | } 37 | i += 1; 38 | } 39 | return closestVal; 40 | } 41 | }; 42 | // @lc code=end 43 | -------------------------------------------------------------------------------- /c++/162.find-peak-element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=162 lang=cpp 6 | * 7 | * [162] Find Peak Element 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int findPeakElement(vector& nums) { 14 | int n = nums.size(); 15 | if (n == 1) return 0; 16 | if (nums[0] > nums[1]) return 0; 17 | if (nums[n - 1] > nums[n - 2]) return n - 1; 18 | int l = 1, r = n - 2; 19 | while (l <= r) { 20 | int mid = l + (r - l) / 2; 21 | if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) 22 | return mid; 23 | else if (nums[mid] < nums[mid + 1]) 24 | l = mid + 1; 25 | else if (nums[mid] < nums[mid - 1]) 26 | r = mid - 1; 27 | } 28 | return -1; 29 | } 30 | }; 31 | // @lc code=end -------------------------------------------------------------------------------- /c++/17.letter-combinations-of-a-phone-number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=17 lang=cpp 6 | * 7 | * [17] Letter Combinations of a Phone Number 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | map> hash; 13 | vector ans; 14 | 15 | void recurse(int i, string curr, string digits) { 16 | if (i == digits.length()) { 17 | ans.push_back(curr); 18 | return; 19 | } 20 | vector vals = hash[digits[i]]; 21 | for (int j = 0; j < vals.size(); j++) { 22 | recurse(i + 1, curr + vals[j], digits); 23 | } 24 | } 25 | 26 | public: 27 | vector letterCombinations(string digits) { 28 | if (digits == "") return {}; 29 | hash['2'] = {'a', 'b', 'c'}; 30 | hash['3'] = {'d', 'e', 'f'}; 31 | hash['4'] = {'g', 'h', 'i'}; 32 | hash['5'] = {'j', 'k', 'l'}; 33 | hash['6'] = {'m', 'n', 'o'}; 34 | hash['7'] = {'p', 'q', 'r', 's'}; 35 | hash['8'] = {'t', 'u', 'v'}; 36 | hash['9'] = {'w', 'x', 'y', 'z'}; 37 | recurse(0, "", digits); 38 | return ans; 39 | } 40 | }; 41 | // @lc code=end 42 | -------------------------------------------------------------------------------- /c++/18.4-sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=18 lang=cpp 6 | * 7 | * [18] 4Sum 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | vector> fourSum(vector& arr, int target) { 14 | int i = 0, j, k, l, n = arr.size(); 15 | sort(arr.begin(), arr.end()); 16 | set> s; 17 | while (i < n - 3) { 18 | j = i + 1; 19 | while (j < n - 2) { 20 | k = j + 1; 21 | l = n - 1; 22 | while (k < l) { 23 | int sum = arr[i] + arr[j] + arr[k] + arr[l]; 24 | if (sum == target) { 25 | s.insert({arr[i], arr[j], arr[k], arr[l]}); 26 | k += 1; 27 | l -= 1; 28 | } 29 | if (sum < target) k += 1; 30 | if (sum > target) l -= 1; 31 | } 32 | j += 1; 33 | } 34 | i += 1; 35 | } 36 | vector> ans; 37 | for (auto it : s) ans.push_back(it); 38 | return ans; 39 | } 40 | }; 41 | // @lc code=end 42 | -------------------------------------------------------------------------------- /c++/19.remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=19 lang=cpp 6 | * 7 | * [19] Remove Nth Node From End of List 8 | */ 9 | 10 | // @lc code=start 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode() : val(0), next(nullptr) {} 17 | * ListNode(int x) : val(x), next(nullptr) {} 18 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | ListNode* removeNthFromEnd(ListNode* head, int k) { 24 | int n = 0; 25 | ListNode* p = head; 26 | while (p != NULL) { 27 | n += 1; 28 | p = p->next; 29 | } 30 | k = (n + 1) - k; 31 | int i = 1; 32 | ListNode *curr = head, *prev = head; 33 | if (i == k) { 34 | head = head->next; 35 | } else { 36 | while (i < k) { 37 | prev = curr; 38 | curr = curr->next; 39 | i += 1; 40 | } 41 | prev->next = curr->next; 42 | } 43 | 44 | return head; 45 | } 46 | }; 47 | // @lc code=end 48 | -------------------------------------------------------------------------------- /c++/1943.Describe the Painting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=1943 lang=cpp 6 | * 7 | * [1943] Describe the Painting 8 | */ 9 | 10 | // TODO Solved with solution 11 | 12 | // @lc code=start 13 | class Solution { 14 | public: 15 | vector> splitPainting(vector>& segments) {} 16 | }; 17 | // @lc code=end 18 | -------------------------------------------------------------------------------- /c++/22.generate-parentheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=22 lang=cpp 6 | * 7 | * [22] Generate Parentheses 8 | */ 9 | 10 | /* 11 | * Backtracking Problem: 12 | * open = no. of open brackets, close = no. of close brackets, n = no. of bracket pairs 13 | * We visit every possibe solution and add it to res 14 | */ 15 | // @lc code=start 16 | class Solution { 17 | public: 18 | vector res; 19 | void backtrack(string s, int open, int close, int n) { 20 | if (s.length() == n * 2) { 21 | res.push_back(s); 22 | return; 23 | } 24 | if (open < n) backtrack(s + "(", open + 1, close, n); 25 | if (close < open) backtrack(s + ")", open, close + 1, n); 26 | } 27 | vector generateParenthesis(int n) { 28 | backtrack("", 0, 0, n); 29 | return res; 30 | } 31 | }; 32 | // @lc code=end 33 | -------------------------------------------------------------------------------- /c++/239.sliding-window-maximum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=239 lang=cpp 6 | * 7 | * [239] Sliding Window Maximum 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | vector maxSlidingWindow(vector& nums, int k) { 14 | deque buffer; 15 | vector res; 16 | 17 | // Edge case: If window size is >= nums.size(), then ans is max element nums array 18 | if (k >= nums.size()) { 19 | return {*max_element(nums.begin(), nums.end())}; 20 | } 21 | 22 | // Creating the initial window 23 | for (int x = 0; x < k; x++) { 24 | while (!buffer.empty() && nums[x] > buffer.back()) buffer.pop_back(); 25 | buffer.push_back(nums[x]); 26 | } 27 | 28 | int i = 0, j = k - 1; // Initial window pointers 29 | 30 | while (j < nums.size()) { 31 | if (!buffer.empty()) res.push_back(buffer.front()); 32 | 33 | // Removing the first element of the current window and then proceeding to the next window 34 | if (!buffer.empty() && buffer.front() == nums[i]) buffer.pop_front(); 35 | 36 | // Sliding the window 37 | i++; 38 | j++; 39 | 40 | if (j == nums.size()) break; 41 | 42 | while (!buffer.empty() && nums[j] > buffer.back()) buffer.pop_back(); 43 | buffer.push_back(nums[j]); 44 | } 45 | return res; 46 | } 47 | }; 48 | // @lc code=end 49 | -------------------------------------------------------------------------------- /c++/283.move-zeroes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=283 lang=cpp 6 | * 7 | * [283] Move Zeroes 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | void moveZeroes(vector& nums) { 14 | int n = nums.size(); 15 | if (n == 1) return; 16 | if (n == 2 && nums[0] == 0) { 17 | swap(nums[0], nums[1]); 18 | return; 19 | } 20 | int replaceIndex = -1, zeroCnt = 0; 21 | for (int i = 0; i < n; i++) { 22 | if (nums[i] == 0) { 23 | if (replaceIndex == -1) replaceIndex = i; 24 | zeroCnt++; 25 | } else { 26 | if (replaceIndex != -1) { 27 | nums[replaceIndex++] = nums[i]; 28 | } 29 | } 30 | } 31 | int i = n - 1; 32 | while (zeroCnt--) { 33 | nums[i--] = 0; 34 | } 35 | } 36 | }; 37 | // @lc code=end 38 | -------------------------------------------------------------------------------- /c++/29.divide-two-integers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=29 lang=cpp 3 | * 4 | * [29] Divide Two Integers 5 | */ 6 | 7 | // * Concept: a/b = e^(ln(a))/e^(ln(b)) = e^(ln(a)-ln(b)) 8 | 9 | // @lc code=start 10 | class Solution { 11 | public: 12 | int divide(int dividend, int divisor) { 13 | if (dividend == 0) return 0; 14 | if (divisor == 0) return INT_MAX; 15 | long long res = double(exp(log(fabs(dividend)) - log(fabs(divisor)))); 16 | if ((dividend < 0) ^ (divisor < 0)) res = -res; 17 | if (res > INT_MAX) res = INT_MAX; 18 | return res; 19 | } 20 | }; 21 | 22 | // @lc code=end 23 | -------------------------------------------------------------------------------- /c++/309.best-time-to-buy-and-sell-stock-with-cooldown.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=309 lang=cpp 6 | * 7 | * [309] Best Time to Buy and Sell Stock with Cooldown 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | vector dp; 14 | int recurse(int curr, const vector& prices) { 15 | int n = prices.size(); 16 | if (curr >= n) return 0; 17 | if (dp[curr] != -1) return dp[curr]; 18 | int ans = 0; 19 | for (int i = curr + 1; i < n; i++) { 20 | ans = max(ans, (prices[i] - prices[curr]) + recurse(i + 2, prices)); 21 | } 22 | for (int i = curr + 1; i < n; i++) { 23 | ans = max(ans, recurse(i, prices)); 24 | } 25 | return dp[curr] = ans; 26 | } 27 | int maxProfit(vector& prices) { 28 | dp.resize(5010, -1); 29 | int ans = recurse(0, prices); 30 | return ans; 31 | } 32 | }; 33 | // @lc code=end 34 | -------------------------------------------------------------------------------- /c++/31.next-permutation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=31 lang=cpp 6 | * 7 | * [31] Next Permutation 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | void nextPermutation(vector& nums) { 14 | int i = 1, n = nums.size(), maxi = -1; 15 | 16 | if (n == 1) return; 17 | while (i < n) { 18 | if (nums[i] > nums[i - 1]) maxi = i; 19 | i += 1; 20 | } 21 | if (maxi == -1) { 22 | sort(nums.begin(), nums.end()); 23 | return; 24 | } 25 | 26 | int next_maxi = maxi, val = nums[maxi]; 27 | i = maxi; 28 | while (i < n) { 29 | if (nums[i] > nums[maxi - 1] && nums[i] < nums[maxi]) { 30 | if (nums[i] < val) { 31 | val = nums[i]; 32 | next_maxi = i; 33 | } 34 | } 35 | i += 1; 36 | } 37 | swap(nums[next_maxi], nums[maxi - 1]); 38 | sort(nums.begin() + maxi, nums.end()); 39 | } 40 | }; 41 | // @lc code=end 42 | -------------------------------------------------------------------------------- /c++/33.search-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=33 lang=cpp 6 | * 7 | * [33] Search in Rotated Sorted Array 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int search(vector& nums, int target) { 14 | int low = 0, high = nums.size() - 1; 15 | 16 | // * We first find the pivot point which is stored in low after the loop 17 | while (low < high) { 18 | int mid = low + (high - low) / 2; 19 | if (nums[mid] > nums[high]) 20 | low = mid + 1; 21 | else 22 | high = mid; 23 | } 24 | int pivot = low; 25 | low = 0, high = nums.size() - 1; 26 | // * We check if the target is in range [pivot, nums.size() - 1]. If so, then we don't need to check the range [0, pivot - 1]. 27 | // * So we run a regular binary search with low=pivot, high=nums.size()-1. 28 | // * If the number is in range [0, pivot - 1], then we make high = pivot - 1 and run binary search with low = 0, high = pivot - 1 29 | if (target >= nums[pivot] && target <= nums[high]) 30 | low = pivot; 31 | else 32 | high = pivot - 1; 33 | while (low <= high) { 34 | int mid = low + (high - low) / 2; 35 | if (target == nums[mid]) return mid; 36 | if (target < nums[mid]) high = mid - 1; 37 | if (target > nums[mid]) low = mid + 1; 38 | } 39 | return -1; 40 | } 41 | }; 42 | // @lc code=end 43 | -------------------------------------------------------------------------------- /c++/34.find-first-and-last-position-of-element-in-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=34 lang=cpp 6 | * 7 | * [34] Find First and Last Position of Element in Sorted Array 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | vector searchRange(vector& nums, int target) { 14 | int l = 0, r = nums.size() - 1; 15 | vector res(2, -1); 16 | if (nums.size() == 0) return res; 17 | if (nums.size() == 1) { 18 | if (nums[0] == target) return {0, 0}; 19 | return res; 20 | } 21 | while (l <= r) { 22 | int mid = l + (r - l) / 2; 23 | if (nums[mid] == target) { 24 | res[0] = mid; 25 | r = mid - 1; 26 | } else if (nums[mid] > target) { 27 | r = mid - 1; 28 | } else { 29 | l = mid + 1; 30 | } 31 | } 32 | l = 0, r = nums.size() - 1; 33 | while (l <= r) { 34 | int mid = l + (r - l) / 2; 35 | if (nums[mid] == target) { 36 | res[1] = mid; 37 | l = mid + 1; 38 | } else if (nums[mid] > target) { 39 | r = mid - 1; 40 | } else { 41 | l = mid + 1; 42 | } 43 | } 44 | return res; 45 | } 46 | }; 47 | // @lc code=end 48 | -------------------------------------------------------------------------------- /c++/343.integer-break.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=343 lang=cpp 6 | * 7 | * [343] Integer Break 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int ans, size; 14 | map dp; 15 | int recurse(int n) { 16 | if (n == 0) return 1; 17 | if (dp.find(n) != dp.end()) return dp[n]; 18 | int res = 1; 19 | for (int i = n; i >= 1; i--) { 20 | if (i != size && n - i >= 0) res = max(res, i * recurse(n - i)); 21 | } 22 | return dp[n] = res; 23 | } 24 | int integerBreak(int n) { 25 | size = n; 26 | int ans = recurse(n); 27 | return ans; 28 | } 29 | }; 30 | // @lc code=end 31 | -------------------------------------------------------------------------------- /c++/35.search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=35 lang=cpp 6 | * 7 | * [35] Search Insert Position 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int searchInsert(vector& nums, int target) { 14 | int l = 0, r = nums.size() - 1; 15 | int ans = 0; 16 | while (l <= r) { 17 | int mid = l + (r - l) / 2; 18 | if (nums[mid] == target) return mid; 19 | if (nums[mid] > target) { 20 | r = mid - 1; 21 | } else { 22 | l = mid + 1; 23 | ans = l; 24 | } 25 | } 26 | return ans; 27 | } 28 | }; 29 | // @lc code=end 30 | -------------------------------------------------------------------------------- /c++/36.valid-sudoku.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=36 lang=cpp 6 | * 7 | * [36] Valid Sudoku 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | bool check_row(const vector>& board, int r, int c) { 14 | int n = board.size(); 15 | for (int i = 0; i < n; i++) { 16 | if (i == r) continue; 17 | if (board[i][c] == board[r][c]) return false; 18 | } 19 | return true; 20 | } 21 | bool check_column(const vector>& board, int r, int c) { 22 | int n = board.size(); 23 | for (int i = 0; i < n; i++) { 24 | if (i == c) continue; 25 | if (board[r][i] == board[r][c]) return false; 26 | } 27 | return true; 28 | } 29 | bool check_grid(const vector>& board, int r, int c) { 30 | bool ans = false; 31 | return ans; 32 | } 33 | bool isValidSudoku(vector>& board) { 34 | bool ans = true; 35 | int n = board.size(); 36 | for (int i = 0; i < n; i++) { 37 | for (int j = 0; j < n; j++) { 38 | if (board[i][j] == '.') continue; 39 | } 40 | } 41 | } 42 | }; 43 | // @lc code=end 44 | -------------------------------------------------------------------------------- /c++/376.wiggle-subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=376 lang=cpp 6 | * 7 | * [376] Wiggle Subsequence 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int wiggleMaxLength(vector& a) { 14 | if (a.size() < 2) return a.size(); 15 | 16 | int i = 1; 17 | while (i < a.size() && a[i] == a[i - 1]) i++; 18 | if (i == a.size()) return 1; 19 | 20 | int c = 2; 21 | bool inc = a[i] > a[i - 1]; 22 | while (i < a.size()) { 23 | if (inc) { 24 | while (i < a.size() && a[i] >= a[i - 1]) i++; 25 | if (i < a.size()) c++; 26 | inc = false; 27 | } else { 28 | while (i < a.size() && a[i] <= a[i - 1]) i++; 29 | if (i < a.size()) c++; 30 | inc = true; 31 | } 32 | } 33 | return c; 34 | } 35 | }; 36 | // @lc code=end 37 | -------------------------------------------------------------------------------- /c++/395.longest-substring-with-at-least-k-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=395 lang=cpp 6 | * 7 | * [395] Longest Substring with At Least K Repeating Characters 8 | */ 9 | 10 | class Solution { 11 | public: 12 | int dnc(int start, int end, string s, int k) { 13 | map freq; 14 | for (int i = start; i <= end; i++) freq[s[i]]++; 15 | vector breakpoints; 16 | breakpoints.push_back(start - 1); 17 | for (int i = start; i <= end; i++) { 18 | if (freq[s[i]] < k) { 19 | breakpoints.push_back(i); 20 | } 21 | } 22 | breakpoints.push_back(end + 1); 23 | if (breakpoints.size() == 2) { 24 | return s.substr(start, end - start + 1).length(); 25 | } 26 | int ans = INT_MIN; 27 | for (int i = 1; i < breakpoints.size(); i++) { 28 | int first = breakpoints[i - 1], second = breakpoints[i]; 29 | ans = max(ans, dnc(first + 1, second - 1, s, k)); 30 | } 31 | return ans; 32 | } 33 | 34 | int longestSubstring(string s, int k) { 35 | int ans = dnc(0, s.length() - 1, s, k); 36 | return ans; 37 | } 38 | }; 39 | 40 | /* 41 | * "bcabbcbaaaa"\n3 42 | */ -------------------------------------------------------------------------------- /c++/413.arithmetic-slices.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=413 lang=cpp 6 | * 7 | * [413] Arithmetic Slices 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int ans; 14 | int recurse(int i, vector& nums) { 15 | if (i < 2) return 0; 16 | int res = 0; 17 | if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) { 18 | // If condition meets then add this subarray to result 19 | // Then continue with next elements 20 | // If we find any valid subarray adjacent to nums[i], then [...subarray, nums[i]] will also be valid 21 | res = 1 + recurse(i - 1, nums); 22 | ans += res; 23 | } else { 24 | // We simply move to the next elements and don't consider the current one 25 | recurse(i - 1, nums); 26 | } 27 | return res; 28 | } 29 | int numberOfArithmeticSlices(vector& nums) { 30 | int n = nums.size(); 31 | if (n < 3) return 0; 32 | ans = 0; 33 | recurse(n - 1, nums); 34 | return ans; 35 | } 36 | }; 37 | // @lc code=end 38 | -------------------------------------------------------------------------------- /c++/486.predict-the-winner.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=486 lang=cpp 6 | * 7 | * [486] Predict the Winner 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | vector> dp; 14 | int recurse(int i, int j, int turn, vector& arr) { 15 | if (i > j) return -1; 16 | if (i == j) return arr[i]; 17 | if (dp[i][j] != -1) return dp[i][j]; 18 | if (turn == 0) { 19 | return dp[i][j] = max(arr[i] + recurse(i + 1, j, 1, arr), arr[j] + recurse(i, j - 1, 1, arr)); 20 | } else { 21 | return dp[i][j] = min(-arr[i] + recurse(i + 1, j, 0, arr), -arr[j] + recurse(i, j - 1, 0, arr)); // Since player 2 will always try to minimise player 1's score 22 | } 23 | } 24 | 25 | bool PredictTheWinner(vector& nums) { 26 | dp.clear(); 27 | dp.resize(21, vector(21, -1)); 28 | int score = recurse(0, nums.size() - 1, 0, nums); // max score of player1 - max score of player 2 29 | return score >= 0; 30 | } 31 | }; 32 | // @lc code=end 33 | -------------------------------------------------------------------------------- /c++/494.target-sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=494 lang=cpp 6 | * 7 | * [494] Target Sum 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | map, int> dp; 14 | int recurse(int i, int sum, int target, vector& nums) { 15 | if (i >= nums.size()) { 16 | if (sum == target) return 1; 17 | return 0; 18 | } 19 | if (dp.find({i, sum}) != dp.end()) return dp[{i, sum}]; 20 | int ways = 0; 21 | ways += recurse(i + 1, sum + nums[i], target, nums); 22 | ways += recurse(i + 1, sum - nums[i], target, nums); 23 | return dp[{i, sum}] = ways; 24 | } 25 | int findTargetSumWays(vector& nums, int target) { 26 | dp.clear(); 27 | return recurse(0, 0, target, nums); 28 | } 29 | }; 30 | // @lc code=end 31 | -------------------------------------------------------------------------------- /c++/51.n-queens.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=51 lang=cpp 6 | * 7 | * [51] N-Queens 8 | */ 9 | 10 | // @lc code=start 11 | 12 | class Solution { 13 | public: 14 | bool isSafe(int r, int c, vector &board) { 15 | for (int j = c - 1; j >= 0; j--) { 16 | if (board[r][j] == 'Q') return false; 17 | } 18 | for (int j = c + 1; j < board.size(); j++) { 19 | if (board[r][j] == 'Q') return false; 20 | } 21 | for (int i = r - 1; i >= 0; i--) { 22 | if (board[i][c] == 'Q') return false; 23 | } 24 | for (int i = r + 1; i < board.size(); i++) { 25 | if (board[i][c] == 'Q') return false; 26 | } 27 | for (int i = r - 1, j = c - 1; i >= 0 && j >= 0; i--, j--) { 28 | if (board[i][j] == 'Q') return false; 29 | } 30 | for (int i = r - 1, j = c + 1; i >= 0 && j < board.size(); i--, j++) { 31 | if (board[i][j] == 'Q') return false; 32 | } 33 | for (int i = r + 1, j = c + 1; i < board.size() && j < board.size(); i++, j++) { 34 | if (board[i][j] == 'Q') return false; 35 | } 36 | for (int i = r + 1, j = c - 1; i < board.size() && j >= 0; i++, j--) { 37 | if (board[i][j] == 'Q') return false; 38 | } 39 | return true; 40 | } 41 | void recurse(int r, vector &board, set> &res) { 42 | if (r == -1) { 43 | res.insert(board); 44 | return; 45 | } 46 | for (int j = 0; j < board.size(); j++) { 47 | if (board[r][j] == 'Q') continue; 48 | if (isSafe(r, j, board)) { 49 | board[r][j] = 'Q'; 50 | recurse(r - 1, board, res); 51 | board[r][j] = '.'; 52 | } 53 | } 54 | } 55 | vector> solveNQueens(int n) { 56 | string s = ""; 57 | for (int i = 0; i < n; i++) s += '.'; 58 | vector board(n, s); 59 | set> res; 60 | recurse(n - 1, board, res); 61 | vector> ans; 62 | for (auto it : res) ans.push_back(it); 63 | return ans; 64 | } 65 | }; 66 | 67 | // @lc code=end -------------------------------------------------------------------------------- /c++/53.maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=53 lang=cpp 6 | * 7 | * [53] Maximum Subarray 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int maxSubArray(vector& nums) { 14 | int n = nums.size(); 15 | 16 | // Creating and filling prefix array 17 | vector pre_sum(n, 0); 18 | pre_sum[0] = nums[0]; 19 | for (int i = 1; i < n; i++) { 20 | pre_sum[i] = nums[i] + pre_sum[i - 1]; 21 | } 22 | 23 | // If curr_element + sum of all prev elements < curr_element, then make prefix_array[curr_element] = current_element, 24 | // So for the next elements, the subarray will start from the curr_element and we discard the previous elements as they result 25 | // in a sum of a smaller value than curr_element. 26 | for (int i = 1; i < n; i++) { 27 | if (nums[i] + pre_sum[i - 1] < nums[i]) { 28 | pre_sum[i] = nums[i]; 29 | } else { 30 | pre_sum[i] = nums[i] + pre_sum[i - 1]; 31 | } 32 | } 33 | 34 | // Returning the max element of the modified prefix array 35 | return *max_element(pre_sum.begin(), pre_sum.end()); 36 | } 37 | }; 38 | // @lc code=end -------------------------------------------------------------------------------- /c++/543.diameter-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=543 lang=cpp 6 | * 7 | * [543] Diameter of Binary Tree 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | int ans; 24 | int recurse(TreeNode *root) { 25 | if (!root) return -1; // Since we are adding +1 after recursion, if we recurse to NULL we return -1 and adding to +1 makes it 0. 26 | if (!root->left && !root->right) return 0; 27 | int l = 1 + recurse(root->left); 28 | int r = 1 + recurse(root->right); 29 | ans = max(ans, l + r); 30 | return max(l, r); 31 | } 32 | int diameterOfBinaryTree(TreeNode *root) { 33 | if (!root) return 0; 34 | ans = 0; 35 | recurse(root); 36 | return ans; 37 | } 38 | }; 39 | // @lc code=end -------------------------------------------------------------------------------- /c++/6.zig-zag-conversion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=6 lang=cpp 6 | * 7 | * [6] ZigZag Conversion 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | string convert(string s, int numRows) { 14 | int n = s.length(); 15 | vector> table(n, vector(n, '#')); 16 | int i = 0, j = 0, pos = 0, direction = 1; 17 | // direction => 1 : Down, 0 : Up 18 | while (pos < n) { 19 | if (i == 0) { 20 | table[i][j] = s[pos]; 21 | pos += 1; 22 | if (i < numRows - 1) { 23 | i += 1; 24 | } else { 25 | j += 1; 26 | } 27 | direction = 1; 28 | } else if (i == numRows - 1) { 29 | table[i][j] = s[pos]; 30 | pos += 1; 31 | if (i > 0) i -= 1; 32 | if (j < n - 1) j += 1; 33 | direction = 0; 34 | } else if (direction == 1) { 35 | table[i][j] = s[pos]; 36 | pos += 1; 37 | if (i < numRows - 1) i += 1; 38 | } else if (direction == 0) { 39 | table[i][j] = s[pos]; 40 | pos += 1; 41 | if (i > 0) i -= 1; 42 | if (j < n - 1) j += 1; 43 | } 44 | } 45 | string ans = ""; 46 | pos = 0, i = 0, j = 0; 47 | for (i = 0; i < n; i++) { 48 | for (j = 0; j < n; j++) { 49 | if (table[i][j] != '#') { 50 | ans.push_back(table[i][j]); 51 | pos += 1; 52 | } 53 | 54 | if (pos >= n) break; 55 | } 56 | if (pos >= n) break; 57 | } 58 | return ans; 59 | } 60 | }; 61 | // @lc code=end 62 | -------------------------------------------------------------------------------- /c++/617.merge-two-binary-trees.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=617 lang=cpp 6 | * 7 | * [617] Merge Two Binary Trees 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | TreeNode *mergeTrees(TreeNode *root1, TreeNode *root2) { 24 | if (root2 == NULL) return root1; 25 | if (root1 == NULL) { 26 | root1 = root2; 27 | } else { 28 | root1->val += root2->val; 29 | } 30 | if (root1->left) { 31 | root1->left = mergeTrees(root1->left, root2->left); 32 | } else { 33 | root1->left = root2->left; 34 | } 35 | if (root1->right) { 36 | root1->right = mergeTrees(root1->right, root2->right); 37 | } else { 38 | root1->right = root2->right; 39 | } 40 | return root1; 41 | } 42 | }; 43 | // @lc code=end 44 | -------------------------------------------------------------------------------- /c++/62.unique-paths.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=62 lang=cpp 6 | * 7 | * [62] Unique Paths 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | vector> dp; 13 | 14 | public: 15 | int getUniquePaths(int i, int j, int m, int n) { 16 | if (i < 1 || j < 1) return 0; 17 | if (i == m && j == n) return 1; 18 | if (dp[i][j] != -1) return dp[i][j]; 19 | if (i == m) { 20 | return dp[i][j] = getUniquePaths(i, j + 1, m, n); 21 | } 22 | if (j == n) { 23 | return dp[i][j] = getUniquePaths(i + 1, j, m, n); 24 | } 25 | return dp[i][j] = getUniquePaths(i + 1, j, m, n) + getUniquePaths(i, j + 1, m, n); 26 | } 27 | int uniquePaths(int m, int n) { 28 | dp.resize(m + 1, vector(n + 1, -1)); 29 | int ans = getUniquePaths(1, 1, m, n); 30 | return ans; 31 | } 32 | }; 33 | // @lc code=end 34 | -------------------------------------------------------------------------------- /c++/63.unique-paths-ii.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=63 lang=cpp 6 | * 7 | * [63] Unique Paths II 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | vector> dp; 13 | 14 | public: 15 | int getUniquePaths(int i, int j, int r, int c, const vector>& grid) { 16 | if (i < 0 || j < 0) return 0; 17 | if (grid[i][j] == 1) return 0; 18 | if (i == r - 1 && j == c - 1) return 1; 19 | if (dp[i][j] != -1) return dp[i][j]; 20 | if (i == r - 1) return dp[i][j] = getUniquePaths(i, j + 1, r, c, grid); 21 | if (j == c - 1) return dp[i][j] = getUniquePaths(i + 1, j, r, c, grid); 22 | return dp[i][j] = getUniquePaths(i + 1, j, r, c, grid) + getUniquePaths(i, j + 1, r, c, grid); 23 | } 24 | int uniquePathsWithObstacles(vector>& obstacleGrid) { 25 | int r = obstacleGrid.size(); 26 | int c = obstacleGrid[0].size(); 27 | dp.resize(r + 1, vector(c + 1, -1)); 28 | int ans = getUniquePaths(0, 0, r, c, obstacleGrid); 29 | return ans; 30 | } 31 | }; 32 | // @lc code=end 33 | -------------------------------------------------------------------------------- /c++/64.minimum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=64 lang=cpp 6 | * 7 | * [64] Minimum Path Sum 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | vector> dp; 13 | 14 | public: 15 | int getMinPathSum(int i, int j, int r, int c, const vector>& grid) { 16 | if (i < 0 || j < 0) return 0; 17 | if (i >= r || j >= c) return 0; 18 | if (i == r - 1 && j == c - 1) return grid[i][j]; 19 | if (dp[i][j] != -1) return dp[i][j]; 20 | if (i == r - 1) return dp[i][j] = grid[i][j] + getMinPathSum(i, j + 1, r, c, grid); 21 | if (j == c - 1) return dp[i][j] = grid[i][j] + getMinPathSum(i + 1, j, r, c, grid); 22 | return dp[i][j] = grid[i][j] + min(getMinPathSum(i + 1, j, r, c, grid), getMinPathSum(i, j + 1, r, c, grid)); 23 | } 24 | int minPathSum(vector>& grid) { 25 | int r = grid.size(); 26 | int c = grid[0].size(); 27 | dp.resize(r + 1, vector(c + 1, -1)); 28 | int ans = getMinPathSum(0, 0, r, c, grid); 29 | return ans; 30 | } 31 | }; 32 | // @lc code=end 33 | -------------------------------------------------------------------------------- /c++/652.find-duplicate-subtrees.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=652 lang=cpp 6 | * 7 | * [652] Find Duplicate Subtrees 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | map hash; 24 | vector res; 25 | string recurse(TreeNode *root) { 26 | if (!root) return "#"; 27 | string l = recurse(root->left); 28 | string r = recurse(root->right); 29 | string tmp = to_string(root->val) + '#' + l + '#' + r; 30 | // Incrementing the count of the subtree structure from current node 31 | hash[tmp] += 1; 32 | // If same structure found, we store the root of the subtree in res. 33 | // For hash[tmp] > 2, we don't do anything as for all the duplicate trees, we need to store the root on any one subtree only once. 34 | // Since, we already store the root at hash[tmp] == 2, we need not store the root again for hash[tmp] > 2 35 | if (hash[tmp] == 2) res.push_back(root); 36 | return tmp; 37 | } 38 | vector findDuplicateSubtrees(TreeNode *root) { 39 | recurse(root); 40 | return res; 41 | } 42 | }; 43 | // @lc code=end 44 | -------------------------------------------------------------------------------- /c++/69.sqrt-x.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=69 lang=cpp 3 | * 4 | * [69] Sqrt(x) 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int mySqrt(int x) { 11 | if (x == 1) return 1; 12 | int l = 1, h = x / 2, ans = 0; 13 | while (l <= h) { 14 | int mid = l + (h - l) / 2; 15 | if (mid == x / mid) { 16 | ans = mid; 17 | return ans; 18 | } 19 | if (mid > x / mid) { 20 | h = mid - 1; 21 | } else { 22 | ans = mid; 23 | l = mid + 1; 24 | } 25 | } 26 | return ans; 27 | } 28 | }; 29 | // @lc code=end 30 | -------------------------------------------------------------------------------- /c++/70.climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=70 lang=cpp 6 | * 7 | * [70] Climbing Stairs 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | map dp; 14 | int recurse(int n) { 15 | if (n == 0) return 0; 16 | if (n == 1) return 1; 17 | if (n == 2) return 2; 18 | if (dp[n]) return dp[n]; 19 | return dp[n] = recurse(n - 1) + recurse(n - 2); 20 | } 21 | int climbStairs(int n) { 22 | int ans = recurse(n); 23 | return ans; 24 | } 25 | }; 26 | // @lc code=end 27 | -------------------------------------------------------------------------------- /c++/714.best-time-to-buy-and-sell-stock-with-transaction-fee.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=714 lang=cpp 6 | * 7 | * [714] Best Time to Buy and Sell Stock with Transaction Fee 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | vector> dp; 14 | int recurse(int i, int bought, int fee, const vector& prices) { 15 | if (i >= prices.size()) return 0; 16 | 17 | if (dp[i][bought] != -1) return dp[i][bought]; 18 | 19 | int ans = 0; 20 | if (!bought) { 21 | ans = max(ans, recurse(i + 1, 1, fee, prices) - prices[i]); 22 | } else { 23 | ans = max(ans, recurse(i + 1, 0, fee, prices) + prices[i] - fee); 24 | } 25 | ans = max(ans, recurse(i + 1, bought, fee, prices)); 26 | return dp[i][bought] = ans; 27 | } 28 | int maxProfit(vector& prices, int fee) { 29 | dp.resize(prices.size() + 1, vector(2, -1)); 30 | int ans = recurse(0, 0, fee, prices); 31 | return ans; 32 | } 33 | }; 34 | // @lc code=end 35 | -------------------------------------------------------------------------------- /c++/74.search-a-2-d-matrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=74 lang=cpp 6 | * 7 | * [74] Search a 2D Matrix 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | bool searchMatrix(vector>& matrix, int target) { 14 | int i = 0, j = matrix[0].size() - 1; 15 | while (i < matrix.size() && j >= 0) { 16 | if (matrix[i][j] == target) return true; 17 | if (matrix[i][j] < target) { 18 | i++; 19 | } else { 20 | j--; 21 | } 22 | } 23 | return false; 24 | } 25 | }; 26 | // @lc code=end 27 | -------------------------------------------------------------------------------- /c++/76.minimum-window-substring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=76 lang=cpp 6 | * 7 | * [76] Minimum Window Substring 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | string minWindow(string s, string t) { 14 | unordered_map hash; 15 | for (char c : t) hash[c]++; 16 | int cnt = hash.size(); 17 | int i = 0, j = 0, minval = INT_MAX, startidx = -1; 18 | while (j < s.length()) { 19 | if (cnt > 0) { 20 | if (hash.find(s[j]) != hash.end()) { 21 | hash[s[j]]--; 22 | } 23 | if (hash.find(s[j]) != hash.end() && hash[s[j]] == 0) cnt--; 24 | if (cnt == 0) { 25 | if (j - i + 1 < minval) { 26 | minval = j - i + 1; 27 | startidx = i; 28 | } 29 | if (hash.find(s[i]) != hash.end()) { 30 | hash[s[i]]++; 31 | if (hash[s[i]] > 0) cnt++, j++; 32 | } 33 | i++; 34 | } else { 35 | j++; 36 | } 37 | } else { 38 | if (j - i + 1 < minval) { 39 | minval = j - i + 1; 40 | startidx = i; 41 | } 42 | if (hash.find(s[i]) != hash.end()) { 43 | hash[s[i]]++; 44 | if (hash[s[i]] > 0) cnt++, j++; 45 | } 46 | i++; 47 | } 48 | } 49 | if (startidx == -1) return ""; 50 | return s.substr(startidx, minval); 51 | } 52 | }; 53 | // @lc code=end 54 | -------------------------------------------------------------------------------- /c++/79.word-search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=79 lang=cpp 6 | * 7 | * [79] Word Search 8 | */ 9 | 10 | // TODO NO-ATTEMPT 11 | 12 | // @lc code=start 13 | class Solution { 14 | public: 15 | bool exist(vector>& board, string word) {} 16 | }; 17 | // @lc code=end 18 | -------------------------------------------------------------------------------- /c++/795.number-of-subarrays-with-bounded-maximum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=795 lang=cpp 6 | * 7 | * [795] Number of Subarrays with Bounded Maximum 8 | */ 9 | 10 | // ! WATCHED SOLUTION 11 | // TODO - ATTEMPT WITHOUT SOLUTION 12 | 13 | // @lc code=start 14 | class Solution { 15 | public: 16 | int numSubarrayBoundedMax(vector& nums, int left, int right) { 17 | int start = -1, end = -1, ans = 0; 18 | for (int i = 0; i < nums.size(); i++) { 19 | if (nums[i] > right) { 20 | start = end = i; 21 | continue; 22 | } 23 | if (nums[i] >= left) { 24 | end = i; 25 | } 26 | ans += end - start; 27 | } 28 | return ans; 29 | } 30 | }; 31 | // @lc code=end 32 | -------------------------------------------------------------------------------- /c++/8.string-to-integer-atoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=8 lang=cpp 6 | * 7 | * [8] String to Integer (atoi) 8 | */ 9 | 10 | // ! UNSOLVED 11 | // TODO ATTEMPT PROPERLY 12 | 13 | // @lc code=start 14 | class Solution { 15 | public: 16 | int myAtoi(string s) { 17 | return stoi(s); 18 | } 19 | }; 20 | // @lc code=end 21 | -------------------------------------------------------------------------------- /c++/81.search-in-rotated-sorted-array-ii.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=81 lang=cpp 6 | * 7 | * [81] Search in Rotated Sorted Array II 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | bool search(vector &nums, int target) { 14 | int s = 0; 15 | int e = nums.size() - 1; 16 | while (s <= e) { 17 | int mid = s + (e - s) / 2; 18 | if (nums[mid] == target) return true; 19 | if (nums[s] == nums[mid] && nums[e] == nums[mid]) { 20 | while (s <= e && nums[s] == nums[mid] && nums[e] == nums[mid]) { 21 | s++; 22 | e--; 23 | } 24 | } else if (nums[s] <= nums[mid]) { // range [s, mid] is sorted 25 | if (target >= nums[s] && target <= nums[mid]) // and target lies in [s, mid], then run binary search in [s, mid] 26 | e = mid - 1; 27 | else 28 | s = mid + 1; 29 | } else { // [mid, e] should be sorted if nums[s] > nums[mid] 30 | if (target >= nums[mid] && target <= nums[e]) // if target lies in [mid, e], then run binary search in [mid, e] 31 | s = mid + 1; 32 | else 33 | e = mid - 1; 34 | } 35 | } 36 | return false; 37 | } 38 | }; 39 | // @lc code=end 40 | -------------------------------------------------------------------------------- /c++/839.similar-string-groups.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=839 lang=cpp 6 | * 7 | * [839] Similar String Groups 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | vector parent, size; 14 | 15 | int findParent(int x) { 16 | if (x == parent[x]) return x; 17 | return parent[x] = findParent(parent[x]); 18 | } 19 | 20 | void merge(int a, int b) { 21 | a = findParent(a); 22 | b = findParent(b); 23 | if (a == b) return; 24 | if (size[a] < size[b]) swap(a, b); 25 | parent[b] = a; 26 | size[a] += size[b]; 27 | } 28 | 29 | bool isSimilar(string a, string b) { 30 | int n = a.size(), cnt = 0; 31 | for (int i = 0; i < n; i++) { 32 | if (a[i] != b[i]) cnt += 1; 33 | if (cnt > 2) return false; 34 | } 35 | return cnt <= 2; 36 | } 37 | 38 | int numSimilarGroups(vector& strs) { 39 | int n = strs.size(); 40 | 41 | // Initializing DSU 42 | for (int i = 0; i < n; i++) { 43 | parent.push_back(i); 44 | size.push_back(1); 45 | } 46 | 47 | // Checking every string with all the other strings and if similar, doing union of their indices. 48 | for (int i = 0; i < n; i++) { 49 | for (int j = i + 1; j < n; j++) { 50 | if (isSimilar(strs[i], strs[j])) { 51 | int a = findParent(i); 52 | int b = findParent(j); 53 | if (a != b) merge(a, b); 54 | } 55 | } 56 | } 57 | int ans = 0; 58 | // If parent[i] == i, then i is not a child of someone else. 59 | // Counting such possibilities gives us the number of disjoint sets present in the DSU. 60 | for (int i = 0; i < n; i++) { 61 | if (parent[i] == i) ans += 1; 62 | } 63 | return ans; 64 | } 65 | }; 66 | // @lc code=end 67 | -------------------------------------------------------------------------------- /c++/88.merge-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=88 lang=cpp 6 | * 7 | * [88] Merge Sorted Array 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | void merge(vector& nums1, int m, vector& nums2, int n) { 14 | int i = m - 1, j = n - 1, k = m + n - 1; 15 | while (k >= 0) { 16 | if (i >= 0 && j >= 0 && nums1[i] >= nums2[j]) { 17 | nums1[k--] = nums1[i--]; 18 | } else if (j >= 0) { 19 | nums1[k--] = nums2[j--]; 20 | } else { 21 | break; 22 | } 23 | } 24 | } 25 | }; 26 | // @lc code=end 27 | -------------------------------------------------------------------------------- /c++/889.construct-binary-tree-from-preorder-and-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=889 lang=cpp 6 | * 7 | * [889] Construct Binary Tree from Preorder and Postorder Traversal 8 | */ 9 | 10 | // @lc code=start 11 | 12 | // Definition for a binary tree node. 13 | struct TreeNode { 14 | int val; 15 | TreeNode* left; 16 | TreeNode* right; 17 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 18 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 19 | TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} 20 | }; 21 | 22 | class Solution { 23 | public: 24 | unordered_map postmap; 25 | TreeNode* generateTree(vector& pre, int pre_start, int pre_end, vector& post, int post_start, int post_end) { 26 | if (pre_start > pre_end) return NULL; 27 | TreeNode* root = new TreeNode(pre[pre_start]); 28 | if (pre_start == pre_end) return root; 29 | int idx = postmap[pre[pre_start + 1]]; 30 | int elem_count = idx - post_start + 1; 31 | root->left = generateTree(pre, pre_start + 1, pre_start + elem_count, post, post_start, idx); 32 | root->right = generateTree(pre, pre_start + elem_count + 1, pre_end, post, idx + 1, post_end - 1); 33 | return root; 34 | } 35 | TreeNode* constructFromPrePost(vector& preorder, vector& postorder) { 36 | int n = preorder.size(); 37 | postmap.clear(); 38 | for (int i = 0; i < n; i++) postmap[postorder[i]] = i; 39 | return generateTree(preorder, 0, n - 1, postorder, 0, n - 1); 40 | } 41 | }; 42 | // @lc code=end 43 | -------------------------------------------------------------------------------- /c++/95.unique-binary-search-trees-ii.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=95 lang=cpp 6 | * 7 | * [95] Unique Binary Search Trees II 8 | */ 9 | 10 | // TODO NO-ATTEMPT 11 | 12 | // @lc code=start 13 | /** 14 | * Definition for a binary tree node. 15 | * struct TreeNode { 16 | * int val; 17 | * TreeNode *left; 18 | * TreeNode *right; 19 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 20 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 21 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | vector generateTrees(int n) { 27 | } 28 | }; 29 | // @lc code=end 30 | -------------------------------------------------------------------------------- /c++/96.unique-binary-search-trees.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=96 lang=cpp 6 | * 7 | * [96] Unique Binary Search Trees 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | vector dp; 14 | int getNthCatalan(int n) { 15 | if (n == 0) return 1; 16 | if (dp[n] != -1) return dp[n]; 17 | int ans = 0; 18 | for (int i = 0; i <= n - 1; i++) { 19 | ans += getNthCatalan(i) * getNthCatalan(n - 1 - i); 20 | } 21 | return dp[n] = ans; 22 | } 23 | int numTrees(int n) { 24 | dp.resize(n + 1, -1); 25 | int ans = getNthCatalan(n); 26 | return ans; 27 | } 28 | }; 29 | // @lc code=end 30 | -------------------------------------------------------------------------------- /c++/978.longest-turbulent-subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=978 lang=cpp 6 | * 7 | * [978] Longest Turbulent Subarray 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public: 13 | int maxTurbulenceSize(vector& arr) { 14 | if (arr.size() == 0) return 0; 15 | if (arr.size() == 1) return 1; 16 | bool flag = true; 17 | for (int i = 0; i < arr.size() - 1; i++) { 18 | if (arr[i] != arr[i + 1]) { 19 | flag = false; 20 | } 21 | } 22 | if (flag) return 1; 23 | int maxlen = 2; 24 | int l = 0, r = 0; 25 | int nextSmall = false; 26 | if (arr[0] > arr[1]) nextSmall = true; 27 | for (int i = 1; i < arr.size() - 1; i++) { 28 | if (arr[i] == arr[i + 1]) { 29 | l = r = i; 30 | nextSmall = -1; 31 | } 32 | if (nextSmall == -1) { 33 | if (arr[i] < arr[i + 1]) { 34 | l = r = i; 35 | nextSmall = false; 36 | } else if (arr[i] > arr[i + 1]) { 37 | l = r = i; 38 | nextSmall = true; 39 | } 40 | } else if (nextSmall == 1) { 41 | if (arr[i] < arr[i + 1]) { 42 | r = i + 1; 43 | maxlen = max(maxlen, r - l + 1); 44 | nextSmall = !nextSmall; 45 | } else { 46 | l = r = i; 47 | nextSmall = true; 48 | } 49 | } else { 50 | if (arr[i] > arr[i + 1]) { 51 | r = i + 1; 52 | maxlen = max(maxlen, r - l + 1); 53 | nextSmall = !nextSmall; 54 | } else { 55 | l = r = i; 56 | nextSmall = false; 57 | } 58 | } 59 | } 60 | return maxlen; 61 | } 62 | }; 63 | // @lc code=end 64 | -------------------------------------------------------------------------------- /c++/98.validate-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | * @lc app=leetcode id=98 lang=cpp 6 | * 7 | * [98] Validate Binary Search Tree 8 | */ 9 | 10 | // @lc code=start 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | bool recurse(TreeNode *root, long left, long right) { 24 | if (!root) return true; 25 | if (!(left < root->val && root->val < right)) return false; 26 | return recurse(root->left, left, root->val) && recurse(root->right, root->val, right); 27 | } 28 | bool isValidBST(TreeNode *root) { 29 | return recurse(root, LONG_MIN, LONG_MAX); 30 | } 31 | }; 32 | // @lc code=end 33 | -------------------------------------------------------------------------------- /c++/993.cousins-in-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=993 lang=cpp 3 | * 4 | * [993] Cousins in Binary Tree 5 | */ 6 | 7 | // @lc code=start 8 | 9 | // struct TreeNode { 10 | // int val; 11 | // TreeNode *left; 12 | // TreeNode *right; 13 | // TreeNode() : val(0), left(nullptr), right(nullptr) {} 14 | // TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 15 | // TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 16 | // }; 17 | 18 | class Solution { 19 | public: 20 | int xd, yd, xp, yp; 21 | void recurse(TreeNode *curr, TreeNode *parent, int depth, int x, int y) { 22 | if (!curr) return; 23 | if (curr->val == x) { 24 | xd = depth; 25 | xp = parent ? parent->val : -1; 26 | return; 27 | } 28 | if (curr->val == y) { 29 | yd = depth; 30 | yp = parent ? parent->val : -1; 31 | return; 32 | } 33 | recurse(curr->left, curr, depth + 1, x, y); 34 | recurse(curr->right, curr, depth + 1, x, y); 35 | } 36 | bool isCousins(TreeNode *root, int x, int y) { 37 | xd = -1, yd = -2, xp = -1, yp = -1; 38 | recurse(root, NULL, 0, x, y); 39 | if (xd == yd && xp != yp) return true; 40 | return false; 41 | } 42 | }; 43 | // @lc code=end 44 | -------------------------------------------------------------------------------- /java/1.two-sum.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | 4 | /* 5 | * @lc app=leetcode id=1 lang=java 6 | * 7 | * [1] Two Sum 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public int[] twoSum(int[] nums, int target) { 13 | int[] ans = new int[2]; 14 | ArrayList arr = new ArrayList<>(); 15 | for (int i = 0; i < nums.length; i++) { 16 | int ar[] = new int[2]; 17 | ar[0] = nums[i]; 18 | ar[1] = i; 19 | arr.add(i, ar); 20 | } 21 | Collections.sort(arr, (a, b) -> a[0] - b[0]); 22 | int i = 0, j = nums.length - 1; 23 | while (i < j) { 24 | int sum = arr.get(i)[0] + arr.get(j)[0]; 25 | if (sum == target) { 26 | ans[0] = arr.get(i)[1]; 27 | ans[1] = arr.get(j)[1]; 28 | break; 29 | } 30 | if (sum < target) 31 | i++; 32 | if (sum > target) 33 | j--; 34 | } 35 | return ans; 36 | } 37 | } 38 | // @lc code=end 39 | -------------------------------------------------------------------------------- /java/101.symmetric-tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=101 lang=java 3 | * 4 | * [101] Symmetric Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode() {} 15 | * TreeNode(int val) { this.val = val; } 16 | * TreeNode(int val, TreeNode left, TreeNode right) { 17 | * this.val = val; 18 | * this.left = left; 19 | * this.right = right; 20 | * } 21 | * } 22 | */ 23 | class Solution { 24 | private boolean check(TreeNode l, TreeNode r) { 25 | if (l == null && r == null) 26 | return true; 27 | if (l == null || r == null) 28 | return false; 29 | if (l.val != r.val) 30 | return false; 31 | if (check(l.left, r.right) && check(l.right, r.left)) 32 | return true; 33 | return false; 34 | } 35 | 36 | public boolean isSymmetric(TreeNode root) { 37 | if (root == null) 38 | return true; 39 | return check(root.left, root.right); 40 | } 41 | } 42 | // @lc code=end 43 | 44 | -------------------------------------------------------------------------------- /java/104.maximum-depth-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=104 lang=java 3 | * 4 | * [104] Maximum Depth of Binary Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode() {} 15 | * TreeNode(int val) { this.val = val; } 16 | * TreeNode(int val, TreeNode left, TreeNode right) { 17 | * this.val = val; 18 | * this.left = left; 19 | * this.right = right; 20 | * } 21 | * } 22 | */ 23 | class Solution { 24 | private int dfs(TreeNode root, int depth) { 25 | if (root == null) 26 | return 1; 27 | int maxDepth = depth; 28 | if (root.left != null) 29 | maxDepth = Math.max(maxDepth, dfs(root.left, depth + 1)); 30 | if (root.right != null) 31 | maxDepth = Math.max(maxDepth, dfs(root.right, depth + 1)); 32 | return maxDepth; 33 | } 34 | 35 | public int maxDepth(TreeNode root) { 36 | if (root == null) 37 | return 0; 38 | return dfs(root, 1); 39 | } 40 | } 41 | // @lc code=end 42 | -------------------------------------------------------------------------------- /java/1137.n-th-tribonacci-number.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | * @lc app=leetcode id=1137 lang=java 5 | * 6 | * [1137] N-th Tribonacci Number 7 | */ 8 | 9 | // @lc code=start 10 | class Solution { 11 | private int dp[]; 12 | 13 | private int recurse(int n) { 14 | if (n == 0) 15 | return 0; 16 | if (n == 1) 17 | return 1; 18 | if (n == 2) 19 | return 1; 20 | if (dp[n] != -1) 21 | return dp[n]; 22 | return dp[n] = recurse(n - 1) + recurse(n - 2) + recurse(n - 3); 23 | } 24 | 25 | public int tribonacci(int n) { 26 | dp = new int[38]; 27 | Arrays.fill(dp, -1); 28 | return recurse(n); 29 | } 30 | } 31 | // @lc code=end 32 | -------------------------------------------------------------------------------- /java/116.populating-next-right-pointers-in-each-node.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | import org.w3c.dom.Node; 4 | 5 | /* 6 | * @lc app=leetcode id=116 lang=java 7 | * 8 | * [116] Populating Next Right Pointers in Each Node 9 | */ 10 | 11 | // @lc code=start 12 | /* 13 | * // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; 14 | * 15 | * public Node() {} 16 | * 17 | * public Node(int _val) { val = _val; } 18 | * 19 | * public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; 20 | */ 21 | 22 | class Solution { 23 | public Node connect(Node root) { 24 | Node head = root; 25 | while(head != null) { 26 | Node p = head; 27 | while(p != null) { 28 | if(p.left == null) break; 29 | p.left.next = p.right; 30 | if(p.next != null && p.right != null) p.right.next = p.next.left; 31 | p = p.next; 32 | } 33 | head = head.left; 34 | } 35 | return root; 36 | } 37 | } 38 | // @lc code=end 39 | 40 | -------------------------------------------------------------------------------- /java/118.pascals-triangle.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | /* 6 | * @lc app=leetcode id=118 lang=java 7 | * 8 | * [118] Pascal's Triangle 9 | */ 10 | 11 | // @lc code=start 12 | class Solution { 13 | public List> generate(int numRows) { 14 | List> ans = new ArrayList<>(); 15 | for (int n = 1; n <= numRows; n++) { 16 | if (n == 1) { 17 | ans.add(Arrays.asList(1)); 18 | continue; 19 | } 20 | List res = new ArrayList<>(); 21 | res.add(1); 22 | for (int i = 1; i <= n - 2; i++) { 23 | res.add(ans.get(n - 2).get(i - 1) + ans.get(n - 2).get(i)); 24 | } 25 | res.add(1); 26 | ans.add(res); 27 | } 28 | return ans; 29 | } 30 | } 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /java/121.best-time-to-buy-and-sell-stock.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | * @lc app=leetcode id=121 lang=java 5 | * 6 | * [121] Best Time to Buy and Sell Stock 7 | */ 8 | 9 | // @lc code=start 10 | class Solution { 11 | public int maxProfit1(int[] prices) { 12 | int n = prices.length; 13 | int[] maxProfits = new int[n]; 14 | Arrays.fill(maxProfits, 0); 15 | int maxval = prices[n - 1]; 16 | maxProfits[n - 1] = prices[n - 1]; 17 | for (int i = n - 2; i >= 0; i--) { 18 | maxval = Math.max(maxval, prices[i]); 19 | maxProfits[i] = maxval; 20 | } 21 | maxval = 0; 22 | for (int i = 0; i < n; i++) { 23 | maxval = Math.max(maxval, maxProfits[i] - prices[i]); 24 | } 25 | return maxval; 26 | } 27 | 28 | public int maxProfit(int[] prices) { 29 | int min = Integer.MAX_VALUE, max = 0; 30 | for (int it : prices) { 31 | min = Math.min(min, it); 32 | if (it > min) 33 | max = Math.max(max, it - min); 34 | } 35 | return max; 36 | } 37 | } 38 | // @lc code=end 39 | 40 | -------------------------------------------------------------------------------- /java/1288.remove-covered-intervals.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1288 lang=java 3 | * 4 | * [1288] Remove Covered Intervals 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int removeCoveredIntervals(int[][] intervals) { 10 | Arrays.sort(intervals, new Comparator<>() { 11 | public int compare(int[] a, int[] b) { 12 | if (a[0] > b[0]) 13 | return 1; 14 | if (a[0] < b[0]) 15 | return -1; 16 | if (a[1] > b[1]) 17 | return -1; 18 | if (a[1] < b[1]) 19 | return 1; 20 | return -1; 21 | } 22 | }); 23 | 24 | int maxEnd = intervals[0][1], ans = intervals.length; 25 | 26 | for (int i = 1; i < intervals.length; i++) { 27 | if (intervals[i][1] <= maxEnd) { 28 | ans--; 29 | } else { 30 | maxEnd = intervals[i][1]; 31 | } 32 | } 33 | 34 | return ans; 35 | } 36 | } 37 | // @lc code=end 38 | -------------------------------------------------------------------------------- /java/136.single-number.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=136 lang=java 3 | * 4 | * [136] Single Number 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int singleNumber(int[] nums) { 10 | int ans = 0; 11 | for (int i = 0; i < nums.length; i++) { 12 | ans = ans ^ nums[i]; 13 | } 14 | return ans; 15 | } 16 | } 17 | // @lc code=end 18 | -------------------------------------------------------------------------------- /java/151.reverse-words-in-a-string.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=151 lang=java 3 | * 4 | * [151] Reverse Words in a String 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public String reverseWords(String s) { 10 | String ans = ""; 11 | for (int i = 0; i < s.length(); i++) { 12 | if (s.charAt(i) == ' ') 13 | continue; 14 | int j = i; 15 | String str = ""; 16 | while (j < s.length() && s.charAt(j) != ' ') { 17 | str += s.charAt(j++); 18 | } 19 | if (ans.length() == 0) 20 | ans += str; 21 | else 22 | ans = str + ' ' + ans; 23 | i = j - 1; 24 | } 25 | return ans; 26 | } 27 | } 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /java/167.two-sum-ii-input-array-is-sorted.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=167 lang=java 3 | * 4 | * [167] Two Sum II - Input array is sorted 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int[] twoSum(int[] numbers, int target) { 10 | int i = 0, j = numbers.length - 1; 11 | while (i < j) { 12 | int sum = numbers[i] + numbers[j]; 13 | if (sum == target) { 14 | return new int[] {i + 1, j + 1}; 15 | } 16 | if (sum < target) 17 | i++; 18 | if (sum > target) 19 | j--; 20 | } 21 | return new int[] {}; 22 | } 23 | } 24 | // @lc code=end 25 | 26 | -------------------------------------------------------------------------------- /java/169.majority-element.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=169 lang=java 3 | * 4 | * [169] Majority Element 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int majorityElement(int[] nums) { 10 | int cnt = 1, majorElem = nums[0]; 11 | 12 | for(int i=1;i= nums.length) 15 | return 0; 16 | if (dp[i] != -1) 17 | return dp[i]; 18 | return dp[i] = Math.max(nums[i] + recurse(i + 2, nums), recurse(i + 1, nums)); 19 | } 20 | 21 | public int rob(int[] nums) { 22 | dp = new int[101]; 23 | Arrays.fill(dp, -1); 24 | return recurse(0, nums); 25 | } 26 | } 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /java/206.reverse-linked-list.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=206 lang=java 3 | * 4 | * [206] Reverse Linked List 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * public class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode() {} 14 | * ListNode(int val) { this.val = val; } 15 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 16 | * } 17 | */ 18 | class Solution { 19 | public ListNode reverseList(ListNode head) { 20 | if (head == null) 21 | return head; 22 | ListNode slow = head, fast = head.next, ff = head.next; 23 | head.next = null; 24 | while (ff != null) { 25 | ff = ff.next; 26 | fast.next = slow; 27 | slow = fast; 28 | fast = ff; 29 | } 30 | return slow; 31 | } 32 | } 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /java/213.house-robber-ii.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | * @lc app=leetcode id=213 lang=java 5 | * 6 | * [213] House Robber II 7 | */ 8 | 9 | // @lc code=start 10 | class Solution { 11 | int[] dp; 12 | 13 | private int recurse(int i, int n, int[] nums) { 14 | if (i >= n) 15 | return 0; 16 | if (dp[i] != -1) 17 | return dp[i]; 18 | return dp[i] = Math.max(nums[i] + recurse(i + 2, n, nums), recurse(i + 1, n, nums)); 19 | } 20 | 21 | public int rob(int[] nums) { 22 | if (nums.length == 1) 23 | return nums[0]; 24 | dp = new int[101]; 25 | Arrays.fill(dp, -1); 26 | // If we loot the 1st house then we cant loot the last and vice versa 27 | // So we check for the array [0, n-2] and [1, n-1] and take their max 28 | int a = recurse(0, nums.length - 1, nums); 29 | Arrays.fill(dp, -1); 30 | int b = recurse(1, nums.length, nums); 31 | return Math.max(a, b); 32 | } 33 | } 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /java/217.contains-duplicate.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | /* 4 | * @lc app=leetcode id=217 lang=java 5 | * 6 | * [217] Contains Duplicate 7 | */ 8 | 9 | // @lc code=start 10 | class Solution { 11 | public boolean containsDuplicate(int[] nums) { 12 | HashMap hash = new HashMap<>(); 13 | for (int it : nums) { 14 | if (hash.containsKey(it)) 15 | return true; 16 | hash.put(it, hash.getOrDefault(it, 0) + 1); 17 | } 18 | return false; 19 | } 20 | } 21 | // @lc code=end 22 | -------------------------------------------------------------------------------- /java/23.merge-k-sorted-lists.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=23 lang=java 3 | * 4 | * [23] Merge k Sorted Lists 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * public class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode() {} 14 | * ListNode(int val) { this.val = val; } 15 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 16 | * } 17 | */ 18 | class Solution { 19 | public ListNode mergeKLists(ListNode[] lists) { 20 | if (lists == null || lists.length == 0) 21 | return null; 22 | PriorityQueue queue = new PriorityQueue<>((ListNode a, ListNode b) -> a.val > b.val ? 1 : a.val < b.val ? -1 : 0); 23 | ListNode ans = new ListNode(0); 24 | ListNode p = ans; 25 | 26 | for (ListNode node : lists) { 27 | if (node != null) 28 | queue.add(node); 29 | } 30 | 31 | while (!queue.isEmpty()) { 32 | p.next = queue.poll(); 33 | p = p.next; 34 | 35 | if (p.next != null) 36 | queue.add(p.next); 37 | } 38 | 39 | return ans.next; 40 | } 41 | } 42 | // @lc code=end 43 | 44 | -------------------------------------------------------------------------------- /java/231.power-of-two.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=231 lang=java 3 | * 4 | * [231] Power of Two 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public boolean isPowerOfTwo(int n) { 10 | if(n <= 0) return false; 11 | if((n & (n-1)) == 0) return true; 12 | return false; 13 | } 14 | } 15 | // @lc code=end 16 | 17 | -------------------------------------------------------------------------------- /java/24.swap-nodes-in-pairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=24 lang=java 3 | * 4 | * [24] Swap Nodes in Pairs 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * public class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode() {} 14 | * ListNode(int val) { this.val = val; } 15 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 16 | * } 17 | */ 18 | class Solution { 19 | public ListNode swapPairs(ListNode head) { 20 | if (head == null || head.next == null) 21 | return head; 22 | 23 | ListNode slower = null, slow = head, fast = head.next; 24 | ListNode ans = head.next; 25 | 26 | while (slow != null && fast != null) { 27 | if (slower != null) 28 | slower.next = fast; 29 | slow.next = fast.next; 30 | fast.next = slow; 31 | 32 | slower = slow; 33 | slow = slow.next; 34 | if (slow != null) 35 | fast = slow.next; 36 | } 37 | 38 | return ans; 39 | } 40 | } 41 | // @lc code=end 42 | -------------------------------------------------------------------------------- /java/258.add-digits.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=258 lang=java 3 | * 4 | * [258] Add Digits 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | int sumdigits(int n) { 10 | int ans = 0; 11 | while(n > 0) { 12 | ans += n % 10; // 0 13 | n = n / 10; 14 | } 15 | return ans; 16 | } 17 | 18 | boolean checkmulti(int n) { 19 | n = n / 10; 20 | if(n > 0) return true; 21 | return false; 22 | } 23 | 24 | public int addDigits(int num) { 25 | while(checkmulti(num)) { 26 | num = sumdigits(num); 27 | } 28 | return num; 29 | } 30 | } 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /java/278.first-bad-version.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=278 lang=java 3 | * 4 | * [278] First Bad Version 5 | */ 6 | 7 | // @lc code=start 8 | /* The isBadVersion API is defined in the parent class VersionControl. 9 | boolean isBadVersion(int version); */ 10 | 11 | public class Solution extends VersionControl { 12 | public int firstBadVersion(int n) { 13 | int l = 1, r = n, ans = -1; 14 | while (l <= r) { 15 | int mid = l + (r - l) / 2; 16 | if (isBadVersion(mid)) { 17 | ans = mid; 18 | r = mid - 1; 19 | } else { 20 | l = mid + 1; 21 | } 22 | } 23 | return ans; 24 | } 25 | } 26 | // @lc code=end 27 | -------------------------------------------------------------------------------- /java/283.move-zeroes.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=283 lang=java 3 | * 4 | * [283] Move Zeroes 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public void moveZeroes(int[] nums) { 10 | int i = 0, j = 1; 11 | // 1 2 0 3 4 12 | while (i < nums.length && nums[i] != 0) { 13 | i++; 14 | } 15 | j = i + 1; 16 | while (j < nums.length) { 17 | if (nums[j] != 0) 18 | nums[i++] = nums[j++]; 19 | else 20 | j++; 21 | } 22 | while (i < nums.length) 23 | nums[i++] = 0; 24 | } 25 | } 26 | // @lc code=end 27 | 28 | -------------------------------------------------------------------------------- /java/287.find-the-duplicate-number.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=287 lang=java 3 | * 4 | * [287] Find the Duplicate Number 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int findDuplicate(int[] nums) { 10 | int slow = nums[0], fast = nums[0]; 11 | do { 12 | slow = nums[slow]; 13 | fast = nums[nums[fast]]; 14 | } while (slow != fast); 15 | fast = nums[0]; 16 | while (slow != fast) { 17 | slow = nums[slow]; 18 | fast = nums[fast]; 19 | } 20 | return slow; 21 | } 22 | } 23 | // @lc code=end 24 | 25 | -------------------------------------------------------------------------------- /java/326.power-of-three.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=326 lang=java 3 | * 4 | * [326] Power of Three 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public boolean isPowerOfThree(int n) { 10 | if (n <= 0) 11 | return false; 12 | while (n > 1) { 13 | if (n % 3 != 0) 14 | return false; 15 | n = n / 3; 16 | } 17 | return true; 18 | } 19 | } 20 | // @lc code=end 21 | 22 | -------------------------------------------------------------------------------- /java/344.reverse-string.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=344 lang=java 3 | * 4 | * [344] Reverse String 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public void reverseString(char[] s) { 10 | for (int i = 0; i < s.length / 2; i++) { 11 | char tmp = s[i]; 12 | s[i] = s[s.length - i - 1]; 13 | s[s.length - i - 1] = tmp; 14 | } 15 | } 16 | } 17 | // @lc code=end 18 | 19 | -------------------------------------------------------------------------------- /java/349.intersection-of-two-arrays.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | 4 | /* 5 | * @lc app=leetcode id=349 lang=java 6 | * 7 | * [349] Intersection of Two Arrays 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public int[] intersection(int[] nums1, int[] nums2) { 13 | HashMap hash = new HashMap<>(); 14 | ArrayList arr = new ArrayList<>(); 15 | for (int it : nums1) { 16 | hash.put(it, 1); 17 | } 18 | for (int it : nums2) { 19 | if (hash.containsKey(it)) { 20 | arr.add(it); 21 | hash.remove(it); 22 | } 23 | } 24 | int[] ans = new int[arr.size()]; 25 | for (int i = 0; i < arr.size(); i++) 26 | ans[i] = arr.get(i); 27 | return ans; 28 | } 29 | } 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /java/35.search-insert-position.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=35 lang=java 3 | * 4 | * [35] Search Insert Position 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int searchInsert(int[] nums, int target) { 10 | int l = 0, r = nums.length - 1, ans = 0; 11 | while (l <= r) { 12 | int mid = l + (r - l) / 2; 13 | if (nums[mid] == target) 14 | return mid; 15 | if (nums[mid] > target) 16 | r = mid - 1; 17 | if (nums[mid] < target) { 18 | l = mid + 1; 19 | ans = l; 20 | } 21 | } 22 | return ans; 23 | } 24 | } 25 | // @lc code=end 26 | -------------------------------------------------------------------------------- /java/350.intersection-of-two-arrays-ii.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | 4 | /* 5 | * @lc app=leetcode id=350 lang=java 6 | * 7 | * [350] Intersection of Two Arrays II 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public int[] intersect(int[] nums1, int[] nums2) { 13 | HashMap hash = new HashMap<>(); 14 | ArrayList arr = new ArrayList<>(); 15 | for (int it : nums1) { 16 | hash.merge(it, 1, Integer::sum); 17 | } 18 | for (int it : nums2) { 19 | if (hash.containsKey(it) && hash.get(it) > 0) { 20 | arr.add(it); 21 | hash.merge(it, -1, Integer::sum); 22 | } 23 | } 24 | int[] ans = new int[arr.size()]; 25 | for (int i = 0; i < arr.size(); i++) 26 | ans[i] = arr.get(i); 27 | return ans; 28 | } 29 | } 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /java/389.find-the-difference.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=389 lang=java 3 | * 4 | * [389] Find the Difference 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public char findTheDifference(String s, String t) { 10 | Map hash = new HashMap<>(); 11 | 12 | for(int i=0;i> ans = new ArrayList<>(); 13 | 14 | public List> combinationSum(int[] candidates, int target) { 15 | recurse(0, new ArrayList(), target, candidates); 16 | return ans; 17 | } 18 | 19 | private void recurse(int start, List currArr, int k, int[] arr) { 20 | if (k == 0) { 21 | ans.add(currArr); 22 | } 23 | 24 | for (int i = start; i < arr.length; i++) { 25 | if (arr[i] <= k) { 26 | List copyArr = new ArrayList<>(currArr); 27 | copyArr.add(arr[i]); 28 | recurse(i, copyArr, k - arr[i], arr); 29 | } 30 | } 31 | } 32 | 33 | } 34 | // @lc code=end -------------------------------------------------------------------------------- /java/438.find-all-anagrams-in-a-string.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=438 lang=java 3 | * 4 | * [438] Find All Anagrams in a String 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | private boolean checkMap(Map hash) { 10 | for (Character ch : hash.keySet()) { 11 | if (hash.get(ch) == 0) 12 | continue; 13 | return false; 14 | } 15 | return true; 16 | } 17 | 18 | public List findAnagrams(String s, String p) { 19 | int n = s.length(), m = p.length(); 20 | if (m > n) 21 | return new ArrayList(); 22 | Map hash = new HashMap<>(); 23 | for (Character ch : p.toCharArray()) { 24 | hash.merge(ch, 1, Integer::sum); 25 | } 26 | List ans = new ArrayList<>(); 27 | for (int i = 0; i < m; i++) { 28 | char ch = s.charAt(i); 29 | if (hash.containsKey(ch)) 30 | hash.merge(ch, -1, Integer::sum); 31 | } 32 | if (checkMap(hash)) 33 | ans.add(0); 34 | for (int i = m; i < n; i++) { 35 | char newCh = s.charAt(i), oldCh = s.charAt(i - m); 36 | if (hash.containsKey(newCh)) 37 | hash.merge(newCh, -1, Integer::sum); 38 | if (hash.containsKey(oldCh)) 39 | hash.merge(oldCh, 1, Integer::sum); 40 | if (checkMap(hash)) 41 | ans.add(i - m + 1); 42 | } 43 | return ans; 44 | } 45 | } 46 | // @lc code=end 47 | 48 | -------------------------------------------------------------------------------- /java/45.jump-game-ii.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | * @lc app=leetcode id=45 lang=java 5 | * 6 | * [45] Jump Game II 7 | */ 8 | 9 | // @lc code=start 10 | class Solution { 11 | int[] dp; 12 | 13 | private int recurse(int curr, int[] nums) { 14 | if (curr >= nums.length - 1) 15 | return 0; 16 | if (dp[curr] != -1) 17 | return dp[curr]; 18 | int min = Integer.MAX_VALUE - 1001; // To prevent overflow after summing 19 | for (int i = 1; i <= nums[curr]; i++) { 20 | min = Math.min(min, 1 + recurse(curr + i, nums)); 21 | } 22 | return dp[curr] = min; 23 | } 24 | 25 | public int jump(int[] nums) { 26 | dp = new int[10001]; 27 | Arrays.fill(dp, -1); 28 | return recurse(0, nums); 29 | } 30 | } 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /java/454.4-sum-ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=454 lang=java 3 | * 4 | * [454] 4Sum II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { 10 | Map hash = new HashMap<>(); 11 | for (int i = 0; i < nums1.length; i++) { 12 | for (int j = 0; j < nums2.length; j++) { 13 | hash.merge(nums1[i] + nums2[j], 1, Integer::sum); 14 | } 15 | } 16 | int ans = 0; 17 | for (int i = 0; i < nums3.length; i++) { 18 | for (int j = 0; j < nums4.length; j++) { 19 | int key = -1 * (nums3[i] + nums4[j]); 20 | if (hash.containsKey(key)) 21 | ans += hash.get(key); 22 | } 23 | } 24 | return ans; 25 | } 26 | } 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /java/496.next-greater-element-i.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=496 lang=java 3 | * 4 | * [496] Next Greater Element I 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int[] nextGreaterElement(int[] nums1, int[] nums2) { 10 | Stack s = new Stack<>(); 11 | Map hash = new HashMap<>(); 12 | int[] res = new int[nums1.length]; 13 | Arrays.fill(res, -1); 14 | 15 | for (int i = 0; i < nums1.length; i++) 16 | hash.put(nums1[i], i); 17 | 18 | for (int i = nums2.length - 1; i >= 0; i--) { 19 | if (!s.isEmpty() && nums2[i] < s.peek()) { 20 | if (hash.containsKey(nums2[i])) 21 | res[hash.get(nums2[i])] = s.peek(); 22 | } else { 23 | while (!s.isEmpty() && nums2[i] > s.peek()) 24 | s.pop(); 25 | if (!s.isEmpty() && hash.containsKey(nums2[i])) { 26 | res[hash.get(nums2[i])] = s.peek(); 27 | } 28 | } 29 | s.push(nums2[i]); 30 | } 31 | 32 | return res; 33 | } 34 | } 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /java/509.fibonacci-number.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | * @lc app=leetcode id=509 lang=java 5 | * 6 | * [509] Fibonacci Number 7 | */ 8 | 9 | // @lc code=start 10 | class Solution { 11 | private int dp[]; 12 | 13 | private int recurse(int n) { 14 | if (n == 0) 15 | return 0; 16 | if (n == 1) 17 | return 1; 18 | if (dp[n] != -1) 19 | return dp[n]; 20 | return dp[n] = recurse(n - 1) + recurse(n - 2); 21 | } 22 | 23 | public int fib(int n) { 24 | dp = new int[31]; 25 | Arrays.fill(dp, -1); 26 | return recurse(n); 27 | } 28 | } 29 | // @lc code=end 30 | -------------------------------------------------------------------------------- /java/525.contiguous-array.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=525 lang=java 3 | * 4 | * [525] Contiguous Array 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int findMaxLength(int[] nums) { 10 | Map hash = new HashMap<>(); 11 | 12 | int curr = 0, max = 0; 13 | 14 | for(int i=0;i hash = new HashMap<>(); 11 | int ans = 0; 12 | 13 | for (int it : nums) 14 | hash.merge(it, 1, Integer::sum); 15 | 16 | for (Map.Entry it : hash.entrySet()) { 17 | if (k == 0) { 18 | if (it.getValue() >= 2) 19 | ans++; 20 | } else if (hash.containsKey(it.getKey() + k)) { 21 | ans++; 22 | } 23 | } 24 | 25 | return ans; 26 | } 27 | } 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /java/55.jump-game.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | * @lc app=leetcode id=55 lang=java 5 | * 6 | * [55] Jump Game 7 | */ 8 | 9 | // @lc code=start 10 | class Solution { 11 | int[] dp; 12 | 13 | private boolean recurse(int curr, int[] nums) { 14 | if (curr >= nums.length - 1) 15 | return true; 16 | if (dp[curr] != -1) 17 | return dp[curr] == 1; 18 | for (int i = 1; i <= nums[curr]; i++) { 19 | if (recurse(curr + i, nums)) { 20 | dp[curr] = 1; 21 | return true; 22 | } 23 | } 24 | dp[curr] = 0; 25 | return false; 26 | } 27 | 28 | public boolean canJump(int[] nums) { 29 | dp = new int[10001]; 30 | Arrays.fill(dp, -1); 31 | return recurse(0, nums); 32 | } 33 | } 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /java/557.reverse-words-in-a-string-iii.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=557 lang=java 3 | * 4 | * [557] Reverse Words in a String III 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public String reverseWords(String s) { 10 | String ans = ""; 11 | for (int i = 0; i < s.length(); i++) { 12 | if (s.charAt(i) == ' ') 13 | continue; 14 | int j = i; 15 | String str = ""; 16 | while (j < s.length() && s.charAt(j) != ' ') { 17 | str += s.charAt(j++); 18 | } 19 | i = j - 1; 20 | str = reverseString(str); 21 | if (i == s.length() - 1) 22 | ans += str; 23 | else 24 | ans += str + ' '; 25 | } 26 | return ans; 27 | } 28 | 29 | private String reverseString(String s) { 30 | String str = ""; 31 | for (int i = s.length() - 1; i >= 0; i--) { 32 | str += s.charAt(i); 33 | } 34 | return str; 35 | } 36 | } 37 | // @lc code=end 38 | 39 | -------------------------------------------------------------------------------- /java/566.reshape-the-matrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=566 lang=java 3 | * 4 | * [566] Reshape the Matrix 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int[][] matrixReshape(int[][] mat, int r, int c) { 10 | int m = mat.length, n = mat[0].length; 11 | if (m * n != r * c) 12 | return mat; 13 | int[][] res = new int[r][c]; 14 | int i1 = 0, j1 = 0; 15 | for (int i = 0; i < m; i++) { 16 | for (int j = 0; j < n; j++) { 17 | res[i1][j1] = mat[i][j]; 18 | j1 += 1; 19 | if (j1 == c) { 20 | j1 = 0; 21 | i1 += 1; 22 | } 23 | } 24 | } 25 | return res; 26 | } 27 | } 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /java/567.permutation-in-string.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /* 5 | * @lc app=leetcode id=567 lang=java 6 | * 7 | * [567] Permutation in String 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | public boolean checkInclusion(String s1, String s2) { 13 | if (s2.length() < s1.length()) 14 | return false; 15 | Map h1 = new HashMap<>(), h2 = new HashMap<>(); 16 | int i = 0, j = 0; 17 | while (j < s1.length()) { 18 | h1.merge(s1.charAt(j), 1, Integer::sum); 19 | h2.merge(s2.charAt(j), 1, Integer::sum); 20 | j++; 21 | } 22 | j--; 23 | while (j < s2.length()) { 24 | if (h1.equals(h2)) { 25 | return true; 26 | } 27 | j++; 28 | if (j == s2.length()) 29 | break; 30 | h2.merge(s2.charAt(j), 1, Integer::sum); 31 | h2.merge(s2.charAt(i), -1, Integer::sum); 32 | if (h2.get(s2.charAt(i)) == 0) 33 | h2.remove(s2.charAt(i)); 34 | i++; 35 | } 36 | return false; 37 | } 38 | } 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /java/695.max-area-of-island.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=695 lang=java 3 | * 4 | * [695] Max Area of Island 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | int dfs(int i, int j, int[][] grid) { 10 | if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) 11 | return 0; 12 | if (grid[i][j] != 1) 13 | return 0; 14 | grid[i][j] = 2; 15 | int ans = 1; 16 | ans += dfs(i + 1, j, grid) + dfs(i - 1, j, grid) + dfs(i, j + 1, grid) + dfs(i, j - 1, grid); 17 | return ans; 18 | } 19 | 20 | public int maxAreaOfIsland(int[][] grid) { 21 | int max = 0; 22 | for (int i = 0; i < grid.length; i++) { 23 | for (int j = 0; j < grid[0].length; j++) { 24 | max = Math.max(max, dfs(i, j, grid)); 25 | } 26 | } 27 | return max; 28 | } 29 | } 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /java/70.climbing-stairs.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | * @lc app=leetcode id=70 lang=java 5 | * 6 | * [70] Climbing Stairs 7 | */ 8 | 9 | // @lc code=start 10 | class Solution { 11 | int dp[]; 12 | 13 | private int recurse(int i, int n) { 14 | if (i == n) 15 | return 1; 16 | if (dp[i] != -1) 17 | return dp[i]; 18 | int ways = 0; 19 | if (i + 1 <= n) 20 | ways += recurse(i + 1, n); 21 | if (i + 2 <= n) 22 | ways += recurse(i + 2, n); 23 | return dp[i] = ways; 24 | } 25 | 26 | public int climbStairs(int n) { 27 | dp = new int[50]; 28 | Arrays.fill(dp, -1); 29 | return recurse(0, n); 30 | } 31 | } 32 | // @lc code=end 33 | -------------------------------------------------------------------------------- /java/704.binary-search.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=704 lang=java 3 | * 4 | * [704] Binary Search 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int search(int[] nums, int target) { 10 | int l = 0, h = nums.length - 1; 11 | while (l <= h) { 12 | int mid = l + (h - l) / 2; 13 | if (nums[mid] == target) 14 | return mid; 15 | if (nums[mid] < target) 16 | l = mid + 1; 17 | if (nums[mid] > target) 18 | h = mid - 1; 19 | } 20 | return -1; 21 | } 22 | } 23 | // @lc code=end 24 | -------------------------------------------------------------------------------- /java/733.flood-fill.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=733 lang=java 3 | * 4 | * [733] Flood Fill 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | void fill(int i, int j, int oldColor, int newColor, int[][] image) { 10 | if (oldColor == newColor) 11 | return; 12 | if (i < 0 || i >= image.length || j < 0 || j >= image[0].length) 13 | return; 14 | if (image[i][j] != oldColor) 15 | return; 16 | image[i][j] = newColor; 17 | fill(i + 1, j, oldColor, newColor, image); 18 | fill(i - 1, j, oldColor, newColor, image); 19 | fill(i, j + 1, oldColor, newColor, image); 20 | fill(i, j - 1, oldColor, newColor, image); 21 | } 22 | 23 | public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { 24 | fill(sr, sc, image[sr][sc], newColor, image); 25 | return image; 26 | } 27 | } 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /java/740.delete-and-earn.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.HashMap; 3 | 4 | /* 5 | * @lc app=leetcode id=740 lang=java 6 | * 7 | * [740] Delete and Earn 8 | */ 9 | 10 | // @lc code=start 11 | class Solution { 12 | 13 | public int deleteAndEarn(int[] nums) { 14 | 15 | } 16 | } 17 | // @lc code=end 18 | 19 | -------------------------------------------------------------------------------- /java/746.min-cost-climbing-stairs.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | * @lc app=leetcode id=746 lang=java 5 | * 6 | * [746] Min Cost Climbing Stairs 7 | */ 8 | 9 | // @lc code=start 10 | class Solution { 11 | int dp[]; 12 | 13 | int recurse(int i, int[] cost) { 14 | if (i > cost.length) 15 | return Integer.MAX_VALUE - 1000; 16 | if (i == cost.length) 17 | return 0; 18 | if (dp[i] != -1) 19 | return dp[i]; 20 | return dp[i] = Math.min(cost[i] + recurse(i + 1, cost), cost[i] + recurse(i + 2, cost)); 21 | } 22 | 23 | public int minCostClimbingStairs(int[] cost) { 24 | dp = new int[1001]; 25 | Arrays.fill(dp, -1); 26 | return Math.min(recurse(0, cost), recurse(1, cost)); 27 | } 28 | } 29 | // @lc code=end 30 | -------------------------------------------------------------------------------- /java/78.subsets.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=78 lang=java 3 | * 4 | * [78] Subsets 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public List> subsets(int[] nums) { 10 | int len = nums.length; 11 | int n = (1 << len) - 1; 12 | 13 | List> ans = new ArrayList<>(); 14 | ans.add(new ArrayList()); 15 | 16 | while (n > 0) { 17 | int tmp = n; 18 | int i = len - 1; 19 | List res = new ArrayList<>(); 20 | while (tmp > 0) { 21 | if ((tmp & 1) > 0) 22 | res.add(nums[i]); 23 | tmp = tmp >> 1; 24 | i -= 1; 25 | } 26 | ans.add(res); 27 | n -= 1; 28 | } 29 | 30 | return ans; 31 | } 32 | } 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /java/80.remove-duplicates-from-sorted-array-ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=80 lang=java 3 | * 4 | * [80] Remove Duplicates from Sorted Array II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int removeDuplicates(int[] arr) { 10 | int n = arr.length, i = -1, cnt = 1; 11 | 12 | int K_VAL = 2; 13 | 14 | for (int j = 1; j < n; j++) { 15 | if (arr[j] != arr[j - 1]) 16 | cnt = 1; 17 | else 18 | cnt++; 19 | if (cnt > K_VAL && i < 0) { 20 | i = j; 21 | } else if (cnt <= K_VAL && i >= 0) { 22 | arr[i++] = arr[j]; 23 | } 24 | } 25 | return i == -1 ? n : i; 26 | } 27 | } 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /java/869.reordered-power-of-2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=869 lang=java 3 | * 4 | * [869] Reordered Power of 2 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public boolean reorderedPowerOf2(int n) { 10 | char[] c = Integer.toString(n).toCharArray(); 11 | Arrays.sort(c); 12 | for (int i = 0; i < 32; i++) { 13 | int tmp = 1 << i; 14 | char[] p = Integer.toString(tmp).toCharArray(); 15 | Arrays.sort(p); 16 | if (new String(c).equals(new String(p))) 17 | return true; 18 | } 19 | return false; 20 | } 21 | } 22 | // @lc code=end 23 | 24 | -------------------------------------------------------------------------------- /java/876.middle-of-the-linked-list.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=876 lang=java 3 | * 4 | * [876] Middle of the Linked List 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * public class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode() {} 14 | * ListNode(int val) { this.val = val; } 15 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 16 | * } 17 | */ 18 | class Solution { 19 | public ListNode middleNode(ListNode head) { 20 | ListNode slow = head, fast = head; 21 | while (fast != null && fast.next != null) { 22 | slow = slow.next; 23 | fast = fast.next.next; 24 | } 25 | return slow; 26 | } 27 | } 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /java/88.merge-sorted-array.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=88 lang=java 3 | * 4 | * [88] Merge Sorted Array 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public void merge(int[] nums1, int m, int[] nums2, int n) { 10 | int i = m - 1, j = n - 1, k = m + n - 1; 11 | while (i >= 0 && j >= 0) { 12 | if (nums1[i] >= nums2[j]) 13 | nums1[k--] = nums1[i--]; 14 | else 15 | nums1[k--] = nums2[j--]; 16 | } 17 | while (j >= 0) { 18 | nums1[k--] = nums2[j--]; 19 | } 20 | } 21 | } 22 | // @lc code=end 23 | -------------------------------------------------------------------------------- /java/92.reverse-linked-list-ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=92 lang=java 3 | * 4 | * [92] Reverse Linked List II 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * public class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode() {} 14 | * ListNode(int val) { this.val = val; } 15 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 16 | * } 17 | */ 18 | class Solution { 19 | public ListNode reverseBetween(ListNode head, int l, int r) { 20 | if (head == null || l == r) 21 | return head; 22 | ListNode beforeLeft = null, left = null, p = head; 23 | for (int i = 1; i < l - 1; i++) { 24 | if (p.next == null) 25 | break; 26 | p = p.next; 27 | } 28 | if (p == null || p.next == null) 29 | return head; 30 | if (l > 1) { 31 | beforeLeft = p; 32 | p = p.next; 33 | } 34 | left = p; 35 | ListNode slow = left, fast = left.next, ff = left.next; 36 | for (int i = l; i < r; i++) { 37 | ff = ff.next; 38 | fast.next = slow; 39 | slow = fast; 40 | fast = ff; 41 | } 42 | left.next = ff; 43 | if (l == 1) { 44 | return slow; 45 | } 46 | beforeLeft.next = slow; 47 | return head; 48 | } 49 | } 50 | // @lc code=end 51 | 52 | -------------------------------------------------------------------------------- /java/977.squares-of-a-sorted-array.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=977 lang=java 3 | * 4 | * [977] Squares of a Sorted Array 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public int[] sortedSquares(int[] nums) { 10 | int n = nums.length; 11 | int posNumPointer = 0; 12 | while (posNumPointer < n && nums[posNumPointer] < 0) { 13 | posNumPointer++; 14 | } 15 | int negNumPointer = posNumPointer - 1; 16 | int[] ans = new int[n]; 17 | int ansPointer = 0; 18 | while (negNumPointer >= 0 && posNumPointer < n) { 19 | int negSq = nums[negNumPointer] * nums[negNumPointer]; 20 | int posSq = nums[posNumPointer] * nums[posNumPointer]; 21 | if (negSq < posSq) { 22 | ans[ansPointer++] = negSq; 23 | negNumPointer--; 24 | } else { 25 | ans[ansPointer++] = posSq; 26 | posNumPointer++; 27 | } 28 | } 29 | while (negNumPointer >= 0) { 30 | int negSq = nums[negNumPointer] * nums[negNumPointer]; 31 | ans[ansPointer++] = negSq; 32 | negNumPointer--; 33 | } 34 | while (posNumPointer < n) { 35 | int posSq = nums[posNumPointer] * nums[posNumPointer]; 36 | ans[ansPointer++] = posSq; 37 | posNumPointer++; 38 | } 39 | return ans; 40 | } 41 | } 42 | // @lc code=end 43 | --------------------------------------------------------------------------------