├── the-latest-login-in-2020 └── the-latest-login-in-2020.sql ├── sum-of-two-integers ├── sum-of-two-integers.java └── README.md ├── remove-duplicates-from-sorted-array └── remove-duplicates-from-sorted-array.java ├── best-time-to-buy-and-sell-stock └── best-time-to-buy-and-sell-stock.java ├── count-sorted-vowel-strings └── count-sorted-vowel-strings.java ├── maximum-number-of-coins-you-can-get └── maximum-number-of-coins-you-can-get.java ├── two-sum └── two-sum.java ├── kth-largest-element-in-an-array ├── kth-largest-element-in-an-array.java └── README.md ├── increasing-triplet-subsequence └── increasing-triplet-subsequence.java ├── check-if-string-is-a-prefix-of-array └── check-if-string-is-a-prefix-of-array.java ├── shifting-letters ├── shifting-letters.java └── README.md ├── divide-two-integers └── divide-two-integers.java ├── first-unique-character-in-a-string ├── first-unique-character-in-a-string.java └── README.md ├── reduction-operations-to-make-the-array-elements-equal └── reduction-operations-to-make-the-array-elements-equal.java ├── subarray-product-less-than-k ├── subarray-product-less-than-k.java └── README.md ├── move-zeroes ├── move-zeroes.java └── README.md ├── daily-temperatures ├── daily-temperatures.java └── README.md ├── minimum-number-of-swaps-to-make-the-string-balanced └── minimum-number-of-swaps-to-make-the-string-balanced.java ├── three-divisors ├── three-divisors.java └── README.md ├── subarray-sum-equals-k ├── subarray-sum-equals-k.java └── README.md ├── product-of-array-except-self └── product-of-array-except-self.java ├── find-pivot-index └── find-pivot-index.java ├── count-binary-substrings └── count-binary-substrings.java ├── arranging-coins ├── arranging-coins.java └── README.md ├── car-pooling └── car-pooling.java ├── generate-parentheses └── README.md ├── largest-odd-number-in-string └── largest-odd-number-in-string.java ├── pairs-of-songs-with-total-durations-divisible-by-60 └── pairs-of-songs-with-total-durations-divisible-by-60.java ├── reveal-cards-in-increasing-order └── reveal-cards-in-increasing-order.java ├── rabbits-in-forest ├── rabbits-in-forest.java └── README.md ├── path-in-zigzag-labelled-binary-tree ├── path-in-zigzag-labelled-binary-tree.java └── README.md ├── longest-line-of-consecutive-one-in-matrix └── README.md ├── maximum-length-of-repeated-subarray └── maximum-length-of-repeated-subarray.java ├── add-minimum-number-of-rungs └── add-minimum-number-of-rungs.java ├── container-with-most-water └── container-with-most-water.java ├── score-of-parentheses ├── score-of-parentheses.java └── README.md ├── fruit-into-baskets └── fruit-into-baskets.java ├── redistribute-characters-to-make-all-strings-equal └── redistribute-characters-to-make-all-strings-equal.java ├── largest-number-after-mutating-substring └── largest-number-after-mutating-substring.java ├── count-square-submatrices-with-all-ones ├── count-square-submatrices-with-all-ones.java └── README.md ├── partition-labels ├── partition-labels.java └── README.md ├── linked-list-cycle └── linked-list-cycle.java ├── longest-common-subsequence └── longest-common-subsequence.java ├── minimum-cost-to-connect-sticks └── minimum-cost-to-connect-sticks.java ├── sum-of-digits-of-string-after-convert └── sum-of-digits-of-string-after-convert.java ├── valid-palindrome ├── valid-palindrome.java └── README.md ├── 4sum-ii └── 4sum-ii.java ├── goal-parser-interpretation └── goal-parser-interpretation.java ├── maximum-units-on-a-truck └── maximum-units-on-a-truck.java ├── convert-1d-array-into-2d-array └── convert-1d-array-into-2d-array.java ├── longer-contiguous-segments-of-ones-than-zeros └── longer-contiguous-segments-of-ones-than-zeros.java ├── koko-eating-bananas └── koko-eating-bananas.java ├── largest-rectangle-in-histogram ├── largest-rectangle-in-histogram.java └── README.md ├── permutation-in-string ├── permutation-in-string.java └── README.md ├── check-if-word-equals-summation-of-two-words └── check-if-word-equals-summation-of-two-words.java ├── eliminate-maximum-number-of-monsters └── eliminate-maximum-number-of-monsters.java ├── reverse-linked-list ├── reverse-linked-list.java └── README.md ├── shortest-word-distance ├── shortest-word-distance.java └── README.md ├── longest-substring-of-all-vowels-in-order └── longest-substring-of-all-vowels-in-order.java ├── reorganize-string └── README.md ├── valid-parentheses └── valid-parentheses.java ├── maximum-swap └── README.md ├── reverse-integer ├── reverse-integer.java └── README.md ├── robot-bounded-in-circle └── robot-bounded-in-circle.java ├── add-strings ├── add-strings.java └── README.md ├── valid-palindrome-ii ├── valid-palindrome-ii.java └── README.md ├── trapping-rain-water ├── trapping-rain-water.java └── README.md ├── repeated-substring-pattern ├── repeated-substring-pattern.java └── README.md ├── meeting-rooms-ii └── README.md ├── roman-to-integer └── roman-to-integer.java ├── invert-binary-tree ├── invert-binary-tree.java └── README.md ├── count-and-say └── count-and-say.java ├── palindromic-substrings ├── README.md └── palindromic-substrings.java ├── sort-colors └── sort-colors.java ├── jump-game-vii └── jump-game-vii.java ├── moving-average-from-data-stream └── moving-average-from-data-stream.java ├── find-the-smallest-divisor-given-a-threshold └── find-the-smallest-divisor-given-a-threshold.java ├── number-of-provinces └── number-of-provinces.java ├── keys-and-rooms └── keys-and-rooms.java ├── find-all-duplicates-in-an-array ├── find-all-duplicates-in-an-array.java └── README.md ├── partition-array-into-disjoint-intervals └── partition-array-into-disjoint-intervals.java ├── kill-process └── kill-process.java ├── palindrome-partitioning └── README.md ├── frequency-of-the-most-frequent-element └── frequency-of-the-most-frequent-element.java ├── insert-interval └── insert-interval.java ├── find-peak-element └── find-peak-element.java ├── flip-equivalent-binary-trees └── flip-equivalent-binary-trees.java ├── k-closest-points-to-origin └── k-closest-points-to-origin.java ├── leftmost-column-with-at-least-a-one └── leftmost-column-with-at-least-a-one.java ├── subsets ├── README.md └── subsets.java ├── intersection-of-two-arrays-ii └── intersection-of-two-arrays-ii.java ├── permutations └── README.md ├── least-number-of-unique-integers-after-k-removals ├── least-number-of-unique-integers-after-k-removals.java └── README.md ├── count-good-numbers └── count-good-numbers.java ├── first-missing-positive └── README.md ├── group-shifted-strings ├── group-shifted-strings.java └── README.md ├── number-of-pairs-of-strings-with-concatenation-equal-to-target └── number-of-pairs-of-strings-with-concatenation-equal-to-target.java ├── partition-to-k-equal-sum-subsets └── README.md ├── next-greater-element-iii └── README.md ├── maximum-number-of-words-you-can-type └── maximum-number-of-words-you-can-type.java ├── merge-triplets-to-form-target-triplet └── merge-triplets-to-form-target-triplet.java ├── number-of-good-ways-to-split-a-string └── number-of-good-ways-to-split-a-string.java ├── 3sum ├── README.md └── 3sum.java ├── inorder-successor-in-bst └── inorder-successor-in-bst.java ├── partition-equal-subset-sum ├── README.md └── partition-equal-subset-sum.java ├── is-graph-bipartite └── is-graph-bipartite.java ├── car-fleet └── car-fleet.java ├── diameter-of-binary-tree ├── diameter-of-binary-tree.java └── README.md ├── perfect-squares └── README.md ├── remove-stones-to-minimize-the-total └── remove-stones-to-minimize-the-total.java ├── binary-tree-inorder-traversal └── binary-tree-inorder-traversal.java ├── path-with-maximum-gold └── path-with-maximum-gold.java ├── time-based-key-value-store └── time-based-key-value-store.java ├── compare-version-numbers └── compare-version-numbers.java ├── count-good-nodes-in-binary-tree └── count-good-nodes-in-binary-tree.java ├── longest-palindromic-substring ├── README.md └── longest-palindromic-substring.java ├── print-words-vertically └── print-words-vertically.java ├── employee-importance └── employee-importance.java ├── maximum-population-year └── maximum-population-year.java ├── minimum-number-of-frogs-croaking └── minimum-number-of-frogs-croaking.java ├── binary-tree-right-side-view └── README.md ├── pancake-sorting └── pancake-sorting.java ├── top-k-frequent-elements └── README.md ├── construct-binary-tree-from-preorder-and-postorder-traversal └── README.md ├── shuffle-an-array └── shuffle-an-array.java ├── remove-duplicates-from-sorted-list-ii ├── remove-duplicates-from-sorted-list-ii.java └── README.md ├── binary-tree-zigzag-level-order-traversal └── README.md ├── lowest-common-ancestor-of-a-binary-tree └── lowest-common-ancestor-of-a-binary-tree.java ├── group-anagrams └── README.md ├── minimum-path-sum └── README.md ├── max-area-of-island ├── README.md └── max-area-of-island.java ├── binary-tree-level-order-traversal ├── README.md └── binary-tree-level-order-traversal.java ├── merge-intervals ├── README.md └── merge-intervals.java ├── number-of-closed-islands └── number-of-closed-islands.java ├── asteroid-collision └── asteroid-collision.java ├── minimum-window-substring └── README.md ├── subdomain-visit-count └── subdomain-visit-count.java ├── task-scheduler └── task-scheduler.java ├── remove-all-adjacent-duplicates-in-string-ii └── remove-all-adjacent-duplicates-in-string-ii.java ├── sliding-window-maximum └── sliding-window-maximum.java ├── two-sum-ii-input-array-is-sorted └── two-sum-ii-input-array-is-sorted.java ├── longest-univalue-path ├── longest-univalue-path.java └── README.md ├── minimum-time-to-collect-all-apples-in-a-tree └── minimum-time-to-collect-all-apples-in-a-tree.java ├── two-sum-bsts └── README.md ├── sentence-screen-fitting └── sentence-screen-fitting.java ├── odd-even-linked-list └── odd-even-linked-list.java ├── letter-combinations-of-a-phone-number ├── letter-combinations-of-a-phone-number.java └── README.md ├── n-queens └── README.md ├── number-of-connected-components-in-an-undirected-graph └── number-of-connected-components-in-an-undirected-graph.java ├── basic-calculator-ii ├── README.md └── basic-calculator-ii.java ├── delete-nodes-and-return-forest ├── delete-nodes-and-return-forest.java └── README.md ├── maximum-product-subarray └── README.md ├── shortest-bridge └── README.md ├── verifying-an-alien-dictionary └── verifying-an-alien-dictionary.java ├── corporate-flight-bookings └── corporate-flight-bookings.java ├── minimum-knight-moves └── minimum-knight-moves.java ├── number-of-islands └── README.md ├── set-matrix-zeroes └── set-matrix-zeroes.java ├── find-and-replace-in-string └── find-and-replace-in-string.java ├── the-kth-factor-of-n └── the-kth-factor-of-n.java ├── 01-matrix └── README.md ├── kth-smallest-element-in-a-bst └── README.md ├── maximum-value-after-insertion └── maximum-value-after-insertion.java ├── invalid-transactions └── invalid-transactions.java ├── reformat-phone-number └── reformat-phone-number.java ├── degree-of-an-array └── degree-of-an-array.java ├── maximum-distance-between-a-pair-of-values └── maximum-distance-between-a-pair-of-values.java └── longest-substring-without-repeating-characters └── README.md /the-latest-login-in-2020/the-latest-login-in-2020.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT 3 | user_id, 4 | MAX(time_stamp) AS last_stamp 5 | FROM Logins 6 | WHERE time_stamp LIKE '2020%' 7 | GROUP BY user_id -------------------------------------------------------------------------------- /sum-of-two-integers/sum-of-two-integers.java: -------------------------------------------------------------------------------- 1 | // Time: O(1) 2 | // Space: O(1) 3 | class Solution { 4 | public int getSum(int a, int b) { 5 | while (b != 0) { 6 | int answer = a ^ b; 7 | int carry = (a & b) << 1; 8 | a = answer; 9 | b = carry; 10 | } 11 | return a; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int removeDuplicates(int[] nums) { 6 | int idx = 1; 7 | for (int i = 1; i < nums.length; i++) { 8 | if (nums[i] > nums[i - 1]) 9 | nums[idx++] = nums[i]; 10 | } 11 | return idx; 12 | } 13 | } -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.java: -------------------------------------------------------------------------------- 1 | // n = prices.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int maxProfit(int[] prices) { 6 | int min = Integer.MAX_VALUE; 7 | int max = 0; 8 | for (int num : prices) { 9 | max = Math.max(max, num - min); 10 | if (num < min) min = num; 11 | } 12 | 13 | return max; 14 | } 15 | } -------------------------------------------------------------------------------- /count-sorted-vowel-strings/count-sorted-vowel-strings.java: -------------------------------------------------------------------------------- 1 | // Time: O(n^2) 2 | // Space: O(1) 3 | class Solution { 4 | public int countVowelStrings(int n) { 5 | int result = 0; 6 | for (int i = 0; i <= n; i++) { 7 | int curr = 0; 8 | for (int j = 0; j <= i; j++) { 9 | curr += j + 1; 10 | result += curr; 11 | } 12 | } 13 | return result; 14 | } 15 | } -------------------------------------------------------------------------------- /maximum-number-of-coins-you-can-get/maximum-number-of-coins-you-can-get.java: -------------------------------------------------------------------------------- 1 | // n = piles.length 2 | // Time: O(n log n) 3 | // Space: O(n) 4 | class Solution { 5 | public int maxCoins(int[] piles) { 6 | Arrays.sort(piles); 7 | 8 | int coins = 0; 9 | for (int i = piles.length - 2; i >= piles.length / 3; i -= 2){ 10 | coins += piles[i]; 11 | } 12 | 13 | return coins; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /two-sum/two-sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | Map map = new HashMap<>(); 4 | for (int i = 0; i < nums.length; i++) { 5 | if (map.containsKey(target - nums[i])) { 6 | return new int[]{map.get(target - nums[i]), i}; 7 | } else { 8 | map.put(nums[i], i); 9 | } 10 | } 11 | return new int[2]; 12 | } 13 | } -------------------------------------------------------------------------------- /kth-largest-element-in-an-array/kth-largest-element-in-an-array.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n log k) 3 | // Space: O(k) 4 | class Solution { 5 | public int findKthLargest(int[] nums, int k) { 6 | PriorityQueue minHeap = new PriorityQueue<>(); 7 | for (int num : nums) { 8 | minHeap.offer(num); 9 | if (minHeap.size() > k) minHeap.poll(); 10 | } 11 | 12 | return minHeap.poll(); 13 | } 14 | } -------------------------------------------------------------------------------- /increasing-triplet-subsequence/increasing-triplet-subsequence.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public boolean increasingTriplet(int[] nums) { 6 | int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE; 7 | for (int num : nums) { 8 | if (num > second) return true; 9 | if (num < first) first = num; 10 | if (num > first) second = num; 11 | } 12 | return false; 13 | } 14 | } -------------------------------------------------------------------------------- /check-if-string-is-a-prefix-of-array/check-if-string-is-a-prefix-of-array.java: -------------------------------------------------------------------------------- 1 | // n = words.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public boolean isPrefixString(String s, String[] words) { 6 | StringBuilder sb = new StringBuilder(); 7 | for (String word : words) { 8 | sb.append(word); 9 | if (sb.toString().equals(s)) { 10 | return true; 11 | } 12 | } 13 | return false; 14 | } 15 | } -------------------------------------------------------------------------------- /shifting-letters/shifting-letters.java: -------------------------------------------------------------------------------- 1 | // n = s.length() = shifts.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public String shiftingLetters(String s, int[] shifts) { 6 | char[] arr = s.toCharArray(); 7 | long shiftSum = 0; 8 | for (int i = arr.length - 1; i >= 0; i--) { 9 | shiftSum = (shiftSum + shifts[i]) % 26; 10 | arr[i] = (char)((arr[i] - 'a' + shiftSum) % 26 + 'a'); 11 | } 12 | return new String(arr); 13 | } 14 | } -------------------------------------------------------------------------------- /divide-two-integers/divide-two-integers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int divide(int dividend, int divisor) { 3 | if (dividend == 1 << 31 && divisor == -1) return (1 << 31) - 1; 4 | int a = Math.abs(dividend), b = Math.abs(divisor), res = 0; 5 | for (int x = 31; x >= 0; x--) { 6 | if ((a >>> x) - b >= 0) { 7 | res += 1 << x; 8 | a -= b << x; 9 | } 10 | } 11 | return (dividend > 0) == (divisor > 0) ? res : -res; 12 | } 13 | } -------------------------------------------------------------------------------- /first-unique-character-in-a-string/first-unique-character-in-a-string.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int firstUniqChar(String s) { 6 | int[] lib = new int[26]; 7 | 8 | for (char c : s.toCharArray()) 9 | lib[c - 'a']++; 10 | 11 | for (int i = 0; i < s.length(); i++) { 12 | if (lib[s.charAt(i) - 'a'] == 1) 13 | return i; 14 | } 15 | 16 | return -1; 17 | } 18 | } -------------------------------------------------------------------------------- /reduction-operations-to-make-the-array-elements-equal/reduction-operations-to-make-the-array-elements-equal.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(nlogn) 3 | // Space: O(n) 4 | class Solution { 5 | public int reductionOperations(int[] nums) { 6 | Arrays.sort(nums); 7 | int n = nums.length; 8 | int count = 0; 9 | for (int i = n - 1; i >= 1; i--) { 10 | if (nums[i] != nums[i - 1]) { 11 | count += n - i; 12 | } 13 | } 14 | return count; 15 | } 16 | } -------------------------------------------------------------------------------- /subarray-product-less-than-k/subarray-product-less-than-k.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int numSubarrayProductLessThanK(int[] nums, int k) { 6 | if (k <= 1) return 0; 7 | int prod = 1, count = 0, left = 0; 8 | for (int right = 0; right < nums.length; right++) { 9 | prod *= nums[right]; 10 | while (prod >= k) prod /= nums[left++]; 11 | count += right - left + 1; 12 | } 13 | return count; 14 | } 15 | } -------------------------------------------------------------------------------- /move-zeroes/move-zeroes.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public void moveZeroes(int[] nums) { 6 | int n = nums.length; 7 | int left = 0; 8 | for (int i = 0; i < n; i++) { 9 | if (nums[i] != 0 && i == left) { 10 | left++; 11 | continue; 12 | } 13 | if (nums[i] != 0 && i != left) { 14 | nums[left++] = nums[i]; 15 | nums[i] = 0; 16 | } 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /daily-temperatures/daily-temperatures.java: -------------------------------------------------------------------------------- 1 | // n = T.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int[] dailyTemperatures(int[] T) { 6 | Stack stack = new Stack<>(); 7 | int[] result = new int[T.length]; 8 | for (int i = 0; i < T.length; i++) { 9 | while (!stack.isEmpty() && T[i] > T[stack.peek()]) { 10 | int day = stack.pop(); 11 | result[day] = i - day; 12 | } 13 | stack.push(i); 14 | } 15 | return result; 16 | } 17 | } -------------------------------------------------------------------------------- /minimum-number-of-swaps-to-make-the-string-balanced/minimum-number-of-swaps-to-make-the-string-balanced.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int minSwaps(String s) { 6 | int n = s.length(); 7 | int count = 0, max = 0; 8 | for (int i = 0; i < n; i++) { 9 | if (s.charAt(i) == ']') { 10 | count++; 11 | } else { 12 | count--; 13 | } 14 | max = Math.max(max, count); 15 | } 16 | return (max + 1) / 2; 17 | } 18 | } -------------------------------------------------------------------------------- /three-divisors/three-divisors.java: -------------------------------------------------------------------------------- 1 | // Time: O(n) 2 | // Space: O(n) 3 | class Solution { 4 | public boolean isThree(int n) { 5 | Set divisors = new HashSet<>(); 6 | int div = 1; 7 | while (div <= n) { 8 | int num = n / div; 9 | int r = n % div; 10 | if (r == 0) { 11 | divisors.add(num); 12 | } 13 | if (divisors.size() > 3) { 14 | return false; 15 | } 16 | div++; 17 | } 18 | return divisors.size() == 3; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /subarray-sum-equals-k/subarray-sum-equals-k.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int subarraySum(int[] nums, int k) { 6 | int result = 0, sum = 0; 7 | Map map = new HashMap<>(); 8 | map.put(0, 1); 9 | for (int num : nums) { 10 | sum += num; 11 | if (map.containsKey(sum - k)) { 12 | result += map.get(sum - k); 13 | } 14 | map.put(sum, map.getOrDefault(sum, 0) + 1); 15 | } 16 | return result; 17 | } 18 | } -------------------------------------------------------------------------------- /product-of-array-except-self/product-of-array-except-self.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int[] productExceptSelf(int[] nums) { 6 | int n = nums.length; 7 | int[] result = new int[n]; 8 | result[0] = 1; 9 | for (int i = 1; i < n; i++) { 10 | result[i] = nums[i - 1] * result[i - 1]; 11 | } 12 | int prev = 1; 13 | for (int i = n - 1; i >= 0; i--) { 14 | result[i] = prev * result[i]; 15 | prev *= nums[i]; 16 | } 17 | return result; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /find-pivot-index/find-pivot-index.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int pivotIndex(int[] nums) { 6 | int totalSum = 0; 7 | for (int num : nums) 8 | totalSum += num; 9 | 10 | int runningSum = 0; 11 | int prevSum = 0; 12 | for (int i = 0; i < nums.length; i++) { 13 | runningSum += nums[i]; 14 | if (prevSum == totalSum - runningSum) { 15 | return i; 16 | } 17 | prevSum += nums[i]; 18 | } 19 | 20 | return -1; 21 | } 22 | } -------------------------------------------------------------------------------- /count-binary-substrings/count-binary-substrings.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int countBinarySubstrings(String s) { 6 | int result = 0; 7 | int prev = 0; 8 | int curr = 1; 9 | for (int i = 1; i < s.length(); i++) { 10 | if (s.charAt(i) == s.charAt(i - 1)) { 11 | curr++; 12 | } else { 13 | result += Math.min(prev, curr); 14 | prev = curr; 15 | curr = 1; 16 | } 17 | } 18 | return result + Math.min(prev, curr); 19 | } 20 | } -------------------------------------------------------------------------------- /arranging-coins/arranging-coins.java: -------------------------------------------------------------------------------- 1 | // n >= k(k+1)/2 2 | // Time: O(logn) 3 | // Space: O(1) 4 | class Solution { 5 | public int arrangeCoins(int n) { 6 | long left = 0, right = n; 7 | long k, curr; 8 | while (left <= right) { 9 | k = left + (right - left) / 2; 10 | curr = k * (k + 1) / 2; 11 | if (curr == n) { 12 | return (int) k; 13 | } 14 | 15 | if (n < curr) { 16 | right = k - 1; 17 | } else { 18 | left = k + 1; 19 | } 20 | } 21 | return (int) right; 22 | } 23 | } -------------------------------------------------------------------------------- /car-pooling/car-pooling.java: -------------------------------------------------------------------------------- 1 | // n = trips.length 2 | // Time: O(max(n, 1001)) 3 | // Space: O(1001) = O(1) 4 | class Solution { 5 | public boolean carPooling(int[][] trips, int capacity) { 6 | int[] timestamp = new int[1001]; 7 | for (int[] trip : trips) { 8 | timestamp[trip[1]] += trip[0]; 9 | timestamp[trip[2]] -= trip[0]; 10 | } 11 | int passengerCount = 0; 12 | for (int num : timestamp) { 13 | passengerCount += num; 14 | if (passengerCount > capacity) { 15 | return false; 16 | } 17 | } 18 | return true; 19 | } 20 | } -------------------------------------------------------------------------------- /generate-parentheses/README.md: -------------------------------------------------------------------------------- 1 |

22. Generate Parentheses

Medium


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

2 | 3 |

 

4 |

Example 1:

5 |
Input: n = 3
 6 | Output: ["((()))","(()())","(())()","()(())","()()()"]
 7 | 

Example 2:

8 |
Input: n = 1
 9 | Output: ["()"]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= n <= 8
  • 16 |
17 |
-------------------------------------------------------------------------------- /largest-odd-number-in-string/largest-odd-number-in-string.java: -------------------------------------------------------------------------------- 1 | // n = num.length() 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public String largestOddNumber(String num) { 6 | StringBuilder sb = new StringBuilder(); 7 | boolean oddFound = false; 8 | for (int i = num.length() - 1; i >= 0; i--) { 9 | if (oddFound) { 10 | sb.insert(0, num.charAt(i)); 11 | } else if (!oddFound && (num.charAt(i) - '0') % 2 != 0) { 12 | sb.insert(0, num.charAt(i)); 13 | oddFound = true; 14 | } 15 | } 16 | return sb.toString(); 17 | } 18 | } -------------------------------------------------------------------------------- /pairs-of-songs-with-total-durations-divisible-by-60/pairs-of-songs-with-total-durations-divisible-by-60.java: -------------------------------------------------------------------------------- 1 | // n = time.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int numPairsDivisibleBy60(int[] time) { 6 | Map map = new HashMap<>(); 7 | int count = 0; 8 | for (int t : time) { 9 | for (int i = 60; i <= 960; i += 60) { 10 | if (map.containsKey(i - t)) { 11 | count += map.get(i - t); 12 | } 13 | } 14 | map.put(t, map.getOrDefault(t, 0) + 1); 15 | } 16 | return count; 17 | } 18 | } -------------------------------------------------------------------------------- /reveal-cards-in-increasing-order/reveal-cards-in-increasing-order.java: -------------------------------------------------------------------------------- 1 | // n = deck.length 2 | // Time: O(nlogn) 3 | // Space: O(n) 4 | class Solution { 5 | public int[] deckRevealedIncreasing(int[] deck) { 6 | int n = deck.length; 7 | Arrays.sort(deck); 8 | 9 | Queue q = new LinkedList<>(); 10 | for (int i = 0; i < n; i++) { 11 | q.add(i); 12 | } 13 | 14 | int[] result = new int[n]; 15 | for (int i = 0; i < n; i++) { 16 | result[q.poll()] = deck[i]; 17 | q.add(q.poll()); 18 | } 19 | 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /rabbits-in-forest/rabbits-in-forest.java: -------------------------------------------------------------------------------- 1 | // n = answers.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int numRabbits(int[] answers) { 6 | Map map = new HashMap<>(); 7 | int count = 0; 8 | for (int num : answers) { 9 | if (num != 0) { 10 | map.put(num, map.getOrDefault(num, -1) + 1); 11 | if (map.get(num) > num) map.put(num, 0); 12 | } 13 | count++; 14 | } 15 | 16 | for (int key : map.keySet()) 17 | count += key - map.get(key); 18 | 19 | return count; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /path-in-zigzag-labelled-binary-tree/path-in-zigzag-labelled-binary-tree.java: -------------------------------------------------------------------------------- 1 | // Time: O(logn) 2 | // Space: O(logn) 3 | class Solution { 4 | public List pathInZigZagTree(int label) { 5 | LinkedList result = new LinkedList<>(); 6 | int parent = label; 7 | result.addFirst(parent); 8 | 9 | while(parent != 1) { 10 | int depth = (int)(Math.log(parent)/Math.log(2)); 11 | int offset = (int)Math.pow(2, depth + 1) - 1 - parent; 12 | parent = ((int)Math.pow(2, depth) + offset) / 2; 13 | result.addFirst(parent); 14 | } 15 | 16 | return result; 17 | } 18 | } -------------------------------------------------------------------------------- /longest-line-of-consecutive-one-in-matrix/README.md: -------------------------------------------------------------------------------- 1 | [Discussion Post (created on 21/3/2021 at 11:47)](https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/solution/) 2 |

562. Longest Line of Consecutive One in Matrix

Medium


Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal. 3 | 4 |

Example:
5 |

Input:
 6 | [[0,1,1,0],
 7 |  [0,1,1,0],
 8 |  [0,0,0,1]]
 9 | Output: 3
10 | 
11 |

12 | 13 |

14 | Hint: 15 | The number of elements in the given matrix will not exceed 10,000. 16 |

-------------------------------------------------------------------------------- /maximum-length-of-repeated-subarray/maximum-length-of-repeated-subarray.java: -------------------------------------------------------------------------------- 1 | // m = A.length, n = B.length 2 | // Time: O(m * n) 3 | // Space: O(m * n) 4 | class Solution { 5 | public int findLength(int[] A, int[] B) { 6 | int m = A.length, n = B.length; 7 | int max = 0; 8 | int[][] dp = new int[m + 1][n + 1]; 9 | for (int i = 1; i <= m; i++) { 10 | for (int j = 1; j <= n; j++) { 11 | if (A[i - 1] == B[j - 1]) { 12 | dp[i][j] = 1 + dp[i - 1][j - 1]; 13 | max = Math.max(max, dp[i][j]); 14 | } 15 | } 16 | } 17 | return max; 18 | } 19 | } -------------------------------------------------------------------------------- /sum-of-two-integers/README.md: -------------------------------------------------------------------------------- 1 |

371. Sum of Two Integers

Medium


Given two integers a and b, return the sum of the two integers without using the operators + and -.

2 | 3 |

 

4 |

Example 1:

5 |
Input: a = 1, b = 2
 6 | Output: 3
 7 | 

Example 2:

8 |
Input: a = 2, b = 3
 9 | Output: 5
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • -1000 <= a, b <= 1000
  • 16 |
17 |
-------------------------------------------------------------------------------- /add-minimum-number-of-rungs/add-minimum-number-of-rungs.java: -------------------------------------------------------------------------------- 1 | // n = rungs.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int addRungs(int[] rungs, int dist) { 6 | int curr = 0; 7 | int xtraRungs = 0; 8 | for (int i = 0; i < rungs.length; i++) { 9 | if (rungs[i] - curr > dist) { 10 | int rungsToAdd = (rungs[i] - curr) / dist; 11 | if (curr + rungsToAdd * dist == rungs[i]) { 12 | rungsToAdd--; 13 | } 14 | xtraRungs += rungsToAdd; 15 | } 16 | curr = rungs[i]; 17 | } 18 | return xtraRungs; 19 | } 20 | } -------------------------------------------------------------------------------- /container-with-most-water/container-with-most-water.java: -------------------------------------------------------------------------------- 1 | // n = height.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int maxArea(int[] height) { 6 | int n = height.length; 7 | int left = 0, right = n - 1; 8 | int maxArea = 0; 9 | while (left < right) { 10 | int currHeight = Math.min(height[left], height[right]); 11 | int area = currHeight * (right - left); 12 | maxArea = Math.max(maxArea, area); 13 | 14 | if (height[left] <= height[right]) 15 | left++; 16 | else 17 | right--; 18 | } 19 | return maxArea; 20 | } 21 | } -------------------------------------------------------------------------------- /score-of-parentheses/score-of-parentheses.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | int i = 0; 6 | public int scoreOfParentheses(String s) { 7 | int score = 0; 8 | while (i < s.length()) { 9 | char c = s.charAt(i); 10 | i++; 11 | if (c == '(') { 12 | if (s.charAt(i) == ')') { 13 | score++; 14 | i++; 15 | } else { 16 | score += 2 * scoreOfParentheses(s); 17 | } 18 | } else { 19 | return score; 20 | } 21 | } 22 | return score; 23 | } 24 | } -------------------------------------------------------------------------------- /fruit-into-baskets/fruit-into-baskets.java: -------------------------------------------------------------------------------- 1 | // n = tree.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int totalFruit(int[] tree) { 6 | Map map = new HashMap<>(); 7 | int max = 0; 8 | for (int i = 0, j = 0; i < tree.length; i++) { 9 | map.put(tree[i], map.getOrDefault(tree[i], 0) + 1); 10 | if (map.size() <= 2) max = Math.max(max, i - j + 1); 11 | while (map.size() > 2) { 12 | map.put(tree[j], map.get(tree[j]) - 1); 13 | if (map.get(tree[j]) == 0) map.remove(tree[j]); 14 | j++; 15 | } 16 | } 17 | return max; 18 | } 19 | } -------------------------------------------------------------------------------- /redistribute-characters-to-make-all-strings-equal/redistribute-characters-to-make-all-strings-equal.java: -------------------------------------------------------------------------------- 1 | // n = words.length, c = max characters in words[i] 2 | // Time: O(n * c) 3 | // Space: O(n * c) 4 | class Solution { 5 | public boolean makeEqual(String[] words) { 6 | Map map = new HashMap<>(); 7 | for (String word : words) { 8 | for (char c : word.toCharArray()) { 9 | map.put(c, map.getOrDefault(c, 0) + 1); 10 | } 11 | } 12 | for (int value : map.values()) { 13 | if (value % words.length != 0) { 14 | return false; 15 | } 16 | } 17 | return true; 18 | } 19 | } -------------------------------------------------------------------------------- /largest-number-after-mutating-substring/largest-number-after-mutating-substring.java: -------------------------------------------------------------------------------- 1 | // n = num.length(); 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public String maximumNumber(String num, int[] change) { 6 | char[] arr = num.toCharArray(); 7 | int prev = 0; 8 | boolean isSub = false; 9 | for (int i = 0; i < arr.length; i++) { 10 | int n = arr[i] - '0'; 11 | if (n < change[n] || n == change[n] && isSub) { 12 | arr[i] = (char) (change[n] + '0'); 13 | isSub = true; 14 | } else if (isSub) { 15 | break; 16 | } 17 | } 18 | return new String(arr); 19 | } 20 | } -------------------------------------------------------------------------------- /count-square-submatrices-with-all-ones/count-square-submatrices-with-all-ones.java: -------------------------------------------------------------------------------- 1 | // Time: O(m*n) 2 | // Space: O(1) 3 | class Solution { 4 | public int countSquares(int[][] matrix) { 5 | int ans = 0; 6 | for (int i = 0; i < matrix.length; i++) { 7 | for (int j = 0; j < matrix[0].length; j++) { 8 | if (matrix[i][j]==1 && i-1>=0 && j-1 >= 0 && matrix[i-1][j-1] != 0 9 | && matrix[i-1][j] != 0 && matrix[i][j-1] != 0) { 10 | matrix[i][j] = Math.min(Math.min(matrix[i-1][j-1], matrix[i-1][j]), matrix[i][j-1]) + 1; 11 | } 12 | ans += matrix[i][j]; 13 | } 14 | } 15 | return ans; 16 | } 17 | } -------------------------------------------------------------------------------- /partition-labels/partition-labels.java: -------------------------------------------------------------------------------- 1 | // n = S.length() 2 | // Time = O(n) 3 | // Space = O(1) 4 | class Solution { 5 | public List partitionLabels(String S) { 6 | List result = new ArrayList<>(); 7 | int[] map = new int[26]; 8 | 9 | for (int i = 0; i < S.length(); i++) 10 | map[S.charAt(i) - 'a'] = i; 11 | 12 | int start = 0, lead = 0; 13 | for (int i = 0; i < S.length(); i++) { 14 | lead = Math.max(lead, map[S.charAt(i) - 'a']); 15 | if (lead == i) { 16 | result.add(lead - start + 1); 17 | start = i + 1; 18 | } 19 | } 20 | 21 | return result; 22 | } 23 | } -------------------------------------------------------------------------------- /linked-list-cycle/linked-list-cycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | 13 | // n = number of nodes 14 | // Time: O(n) 15 | // Space: O(1) 16 | public class Solution { 17 | public boolean hasCycle(ListNode head) { 18 | ListNode slow = head; 19 | ListNode fast = head; 20 | 21 | while (fast != null && fast.next != null) { 22 | slow = slow.next; 23 | fast = fast.next.next; 24 | if (slow == fast) return true; 25 | } 26 | 27 | return false; 28 | } 29 | } -------------------------------------------------------------------------------- /longest-common-subsequence/longest-common-subsequence.java: -------------------------------------------------------------------------------- 1 | // m = text1.length(), n = text2.length() 2 | // Time: O(m * n) 3 | // Space: O(m * n) 4 | class Solution { 5 | public int longestCommonSubsequence(String text1, String text2) { 6 | int m = text1.length(), n = text2.length(); 7 | int[][] dp = new int[m + 1][n + 1]; 8 | for (int i = 1; i <= m; i++) { 9 | for (int j = 1; j <= n; j++) { 10 | if (text1.charAt(i - 1) == text2.charAt(j - 1)) { 11 | dp[i][j] = 1 + dp[i - 1][j - 1]; 12 | } else { 13 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 14 | } 15 | } 16 | } 17 | return dp[m][n]; 18 | } 19 | } -------------------------------------------------------------------------------- /minimum-cost-to-connect-sticks/minimum-cost-to-connect-sticks.java: -------------------------------------------------------------------------------- 1 | // n = sticks.length 2 | // Time: O(n log n) 3 | // Space: O(n) 4 | class Solution { 5 | public int connectSticks(int[] sticks) { 6 | int totalCost = 0; 7 | PriorityQueue minHeap = new PriorityQueue<>(); 8 | 9 | for (int stick : sticks) { 10 | minHeap.offer(stick); 11 | } 12 | 13 | while (minHeap.size() > 1) { 14 | int smallest = minHeap.poll(); 15 | int nextSmallest = minHeap.poll(); 16 | int cost = smallest + nextSmallest; 17 | totalCost += cost; 18 | minHeap.offer(cost); 19 | } 20 | 21 | return totalCost; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /sum-of-digits-of-string-after-convert/sum-of-digits-of-string-after-convert.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n * k) 3 | // Space: O(1) 4 | // Not sure if complexity analysis is correct 5 | class Solution { 6 | public int getLucky(String s, int k) { 7 | StringBuilder sb = new StringBuilder(); 8 | for (int i = 0; i < s.length(); i++) { 9 | sb.append(s.charAt(i) - 'a' + 1); 10 | } 11 | while (k-- > 0) { 12 | int sum = 0; 13 | for (int i = 0; i < sb.length(); i++) { 14 | sum += sb.charAt(i) - '0'; 15 | } 16 | sb = new StringBuilder(); 17 | sb.append(sum); 18 | } 19 | return Integer.valueOf(sb.toString()); 20 | } 21 | } -------------------------------------------------------------------------------- /valid-palindrome/valid-palindrome.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | public class Solution { 5 | public boolean isPalindrome(String s) { 6 | StringBuilder sb = new StringBuilder(); 7 | for (char c : s.toCharArray()) { 8 | if (Character.isLetter(c)) 9 | sb.append(Character.toLowerCase(c)); 10 | 11 | if (Character.isDigit(c)) 12 | sb.append(c); 13 | } 14 | 15 | String parsed = sb.toString(); 16 | for (int l = 0, r = parsed.length() - 1; l < r; l++, r--) { 17 | if (parsed.charAt(l) != parsed.charAt(r)) 18 | return false; 19 | } 20 | 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /4sum-ii/4sum-ii.java: -------------------------------------------------------------------------------- 1 | // Time: O(n^2) 2 | // Space: O(n^2) 3 | class Solution { 4 | public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { 5 | Map map = new HashMap<>(); 6 | int count = 0; 7 | for (int n1 : nums1) { 8 | for (int n2 : nums2) { 9 | int sum = n1 + n2; 10 | map.put(sum, map.getOrDefault(sum, 0) + 1); 11 | } 12 | } 13 | for (int n3 : nums3) { 14 | for (int n4 : nums4) { 15 | int sum = n3 + n4; 16 | if (map.containsKey(-sum)) { 17 | count += map.get(-sum); 18 | } 19 | } 20 | } 21 | return count; 22 | } 23 | } -------------------------------------------------------------------------------- /goal-parser-interpretation/goal-parser-interpretation.java: -------------------------------------------------------------------------------- 1 | // n = command.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public String interpret(String command) { 6 | StringBuilder result = new StringBuilder(); 7 | int i = 0; 8 | while (i < command.length()) { 9 | char c = command.charAt(i); 10 | if (c == 'G') { 11 | result.append(c); 12 | i++; 13 | } else if (c == '(' && command.charAt(i + 1) == ')') { 14 | result.append('o'); 15 | i += 2; 16 | } else { 17 | result.append("al"); 18 | i += 4; 19 | } 20 | } 21 | return result.toString(); 22 | } 23 | } -------------------------------------------------------------------------------- /maximum-units-on-a-truck/maximum-units-on-a-truck.java: -------------------------------------------------------------------------------- 1 | // n = boxTypes.length; 2 | // Time: O(n log n) 3 | // Space: O(1) 4 | class Solution { 5 | public int maximumUnits(int[][] boxTypes, int truckSize) { 6 | Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]); 7 | int boxCount = 0; 8 | int unitCount = 0; 9 | for (int[] boxType : boxTypes) { 10 | if (boxCount + boxType[0] > truckSize) { 11 | int boxesLeft = truckSize - boxCount; 12 | unitCount += boxesLeft * boxType[1]; 13 | break; 14 | } else { 15 | unitCount += boxType[0] * boxType[1]; 16 | boxCount += boxType[0]; 17 | } 18 | } 19 | return unitCount; 20 | } 21 | } -------------------------------------------------------------------------------- /convert-1d-array-into-2d-array/convert-1d-array-into-2d-array.java: -------------------------------------------------------------------------------- 1 | // Time: O(m * n) 2 | // Space: O(m * n) 3 | class Solution { 4 | public int[][] construct2DArray(int[] original, int m, int n) { 5 | int len = original.length; 6 | int[][] res = new int[m][n]; 7 | int idx = 0; 8 | for (int i = 0; i < m; i++) { 9 | for (int j = 0; j < n; j++) { 10 | res[i][j] = original[idx++]; 11 | if (idx == len) { 12 | if (i == m - 1 && j == n - 1) { 13 | return res; 14 | } else { 15 | return new int[0][0]; 16 | } 17 | } 18 | } 19 | } 20 | return new int[0][0]; 21 | } 22 | } -------------------------------------------------------------------------------- /longer-contiguous-segments-of-ones-than-zeros/longer-contiguous-segments-of-ones-than-zeros.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public boolean checkZeroOnes(String s) { 6 | int maxZero = 0, maxOne = 0; 7 | int currZero = 0, currOne = 0; 8 | 9 | for (char c : s.toCharArray()) { 10 | if (c == '0') { 11 | currOne = 0; 12 | currZero++; 13 | maxZero = Math.max(maxZero, currZero); 14 | } 15 | if (c == '1') { 16 | currZero = 0; 17 | currOne++; 18 | maxOne = Math.max(maxOne, currOne); 19 | } 20 | } 21 | 22 | return maxOne > maxZero; 23 | } 24 | } -------------------------------------------------------------------------------- /koko-eating-bananas/koko-eating-bananas.java: -------------------------------------------------------------------------------- 1 | // n = number of piles, w = max size of a pile 2 | // Time: O(n log w) 3 | // Space: O(1) 4 | class Solution { 5 | public int minEatingSpeed(int[] piles, int h) { 6 | int lo = 1, hi = Arrays.stream(piles).max().getAsInt(); 7 | while (lo <= hi) { 8 | int mid = lo + (hi - lo) / 2; 9 | if (possible(piles, h, mid)) 10 | hi = mid - 1; 11 | else 12 | lo = mid + 1; 13 | } 14 | return lo; 15 | } 16 | 17 | public boolean possible(int[] piles, int h, int k) { 18 | int time = 0; 19 | for (int pile : piles) { 20 | time += pile / k; 21 | if (pile % k > 0) time++; 22 | } 23 | return time <= h; 24 | } 25 | } -------------------------------------------------------------------------------- /largest-rectangle-in-histogram/largest-rectangle-in-histogram.java: -------------------------------------------------------------------------------- 1 | // n = heights.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int largestRectangleArea(int[] heights) { 6 | ArrayDeque stack = new ArrayDeque<>(); 7 | int n = heights.length; 8 | int maxArea = 0; 9 | for (int i = 0; i <= n; i++) { 10 | int h = i == n ? 0 : heights[i]; 11 | if (stack.isEmpty() || h >= heights[stack.peek()]) { 12 | stack.push(i); 13 | } else { 14 | int popped = stack.pop(); 15 | maxArea = Math.max(maxArea, heights[popped] * (stack.isEmpty() ? i : i - 1 - stack.peek())); 16 | i--; 17 | } 18 | } 19 | return maxArea; 20 | } 21 | } -------------------------------------------------------------------------------- /permutation-in-string/permutation-in-string.java: -------------------------------------------------------------------------------- 1 | // Time: O(len1 + len2) 2 | // Space: O(1) 3 | class Solution { 4 | public boolean checkInclusion(String s1, String s2) { 5 | int len1 = s1.length(); 6 | int len2 = s2.length(); 7 | 8 | int[] mapS1 = new int[26]; 9 | int[] mapS2 = new int[26]; 10 | 11 | for (char c : s1.toCharArray()) 12 | mapS1[c - 'a']++; 13 | 14 | for (int i = 0; i < len2; i++) { 15 | if (i >= len1) 16 | mapS2[s2.charAt(i - len1) - 'a']--; 17 | 18 | mapS2[s2.charAt(i) - 'a']++; 19 | 20 | if (Arrays.equals(mapS1, mapS2)) 21 | return true; 22 | } 23 | 24 | return false; 25 | } 26 | } -------------------------------------------------------------------------------- /check-if-word-equals-summation-of-two-words/check-if-word-equals-summation-of-two-words.java: -------------------------------------------------------------------------------- 1 | // i = firstWord.length(), j = secondWord.length(), k = targetWord.length() 2 | // Time: O(i + j + k) 3 | // Space: O(1) 4 | class Solution { 5 | public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { 6 | int target = stringToInt(targetWord); 7 | int first = stringToInt(firstWord); 8 | int second = stringToInt(secondWord); 9 | 10 | return target == first + second; 11 | } 12 | 13 | private int stringToInt(String word) { 14 | StringBuilder sb = new StringBuilder(); 15 | for (char c : word.toCharArray()) { 16 | sb.append(c - 'a'); 17 | } 18 | return Integer.valueOf(sb.toString()); 19 | } 20 | } -------------------------------------------------------------------------------- /eliminate-maximum-number-of-monsters/eliminate-maximum-number-of-monsters.java: -------------------------------------------------------------------------------- 1 | // n = dist.length 2 | // Time: O(n log n) 3 | // Space: O(n) 4 | 5 | class Solution { 6 | public int eliminateMaximum(int[] dist, int[] speed) { 7 | int n = dist.length; 8 | int monsterCount = 1; 9 | int minute = 1; 10 | 11 | double[] time = new double[n]; 12 | for (int i = 0; i < n; i++) { 13 | time[i] = (double)dist[i] / (double)speed[i]; 14 | } 15 | Arrays.sort(time); 16 | 17 | for (int i = 1; i < n; i++) { 18 | if (time[i] - minute <= 0) { 19 | break; 20 | } 21 | monsterCount++; 22 | minute++; 23 | } 24 | 25 | return monsterCount; 26 | } 27 | } -------------------------------------------------------------------------------- /reverse-linked-list/reverse-linked-list.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 | 12 | // n = head.length 13 | // Time: O(n) 14 | // Space: O(1) 15 | class Solution { 16 | public ListNode reverseList(ListNode head) { 17 | ListNode curr = head; 18 | ListNode prev = null; 19 | ListNode next = null; 20 | while (curr != null) { 21 | next = curr.next; 22 | curr.next = prev; 23 | prev = curr; 24 | curr = next; 25 | } 26 | return prev; 27 | } 28 | } -------------------------------------------------------------------------------- /shortest-word-distance/shortest-word-distance.java: -------------------------------------------------------------------------------- 1 | // n = wordsDict.length 2 | // m = word1.length() + word2.length() 3 | // Time: O(n * m) 4 | // Space: O(1) 5 | class Solution { 6 | public int shortestDistance(String[] wordsDict, String word1, String word2) { 7 | int idx1 = -1, idx2 = -1; 8 | int minDist = Integer.MAX_VALUE; 9 | for (int i = 0; i < wordsDict.length; i++) { 10 | if (wordsDict[i].equals(word1)) { 11 | idx1 = i; 12 | } 13 | if (wordsDict[i].equals(word2)) { 14 | idx2 = i; 15 | } 16 | 17 | if (idx1 != -1 && idx2 != -1) { 18 | minDist = Math.min(minDist, Math.abs(idx1 - idx2)); 19 | } 20 | } 21 | return minDist; 22 | } 23 | } -------------------------------------------------------------------------------- /longest-substring-of-all-vowels-in-order/longest-substring-of-all-vowels-in-order.java: -------------------------------------------------------------------------------- 1 | // n = word.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int longestBeautifulSubstring(String word) { 6 | int max = 0, vowelCount = 1, subLength = 1; 7 | for (int i = 1; i < word.length(); i++) { 8 | subLength++; 9 | 10 | if (word.charAt(i) < word.charAt(i - 1)) { 11 | vowelCount = 0; 12 | subLength = 1; 13 | } 14 | 15 | if (word.charAt(i) != word.charAt(i - 1)) 16 | vowelCount++; 17 | 18 | if (vowelCount == 5) 19 | max = Math.max(max, subLength); 20 | } 21 | 22 | return max; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /reorganize-string/README.md: -------------------------------------------------------------------------------- 1 |

767. Reorganize String

Medium


Given a string s, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

2 | 3 |

If possible, output any possible result.  If not possible, return the empty string.

4 | 5 |

Example 1:

6 | 7 |
Input: s = "aab"
 8 | Output: "aba"
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: s = "aaab"
14 | Output: ""
15 | 
16 | 17 |

Note:

18 | 19 |
    20 |
  • s will consist of lowercase letters and have length in range [1, 500].
  • 21 |
22 | 23 |

 

24 |
-------------------------------------------------------------------------------- /valid-parentheses/valid-parentheses.java: -------------------------------------------------------------------------------- 1 | // n = s.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public boolean isValid(String s) { 6 | int n = s.length(); 7 | Stack stack = new Stack<>(); 8 | for (int i = 0; i < n; i++) { 9 | char c = s.charAt(i); 10 | if (stack.isEmpty()) { 11 | stack.push(c); 12 | } else if (c == ')' && stack.peek() == '(') { 13 | stack.pop(); 14 | } else if (c == ']' && stack.peek() == '[') { 15 | stack.pop(); 16 | } else if (c == '}' && stack.peek() == '{') { 17 | stack.pop(); 18 | } else { 19 | stack.push(c); 20 | } 21 | } 22 | return stack.isEmpty(); 23 | } 24 | } -------------------------------------------------------------------------------- /maximum-swap/README.md: -------------------------------------------------------------------------------- 1 |

670. Maximum Swap

Medium


You are given an integer num. You can swap two digits at most once to get the maximum valued number.

2 | 3 |

Return the maximum valued number you can get.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: num = 2736
 9 | Output: 7236
10 | Explanation: Swap the number 2 and the number 7.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: num = 9973
16 | Output: 9973
17 | Explanation: No swap.
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 0 <= num <= 108
  • 25 |
26 |
-------------------------------------------------------------------------------- /reverse-integer/reverse-integer.java: -------------------------------------------------------------------------------- 1 | // n = number of digits in x 2 | // Time: O(n) 3 | // Space: O(n) 4 | // although -2^31 <= x <= 2^31 - 1 so you could also consider O(1) 5 | class Solution { 6 | public int reverse(int x) { 7 | int start = 0; 8 | char[] numChar = String.valueOf(x).toCharArray(); 9 | 10 | if (numChar[0] == '-') start = 1; 11 | 12 | for (int l = start, r = numChar.length - 1; l < r; l++, r--) { 13 | char temp = numChar[l]; 14 | numChar[l] = numChar[r]; 15 | numChar[r] = temp; 16 | } 17 | 18 | long newNum = Long.valueOf(new String(numChar)); 19 | if (newNum > Integer.MAX_VALUE || newNum < Integer.MIN_VALUE) 20 | return 0; 21 | 22 | return (int) newNum; 23 | } 24 | } -------------------------------------------------------------------------------- /daily-temperatures/README.md: -------------------------------------------------------------------------------- 1 | [

Click here for detailed solution

](https://www.danielleskosky.com/daily-temperatures/) 2 | 3 |

739. Daily Temperatures

Medium


4 | Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. 5 |

6 | For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 7 |

8 | 9 |

Note: 10 | The length of temperatures will be in the range [1, 30000]. 11 | Each temperature will be an integer in the range [30, 100]. 12 |

13 | -------------------------------------------------------------------------------- /robot-bounded-in-circle/robot-bounded-in-circle.java: -------------------------------------------------------------------------------- 1 | // n = instructions.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public boolean isRobotBounded(String instructions) { 6 | int x = 0, y = 0; 7 | int idx = 0; 8 | // north = 0, east = 1, south = 2, west = 3 9 | int[][] dirs = new int[][]{{0,1}, {1,0}, {0,-1}, {-1,0}}; 10 | for (int i = 0; i < instructions.length(); i++) { 11 | if (instructions.charAt(i) == 'L') { 12 | idx = (idx + 3) % 4; 13 | } else if (instructions.charAt(i) == 'R') { 14 | idx = (idx + 1) % 4; 15 | } else { 16 | x += dirs[idx][0]; 17 | y += dirs[idx][1]; 18 | } 19 | } 20 | return (x == 0 && y == 0) || (idx != 0); 21 | } 22 | } -------------------------------------------------------------------------------- /add-strings/add-strings.java: -------------------------------------------------------------------------------- 1 | // m = num1.length, n = num2.length 2 | // Time: O(max(m, n)) 3 | // Space: O(max(m, n)) 4 | class Solution { 5 | public String addStrings(String num1, String num2) { 6 | int m = num1.length() - 1, n = num2.length() - 1; 7 | int carry = 0; 8 | 9 | StringBuilder sb = new StringBuilder(); 10 | while (m >= 0 || n >= 0) { 11 | int p = m >= 0 ? num1.charAt(m) - '0' : 0; 12 | int q = n >= 0 ? num2.charAt(n) - '0' : 0; 13 | 14 | int value = (p + q + carry) % 10; 15 | carry = (p + q + carry) / 10; 16 | sb.insert(0, value); 17 | m--; 18 | n--; 19 | } 20 | 21 | if (carry != 0) sb.insert(0, carry); 22 | 23 | return sb.toString(); 24 | } 25 | } -------------------------------------------------------------------------------- /valid-palindrome-ii/valid-palindrome-ii.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public boolean validPalindrome(String s) { 6 | int l = 0, r = s.length() - 1; 7 | while (l <= r) { 8 | if (s.charAt(l) == s.charAt(r)) { 9 | l++; 10 | r--; 11 | } else { 12 | return isValid(s, l + 1, r) || isValid(s, l, r - 1); 13 | } 14 | } 15 | return true; 16 | } 17 | 18 | private boolean isValid(String s, int l, int r) { 19 | while (l <= r) { 20 | if (s.charAt(l) == s.charAt(r)) { 21 | l++; 22 | r--; 23 | } else { 24 | return false; 25 | } 26 | } 27 | return true; 28 | } 29 | } -------------------------------------------------------------------------------- /subarray-sum-equals-k/README.md: -------------------------------------------------------------------------------- 1 |

560. Subarray Sum Equals K

Medium


Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.

2 | 3 |

 

4 |

Example 1:

5 |
Input: nums = [1,1,1], k = 2
 6 | Output: 2
 7 | 

Example 2:

8 |
Input: nums = [1,2,3], k = 3
 9 | Output: 2
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= nums.length <= 2 * 104
  • 16 |
  • -1000 <= nums[i] <= 1000
  • 17 |
  • -107 <= k <= 107
  • 18 |
19 |
-------------------------------------------------------------------------------- /trapping-rain-water/trapping-rain-water.java: -------------------------------------------------------------------------------- 1 | // n = height.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int trap(int[] height) { 6 | ArrayDeque stack = new ArrayDeque<>(); 7 | int result = 0, max = 0; 8 | for (int i = 0; i < height.length; i++) { 9 | if (stack.isEmpty() || height[i] <= height[stack.peek()]) { 10 | stack.push(i); 11 | } 12 | else { 13 | int popped = stack.pop(); 14 | if (!stack.isEmpty()) { 15 | int minHeight = Math.min(height[i], height[stack.peek()]); 16 | result += (minHeight - height[popped]) * (i - stack.peek() - 1); 17 | } 18 | i--; 19 | } 20 | } 21 | return result; 22 | } 23 | } -------------------------------------------------------------------------------- /repeated-substring-pattern/repeated-substring-pattern.java: -------------------------------------------------------------------------------- 1 | // n = s.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public boolean repeatedSubstringPattern(String s) { 6 | Set set = new HashSet<>(); 7 | int n = s.length(); 8 | for (int i = 1; i < n / 2 + 1; i++) { 9 | set.add(s.substring(0, i)); 10 | } 11 | for (String sub : set) { 12 | int len = sub.length(); 13 | for (int i = 0; i <= n - len; i += len) { 14 | String currSub = s.substring(i, i + len); 15 | if (!currSub.equals(sub)) { 16 | break; 17 | } 18 | if (i == n - len) { 19 | return true; 20 | } 21 | } 22 | } 23 | return false; 24 | } 25 | } -------------------------------------------------------------------------------- /meeting-rooms-ii/README.md: -------------------------------------------------------------------------------- 1 |

253. Meeting Rooms II

Medium


Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.

2 | 3 |

 

4 |

Example 1:

5 |
Input: intervals = [[0,30],[5,10],[15,20]]
 6 | Output: 2
 7 | 

Example 2:

8 |
Input: intervals = [[7,10],[2,4]]
 9 | Output: 1
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= intervals.length <= 104
  • 16 |
  • 0 <= starti < endi <= 106
  • 17 |
18 |
-------------------------------------------------------------------------------- /roman-to-integer/roman-to-integer.java: -------------------------------------------------------------------------------- 1 | // n = s.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int romanToInt(String s) { 6 | Map map = new HashMap<>(); 7 | map.put('I', 1); 8 | map.put('V', 5); 9 | map.put('X', 10); 10 | map.put('L', 50); 11 | map.put('C', 100); 12 | map.put('D', 500); 13 | map.put('M', 1000); 14 | 15 | int n = s.length(); 16 | int result = 0; 17 | int prev = 0; 18 | for (int i = n - 1; i >= 0; i--) { 19 | int curr = map.get(s.charAt(i)); 20 | if (curr < prev) { 21 | result -= curr; 22 | } else { 23 | result += curr; 24 | } 25 | prev = curr; 26 | } 27 | return result; 28 | } 29 | } -------------------------------------------------------------------------------- /invert-binary-tree/invert-binary-tree.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 | 17 | // n = number of nodes 18 | // Time: O(n) 19 | // Space: O(n) 20 | class Solution { 21 | public TreeNode invertTree(TreeNode root) { 22 | if (root == null) return null; 23 | TreeNode temp = root.left; 24 | root.left = root.right; 25 | root.right = temp; 26 | invertTree(root.left); 27 | invertTree(root.right); 28 | return root; 29 | } 30 | } -------------------------------------------------------------------------------- /count-and-say/count-and-say.java: -------------------------------------------------------------------------------- 1 | // m = curr.length(); 2 | // Time: O(n * m) 3 | // Space: O(m) 4 | class Solution { 5 | public String countAndSay(int n) { 6 | String curr = "1"; 7 | while (n-- > 1) { 8 | StringBuilder sb = new StringBuilder(); 9 | char c = curr.charAt(0); 10 | int count = 1; 11 | for (int i = 1; i < curr.length(); i++) { 12 | if (curr.charAt(i) == c) { 13 | count++; 14 | } else { 15 | sb.append(count); 16 | sb.append(c); 17 | c = curr.charAt(i); 18 | count = 1; 19 | } 20 | } 21 | sb.append(count); 22 | sb.append(c); 23 | curr = sb.toString(); 24 | } 25 | return curr; 26 | } 27 | } -------------------------------------------------------------------------------- /palindromic-substrings/README.md: -------------------------------------------------------------------------------- 1 |

647. Palindromic Substrings

Medium


Given a string, your task is to count how many palindromic substrings in this string.

2 | 3 |

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

4 | 5 |

Example 1:

6 | 7 |
Input: "abc"
 8 | Output: 3
 9 | Explanation: Three palindromic strings: "a", "b", "c".
10 | 
11 | 12 |

 

13 | 14 |

Example 2:

15 | 16 |
Input: "aaa"
17 | Output: 6
18 | Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
19 | 
20 | 21 |

 

22 | 23 |

Note:

24 | 25 |
    26 |
  1. The input string length won't exceed 1000.
  2. 27 |
28 | 29 |

 

-------------------------------------------------------------------------------- /sort-colors/sort-colors.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public void sortColors(int[] nums) { 6 | if (nums.length < 2) return; 7 | 8 | int i = 0, left = 0, right = nums.length - 1; 9 | while (left < right && i < nums.length) { 10 | if (nums[i] == 0) { 11 | if (i != left) swap(nums, i, left); 12 | left++; 13 | i++; 14 | } else if (nums[i] == 2) { 15 | if (i < right) swap(nums, i, right); 16 | right--; 17 | } else if (nums[i] == 1) { 18 | i++; 19 | } 20 | } 21 | } 22 | 23 | private void swap(int[] nums, int a, int b) { 24 | int temp = nums[a]; 25 | nums[a] = nums[b]; 26 | nums[b] = temp; 27 | } 28 | } -------------------------------------------------------------------------------- /subarray-product-less-than-k/README.md: -------------------------------------------------------------------------------- 1 |

713. Subarray Product Less Than K

Medium


Your are given an array of positive integers nums.

2 |

Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.

3 | 4 |

Example 1:
5 |

Input: nums = [10, 5, 2, 6], k = 100
 6 | Output: 8
 7 | Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
 8 | Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
 9 | 
10 |

11 | 12 |

Note: 13 |

  • 0 < nums.length <= 50000.
  • 14 |
  • 0 < nums[i] < 1000.
  • 15 |
  • 0 <= k < 10^6.
  • 16 |

    -------------------------------------------------------------------------------- /jump-game-vii/jump-game-vii.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public boolean canReach(String s, int minJump, int maxJump) { 6 | int n = s.length(); 7 | Queue queue = new LinkedList<>(); 8 | queue.offer(0); 9 | int farthest = 0; 10 | 11 | while (!queue.isEmpty()) { 12 | int curr = queue.poll(); 13 | int start = Math.max(curr + minJump, farthest + 1); 14 | for (int j = start; j < curr + maxJump + 1; j++) { 15 | if (j >= n) break; 16 | if (s.charAt(j) == '0') { 17 | if (j == n - 1) return true; 18 | queue.offer(j); 19 | } 20 | } 21 | farthest = curr + maxJump; 22 | } 23 | 24 | return false; 25 | } 26 | } -------------------------------------------------------------------------------- /moving-average-from-data-stream/moving-average-from-data-stream.java: -------------------------------------------------------------------------------- 1 | // n = size 2 | // Time: O(1) 3 | // Space: O(n) 4 | class MovingAverage { 5 | Queue queue; 6 | double sum; 7 | int size; 8 | 9 | /** Initialize your data structure here. */ 10 | public MovingAverage(int size) { 11 | this.queue = new LinkedList<>(); 12 | this.size = size; 13 | this.sum = 0; 14 | } 15 | 16 | public double next(int val) { 17 | sum += val; 18 | 19 | if (queue.size() == size) 20 | sum -= queue.poll(); 21 | 22 | queue.offer(val); 23 | 24 | return sum / queue.size(); 25 | } 26 | } 27 | 28 | /** 29 | * Your MovingAverage object will be instantiated and called as such: 30 | * MovingAverage obj = new MovingAverage(size); 31 | * double param_1 = obj.next(val); 32 | */ -------------------------------------------------------------------------------- /find-the-smallest-divisor-given-a-threshold/find-the-smallest-divisor-given-a-threshold.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n log (max)) 3 | // Space: O(1) 4 | class Solution { 5 | public int smallestDivisor(int[] nums, int threshold) { 6 | int min = 1; 7 | int max = 1_000_000; 8 | int mid = 0; 9 | while (min < max) { 10 | mid = min + (max - min) / 2; 11 | int currSum = divSum(nums, mid); 12 | if (currSum > threshold) { 13 | min = mid + 1; 14 | } else { 15 | max = mid; 16 | } 17 | } 18 | return min; 19 | } 20 | 21 | private int divSum(int[] nums, int mid) { 22 | int sum = 0; 23 | for (int num : nums) { 24 | sum += (int) Math.ceil((double) num / mid); 25 | } 26 | return sum; 27 | } 28 | } -------------------------------------------------------------------------------- /number-of-provinces/number-of-provinces.java: -------------------------------------------------------------------------------- 1 | // n = isConnected.length 2 | // Time: O(n^2) 3 | // Space: O(n) 4 | class Solution { 5 | public int findCircleNum(int[][] isConnected) { 6 | int n = isConnected.length; 7 | int provinceCount = 0; 8 | boolean[] visited = new boolean[n]; 9 | for (int i = 0; i < n; i++) { 10 | if (!visited[i]) { 11 | dfs(isConnected, visited, i); 12 | provinceCount++; 13 | } 14 | } 15 | return provinceCount; 16 | } 17 | 18 | private void dfs(int[][] isConnected, boolean[] visited, int i) { 19 | for (int j = 0; j < isConnected.length; j++) { 20 | if (!visited[j] && isConnected[i][j] == 1) { 21 | visited[j] = true; 22 | dfs(isConnected, visited, j); 23 | } 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /keys-and-rooms/keys-and-rooms.java: -------------------------------------------------------------------------------- 1 | // n = number of rooms, e = number of keys 2 | // Time: O(n + e) 3 | // Space: O(n) 4 | class Solution { 5 | public boolean canVisitAllRooms(List> rooms) { 6 | int n = rooms.size(); 7 | boolean[] visited = new boolean[n]; 8 | 9 | visitRooms(rooms, visited, 0); 10 | 11 | for (boolean hasVisited : visited) { 12 | if (!hasVisited) 13 | return false; 14 | } 15 | 16 | return true; 17 | } 18 | 19 | private void visitRooms(List> rooms, boolean[] visited, int room) { 20 | if (visited[room]) return; 21 | visited[room] = true; 22 | for (int key : rooms.get(room)) { 23 | if (!visited[key]) { 24 | visitRooms(rooms, visited, key); 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /permutation-in-string/README.md: -------------------------------------------------------------------------------- 1 |

    567. Permutation in String

    Medium


    Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.

    2 | 3 |

     

    4 | 5 |

    Example 1:

    6 | 7 |
    Input: s1 = "ab" s2 = "eidbaooo"
     8 | Output: True
     9 | Explanation: s2 contains one permutation of s1 ("ba").
    10 | 
    11 | 12 |

    Example 2:

    13 | 14 |
    Input:s1= "ab" s2 = "eidboaoo"
    15 | Output: False
    16 | 
    17 | 18 |

     

    19 |

    Constraints:

    20 | 21 |
      22 |
    • The input strings only contain lower case letters.
    • 23 |
    • The length of both given strings is in range [1, 10,000].
    • 24 |
    25 |
    -------------------------------------------------------------------------------- /find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public List findDuplicates(int[] nums) { 6 | List result = new ArrayList<>(); 7 | int n = nums.length; 8 | 9 | for (int i = 0; i < n; i++) { 10 | if (nums[i] - 1 != i && nums[i] != nums[nums[i] - 1]) { 11 | swap(nums, i, nums[i] - 1); 12 | i--; 13 | } 14 | } 15 | 16 | for (int i = 0; i < n; i++) { 17 | if (nums[i] - 1 != i) 18 | result.add(nums[i]); 19 | } 20 | 21 | return result; 22 | } 23 | 24 | private void swap(int[] nums, int a, int b) { 25 | int temp = nums[a]; 26 | nums[a] = nums[b]; 27 | nums[b] = temp; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /first-unique-character-in-a-string/README.md: -------------------------------------------------------------------------------- 1 |

    387. First Unique Character in a String

    Easy


    Given a string s, return the first non-repeating character in it and return its index. If it does not exist, return -1.

    2 | 3 |

     

    4 |

    Example 1:

    5 |
    Input: s = "leetcode"
     6 | Output: 0
     7 | 

    Example 2:

    8 |
    Input: s = "loveleetcode"
     9 | Output: 2
    10 | 

    Example 3:

    11 |
    Input: s = "aabb"
    12 | Output: -1
    13 | 
    14 |

     

    15 |

    Constraints:

    16 | 17 |
      18 |
    • 1 <= s.length <= 105
    • 19 |
    • s consists of only lowercase English letters.
    • 20 |
    21 |
    -------------------------------------------------------------------------------- /partition-array-into-disjoint-intervals/partition-array-into-disjoint-intervals.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int partitionDisjoint(int[] nums) { 6 | int n = nums.length; 7 | int[] maxes = new int[n]; 8 | int[] mins = new int[n]; 9 | 10 | int max = nums[0]; 11 | int min = nums[n - 1]; 12 | 13 | for (int i = 0; i < n; i++) { 14 | max = Math.max(max, nums[i]); 15 | maxes[i] = max; 16 | } 17 | for (int i = n - 1; i >= 0; i--) { 18 | min = Math.min(min, nums[i]); 19 | mins[i] = min; 20 | } 21 | 22 | for (int i = 0; i < n; i++) { 23 | if (maxes[i] <= mins[i + 1]) { 24 | return i + 1; 25 | } 26 | } 27 | 28 | return -1; 29 | } 30 | } -------------------------------------------------------------------------------- /kill-process/kill-process.java: -------------------------------------------------------------------------------- 1 | // n = pid.size = ppid.size 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | List result = new ArrayList<>(); 6 | 7 | public List killProcess(List pid, List ppid, int kill) { 8 | int n = pid.size(); 9 | Map> adj = new HashMap<>(); 10 | for (int i = 0; i < n; i++) { 11 | adj.putIfAbsent(ppid.get(i), new ArrayList<>()); 12 | adj.get(ppid.get(i)).add(pid.get(i)); 13 | } 14 | dfs(kill, adj); 15 | return result; 16 | } 17 | 18 | private void dfs(int parent, Map> adj) { 19 | result.add(parent); 20 | if (!adj.containsKey(parent)) { 21 | return; 22 | } 23 | for (int child : adj.get(parent)) { 24 | dfs(child, adj); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /palindrome-partitioning/README.md: -------------------------------------------------------------------------------- 1 |

    131. Palindrome Partitioning

    Medium


    Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

    2 | 3 |

    A palindrome string is a string that reads the same backward as forward.

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: s = "aab"
     8 | Output: [["a","a","b"],["aa","b"]]
     9 | 

    Example 2:

    10 |
    Input: s = "a"
    11 | Output: [["a"]]
    12 | 
    13 |

     

    14 |

    Constraints:

    15 | 16 |
      17 |
    • 1 <= s.length <= 16
    • 18 |
    • s contains only lowercase English letters.
    • 19 |
    20 |
    -------------------------------------------------------------------------------- /valid-palindrome/README.md: -------------------------------------------------------------------------------- 1 |

    125. Valid Palindrome

    Easy


    Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: s = "A man, a plan, a canal: Panama"
     7 | Output: true
     8 | Explanation: "amanaplanacanalpanama" is a palindrome.
     9 | 
    10 | 11 |

    Example 2:

    12 | 13 |
    Input: s = "race a car"
    14 | Output: false
    15 | Explanation: "raceacar" is not a palindrome.
    16 | 
    17 | 18 |

     

    19 |

    Constraints:

    20 | 21 |
      22 |
    • 1 <= s.length <= 2 * 105
    • 23 |
    • s consists only of printable ASCII characters.
    • 24 |
    25 |
    -------------------------------------------------------------------------------- /frequency-of-the-most-frequent-element/frequency-of-the-most-frequent-element.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n log n) 3 | // Space: O(n) 4 | class Solution { 5 | public int maxFrequency(int[] nums, int k) { 6 | int n = nums.length; 7 | int max = 1; 8 | long sum = 0; 9 | Arrays.sort(nums); 10 | 11 | for (int right = 0, left = 0; right < n; right++) { 12 | sum += nums[right]; 13 | 14 | long operationsToMakeWindowEqual = (long) nums[right] * (right - left + 1) - sum; 15 | while (k < operationsToMakeWindowEqual) { 16 | sum -= nums[left++]; 17 | operationsToMakeWindowEqual = (long) nums[right] * (right - left + 1) - sum; 18 | } 19 | 20 | max = Math.max(max, right - left + 1); 21 | } 22 | 23 | return max; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /insert-interval/insert-interval.java: -------------------------------------------------------------------------------- 1 | /* 2 | In the case thtat there is just overlap with one interval If NI[0] > I[i][0] then I[i][1] = NI[1] 3 | */ 4 | class Solution { 5 | public int[][] insert(int[][] intervals, int[] newInterval) { 6 | List result = new ArrayList<>(); 7 | int[] toAdd = newInterval; 8 | 9 | for (int i = 0; i < intervals.length; i++) { 10 | if(intervals[i][0] > toAdd[1]) { 11 | result.add(toAdd); 12 | toAdd = intervals[i]; 13 | } else if (intervals[i][1] >= toAdd[0]) { 14 | toAdd = new int[]{Math.min(intervals[i][0], toAdd[0]), 15 | Math.max(intervals[i][1], toAdd[1])}; 16 | } else { 17 | result.add(intervals[i]); 18 | } 19 | } 20 | result.add(toAdd); 21 | return result.toArray(new int[result.size()][2]); 22 | } 23 | } -------------------------------------------------------------------------------- /find-peak-element/find-peak-element.java: -------------------------------------------------------------------------------- 1 | // Linear scan - probably over-complicated 2 | class Solution { 3 | public int findPeakElement(int[] nums) { 4 | if (nums.length == 1) return 0; 5 | for (int i = 0; i < nums.length; i++) { 6 | if (i > 0 && i < nums.length - 1 && nums[i] > nums[i-1] && nums[i] > nums[i+1]) return i; 7 | if (i == 0 && nums[i] > nums[i+1]) return i; 8 | if (i == nums.length - 1 && nums[i] > nums[i-1]) return i; 9 | } 10 | return 0; 11 | } 12 | } 13 | 14 | // Binary search 15 | class Solution { 16 | public int findPeakElement(int[] nums) { 17 | int lo = 0, hi = nums.length - 1; 18 | while (lo < hi) { 19 | int mid = lo + (hi - lo) / 2; 20 | if (nums[mid] < nums[mid + 1]) 21 | lo = mid + 1; 22 | else 23 | hi = mid; 24 | } 25 | return lo; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /flip-equivalent-binary-trees/flip-equivalent-binary-trees.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 | public boolean flipEquiv(TreeNode root1, TreeNode root2) { 18 | if (root1 == null && root2 == null) 19 | return true; 20 | else if (root1 == null || root2 == null || root1.val != root2.val) 21 | return false; 22 | 23 | return flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right) || 24 | flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left); 25 | } 26 | } -------------------------------------------------------------------------------- /move-zeroes/README.md: -------------------------------------------------------------------------------- 1 |

    283. Move Zeroes

    Easy


    Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

    2 | 3 |

    Note that you must do this in-place without making a copy of the array.

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: nums = [0,1,0,3,12]
     8 | Output: [1,3,12,0,0]
     9 | 

    Example 2:

    10 |
    Input: nums = [0]
    11 | Output: [0]
    12 | 
    13 |

     

    14 |

    Constraints:

    15 | 16 |
      17 |
    • 1 <= nums.length <= 104
    • 18 |
    • -231 <= nums[i] <= 231 - 1
    • 19 |
    20 | 21 |

     

    22 | Follow up: Could you minimize the total number of operations done?
    -------------------------------------------------------------------------------- /k-closest-points-to-origin/k-closest-points-to-origin.java: -------------------------------------------------------------------------------- 1 | // n = points.length 2 | // Time: O(n log n) 3 | // Space: O(n) 4 | class Dist { 5 | int dist; 6 | int[] point; 7 | public Dist(int dist, int[] point) { 8 | this.dist = dist; 9 | this.point = point; 10 | } 11 | } 12 | 13 | class Solution { 14 | public int[][] kClosest(int[][] points, int k) { 15 | int n = points.length; 16 | Dist[] distances = new Dist[n]; 17 | for (int i = 0; i < n; i++) { 18 | int currDist = points[i][0] * points[i][0] + points[i][1] * points[i][1]; 19 | distances[i] = new Dist(currDist, points[i]); 20 | } 21 | 22 | Arrays.sort(distances, (a, b) -> a.dist - b.dist); 23 | 24 | int[][] result = new int[k][2]; 25 | for (int i = 0; i < k; i++) { 26 | result[i] = distances[i].point; 27 | } 28 | 29 | return result; 30 | } 31 | } -------------------------------------------------------------------------------- /leftmost-column-with-at-least-a-one/leftmost-column-with-at-least-a-one.java: -------------------------------------------------------------------------------- 1 | /** 2 | * // This is the BinaryMatrix's API interface. 3 | * // You should not implement it, or speculate about its implementation 4 | * interface BinaryMatrix { 5 | * public int get(int row, int col) {} 6 | * public List dimensions {} 7 | * }; 8 | */ 9 | 10 | // Time: O(m + n) 11 | // Space: O(1) 12 | class Solution { 13 | public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) { 14 | List dimensions = binaryMatrix.dimensions(); 15 | int m = dimensions.get(0); 16 | int n = dimensions.get(1); 17 | 18 | int row = 0, col = n - 1; 19 | while (row < m && col >= 0) { 20 | if (binaryMatrix.get(row, col) == 0) { 21 | row++; 22 | } else { 23 | col--; 24 | } 25 | } 26 | 27 | return col == n - 1 ? -1 : col + 1; 28 | } 29 | } -------------------------------------------------------------------------------- /subsets/README.md: -------------------------------------------------------------------------------- 1 |

    78. Subsets

    Medium


    Given an integer array nums of unique elements, return all possible subsets (the power set).

    2 | 3 |

    The solution set must not contain duplicate subsets. Return the solution in any order.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: nums = [1,2,3]
     9 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
    10 | 
    11 | 12 |

    Example 2:

    13 | 14 |
    Input: nums = [0]
    15 | Output: [[],[0]]
    16 | 
    17 | 18 |

     

    19 |

    Constraints:

    20 | 21 |
      22 |
    • 1 <= nums.length <= 10
    • 23 |
    • -10 <= nums[i] <= 10
    • 24 |
    • All the numbers of nums are unique.
    • 25 |
    26 |
    -------------------------------------------------------------------------------- /intersection-of-two-arrays-ii/intersection-of-two-arrays-ii.java: -------------------------------------------------------------------------------- 1 | // m = nums1.length, n = nums2.length 2 | // Time: O(m + n) 3 | // Space: O(min(m, n)) 4 | class Solution { 5 | public int[] intersect(int[] nums1, int[] nums2) { 6 | List list = new ArrayList<>(); 7 | Map map = new HashMap<>(); 8 | 9 | for (int num : nums1) 10 | map.put(num, map.getOrDefault(num, 0) + 1); 11 | 12 | for (int num : nums2) { 13 | if (map.containsKey(num)) { 14 | list.add(num); 15 | map.put(num, map.get(num) - 1); 16 | if (map.get(num) == 0) { 17 | map.remove(num); 18 | } 19 | } 20 | } 21 | 22 | int[] result = new int[list.size()]; 23 | for (int i = 0; i < list.size(); i++) 24 | result[i] = list.get(i); 25 | 26 | return result; 27 | } 28 | } -------------------------------------------------------------------------------- /permutations/README.md: -------------------------------------------------------------------------------- 1 |

    46. Permutations

    Medium


    Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

    2 | 3 |

     

    4 |

    Example 1:

    5 |
    Input: nums = [1,2,3]
     6 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
     7 | 

    Example 2:

    8 |
    Input: nums = [0,1]
     9 | Output: [[0,1],[1,0]]
    10 | 

    Example 3:

    11 |
    Input: nums = [1]
    12 | Output: [[1]]
    13 | 
    14 |

     

    15 |

    Constraints:

    16 | 17 |
      18 |
    • 1 <= nums.length <= 6
    • 19 |
    • -10 <= nums[i] <= 10
    • 20 |
    • All the integers of nums are unique.
    • 21 |
    22 |
    -------------------------------------------------------------------------------- /kth-largest-element-in-an-array/README.md: -------------------------------------------------------------------------------- 1 |

    215. Kth Largest Element in an Array

    Medium


    Given an integer array nums and an integer k, return the kth largest element in the array.

    2 | 3 |

    Note that it is the kth largest element in the sorted order, not the kth distinct element.

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: nums = [3,2,1,5,6,4], k = 2
     8 | Output: 5
     9 | 

    Example 2:

    10 |
    Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
    11 | Output: 4
    12 | 
    13 |

     

    14 |

    Constraints:

    15 | 16 |
      17 |
    • 1 <= k <= nums.length <= 104
    • 18 |
    • -104 <= nums[i] <= 104
    • 19 |
    20 |
    -------------------------------------------------------------------------------- /least-number-of-unique-integers-after-k-removals/least-number-of-unique-integers-after-k-removals.java: -------------------------------------------------------------------------------- 1 | // n = arr.length 2 | // Time: O(n log n) 3 | // Space: O(n) 4 | class Solution { 5 | public int findLeastNumOfUniqueInts(int[] arr, int k) { 6 | Map map = new HashMap<>(); 7 | for (int num : arr) { 8 | map.put(num, map.getOrDefault(num, 0) + 1); 9 | } 10 | PriorityQueue> pq = new PriorityQueue<>((a, b) -> a.getValue() - b.getValue()); 11 | for (Map.Entry entry : map.entrySet()) { 12 | pq.offer(entry); 13 | } 14 | while (k > 0) { 15 | Map.Entry polled = pq.poll(); 16 | if (k - polled.getValue() < 0) { 17 | return pq.size() + 1; 18 | } else { 19 | k -= polled.getValue(); 20 | } 21 | } 22 | return pq.size(); 23 | } 24 | } -------------------------------------------------------------------------------- /count-good-numbers/count-good-numbers.java: -------------------------------------------------------------------------------- 1 | // Time: O(log n) 2 | // Space: O(1) 3 | class Solution { 4 | public int countGoodNumbers(long n) { 5 | long result = 0; 6 | long even = 0, odd = 0; 7 | if (n % 2 != 0) { 8 | even = n / 2 + 1; 9 | odd = n / 2; 10 | } else { 11 | even = n / 2; 12 | odd = n / 2; 13 | } 14 | long mod = 1_000_000_007; 15 | result += fastPower(5, even, mod) * fastPower(4, odd, mod); 16 | return (int)(result % mod); 17 | } 18 | 19 | private long fastPower(int x, long n, long mod) { 20 | long result = 1; 21 | long currentProduct = x; 22 | for (long i = n; i > 0; i /= 2) { 23 | if (i % 2 == 1) { 24 | result = (result * currentProduct) % mod; 25 | } 26 | currentProduct = (currentProduct * currentProduct) % mod; 27 | } 28 | return result; 29 | } 30 | } -------------------------------------------------------------------------------- /first-missing-positive/README.md: -------------------------------------------------------------------------------- 1 |

    41. First Missing Positive

    Hard


    Given an unsorted integer array nums, find the smallest missing positive integer.

    2 | 3 |

     

    4 |

    Example 1:

    5 |
    Input: nums = [1,2,0]
     6 | Output: 3
     7 | 

    Example 2:

    8 |
    Input: nums = [3,4,-1,1]
     9 | Output: 2
    10 | 

    Example 3:

    11 |
    Input: nums = [7,8,9,11,12]
    12 | Output: 1
    13 | 
    14 |

     

    15 |

    Constraints:

    16 | 17 |
      18 |
    • 0 <= nums.length <= 300
    • 19 |
    • -231 <= nums[i] <= 231 - 1
    • 20 |
    21 | 22 |

     

    23 |

    Follow up: Could you implement an algorithm that runs in O(n) time and uses constant extra space?

    24 |
    -------------------------------------------------------------------------------- /group-shifted-strings/group-shifted-strings.java: -------------------------------------------------------------------------------- 1 | // m = strings.length, n = max(strings[i].length) 2 | // Time: O(m * n) 3 | // Space: O(m) 4 | class Solution { 5 | public List> groupStrings(String[] strings) { 6 | List> result = new ArrayList<>(); 7 | Map, List> map = new HashMap<>(); 8 | 9 | for (String string : strings) { 10 | List list = new ArrayList<>(); 11 | for (int i = 1; i < string.length(); i++) { 12 | int diff = string.charAt(i) - string.charAt(i - 1); 13 | if (diff < 0) diff = 26 + diff; 14 | list.add(diff); 15 | } 16 | map.putIfAbsent(list, new ArrayList<>()); 17 | map.get(list).add(string); 18 | } 19 | 20 | for (List list : map.keySet()) 21 | result.add(map.get(list)); 22 | 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /number-of-pairs-of-strings-with-concatenation-equal-to-target/number-of-pairs-of-strings-with-concatenation-equal-to-target.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int numOfPairs(String[] nums, String target) { 6 | Map map = new HashMap<>(); 7 | int count = 0; 8 | for (String num : nums) { 9 | map.put(num, map.getOrDefault(num, 0) + 1); 10 | } 11 | for (String num : nums) { 12 | if (num.length() > target.length()) { 13 | continue; 14 | } 15 | String toConcat = target.substring(num.length(), target.length()); 16 | if (map.containsKey(toConcat) && (num + toConcat).equals(target)) { 17 | count += map.get(toConcat); 18 | if (num.equals(toConcat)) { 19 | count--; 20 | } 21 | } 22 | } 23 | return count; 24 | } 25 | } -------------------------------------------------------------------------------- /partition-to-k-equal-sum-subsets/README.md: -------------------------------------------------------------------------------- 1 |

    698. Partition to K Equal Sum Subsets

    Medium


    Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: nums = [4,3,2,3,5,2,1], k = 4
     7 | Output: true
     8 | Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
     9 | 
    10 | 11 |

    Example 2:

    12 | 13 |
    Input: nums = [1,2,3,4], k = 3
    14 | Output: false
    15 | 
    16 | 17 |

     

    18 |

    Constraints:

    19 | 20 |
      21 |
    • 1 <= k <= nums.length <= 16
    • 22 |
    • 0 <= nums[i] <= 104
    • 23 |
    24 |
    -------------------------------------------------------------------------------- /next-greater-element-iii/README.md: -------------------------------------------------------------------------------- 1 |

    556. Next Greater Element III

    Medium


    Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.

    2 | 3 |

    Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: n = 12
     8 | Output: 21
     9 | 

    Example 2:

    10 |
    Input: n = 21
    11 | Output: -1
    12 | 
    13 |

     

    14 |

    Constraints:

    15 | 16 |
      17 |
    • 1 <= n <= 231 - 1
    • 18 |
    19 |
    -------------------------------------------------------------------------------- /maximum-number-of-words-you-can-type/maximum-number-of-words-you-can-type.java: -------------------------------------------------------------------------------- 1 | // n = text.split(" ").length, m = max(text[i].length()) 2 | // Time: O(m * n) 3 | // Space: O(1) - set will contain max of 26 characters 4 | class Solution { 5 | public int canBeTypedWords(String text, String brokenLetters) { 6 | Set set = new HashSet<>(); 7 | for (int i = 0; i < brokenLetters.length(); i++) { 8 | set.add(brokenLetters.charAt(i)); 9 | } 10 | 11 | int count = 0; 12 | String[] arr = text.split(" "); 13 | for (String word : arr) { 14 | boolean isBroken = false; 15 | for (int i = 0; i < word.length(); i++) { 16 | if (set.contains(word.charAt(i))) { 17 | isBroken = true; 18 | } 19 | } 20 | if (!isBroken) { 21 | count++; 22 | } 23 | } 24 | 25 | return count; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /merge-triplets-to-form-target-triplet/merge-triplets-to-form-target-triplet.java: -------------------------------------------------------------------------------- 1 | // n = triplets.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public boolean mergeTriplets(int[][] triplets, int[] target) { 6 | int[] hopefulTriplet = new int[3]; 7 | for (int i = 0; i < triplets.length; i++) { 8 | if (triplets[i][0] > target[0] 9 | || triplets[i][1] > target[1] 10 | || triplets[i][2] > target[2]) 11 | { 12 | continue; 13 | } else { 14 | hopefulTriplet[0] = Math.max(hopefulTriplet[0], triplets[i][0]); 15 | hopefulTriplet[1] = Math.max(hopefulTriplet[1], triplets[i][1]); 16 | hopefulTriplet[2] = Math.max(hopefulTriplet[2], triplets[i][2]); 17 | } 18 | } 19 | 20 | return hopefulTriplet[0] == target[0] && hopefulTriplet[1] == target[1] 21 | && hopefulTriplet[2] == target[2]; 22 | } 23 | } -------------------------------------------------------------------------------- /number-of-good-ways-to-split-a-string/number-of-good-ways-to-split-a-string.java: -------------------------------------------------------------------------------- 1 | // n = s.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int numSplits(String s) { 6 | int n = s.length(); 7 | Map mapL = new HashMap<>(); 8 | Map mapR = new HashMap<>(); 9 | 10 | for (int i = 0; i < n; i++) { 11 | mapR.put(s.charAt(i), mapR.getOrDefault(s.charAt(i), 0) + 1); 12 | } 13 | 14 | int waysToSplit = 0; 15 | for (int i = 0; i < n; i++) { 16 | char c = s.charAt(i); 17 | mapL.put(c, mapL.getOrDefault(c, 0) + 1); 18 | mapR.put(c, mapR.get(c) - 1); 19 | if (mapR.get(c) == 0) { 20 | mapR.remove(c); 21 | } 22 | if (mapL.size() == mapR.size()) { 23 | waysToSplit++; 24 | } 25 | } 26 | 27 | return waysToSplit; 28 | } 29 | } -------------------------------------------------------------------------------- /valid-palindrome-ii/README.md: -------------------------------------------------------------------------------- 1 |

    680. Valid Palindrome II

    Easy


    Given a string s, return true if the s can be palindrome after deleting at most one character from it.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: s = "aba"
     7 | Output: true
     8 | 
    9 | 10 |

    Example 2:

    11 | 12 |
    Input: s = "abca"
    13 | Output: true
    14 | Explanation: You could delete the character 'c'.
    15 | 
    16 | 17 |

    Example 3:

    18 | 19 |
    Input: s = "abc"
    20 | Output: false
    21 | 
    22 | 23 |

     

    24 |

    Constraints:

    25 | 26 |
      27 |
    • 1 <= s.length <= 105
    • 28 |
    • s consists of lowercase English letters.
    • 29 |
    30 |
    -------------------------------------------------------------------------------- /three-divisors/README.md: -------------------------------------------------------------------------------- 1 |

    1952. Three Divisors

    Easy


    Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.

    2 | 3 |

    An integer m is a divisor of n if there exists an integer k such that n = k * m.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: n = 2
     9 | Output: false
    10 | Explantion: 2 has only two divisors: 1 and 2.
    11 | 
    12 | 13 |

    Example 2:

    14 | 15 |
    Input: n = 4
    16 | Output: true
    17 | Explantion: 4 has three divisors: 1, 2, and 4.
    18 | 
    19 | 20 |

     

    21 |

    Constraints:

    22 | 23 |
      24 |
    • 1 <= n <= 104
    • 25 |
    26 |
    -------------------------------------------------------------------------------- /3sum/README.md: -------------------------------------------------------------------------------- 1 |

    15. 3Sum

    Medium


    Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

    2 | 3 |

    Notice that the solution set must not contain duplicate triplets.

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: nums = [-1,0,1,2,-1,-4]
     8 | Output: [[-1,-1,2],[-1,0,1]]
     9 | 

    Example 2:

    10 |
    Input: nums = []
    11 | Output: []
    12 | 

    Example 3:

    13 |
    Input: nums = [0]
    14 | Output: []
    15 | 
    16 |

     

    17 |

    Constraints:

    18 | 19 |
      20 |
    • 0 <= nums.length <= 3000
    • 21 |
    • -105 <= nums[i] <= 105
    • 22 |
    23 |
    -------------------------------------------------------------------------------- /inorder-successor-in-bst/inorder-successor-in-bst.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | /* 11 | After passing the tests and looking at the official solution, 12 | I realize that 'prev' might not have been the best name choice, 13 | as sometimes 'prev' will sometimes not correspond to the immediately 14 | previous node. Just a heads up. 15 | */ 16 | // n = number of nodes 17 | // Time: O(n) 18 | // Space: O(1) 19 | class Solution { 20 | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { 21 | TreeNode prev = null; 22 | while (root != null) { 23 | if (root.val > p.val) { 24 | prev = root; 25 | root = root.left; 26 | } else { 27 | root = root.right; 28 | } 29 | } 30 | return prev; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /partition-equal-subset-sum/README.md: -------------------------------------------------------------------------------- 1 |

    416. Partition Equal Subset Sum

    Medium


    Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: nums = [1,5,11,5]
     7 | Output: true
     8 | Explanation: The array can be partitioned as [1, 5, 5] and [11].
     9 | 
    10 | 11 |

    Example 2:

    12 | 13 |
    Input: nums = [1,2,3,5]
    14 | Output: false
    15 | Explanation: The array cannot be partitioned into equal sum subsets.
    16 | 
    17 | 18 |

     

    19 |

    Constraints:

    20 | 21 |
      22 |
    • 1 <= nums.length <= 200
    • 23 |
    • 1 <= nums[i] <= 100
    • 24 |
    25 |
    -------------------------------------------------------------------------------- /is-graph-bipartite/is-graph-bipartite.java: -------------------------------------------------------------------------------- 1 | // n = number of nodes, e = number of edges 2 | // Time: O(n + e) 3 | // Space: O(n) 4 | class Solution { 5 | public boolean isBipartite(int[][] graph) { 6 | int n = graph.length; 7 | int[] colors = new int[n]; 8 | Arrays.fill(colors, -1); 9 | 10 | for (int i = 0; i < n; i++) { 11 | if (colors[i] == -1) { 12 | if (!canColor(colors, graph, i, 0)) 13 | return false; 14 | } 15 | } 16 | 17 | return true; 18 | } 19 | 20 | private boolean canColor(int[] colors, int[][] graph, int u, int color) { 21 | if (colors[u] != -1) { 22 | return colors[u] == color; 23 | } 24 | 25 | colors[u] = color; 26 | 27 | for (int v : graph[u]) { 28 | if (!canColor(colors, graph, v, color^1)) 29 | return false; 30 | } 31 | 32 | return true; 33 | } 34 | } -------------------------------------------------------------------------------- /car-fleet/car-fleet.java: -------------------------------------------------------------------------------- 1 | // n = position.length 2 | // Time: O(n logn) 3 | // Space: O(n) 4 | class CarSort implements Comparator { 5 | @Override 6 | public int compare(double[] a, double[] b) { 7 | return Double.compare(a[0], b[0]); 8 | } 9 | } 10 | 11 | class Solution { 12 | public int carFleet(int target, int[] position, int[] speed) { 13 | int n = position.length; 14 | int fleetCount = 0; 15 | 16 | double[][] cars = new double[n][2]; 17 | for (int i = 0; i < n; i++) { 18 | cars[i][0] = (double) position[i]; 19 | cars[i][1] = (double) (target - position[i]) / speed[i]; 20 | } 21 | 22 | Arrays.sort(cars, new CarSort()); 23 | double slowCar = 0; 24 | for (int i = n - 1; i >= 0; i--) { 25 | if (cars[i][1] > slowCar) { 26 | fleetCount++; 27 | slowCar = cars[i][1]; 28 | } 29 | } 30 | 31 | return fleetCount; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /diameter-of-binary-tree/diameter-of-binary-tree.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 | 17 | // n = number of nodes 18 | // Time: O(n) 19 | // Space: O(n) 20 | class Solution { 21 | int max = 0; 22 | 23 | public int diameterOfBinaryTree(TreeNode root) { 24 | maxDepth(root); 25 | return max; 26 | } 27 | 28 | private int maxDepth(TreeNode node) { 29 | if (node == null) return 0; 30 | 31 | int left = maxDepth(node.left); 32 | int right = maxDepth(node.right); 33 | 34 | max = Math.max(max, left + right); 35 | 36 | return Math.max(left, right) + 1; 37 | } 38 | } -------------------------------------------------------------------------------- /partition-labels/README.md: -------------------------------------------------------------------------------- 1 |

    763. Partition Labels

    Medium


    A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

    2 | 3 |

     

    4 | 5 |

    Example 1:

    6 | 7 |
    Input: S = "ababcbacadefegdehijhklij"
     8 | Output: [9,7,8]
     9 | Explanation:
    10 | The partition is "ababcbaca", "defegde", "hijhklij".
    11 | This is a partition so that each letter appears in at most one part.
    12 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
    13 | 
    14 | 15 |

     

    16 | 17 |

    Note:

    18 | 19 |
      20 |
    • S will have length in range [1, 500].
    • 21 |
    • S will consist of lowercase English letters ('a' to 'z') only.
    • 22 |
    23 | 24 |

     

    25 |
    -------------------------------------------------------------------------------- /perfect-squares/README.md: -------------------------------------------------------------------------------- 1 |

    279. Perfect Squares

    Medium


    Given an integer n, return the least number of perfect square numbers that sum to n.

    2 | 3 |

    A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: n = 12
     9 | Output: 3
    10 | Explanation: 12 = 4 + 4 + 4.
    11 | 
    12 | 13 |

    Example 2:

    14 | 15 |
    Input: n = 13
    16 | Output: 2
    17 | Explanation: 13 = 4 + 9.
    18 | 
    19 | 20 |

     

    21 |

    Constraints:

    22 | 23 |
      24 |
    • 1 <= n <= 104
    • 25 |
    26 |
    -------------------------------------------------------------------------------- /remove-stones-to-minimize-the-total/remove-stones-to-minimize-the-total.java: -------------------------------------------------------------------------------- 1 | // n = piles.length 2 | // Time: O(n log k) 3 | // Space: O(k) 4 | class Solution { 5 | public int minStoneSum(int[] piles, int k) { 6 | PriorityQueue minHeap = new PriorityQueue<>(); 7 | int stoneCount = 0; 8 | for (int pile : piles) { 9 | stoneCount += pile; 10 | minHeap.offer(pile); 11 | if (minHeap.size() > k) { 12 | minHeap.poll(); 13 | } 14 | } 15 | 16 | PriorityQueue maxHeap = new PriorityQueue<>((a,b) -> b - a); 17 | while(!minHeap.isEmpty()) { 18 | maxHeap.offer(minHeap.poll()); 19 | } 20 | 21 | while (k-- > 0) { 22 | int pile = maxHeap.poll(); 23 | int toRemove = (int) Math.floor(pile / 2); 24 | stoneCount -= toRemove; 25 | pile -= toRemove; 26 | maxHeap.offer(pile); 27 | } 28 | 29 | return stoneCount; 30 | } 31 | } -------------------------------------------------------------------------------- /binary-tree-inorder-traversal/binary-tree-inorder-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 | // Time: O(n) 17 | // Space: O(n) 18 | class Solution { 19 | public List inorderTraversal(TreeNode root) { 20 | List result = new ArrayList<>(); 21 | if (root == null) return result; 22 | getInorderList(root, result); 23 | return result; 24 | } 25 | 26 | private void getInorderList(TreeNode node, List result) { 27 | if (node == null) return; 28 | 29 | getInorderList(node.left, result); 30 | result.add(node.val); 31 | getInorderList(node.right, result); 32 | } 33 | } -------------------------------------------------------------------------------- /palindromic-substrings/palindromic-substrings.java: -------------------------------------------------------------------------------- 1 | // Time: O(n^2) 2 | // Space: O(n^2) 3 | class Solution { 4 | public int countSubstrings(String s) { 5 | int n = s.length(); 6 | int result = 0; 7 | 8 | boolean[][] dp = new boolean[n][n]; 9 | 10 | // single letter palindromes 11 | for (int i = 0; i < n; i++) { 12 | dp[i][i] = true; 13 | result++; 14 | } 15 | 16 | // double letter palindromes 17 | for (int i = 0; i < n - 1; i++) { 18 | dp[i][i + 1] = s.charAt(i) == s.charAt(i + 1); 19 | if (dp[i][i + 1]) result++; 20 | } 21 | 22 | // palindromes greater than or equal to 3 letters 23 | for (int len = 3; len <= n; len++) { 24 | for (int i = 0, j = i + len - 1; j < n; i++, j++) { 25 | dp[i][j] = dp[i + 1][j - 1] && s.charAt(i) == s.charAt(j); 26 | if (dp[i][j]) result++; 27 | } 28 | } 29 | 30 | return result; 31 | } 32 | } -------------------------------------------------------------------------------- /path-with-maximum-gold/path-with-maximum-gold.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private final int[] DIR = new int[]{0, 1, 0, -1, 0}; 3 | 4 | public int getMaximumGold(int[][] grid) { 5 | int m = grid.length, n = grid[0].length; 6 | int maxGold = 0; 7 | for (int r = 0; r < m; r++) 8 | for (int c = 0; c < n; c++) 9 | maxGold = Math.max(maxGold, findMaxGold(grid, m, n, r, c)); 10 | 11 | return maxGold; 12 | } 13 | 14 | private int findMaxGold(int[][] grid, int m, int n, int r, int c) { 15 | if (r < 0 || r == m || c < 0 || c == n || grid[r][c] == 0) 16 | return 0; 17 | 18 | int origin = grid[r][c]; 19 | grid[r][c] = 0; // mark as visited 20 | int maxGold = 0; 21 | 22 | for (int i = 0; i < 4; i++) 23 | maxGold = Math.max(maxGold, findMaxGold(grid, m, n, DIR[i] + r, DIR[i+1] + c)); 24 | 25 | grid[r][c] = origin; // backtrack 26 | 27 | return maxGold + origin; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /time-based-key-value-store/time-based-key-value-store.java: -------------------------------------------------------------------------------- 1 | // Space: O(n) 2 | class TimeMap { 3 | private Map> map; 4 | 5 | /** Initialize your data structure here. */ 6 | public TimeMap() { 7 | map = new TreeMap<>(); 8 | } 9 | 10 | // Time: O(log n) 11 | public void set(String key, String value, int timestamp) { 12 | if (!map.containsKey(key)) 13 | map.put(key, new TreeMap()); 14 | 15 | map.get(key).put(timestamp, value); 16 | } 17 | 18 | // Time: O(log n) 19 | public String get(String key, int timestamp) { 20 | if (!map.containsKey(key)) return ""; 21 | 22 | TreeMap tree = map.get(key); 23 | Integer t = tree.floorKey(timestamp); 24 | return t != null ? tree.get(t) : ""; 25 | } 26 | } 27 | 28 | /** 29 | * Your TimeMap object will be instantiated and called as such: 30 | * TimeMap obj = new TimeMap(); 31 | * obj.set(key,value,timestamp); 32 | * String param_2 = obj.get(key,timestamp); 33 | */ -------------------------------------------------------------------------------- /compare-version-numbers/compare-version-numbers.java: -------------------------------------------------------------------------------- 1 | // n = version1.length, m = version2.length 2 | // Time: O(m + n) 3 | // Space: O(m + n) 4 | class Solution { 5 | public int compareVersion(String version1, String version2) { 6 | String[] v1arrStr = version1.split("\\."); 7 | String[] v2arrStr = version2.split("\\."); 8 | int n = Math.max(v1arrStr.length, v2arrStr.length); 9 | int[] v1arrInt = new int[n]; 10 | int[] v2arrInt = new int[n]; 11 | for (int i = 0; i < n; i++) { 12 | if (i < v1arrStr.length) { 13 | v1arrInt[i] = Integer.valueOf(v1arrStr[i]); 14 | } 15 | if (i < v2arrStr.length) { 16 | v2arrInt[i] = Integer.valueOf(v2arrStr[i]); 17 | } 18 | } 19 | for (int i = 0; i < n; i++) { 20 | if (v1arrInt[i] < v2arrInt[i]) { 21 | return -1; 22 | } 23 | if (v1arrInt[i] > v2arrInt[i]) { 24 | return 1; 25 | } 26 | } 27 | return 0; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /count-good-nodes-in-binary-tree/count-good-nodes-in-binary-tree.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 | 17 | // n = number of nodes 18 | // Time: O(n) 19 | // Space: O(n) 20 | class Solution { 21 | public int goodNodes(TreeNode root) { 22 | if (root == null) return 0; 23 | return countGoodNodes(root, root.val); 24 | } 25 | 26 | private int countGoodNodes(TreeNode node, int max) { 27 | if (node == null) return 0; 28 | 29 | if (node.val > max) max = node.val; 30 | int left = countGoodNodes(node.left, max); 31 | int right = countGoodNodes(node.right, max); 32 | 33 | return right + left + (node.val == max ? 1 : 0); 34 | } 35 | } -------------------------------------------------------------------------------- /longest-palindromic-substring/README.md: -------------------------------------------------------------------------------- 1 |

    5. Longest Palindromic Substring

    Medium


    Given a string s, return the longest palindromic substring in s.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: s = "babad"
     7 | Output: "bab"
     8 | Note: "aba" is also a valid answer.
     9 | 
    10 | 11 |

    Example 2:

    12 | 13 |
    Input: s = "cbbd"
    14 | Output: "bb"
    15 | 
    16 | 17 |

    Example 3:

    18 | 19 |
    Input: s = "a"
    20 | Output: "a"
    21 | 
    22 | 23 |

    Example 4:

    24 | 25 |
    Input: s = "ac"
    26 | Output: "a"
    27 | 
    28 | 29 |

     

    30 |

    Constraints:

    31 | 32 |
      33 |
    • 1 <= s.length <= 1000
    • 34 |
    • s consist of only digits and English letters (lower-case and/or upper-case),
    • 35 |
    -------------------------------------------------------------------------------- /print-words-vertically/print-words-vertically.java: -------------------------------------------------------------------------------- 1 | // n = s.length(), m = max length of word in s 2 | // Time: O(m * n) 3 | // Space: O(m + n) 4 | class Solution { 5 | public List printVertically(String s) { 6 | List result = new ArrayList<>(); 7 | String[] split = s.split("\\s+"); 8 | int n = split.length; 9 | 10 | int max = 0; 11 | for (String word : split) 12 | max = Math.max(max, word.length()); 13 | 14 | for (int i = 0; i < max; i++) { 15 | StringBuilder sb = new StringBuilder(); 16 | for (int j = 0; j < n; j++) { 17 | if (i >= split[j].length()) { 18 | sb.append(" "); 19 | } else { 20 | sb.append(split[j].charAt(i)); 21 | } 22 | } 23 | while (sb.charAt(sb.length() - 1) == ' ') { 24 | sb.deleteCharAt(sb.length() - 1); 25 | } 26 | result.add(sb.toString()); 27 | } 28 | 29 | return result; 30 | } 31 | } -------------------------------------------------------------------------------- /repeated-substring-pattern/README.md: -------------------------------------------------------------------------------- 1 |

    459. Repeated Substring Pattern

    Easy


    Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: s = "abab"
     7 | Output: true
     8 | Explanation: It is the substring "ab" twice.
     9 | 
    10 | 11 |

    Example 2:

    12 | 13 |
    Input: s = "aba"
    14 | Output: false
    15 | 
    16 | 17 |

    Example 3:

    18 | 19 |
    Input: s = "abcabcabcabc"
    20 | Output: true
    21 | Explanation: It is the substring "abc" four times or the substring "abcabc" twice.
    22 | 
    23 | 24 |

     

    25 |

    Constraints:

    26 | 27 |
      28 |
    • 1 <= s.length <= 104
    • 29 |
    • s consists of lowercase English letters.
    • 30 |
    31 |
    -------------------------------------------------------------------------------- /employee-importance/employee-importance.java: -------------------------------------------------------------------------------- 1 | // n = employees.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | 5 | /* 6 | // Definition for Employee. 7 | class Employee { 8 | public int id; 9 | public int importance; 10 | public List subordinates; 11 | }; 12 | */ 13 | 14 | class Solution { 15 | public int getImportance(List employees, int id) { 16 | Map map = new HashMap<>(); 17 | Map> adjList = new HashMap<>(); 18 | int total = 0; 19 | 20 | for (Employee emp : employees) { 21 | map.put(emp.id, emp.importance); 22 | adjList.put(emp.id, emp.subordinates); 23 | } 24 | 25 | Stack stack = new Stack<>(); 26 | stack.push(id); 27 | 28 | while (!stack.isEmpty()) { 29 | int currId = stack.pop(); 30 | total += map.get(currId); 31 | for (int sub : adjList.get(currId)) 32 | stack.push(sub); 33 | } 34 | 35 | return total; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /maximum-population-year/maximum-population-year.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximumPopulation(int[][] logs) { 3 | int min = Integer.MAX_VALUE; 4 | int max = Integer.MIN_VALUE; 5 | for (int[] log : logs) { 6 | min = Math.min(min, log[0]); 7 | max = Math.max(max, log[1]); 8 | } 9 | 10 | int span = max - min; 11 | int[] years = new int[span]; 12 | 13 | for (int[] log : logs) { 14 | int start = log[0] - min; 15 | int end = log[1] - min; 16 | for (int i = start; i < end; i++) { 17 | years[i]++; 18 | } 19 | } 20 | 21 | int maxPop = 0; 22 | for (int p : years) 23 | maxPop = Math.max(maxPop, p); 24 | 25 | int earliest = 0; 26 | for (int i = 0; i < years.length; i++) { 27 | if (years[i] == maxPop) { 28 | earliest = i; 29 | break; 30 | } 31 | } 32 | 33 | return min + earliest; 34 | } 35 | } -------------------------------------------------------------------------------- /minimum-number-of-frogs-croaking/minimum-number-of-frogs-croaking.java: -------------------------------------------------------------------------------- 1 | // n = croakOfFrogs.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int minNumberOfFrogs(String croakOfFrogs) { 6 | int[] counts = new int[5]; 7 | Map map = new HashMap<>(); 8 | map.put('c', 0); 9 | map.put('r', 1); 10 | map.put('o', 2); 11 | map.put('a', 3); 12 | map.put('k', 4); 13 | int result = 0; 14 | int count = 0; 15 | for (int i = 0; i < croakOfFrogs.length(); i++) { 16 | char c = croakOfFrogs.charAt(i); 17 | counts[map.get(c)]++; 18 | if (map.get(c) > 0) { 19 | counts[map.get(c) - 1]--; 20 | } 21 | if (c == 'c') { 22 | result = Math.max(result, ++count); 23 | } else if (counts[map.get(c) - 1] < 0) { 24 | return -1; 25 | } else if (c == 'k') { 26 | count--; 27 | } 28 | } 29 | return count == 0 ? result : -1; 30 | } 31 | } -------------------------------------------------------------------------------- /partition-equal-subset-sum/partition-equal-subset-sum.java: -------------------------------------------------------------------------------- 1 | // Bottom Up Dynamic Programming 2 | // n = nums.length, s = subsetSum 3 | // Time: O(n * s) 4 | // Space: O(n * s) 5 | class Solution { 6 | public boolean canPartition(int[] nums) { 7 | int sum = 0; 8 | for (int num : nums) sum += num; 9 | if (sum % 2 != 0) return false; 10 | 11 | // the target sum is the total 12 | // sum divided by two 13 | int subsetSum = sum / 2; 14 | 15 | int n = nums.length, s = subsetSum; 16 | boolean[][] dp = new boolean[n + 1][s + 1]; 17 | for (int i = 0; i < n; i++) 18 | dp[i][0] = true; 19 | 20 | for (int i = 1; i <= n; i++) { 21 | for (int j = 1; j <= s; j++) { 22 | if (j < nums[i - 1]) { 23 | dp[i][j] = dp[i - 1][j]; 24 | } else { 25 | dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]]; 26 | } 27 | } 28 | } 29 | 30 | return dp[n][s]; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /3sum/3sum.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n^2) 3 | // Space: O(n) - this is for sort; ignoring space for output 4 | class Solution { 5 | List> result = new ArrayList<>(); 6 | 7 | public List> threeSum(int[] nums) { 8 | int n = nums.length; 9 | Arrays.sort(nums); 10 | for (int i = 0; i < n - 2 && nums[i] <= 0; i++) { 11 | if (i > 0) { 12 | while (i < n - 2 && nums[i] == nums[i - 1]) i++; 13 | } 14 | getThreeSum(nums, i, i + 1, n - 1); 15 | } 16 | return result; 17 | } 18 | 19 | private void getThreeSum(int[] nums, int l, int m, int r) { 20 | while (m < r) { 21 | if (nums[l] + nums[m] + nums[r] == 0) { 22 | result.add(List.of(nums[l], nums[m], nums[r])); 23 | while (m < r && nums[m] == nums[m + 1]) m++; 24 | m++; 25 | } else if (nums[l] + nums[m] + nums[r] < 0) { 26 | m++; 27 | } else { 28 | r--; 29 | } 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /binary-tree-right-side-view/README.md: -------------------------------------------------------------------------------- 1 |

    199. Binary Tree Right Side View

    Medium


    Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: root = [1,2,3,null,5,null,4]
     7 | Output: [1,3,4]
     8 | 
    9 | 10 |

    Example 2:

    11 | 12 |
    Input: root = [1,null,3]
    13 | Output: [1,3]
    14 | 
    15 | 16 |

    Example 3:

    17 | 18 |
    Input: root = []
    19 | Output: []
    20 | 
    21 | 22 |

     

    23 |

    Constraints:

    24 | 25 |
      26 |
    • The number of nodes in the tree is in the range [0, 100].
    • 27 |
    • -100 <= Node.val <= 100
    • 28 |
    29 |
    -------------------------------------------------------------------------------- /invert-binary-tree/README.md: -------------------------------------------------------------------------------- 1 |

    226. Invert Binary Tree

    Easy


    Given the root of a binary tree, invert the tree, and return its root.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: root = [4,2,7,1,3,6,9]
     7 | Output: [4,7,2,9,6,3,1]
     8 | 
    9 | 10 |

    Example 2:

    11 | 12 |
    Input: root = [2,1,3]
    13 | Output: [2,3,1]
    14 | 
    15 | 16 |

    Example 3:

    17 | 18 |
    Input: root = []
    19 | Output: []
    20 | 
    21 | 22 |

     

    23 |

    Constraints:

    24 | 25 |
      26 |
    • The number of nodes in the tree is in the range [0, 100].
    • 27 |
    • -100 <= Node.val <= 100
    • 28 |
    29 |
    -------------------------------------------------------------------------------- /pancake-sorting/pancake-sorting.java: -------------------------------------------------------------------------------- 1 | // n = arr.length 2 | // Time: O(n^2) 3 | // Space: O(1) 4 | class Solution { 5 | public List pancakeSort(int[] arr) { 6 | List result = new ArrayList<>(); 7 | int n = arr.length; 8 | int biggest = arr.length; 9 | for (int i = 0; i < n ; i++) { 10 | int idx = find(arr, biggest); 11 | pancakeFlip(arr, idx); 12 | result.add(idx + 1); 13 | pancakeFlip(arr, biggest - 1); 14 | result.add(biggest--); 15 | } 16 | return result; 17 | } 18 | 19 | private void pancakeFlip(int[] arr, int k) { 20 | int l = 0, r = k; 21 | while (l < r) { 22 | int temp = arr[l]; 23 | arr[l] = arr[r]; 24 | arr[r] = temp; 25 | l++; 26 | r--; 27 | } 28 | } 29 | 30 | private int find(int[] arr, int target) { 31 | for (int i = 0; i < arr.length; i++) { 32 | if (arr[i] == target) 33 | return i; 34 | } 35 | return -1; 36 | } 37 | } -------------------------------------------------------------------------------- /top-k-frequent-elements/README.md: -------------------------------------------------------------------------------- 1 |

    347. Top K Frequent Elements

    Medium


    Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

    2 | 3 |

     

    4 |

    Example 1:

    5 |
    Input: nums = [1,1,1,2,2,3], k = 2
     6 | Output: [1,2]
     7 | 

    Example 2:

    8 |
    Input: nums = [1], k = 1
     9 | Output: [1]
    10 | 
    11 |

     

    12 |

    Constraints:

    13 | 14 |
      15 |
    • 1 <= nums.length <= 105
    • 16 |
    • k is in the range [1, the number of unique elements in the array].
    • 17 |
    • It is guaranteed that the answer is unique.
    • 18 |
    19 | 20 |

     

    21 |

    Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

    22 |
    -------------------------------------------------------------------------------- /construct-binary-tree-from-preorder-and-postorder-traversal/README.md: -------------------------------------------------------------------------------- 1 |

    889. Construct Binary Tree from Preorder and Postorder Traversal

    Medium


    Return any binary tree that matches the given preorder and postorder traversals.

    2 | 3 |

    Values in the traversals pre and post are distinct positive integers.

    4 | 5 |

     

    6 | 7 |
    8 |

    Example 1:

    9 | 10 |
    Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
    11 | Output: [1,2,3,4,5,6,7]
    12 | 
    13 | 14 |

     

    15 | 16 |

    Note:

    17 | 18 |
      19 |
    • 1 <= pre.length == post.length <= 30
    • 20 |
    • pre[] and post[] are both permutations of 1, 2, ..., pre.length.
    • 21 |
    • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.
    • 22 |
    23 |
    24 |
    -------------------------------------------------------------------------------- /shuffle-an-array/shuffle-an-array.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | int[] orig; 6 | int[] mod; 7 | 8 | public Solution(int[] nums) { 9 | this.orig = nums; 10 | this.mod = nums.clone(); 11 | } 12 | 13 | /** Resets the array to its original configuration and return it. */ 14 | public int[] reset() { 15 | mod = orig.clone(); 16 | return mod; 17 | } 18 | 19 | /** Returns a random shuffling of the array. */ 20 | public int[] shuffle() { 21 | Random rand = new Random(); 22 | for (int i = 0; i < mod.length; i++) 23 | swap(i, rand.nextInt(mod.length - i) + i); 24 | 25 | return mod; 26 | } 27 | 28 | private void swap(int a, int b) { 29 | int temp = mod[a]; 30 | mod[a] = mod[b]; 31 | mod[b] = temp; 32 | } 33 | } 34 | 35 | /** 36 | * Your Solution object will be instantiated and called as such: 37 | * Solution obj = new Solution(nums); 38 | * int[] param_1 = obj.reset(); 39 | * int[] param_2 = obj.shuffle(); 40 | */ 41 | -------------------------------------------------------------------------------- /least-number-of-unique-integers-after-k-removals/README.md: -------------------------------------------------------------------------------- 1 |

    1481. Least Number of Unique Integers after K Removals

    Medium


    Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.

    2 | 3 |
      4 |
    5 | 6 |

     

    7 |

    Example 1:

    8 | 9 |
    Input: arr = [5,5,4], k = 1
    10 | Output: 1
    11 | Explanation: Remove the single 4, only 5 is left.
    12 | 
    13 | Example 2: 14 | 15 |
    Input: arr = [4,3,1,1,3,3,2], k = 3
    16 | Output: 2
    17 | Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
    18 | 19 |

     

    20 |

    Constraints:

    21 | 22 |
      23 |
    • 1 <= arr.length <= 10^5
    • 24 |
    • 1 <= arr[i] <= 10^9
    • 25 |
    • 0 <= k <= arr.length
    • 26 |
    -------------------------------------------------------------------------------- /reverse-integer/README.md: -------------------------------------------------------------------------------- 1 |

    7. Reverse Integer

    Easy


    Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

    2 | 3 |

    Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: x = 123
     8 | Output: 321
     9 | 

    Example 2:

    10 |
    Input: x = -123
    11 | Output: -321
    12 | 

    Example 3:

    13 |
    Input: x = 120
    14 | Output: 21
    15 | 

    Example 4:

    16 |
    Input: x = 0
    17 | Output: 0
    18 | 
    19 |

     

    20 |

    Constraints:

    21 | 22 |
      23 |
    • -231 <= x <= 231 - 1
    • 24 |
    25 |
    -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-list-ii/remove-duplicates-from-sorted-list-ii.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 | 12 | // n = number of nodes 13 | // Time: O(n) 14 | // Space: O(1) 15 | class Solution { 16 | public ListNode deleteDuplicates(ListNode head) { 17 | ListNode dummy = new ListNode(); 18 | dummy.next = head; 19 | 20 | ListNode curr = dummy; 21 | while (curr.next != null && curr.next.next != null) { 22 | if (curr.next.val == curr.next.next.val) { 23 | while (curr.next.next != null && curr.next.val == curr.next.next.val) { 24 | curr.next = curr.next.next; 25 | } 26 | curr.next = curr.next.next; 27 | } else { 28 | curr = curr.next; 29 | } 30 | } 31 | 32 | return dummy.next; 33 | } 34 | } -------------------------------------------------------------------------------- /longest-palindromic-substring/longest-palindromic-substring.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String longestPalindrome(String s) { 3 | boolean[][] dp = new boolean[s.length()][s.length()]; 4 | 5 | for (int i = 0; i < s.length(); i++) 6 | dp[i][i] = true; 7 | 8 | int maxLength = 0; 9 | String result = s.substring(0, 1); 10 | for (int startIndex = s.length() - 1; startIndex >= 0; startIndex--) { 11 | for (int endIndex = startIndex + 1; endIndex < s.length(); endIndex++) { 12 | if (s.charAt(startIndex) == s.charAt(endIndex)) { 13 | if (endIndex - startIndex == 1 || dp[startIndex + 1][endIndex - 1]) { 14 | dp[startIndex][endIndex] = true; 15 | if (endIndex - startIndex + 1 > maxLength) { 16 | maxLength = endIndex - startIndex + 1; 17 | result = s.substring(startIndex, endIndex + 1); 18 | } 19 | } 20 | } 21 | } 22 | } 23 | return result; 24 | } 25 | } -------------------------------------------------------------------------------- /binary-tree-zigzag-level-order-traversal/README.md: -------------------------------------------------------------------------------- 1 |

    103. Binary Tree Zigzag Level Order Traversal

    Medium


    Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: root = [3,9,20,null,null,15,7]
     7 | Output: [[3],[20,9],[15,7]]
     8 | 
    9 | 10 |

    Example 2:

    11 | 12 |
    Input: root = [1]
    13 | Output: [[1]]
    14 | 
    15 | 16 |

    Example 3:

    17 | 18 |
    Input: root = []
    19 | Output: []
    20 | 
    21 | 22 |

     

    23 |

    Constraints:

    24 | 25 |
      26 |
    • The number of nodes in the tree is in the range [0, 2000].
    • 27 |
    • -100 <= Node.val <= 100
    • 28 |
    29 |
    -------------------------------------------------------------------------------- /lowest-common-ancestor-of-a-binary-tree/lowest-common-ancestor-of-a-binary-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | 11 | // n = number of nodes 12 | // Time: O(n) 13 | // Space: O(n) 14 | class Solution { 15 | TreeNode LCA = null; 16 | 17 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 18 | findLCA(root, p, q); 19 | return LCA; 20 | } 21 | 22 | private boolean findLCA(TreeNode node, TreeNode p, TreeNode q) { 23 | if (node == null) { 24 | return false; 25 | } 26 | 27 | boolean left = findLCA(node.left, p, q) ? true : false; 28 | boolean right = findLCA(node.right, p, q) ? true : false; 29 | boolean found = (node == p || node == q) ? true : false; 30 | 31 | if (left && right || left && found || right && found) { 32 | LCA = node; 33 | } 34 | 35 | return left || right || found; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /trapping-rain-water/README.md: -------------------------------------------------------------------------------- 1 |

    42. Trapping Rain Water

    Hard


    Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
     7 | Output: 6
     8 | Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
     9 | 
    10 | 11 |

    Example 2:

    12 | 13 |
    Input: height = [4,2,0,3,2,5]
    14 | Output: 9
    15 | 
    16 | 17 |

     

    18 |

    Constraints:

    19 | 20 |
      21 |
    • n == height.length
    • 22 |
    • 0 <= n <= 3 * 104
    • 23 |
    • 0 <= height[i] <= 105
    • 24 |
    25 |
    -------------------------------------------------------------------------------- /group-anagrams/README.md: -------------------------------------------------------------------------------- 1 |

    49. Group Anagrams

    Medium


    Given an array of strings strs, group the anagrams together. You can return the answer in any order.

    2 | 3 |

    An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: strs = ["eat","tea","tan","ate","nat","bat"]
     8 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
     9 | 

    Example 2:

    10 |
    Input: strs = [""]
    11 | Output: [[""]]
    12 | 

    Example 3:

    13 |
    Input: strs = ["a"]
    14 | Output: [["a"]]
    15 | 
    16 |

     

    17 |

    Constraints:

    18 | 19 |
      20 |
    • 1 <= strs.length <= 104
    • 21 |
    • 0 <= strs[i].length <= 100
    • 22 |
    • strs[i] consists of lower-case English letters.
    • 23 |
    24 |
    -------------------------------------------------------------------------------- /minimum-path-sum/README.md: -------------------------------------------------------------------------------- 1 |

    64. Minimum Path Sum

    Medium


    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

    2 | 3 |

    Note: You can only move either down or right at any point in time.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
     9 | Output: 7
    10 | Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
    11 | 
    12 | 13 |

    Example 2:

    14 | 15 |
    Input: grid = [[1,2,3],[4,5,6]]
    16 | Output: 12
    17 | 
    18 | 19 |

     

    20 |

    Constraints:

    21 | 22 |
      23 |
    • m == grid.length
    • 24 |
    • n == grid[i].length
    • 25 |
    • 1 <= m, n <= 200
    • 26 |
    • 0 <= grid[i][j] <= 100
    • 27 |
    28 |
    -------------------------------------------------------------------------------- /max-area-of-island/README.md: -------------------------------------------------------------------------------- 1 |

    695. Max Area of Island

    Medium


    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

    2 | 3 |

    Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

    4 | 5 |

    Example 1:

    6 | 7 |
    [[0,0,1,0,0,0,0,1,0,0,0,0,0],
     8 |  [0,0,0,0,0,0,0,1,1,1,0,0,0],
     9 |  [0,1,1,0,1,0,0,0,0,0,0,0,0],
    10 |  [0,1,0,0,1,1,0,0,1,0,1,0,0],
    11 |  [0,1,0,0,1,1,0,0,1,1,1,0,0],
    12 |  [0,0,0,0,0,0,0,0,0,0,1,0,0],
    13 |  [0,0,0,0,0,0,0,1,1,1,0,0,0],
    14 |  [0,0,0,0,0,0,0,1,1,0,0,0,0]]
    15 | 
    16 | Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally. 17 | 18 |

    Example 2:

    19 | 20 |
    [[0,0,0,0,0,0,0,0]]
    21 | Given the above grid, return 0. 22 | 23 |

    Note: The length of each dimension in the given grid does not exceed 50.

    24 |
    -------------------------------------------------------------------------------- /binary-tree-level-order-traversal/README.md: -------------------------------------------------------------------------------- 1 | [

    Click here for detailed solution

    ](https://www.danielleskosky.com/make-bfs-your-bff/) 2 | 3 |

    102. Binary Tree Level Order Traversal

    Medium


    Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: root = [3,9,20,null,null,15,7]
     9 | Output: [[3],[9,20],[15,7]]
    10 | 
    11 | 12 |

    Example 2:

    13 | 14 |
    Input: root = [1]
    15 | Output: [[1]]
    16 | 
    17 | 18 |

    Example 3:

    19 | 20 |
    Input: root = []
    21 | Output: []
    22 | 
    23 | 24 |

     

    25 |

    Constraints:

    26 | 27 |
      28 |
    • The number of nodes in the tree is in the range [0, 2000].
    • 29 |
    • -1000 <= Node.val <= 1000
    • 30 |
    31 |
    32 | -------------------------------------------------------------------------------- /merge-intervals/README.md: -------------------------------------------------------------------------------- 1 |

    56. Merge Intervals

    Medium


    Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
     7 | Output: [[1,6],[8,10],[15,18]]
     8 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
     9 | 
    10 | 11 |

    Example 2:

    12 | 13 |
    Input: intervals = [[1,4],[4,5]]
    14 | Output: [[1,5]]
    15 | Explanation: Intervals [1,4] and [4,5] are considered overlapping.
    16 | 
    17 | 18 |

     

    19 |

    Constraints:

    20 | 21 |
      22 |
    • 1 <= intervals.length <= 104
    • 23 |
    • intervals[i].length == 2
    • 24 |
    • 0 <= starti <= endi <= 104
    • 25 |
    26 |
    -------------------------------------------------------------------------------- /number-of-closed-islands/number-of-closed-islands.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] dir = new int[]{0, 1, 0, -1, 0}; 3 | 4 | public int closedIsland(int[][] grid) { 5 | for (int i = 0; i < grid.length; i++) { 6 | for (int j = 0; j < grid[i].length; j++) { 7 | if (i == 0 || j == 0 || i == grid.length - 1 || j == grid[i].length - 1) { 8 | fill(grid, i, j); 9 | } 10 | } 11 | } 12 | 13 | int result = 0; 14 | for (int i = 0; i < grid.length; i++) { 15 | for (int j = 0; j < grid[i].length; j++) { 16 | if (grid[i][j] == 0) { 17 | result++; 18 | fill(grid, i, j); 19 | } 20 | } 21 | } 22 | 23 | return result; 24 | } 25 | 26 | private void fill(int[][] grid, int r, int c) { 27 | if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] == 1) 28 | return; 29 | grid[r][c] = 1; 30 | for (int i = 0; i < dir.length - 1; i++) { 31 | fill(grid, r + dir[i], c + dir[i+1]); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /asteroid-collision/asteroid-collision.java: -------------------------------------------------------------------------------- 1 | // n = asteroids.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int[] asteroidCollision(int[] asteroids) { 6 | Stack stack = new Stack<>(); 7 | for (int asteroid : asteroids) { 8 | if (asteroid > 0) { 9 | stack.push(asteroid); 10 | } else { 11 | boolean push = true; 12 | while (!stack.isEmpty() && stack.peek() > 0 && asteroid < 0) { 13 | if (stack.peek() < -asteroid) { 14 | stack.pop(); 15 | continue; 16 | } else if (stack.peek() == -asteroid) { 17 | stack.pop(); 18 | } 19 | push = false; 20 | break; 21 | } 22 | if (push) { 23 | stack.push(asteroid); 24 | } 25 | } 26 | } 27 | int[] result = new int[stack.size()]; 28 | for (int i = stack.size() - 1; i >= 0; i--) { 29 | result[i] = stack.pop(); 30 | } 31 | return result; 32 | } 33 | } -------------------------------------------------------------------------------- /max-area-of-island/max-area-of-island.java: -------------------------------------------------------------------------------- 1 | // m = grid.length, n = grid[0].length 2 | // Time: O(m * n) 3 | // Space: O(m * n) 4 | class Solution { 5 | int area, max = 0; 6 | int m, n; 7 | 8 | public int maxAreaOfIsland(int[][] grid) { 9 | m = grid.length; 10 | n = grid[0].length; 11 | boolean[][] visited = new boolean[m][n]; 12 | 13 | for (int i = 0; i < m; i++) { 14 | for (int j = 0; j < n; j++) { 15 | if (grid[i][j] == 1) { 16 | area = 0; 17 | dfs(grid, visited, i, j); 18 | max = Math.max(max, area); 19 | } 20 | } 21 | } 22 | 23 | return max; 24 | } 25 | 26 | private void dfs(int[][] grid, boolean[][] visited, int i, int j) { 27 | if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || grid[i][j] != 1) 28 | return; 29 | 30 | area++; 31 | visited[i][j] = true; 32 | 33 | dfs(grid, visited, i + 1, j); 34 | dfs(grid, visited, i, j + 1); 35 | dfs(grid, visited, i - 1, j); 36 | dfs(grid, visited, i, j - 1); 37 | } 38 | } -------------------------------------------------------------------------------- /minimum-window-substring/README.md: -------------------------------------------------------------------------------- 1 |

    76. Minimum Window Substring

    Hard


    Given two strings s and t, return the minimum window in s which will contain all the characters in t. If there is no such window in s that covers all characters in t, return the empty string "".

    2 | 3 |

    Note that If there is such a window, it is guaranteed that there will always be only one unique minimum window in s.

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: s = "ADOBECODEBANC", t = "ABC"
     8 | Output: "BANC"
     9 | 

    Example 2:

    10 |
    Input: s = "a", t = "a"
    11 | Output: "a"
    12 | 
    13 |

     

    14 |

    Constraints:

    15 | 16 |
      17 |
    • 1 <= s.length, t.length <= 105
    • 18 |
    • s and t consist of English letters.
    • 19 |
    20 | 21 |

     

    22 | Follow up: Could you find an algorithm that runs in O(n) time?
    -------------------------------------------------------------------------------- /subdomain-visit-count/subdomain-visit-count.java: -------------------------------------------------------------------------------- 1 | // n = cpdomains.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public List subdomainVisits(String[] cpdomains) { 6 | List result = new ArrayList<>(); 7 | Map map = new HashMap<>(); 8 | for (String cpdomain : cpdomains) { 9 | String[] cp = cpdomain.split("\\s+"); 10 | 11 | int count = Integer.valueOf(cp[0]); 12 | String[] url = cp[1].split("\\."); 13 | 14 | StringBuilder sb = new StringBuilder(); 15 | for (int i = url.length - 1; i >= 0; i--) { 16 | sb.insert(0, url[i]); 17 | String key = sb.toString(); 18 | map.put(key, map.getOrDefault(key, 0) + count); 19 | sb.insert(0, "."); 20 | } 21 | } 22 | 23 | for (String key : map.keySet()) { 24 | StringBuilder sb = new StringBuilder(); 25 | sb.append(map.get(key)); 26 | sb.append(" "); 27 | sb.append(key); 28 | result.add(sb.toString()); 29 | } 30 | 31 | return result; 32 | } 33 | } -------------------------------------------------------------------------------- /task-scheduler/task-scheduler.java: -------------------------------------------------------------------------------- 1 | // Time : O(n) 2 | // Space: O(1) 3 | class Solution { 4 | public int leastInterval(char[] tasks, int n) { 5 | if (n == 0) return tasks.length; 6 | 7 | int[] taskTracker = new int[26]; 8 | for (char task : tasks) { 9 | taskTracker[task - 'A']++; 10 | } 11 | 12 | PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); 13 | for (int count : taskTracker) { 14 | if (count != 0) { 15 | pq.offer(count); 16 | } 17 | } 18 | 19 | Map coolDown = new HashMap<>(); 20 | int time = 0; 21 | while (!pq.isEmpty() || !coolDown.isEmpty()) { 22 | if (coolDown.containsKey(time - n - 1)) { 23 | pq.offer(coolDown.get(time - n - 1)); 24 | coolDown.remove(time - n - 1); 25 | } 26 | if (!pq.isEmpty()) { 27 | int polled = pq.poll() - 1; 28 | if (polled != 0) { 29 | coolDown.put(time, polled); 30 | } 31 | } 32 | time++; 33 | } 34 | return time; 35 | } 36 | } -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-list-ii/README.md: -------------------------------------------------------------------------------- 1 |

    82. Remove Duplicates from Sorted List II

    Medium


    Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: head = [1,2,3,3,4,4,5]
     7 | Output: [1,2,5]
     8 | 
    9 | 10 |

    Example 2:

    11 | 12 |
    Input: head = [1,1,1,2,3]
    13 | Output: [2,3]
    14 | 
    15 | 16 |

     

    17 |

    Constraints:

    18 | 19 |
      20 |
    • The number of nodes in the list is in the range [0, 300].
    • 21 |
    • -100 <= Node.val <= 100
    • 22 |
    • The list is guaranteed to be sorted in ascending order.
    • 23 |
    24 |
    -------------------------------------------------------------------------------- /shortest-word-distance/README.md: -------------------------------------------------------------------------------- 1 |

    243. Shortest Word Distance

    Easy


    Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
     7 | Output: 3
     8 | 
    9 | 10 |

    Example 2:

    11 | 12 |
    Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
    13 | Output: 1
    14 | 
    15 | 16 |

     

    17 |

    Constraints:

    18 | 19 |
      20 |
    • 1 <= wordsDict.length <= 3 * 104
    • 21 |
    • 1 <= wordsDict[i].length <= 10
    • 22 |
    • wordsDict[i] consists of lowercase English letters.
    • 23 |
    • word1 and word2 are in wordsDict.
    • 24 |
    • word1 != word2
    • 25 |
    26 |
    -------------------------------------------------------------------------------- /remove-all-adjacent-duplicates-in-string-ii/remove-all-adjacent-duplicates-in-string-ii.java: -------------------------------------------------------------------------------- 1 | // n = s.length() 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public String removeDuplicates(String s, int k) { 6 | ArrayDeque> stack = new ArrayDeque<>(); 7 | for (char c : s.toCharArray()) { 8 | if (!stack.isEmpty() && stack.peek().getKey() == c) { 9 | int currVal = stack.peek().getValue(); 10 | stack.pop(); 11 | stack.push(new Pair(c, currVal + 1)); 12 | if (stack.peek().getValue() == k) { 13 | stack.pop(); 14 | } 15 | } else { 16 | stack.push(new Pair(c, 1)); 17 | } 18 | } 19 | 20 | StringBuilder sb = new StringBuilder(); 21 | while (!stack.isEmpty()) { 22 | Pair popped = stack.pop(); 23 | char key = popped.getKey(); 24 | int value = popped.getValue(); 25 | for (int i = 0; i < value; i++) { 26 | sb.append(key); 27 | } 28 | } 29 | 30 | return sb.reverse().toString(); 31 | } 32 | } -------------------------------------------------------------------------------- /sliding-window-maximum/sliding-window-maximum.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int[] maxSlidingWindow(int[] nums, int k) { 6 | int n = nums.length; 7 | if (k == 1) return nums; 8 | 9 | int[] result = new int[n - k + 1]; 10 | ArrayDeque deq = new ArrayDeque<>(); 11 | int maxIdx = 0; 12 | 13 | for (int i = 0; i < k; i++) { 14 | cleanDeque(nums, deq, k, i); 15 | deq.addLast(i); 16 | if (nums[i] > nums[maxIdx]) maxIdx = i; 17 | } 18 | 19 | result[0] = nums[maxIdx]; 20 | 21 | for (int i = k; i < n; i++) { 22 | cleanDeque(nums, deq, k, i); 23 | deq.addLast(i); 24 | result[i - k + 1] = nums[deq.getFirst()]; 25 | } 26 | 27 | return result; 28 | } 29 | 30 | private void cleanDeque(int[] nums, ArrayDeque deq, int k, int i) { 31 | if (!deq.isEmpty() && deq.getFirst() == i - k) 32 | deq.removeFirst(); 33 | 34 | while (!deq.isEmpty() && nums[i] > nums[deq.getLast()]) 35 | deq.removeLast(); 36 | } 37 | } -------------------------------------------------------------------------------- /two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.java: -------------------------------------------------------------------------------- 1 | // n = numbers.length 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public int[] twoSum(int[] numbers, int target) { 6 | Map map = new HashMap<>(); 7 | for (int i = 0; i < numbers.length; i++) { 8 | if (map.containsKey(target - numbers[i])) 9 | return new int[]{map.get(target - numbers[i]) + 1, i + 1}; 10 | 11 | map.put(numbers[i], i); 12 | } 13 | 14 | return new int[0]; 15 | } 16 | } 17 | 18 | // Time: O(n) 19 | // Space: O(1) 20 | class Solution { 21 | public int[] twoSum(int[] numbers, int target) { 22 | int n = numbers.length; 23 | int left = 0, right = numbers.length - 1; 24 | while (left < right) { 25 | if (numbers[left] + numbers[right] == target) 26 | return new int[]{left + 1, right + 1}; 27 | 28 | if (numbers[left] + numbers[right] > target) 29 | right--; 30 | if (numbers[left] + numbers[right] < target) 31 | left++; 32 | } 33 | 34 | return new int[0]; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /longest-univalue-path/longest-univalue-path.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 | 17 | // Time: O(N) where N is the number of nodes in tree 18 | // Space: O(H) where H is the height of the tree 19 | class Solution { 20 | int longest = 0; 21 | 22 | public int longestUnivaluePath(TreeNode root) { 23 | if (root == null) return 0; 24 | getLongPath(root, root.val); 25 | return longest; 26 | } 27 | 28 | private int getLongPath(TreeNode node, int prev) { 29 | if (node == null) return 0; 30 | 31 | int left = getLongPath(node.left, node.val); 32 | int right = getLongPath(node.right, node.val); 33 | 34 | longest = Math.max(longest, left + right); 35 | 36 | if (prev == node.val) return Math.max(left, right) + 1; 37 | return 0; 38 | } 39 | } -------------------------------------------------------------------------------- /minimum-time-to-collect-all-apples-in-a-tree/minimum-time-to-collect-all-apples-in-a-tree.java: -------------------------------------------------------------------------------- 1 | // n = number of nodes 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | Set visited = new HashSet<>(); 6 | 7 | public int minTime(int n, int[][] edges, List hasApple) { 8 | Map> adj = new HashMap<>(); 9 | for (int[] edge : edges) { 10 | adj.putIfAbsent(edge[0], new ArrayList<>()); 11 | adj.putIfAbsent(edge[1], new ArrayList<>()); 12 | adj.get(edge[0]).add(edge[1]); 13 | adj.get(edge[1]).add(edge[0]); 14 | } 15 | return dfs(0, adj, hasApple, 0); 16 | } 17 | 18 | private int dfs(int parent, Map> adj, List hasApple, int baseTime) { 19 | if (visited.contains(parent)) { 20 | return 0; 21 | } 22 | visited.add(parent); 23 | int totalTime = 0; 24 | for (int child : adj.get(parent)) { 25 | totalTime += dfs(child, adj, hasApple, 2); 26 | } 27 | if (totalTime == 0 && !hasApple.get(parent)) { 28 | return 0; 29 | } 30 | return totalTime + baseTime; 31 | } 32 | } -------------------------------------------------------------------------------- /two-sum-bsts/README.md: -------------------------------------------------------------------------------- 1 |

    1214. Two Sum BSTs

    Medium


    Given the roots of two binary search trees, root1 and root2, return true if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer target.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: root1 = [2,1,4], root2 = [1,0,3], target = 5
     7 | Output: true
     8 | Explanation: 2 and 3 sum up to 5.
     9 | 
    10 | 11 |

    Example 2:

    12 | 13 |
    Input: root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18
    14 | Output: false
    15 | 
    16 | 17 |

     

    18 |

    Constraints:

    19 | 20 |
      21 |
    • The number of nodes in each tree is in the range [1, 5000].
    • 22 |
    • -109 <= Node.val, target <= 109
    • 23 |
    24 |
    -------------------------------------------------------------------------------- /sentence-screen-fitting/sentence-screen-fitting.java: -------------------------------------------------------------------------------- 1 | // n = all characters in each string in sentence array 2 | // plus 1 for every string in that array for spacing 3 | // Time: O((rows * cols) / n) 4 | // Space: O(1) 5 | class Solution { 6 | public int wordsTyping(String[] sentence, int rows, int cols) { 7 | int sentenceCount = 0; 8 | int rowCount = 1; 9 | int currRowWidth = 0; 10 | boolean isRoom = true; 11 | while (rowCount <= rows) { 12 | for (String word : sentence) { 13 | if (word.length() > cols) { 14 | return 0; 15 | } 16 | currRowWidth += word.length() + 1; 17 | if (currRowWidth == cols + 1) { 18 | currRowWidth--; 19 | } 20 | if (currRowWidth > cols) { 21 | rowCount++; 22 | if (rowCount > rows) { 23 | isRoom = false; 24 | break; 25 | } 26 | currRowWidth = word.length() + 1; 27 | } 28 | } 29 | if (isRoom) sentenceCount++; 30 | } 31 | return sentenceCount; 32 | } 33 | } -------------------------------------------------------------------------------- /odd-even-linked-list/odd-even-linked-list.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 | // Time: O(n) 12 | // Space: O(1) 13 | class Solution { 14 | public ListNode oddEvenList(ListNode head) { 15 | if (head == null || head.next == null || head.next.next == null) 16 | return head; 17 | 18 | ListNode oddHead = head; 19 | ListNode evenHead = head.next; 20 | 21 | ListNode oddNode = oddHead; 22 | ListNode evenNode = evenHead; 23 | 24 | ListNode current = head.next.next; 25 | while (current != null) { 26 | oddNode.next = current; 27 | oddNode = oddNode.next; 28 | current = current.next; 29 | 30 | evenNode.next = current; 31 | evenNode = evenNode.next; 32 | if (current != null) current = current.next; 33 | } 34 | 35 | oddNode.next = evenHead; 36 | 37 | return oddHead; 38 | } 39 | } -------------------------------------------------------------------------------- /letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.java: -------------------------------------------------------------------------------- 1 | // n = digits.length() 2 | // Time: O((4^n) * n) 4 represents longest String in keys[] 3 | // Space: O(n) 4 | 5 | class Solution { 6 | final String[] keys = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", 7 | "pqrs", "tuv", "wxyz"}; 8 | 9 | public List letterCombinations(String digits) { 10 | List result = new ArrayList<>(); 11 | if (digits.length() == 0) return result; 12 | 13 | backtrack(digits, 0, new StringBuilder(), result); 14 | return result; 15 | } 16 | 17 | private void backtrack(String digits, int index, StringBuilder combo, List result) { 18 | if (index == digits.length()) { 19 | result.add(new String(combo)); 20 | return; 21 | } 22 | 23 | String currKey = keys[digits.charAt(index) - '0']; 24 | 25 | for (int i = 0; i < currKey.length(); i++) { 26 | combo.append(currKey.charAt(i)); 27 | backtrack(digits, index + 1, new StringBuilder(combo), result); 28 | combo.deleteCharAt(combo.length() - 1); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /longest-univalue-path/README.md: -------------------------------------------------------------------------------- 1 |

    687. Longest Univalue Path

    Medium


    Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.

    2 | 3 |

    The length of the path between two nodes is represented by the number of edges between them.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: root = [5,4,5,1,1,5]
     9 | Output: 2
    10 | 
    11 | 12 |

    Example 2:

    13 | 14 |
    Input: root = [1,4,5,4,4,5]
    15 | Output: 2
    16 | 
    17 | 18 |

     

    19 |

    Constraints:

    20 | 21 |
      22 |
    • The number of nodes in the tree is in the range [0, 104].
    • 23 |
    • -1000 <= Node.val <= 1000
    • 24 |
    • The depth of the tree will not exceed 1000.
    • 25 |
    26 |
    -------------------------------------------------------------------------------- /n-queens/README.md: -------------------------------------------------------------------------------- 1 |

    51. N-Queens

    Hard


    The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

    2 | 3 |

    Given an integer n, return all distinct solutions to the n-queens puzzle.

    4 | 5 |

    Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

    6 | 7 |

     

    8 |

    Example 1:

    9 | 10 |
    Input: n = 4
    11 | Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
    12 | Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
    13 | 
    14 | 15 |

    Example 2:

    16 | 17 |
    Input: n = 1
    18 | Output: [["Q"]]
    19 | 
    20 | 21 |

     

    22 |

    Constraints:

    23 | 24 |
      25 |
    • 1 <= n <= 9
    • 26 |
    27 |
    -------------------------------------------------------------------------------- /number-of-connected-components-in-an-undirected-graph/number-of-connected-components-in-an-undirected-graph.java: -------------------------------------------------------------------------------- 1 | // E = number of edges, V = number of vertices 2 | // Time: O(E + V) 3 | // Space: O(E + V) 4 | class Solution { 5 | Set visited; 6 | public int countComponents(int n, int[][] edges) { 7 | Map> adj = new HashMap<>(); 8 | int count = 0; 9 | for (int[] edge : edges) { 10 | adj.putIfAbsent(edge[0], new ArrayList<>()); 11 | adj.get(edge[0]).add(edge[1]); 12 | adj.putIfAbsent(edge[1], new ArrayList<>()); 13 | adj.get(edge[1]).add(edge[0]); 14 | } 15 | visited = new HashSet<>(); 16 | for (int node : adj.keySet()) { 17 | if (!visited.contains(node)) { 18 | count++; 19 | dfs(adj, node); 20 | } 21 | } 22 | return n > adj.size() ? count + (n - adj.size()) : count; 23 | } 24 | 25 | private void dfs(Map> adj, int node) { 26 | visited.add(node); 27 | for (int nei : adj.get(node)) { 28 | if (!visited.contains(nei)) { 29 | dfs(adj, nei); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /reverse-linked-list/README.md: -------------------------------------------------------------------------------- 1 |

    206. Reverse Linked List

    Easy


    Given the head of a singly linked list, reverse the list, and return the reversed list.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: head = [1,2,3,4,5]
     7 | Output: [5,4,3,2,1]
     8 | 
    9 | 10 |

    Example 2:

    11 | 12 |
    Input: head = [1,2]
    13 | Output: [2,1]
    14 | 
    15 | 16 |

    Example 3:

    17 | 18 |
    Input: head = []
    19 | Output: []
    20 | 
    21 | 22 |

     

    23 |

    Constraints:

    24 | 25 |
      26 |
    • The number of nodes in the list is the range [0, 5000].
    • 27 |
    • -5000 <= Node.val <= 5000
    • 28 |
    29 | 30 |

     

    31 |

    Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

    32 |
    -------------------------------------------------------------------------------- /basic-calculator-ii/README.md: -------------------------------------------------------------------------------- 1 |

    227. Basic Calculator II

    Medium


    Given a string s which represents an expression, evaluate this expression and return its value

    2 | 3 |

    The integer division should truncate toward zero.

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: s = "3+2*2"
     8 | Output: 7
     9 | 

    Example 2:

    10 |
    Input: s = " 3/2 "
    11 | Output: 1
    12 | 

    Example 3:

    13 |
    Input: s = " 3+5 / 2 "
    14 | Output: 5
    15 | 
    16 |

     

    17 |

    Constraints:

    18 | 19 |
      20 |
    • 1 <= s.length <= 3 * 105
    • 21 |
    • s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
    • 22 |
    • s represents a valid expression.
    • 23 |
    • All the integers in the expression are non-negative integers in the range [0, 231 - 1].
    • 24 |
    • The answer is guaranteed to fit in a 32-bit integer.
    • 25 |
    26 |
    -------------------------------------------------------------------------------- /delete-nodes-and-return-forest/delete-nodes-and-return-forest.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 | Set to_delete_set; 18 | List result; 19 | public List delNodes(TreeNode root, int[] to_delete) { 20 | to_delete_set = new HashSet<>(); 21 | result = new ArrayList<>(); 22 | for (int i : to_delete) { 23 | to_delete_set.add(i); 24 | } 25 | helper(root, true); 26 | return result; 27 | } 28 | 29 | private TreeNode helper(TreeNode node, boolean is_root) { 30 | if (node == null) return null; 31 | boolean deleted = to_delete_set.contains(node.val); 32 | if (is_root && !deleted) result.add(node); 33 | node.left = helper(node.left, deleted); 34 | node.right = helper(node.right, deleted); 35 | return deleted ? null : node; 36 | } 37 | } -------------------------------------------------------------------------------- /maximum-product-subarray/README.md: -------------------------------------------------------------------------------- 1 |

    152. Maximum Product Subarray

    Medium


    Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

    2 | 3 |

    It is guaranteed that the answer will fit in a 32-bit integer.

    4 | 5 |

    A subarray is a contiguous subsequence of the array.

    6 | 7 |

     

    8 |

    Example 1:

    9 | 10 |
    Input: nums = [2,3,-2,4]
    11 | Output: 6
    12 | Explanation: [2,3] has the largest product 6.
    13 | 
    14 | 15 |

    Example 2:

    16 | 17 |
    Input: nums = [-2,0,-1]
    18 | Output: 0
    19 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
    20 | 
    21 | 22 |

     

    23 |

    Constraints:

    24 | 25 |
      26 |
    • 1 <= nums.length <= 2 * 104
    • 27 |
    • -10 <= nums[i] <= 10
    • 28 |
    • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
    • 29 |
    30 |
    -------------------------------------------------------------------------------- /diameter-of-binary-tree/README.md: -------------------------------------------------------------------------------- 1 |

    543. Diameter of Binary Tree

    Easy


    Given the root of a binary tree, return the length of the diameter of the tree.

    2 | 3 |

    The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

    4 | 5 |

    The length of a path between two nodes is represented by the number of edges between them.

    6 | 7 |

     

    8 |

    Example 1:

    9 | 10 |
    Input: root = [1,2,3,4,5]
    11 | Output: 3
    12 | Explanation: 3is the length of the path [4,2,1,3] or [5,2,1,3].
    13 | 
    14 | 15 |

    Example 2:

    16 | 17 |
    Input: root = [1,2]
    18 | Output: 1
    19 | 
    20 | 21 |

     

    22 |

    Constraints:

    23 | 24 |
      25 |
    • The number of nodes in the tree is in the range [1, 104].
    • 26 |
    • -100 <= Node.val <= 100
    • 27 |
    28 |
    -------------------------------------------------------------------------------- /shortest-bridge/README.md: -------------------------------------------------------------------------------- 1 |

    934. Shortest Bridge

    Medium


    In a given 2D binary array grid, there are two islands.  (An island is a 4-directionally connected group of 1s not connected to any other 1s.)

    2 | 3 |

    Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.

    4 | 5 |

    Return the smallest number of 0s that must be flipped.  (It is guaranteed that the answer is at least 1.)

    6 | 7 |

     

    8 |

    Example 1:

    9 | 10 |
    Input: grid = [[0,1],[1,0]]
    11 | Output: 1
    12 | 
    13 | 14 |

    Example 2:

    15 | 16 |
    Input: grid = [[0,1,0],[0,0,0],[0,0,1]]
    17 | Output: 2
    18 | 
    19 | 20 |

    Example 3:

    21 | 22 |
    Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
    23 | Output: 1
    24 | 
    25 | 26 |

     

    27 |

    Constraints:

    28 | 29 |
      30 |
    • 2 <= grid.length == grid[0].length <= 100
    • 31 |
    • grid[i][j] == 0 or grid[i][j] == 1
    • 32 |
    33 |
    -------------------------------------------------------------------------------- /find-all-duplicates-in-an-array/README.md: -------------------------------------------------------------------------------- 1 |

    442. Find All Duplicates in an Array

    Medium


    Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

    2 | 3 |

    You must write an algorithm that runs in O(n) time and uses only constant extra space.

    4 | 5 |

     

    6 |

    Example 1:

    7 |
    Input: nums = [4,3,2,7,8,2,3,1]
     8 | Output: [2,3]
     9 | 

    Example 2:

    10 |
    Input: nums = [1,1,2]
    11 | Output: [1]
    12 | 

    Example 3:

    13 |
    Input: nums = [1]
    14 | Output: []
    15 | 
    16 |

     

    17 |

    Constraints:

    18 | 19 |
      20 |
    • n == nums.length
    • 21 |
    • 1 <= n <= 105
    • 22 |
    • 1 <= nums[i] <= n
    • 23 |
    • Each element in nums appears once or twice.
    • 24 |
    25 |
    -------------------------------------------------------------------------------- /add-strings/README.md: -------------------------------------------------------------------------------- 1 |

    415. Add Strings

    Easy


    Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

    2 | 3 |

    You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: num1 = "11", num2 = "123"
     9 | Output: "134"
    10 | 
    11 | 12 |

    Example 2:

    13 | 14 |
    Input: num1 = "456", num2 = "77"
    15 | Output: "533"
    16 | 
    17 | 18 |

    Example 3:

    19 | 20 |
    Input: num1 = "0", num2 = "0"
    21 | Output: "0"
    22 | 
    23 | 24 |

     

    25 |

    Constraints:

    26 | 27 |
      28 |
    • 1 <= num1.length, num2.length <= 104
    • 29 |
    • num1 and num2 consist of only digits.
    • 30 |
    • num1 and num2 don't have any leading zeros except for the zero itself.
    • 31 |
    32 |
    -------------------------------------------------------------------------------- /path-in-zigzag-labelled-binary-tree/README.md: -------------------------------------------------------------------------------- 1 | [

    Click here for detailed solution

    ](https://www.danielleskosky.com/path-in-zigzag-labelled-binary-tree/) 2 | 3 |

    1104. Path In Zigzag Labelled Binary Tree

    Medium


    In an infinite binary tree where every node has two children, the nodes are labelled in row order.

    4 | 5 |

    In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.

    6 | 7 |

    8 | 9 |

    Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.

    10 | 11 |

     

    12 |

    Example 1:

    13 | 14 |
    Input: label = 14
    15 | Output: [1,3,4,14]
    16 | 
    17 | 18 |

    Example 2:

    19 | 20 |
    Input: label = 26
    21 | Output: [1,2,6,10,26]
    22 | 
    23 | 24 |

     

    25 |

    Constraints:

    26 | 27 |
      28 |
    • 1 <= label <= 10^6
    • 29 |
    30 |
    31 | -------------------------------------------------------------------------------- /score-of-parentheses/README.md: -------------------------------------------------------------------------------- 1 |

    856. Score of Parentheses

    Medium


    Given a balanced parentheses string s, compute the score of the string based on the following rule:

    2 | 3 |
      4 |
    • () has score 1
    • 5 |
    • AB has score A + B, where A and B are balanced parentheses strings.
    • 6 |
    • (A) has score 2 * A, where A is a balanced parentheses string.
    • 7 |
    8 | 9 |

     

    10 | 11 |

    Example 1:

    12 | 13 |
    Input: s = "()"
    14 | Output: 1
    15 | 
    16 | 17 |

    Example 2:

    18 | 19 |
    Input: s = "(())"
    20 | Output: 2
    21 | 
    22 | 23 |

    Example 3:

    24 | 25 |
    Input: s = "()()"
    26 | Output: 2
    27 | 
    28 | 29 |

    Example 4:

    30 | 31 |
    Input: s = "(()(()))"
    32 | Output: 6
    33 | 
    34 | 35 |

     

    36 | 37 |

    Note:

    38 | 39 |
      40 |
    1. s is a balanced parentheses string, containing only ( and ).
    2. 41 |
    3. 2 <= s.length <= 50
    4. 42 |
    43 |
    -------------------------------------------------------------------------------- /verifying-an-alien-dictionary/verifying-an-alien-dictionary.java: -------------------------------------------------------------------------------- 1 | // n = words.length 2 | // Time: O(n) 3 | // Space: O(1) 4 | // words[i].length() <= 20 so can be considered constant 5 | // order.length() == 26 so can be considered constant 6 | class Solution { 7 | public boolean isAlienSorted(String[] words, String order) { 8 | for (int i = 1; i < words.length; i++) { 9 | String curr = words[i]; 10 | String prev = words[i - 1]; 11 | if (curr.equals(prev)) { 12 | continue; 13 | } 14 | for (int j = 0; j < prev.length() && j < curr.length(); j++) { 15 | if (prev.charAt(j) == curr.charAt(j)) { 16 | if (j == curr.length() - 1) { 17 | return false; 18 | } 19 | continue; 20 | } 21 | for (int k = 0; k < order.length(); k++) { 22 | if (order.charAt(k) == prev.charAt(j)) { 23 | break; 24 | } 25 | if (order.charAt(k) == curr.charAt(j)) { 26 | return false; 27 | } 28 | } 29 | break; 30 | } 31 | } 32 | return true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /corporate-flight-bookings/corporate-flight-bookings.java: -------------------------------------------------------------------------------- 1 | // initial attempt 2 | // b = bookings.length 3 | // Time: O(n * b) 4 | // Space: O(n) 5 | class Solution { 6 | public int[] corpFlightBookings(int[][] bookings, int n) { 7 | int[] result = new int[n]; 8 | for (int[] booking : bookings) { 9 | int first = booking[0]; 10 | int last = booking[1]; 11 | int seats = booking[2]; 12 | 13 | for (int i = first; i <= last; i++) { 14 | result[i - 1] += seats; 15 | } 16 | } 17 | return result; 18 | } 19 | } 20 | 21 | // inspired by folks on discussion board 22 | // b = bookings.length 23 | // Time: O(n + b) 24 | // Space: O(n) 25 | class Solution { 26 | public int[] corpFlightBookings(int[][] bookings, int n) { 27 | int[] result = new int[n]; 28 | for (int booking[] : bookings) { 29 | int first = booking[0]; 30 | int last = booking[1]; 31 | int seats = booking[2]; 32 | 33 | result[first - 1] += seats; 34 | if (last < n) result[last] += -seats; 35 | } 36 | 37 | for (int i = 1; i < n; i++) 38 | result[i] += result[i - 1]; 39 | 40 | return result; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /minimum-knight-moves/minimum-knight-moves.java: -------------------------------------------------------------------------------- 1 | // Time: O(max(x, y)^2) 2 | // Space: O(max(x, y)^2) 3 | class Solution { 4 | int[][] moves = new int[][]{{2,-1},{2,1},{1,2},{-1,2}, 5 | {-2,1},{-2,-1},{-1,-2},{1,-2}}; 6 | 7 | public int minKnightMoves(int x, int y) { 8 | int steps = 0; 9 | boolean[][] visited = new boolean[605][605]; 10 | Queue queue = new LinkedList<>(); 11 | queue.offer(new int[]{0,0}); 12 | 13 | while (!queue.isEmpty()) { 14 | int size = queue.size(); 15 | for (int i = 0; i < size; i++) { 16 | int[] curr = queue.poll(); 17 | if (curr[0] == x && curr[1] == y) { 18 | return steps; 19 | } 20 | for (int j = 0; j < moves.length; j++) { 21 | int nextX = curr[0] + moves[j][0]; 22 | int nextY = curr[1] + moves[j][1]; 23 | if (!visited[nextX + 302][nextY + 302]) { 24 | visited[nextX + 302][nextY + 302] = true; 25 | queue.offer(new int[]{nextX, nextY}); 26 | } 27 | } 28 | } 29 | steps++; 30 | } 31 | 32 | return -1; 33 | } 34 | } -------------------------------------------------------------------------------- /number-of-islands/README.md: -------------------------------------------------------------------------------- 1 |

    200. Number of Islands

    Medium


    Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

    2 | 3 |

    An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: grid = [
     9 |   ["1","1","1","1","0"],
    10 |   ["1","1","0","1","0"],
    11 |   ["1","1","0","0","0"],
    12 |   ["0","0","0","0","0"]
    13 | ]
    14 | Output: 1
    15 | 
    16 | 17 |

    Example 2:

    18 | 19 |
    Input: grid = [
    20 |   ["1","1","0","0","0"],
    21 |   ["1","1","0","0","0"],
    22 |   ["0","0","1","0","0"],
    23 |   ["0","0","0","1","1"]
    24 | ]
    25 | Output: 3
    26 | 
    27 | 28 |

     

    29 |

    Constraints:

    30 | 31 |
      32 |
    • m == grid.length
    • 33 |
    • n == grid[i].length
    • 34 |
    • 1 <= m, n <= 300
    • 35 |
    • grid[i][j] is '0' or '1'.
    • 36 |
    37 |
    -------------------------------------------------------------------------------- /set-matrix-zeroes/set-matrix-zeroes.java: -------------------------------------------------------------------------------- 1 | // m = matrix.length, n = matrix[0].length 2 | // Time: O(m * n) 3 | // Space: O(1) 4 | class Solution { 5 | public void setZeroes(int[][] matrix) { 6 | int m = matrix.length, n = matrix[0].length; 7 | boolean zeroInRow1 = false; 8 | boolean zeroInCol1 = false; 9 | 10 | for (int i = 0; i < m; i++) { 11 | for (int j = 0; j < n; j++) { 12 | if (matrix[i][j] == 0) { 13 | if (i == 0) zeroInRow1 = true; 14 | if (j == 0) zeroInCol1 = true; 15 | matrix[i][0] = 0; 16 | matrix[0][j] = 0; 17 | } 18 | } 19 | } 20 | 21 | for (int i = 1; i < m; i++) { 22 | for (int j = 1; j < n; j++) { 23 | if (matrix[i][0] == 0 || matrix[0][j] == 0) { 24 | matrix[i][j] = 0; 25 | } 26 | } 27 | } 28 | 29 | if (zeroInRow1) { 30 | for (int i = 0; i < n; i++) { 31 | matrix[0][i] = 0; 32 | } 33 | } 34 | 35 | if (zeroInCol1) { 36 | for (int i = 0; i < m; i++) { 37 | matrix[i][0] = 0; 38 | } 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /find-and-replace-in-string/find-and-replace-in-string.java: -------------------------------------------------------------------------------- 1 | // n = S.length() 2 | // Time: O(n) 3 | // Space: O(n) 4 | // indexes.length will never exceed n, so it can just be considered O(n) 5 | class Solution { 6 | public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) { 7 | Map map = new HashMap<>(); 8 | for (int i = 0; i < indexes.length; i++) { 9 | map.put(indexes[i], new String[]{sources[i], targets[i]}); 10 | } 11 | 12 | StringBuilder result = new StringBuilder(); 13 | int i = 0; 14 | while (i < S.length()) { 15 | if (map.containsKey(i)) { 16 | String[] value = map.get(i); 17 | String source = value[0]; 18 | String target = value[1]; 19 | if (S.substring(i, i + source.length()).equals(source)) { 20 | result.append(target); 21 | i += source.length(); 22 | } else { 23 | result.append(S.charAt(i)); 24 | i++; 25 | } 26 | } else { 27 | result.append(S.charAt(i)); 28 | i++; 29 | } 30 | } 31 | 32 | return result.toString(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /basic-calculator-ii/basic-calculator-ii.java: -------------------------------------------------------------------------------- 1 | // Time: O(n) 2 | // Space: O(n) 3 | class Solution { 4 | public int calculate(String s) { 5 | Stack stack = new Stack(); 6 | int operator = '+'; 7 | int num = 0; 8 | for (int i = 0; i < s.length(); i++) { 9 | char currChar = s.charAt(i); 10 | if (Character.isDigit(currChar)) { 11 | num = num * 10 + (currChar - '0'); 12 | } 13 | if (!Character.isDigit(currChar) 14 | && !Character.isWhitespace(currChar) 15 | || i == s.length() - 1) { 16 | if (operator == '+') { 17 | stack.push(num); 18 | } 19 | if (operator == '-') { 20 | stack.push(-num); 21 | } 22 | if (operator == '*') { 23 | stack.push(stack.pop() * num); 24 | } 25 | if (operator == '/') { 26 | stack.push(stack.pop() / num); 27 | } 28 | operator = currChar; 29 | num = 0; 30 | } 31 | } 32 | int result = 0; 33 | while (!stack.isEmpty()) { 34 | result += stack.pop(); 35 | } 36 | return result; 37 | } 38 | } -------------------------------------------------------------------------------- /binary-tree-level-order-traversal/binary-tree-level-order-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 | // Time: O(n) 17 | // Space: O(n) 18 | class Solution { 19 | public List> levelOrder(TreeNode root) { 20 | List> result = new ArrayList<>(); 21 | if (root == null) return result; 22 | Queue queue = new LinkedList<>(); 23 | queue.offer(root); 24 | 25 | while (!queue.isEmpty()) { 26 | int size = queue.size(); 27 | List level = new ArrayList<>(size); 28 | for (int i = 0; i < size; i++) { 29 | TreeNode curr = queue.poll(); 30 | level.add(curr.val); 31 | if (curr.left != null) queue.offer(curr.left); 32 | if (curr.right != null) queue.offer(curr.right); 33 | } 34 | result.add(level); 35 | } 36 | return result; 37 | } 38 | } -------------------------------------------------------------------------------- /the-kth-factor-of-n/the-kth-factor-of-n.java: -------------------------------------------------------------------------------- 1 | // Brute Force 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public int kthFactor(int n, int k) { 6 | List factors = new ArrayList<>(); 7 | for (int i = 1; i < n / 2 + 1; i++) { 8 | if (n % i == 0) { 9 | k--; 10 | } 11 | if (k == 0) { 12 | return i; 13 | } 14 | } 15 | return k == 1 ? n : -1; 16 | } 17 | } 18 | 19 | // Heap 20 | // Time: O(sqrt(n) * log k) 21 | // Space: O(min(k, sqrt(n))) 22 | class Solution { 23 | public int kthFactor(int n, int k) { 24 | PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b - a); 25 | int sqrtN = (int) Math.sqrt(n); 26 | for (int i = 1; i < sqrtN + 1; i++) { 27 | if (n % i == 0) { 28 | maxHeap.offer(i); 29 | if (maxHeap.size() > k) { 30 | maxHeap.poll(); 31 | } 32 | if (i != n / i) { 33 | maxHeap.offer(n / i); 34 | if (maxHeap.size() > k) { 35 | maxHeap.poll(); 36 | } 37 | } 38 | } 39 | } 40 | return maxHeap.size() == k ? maxHeap.poll() : -1; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /shifting-letters/README.md: -------------------------------------------------------------------------------- 1 |

    848. Shifting Letters

    Medium


    We have a string s of lowercase letters, and an integer array shifts.

    2 | 3 |

    Call the shift of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). 

    4 | 5 |

    For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.

    6 | 7 |

    Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times.

    8 | 9 |

    Return the final string after all such shifts to s are applied.

    10 | 11 |

    Example 1:

    12 | 13 |
    Input: s = "abc", shifts = [3,5,9]
    14 | Output: "rpl"
    15 | Explanation: 
    16 | We start with "abc".
    17 | After shifting the first 1 letters of S by 3, we have "dbc".
    18 | After shifting the first 2 letters of S by 5, we have "igc".
    19 | After shifting the first 3 letters of S by 9, we have "rpl", the answer.
    20 | 
    21 | 22 |

    Note:

    23 | 24 |
      25 |
    1. 1 <= s.length = shifts.length <= 20000
    2. 26 |
    3. 0 <= shifts[i] <= 109
    4. 27 |
    28 |
    -------------------------------------------------------------------------------- /01-matrix/README.md: -------------------------------------------------------------------------------- 1 |

    542. 01 Matrix

    Medium


    Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

    2 | 3 |

    The distance between two adjacent cells is 1.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
     9 | Output: [[0,0,0],[0,1,0],[0,0,0]]
    10 | 
    11 | 12 |

    Example 2:

    13 | 14 |
    Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
    15 | Output: [[0,0,0],[0,1,0],[1,2,1]]
    16 | 
    17 | 18 |

     

    19 |

    Constraints:

    20 | 21 |
      22 |
    • m == mat.length
    • 23 |
    • n == mat[i].length
    • 24 |
    • 1 <= m, n <= 104
    • 25 |
    • 1 <= m * n <= 104
    • 26 |
    • mat[i][j] is either 0 or 1.
    • 27 |
    • There is at least one 0 in mat.
    • 28 |
    29 |
    -------------------------------------------------------------------------------- /rabbits-in-forest/README.md: -------------------------------------------------------------------------------- 1 |

    781. Rabbits in Forest

    Medium


    In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.

    2 | 3 |

    Return the minimum number of rabbits that could be in the forest.

    4 | 5 |
    Examples:
     6 | Input: answers = [1, 1, 2]
     7 | Output: 5
     8 | Explanation:
     9 | The two rabbits that answered "1" could both be the same color, say red.
    10 | The rabbit than answered "2" can't be red or the answers would be inconsistent.
    11 | Say the rabbit that answered "2" was blue.
    12 | Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
    13 | The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
    14 | 
    15 | Input: answers = [10, 10, 10]
    16 | Output: 11
    17 | 
    18 | Input: answers = []
    19 | Output: 0
    20 | 
    21 | 22 |

    Note:

    23 | 24 |
      25 |
    1. answers will have length at most 1000.
    2. 26 |
    3. Each answers[i] will be an integer in the range [0, 999].
    4. 27 |
    28 |
    -------------------------------------------------------------------------------- /arranging-coins/README.md: -------------------------------------------------------------------------------- 1 |

    441. Arranging Coins

    Easy


    You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

    2 | 3 |

    Given the integer n, return the number of complete rows of the staircase you will build.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: n = 5
     9 | Output: 2
    10 | Explanation: Because the 3rd row is incomplete, we return 2.
    11 | 
    12 | 13 |

    Example 2:

    14 | 15 |
    Input: n = 8
    16 | Output: 3
    17 | Explanation: Because the 4th row is incomplete, we return 3.
    18 | 
    19 | 20 |

     

    21 |

    Constraints:

    22 | 23 |
      24 |
    • 1 <= n <= 231 - 1
    • 25 |
    26 |
    -------------------------------------------------------------------------------- /kth-smallest-element-in-a-bst/README.md: -------------------------------------------------------------------------------- 1 |

    230. Kth Smallest Element in a BST

    Medium


    Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: root = [3,1,4,null,2], k = 1
     7 | Output: 1
     8 | 
    9 | 10 |

    Example 2:

    11 | 12 |
    Input: root = [5,3,6,2,4,null,null,1], k = 3
    13 | Output: 3
    14 | 
    15 | 16 |

     

    17 |

    Constraints:

    18 | 19 |
      20 |
    • The number of nodes in the tree is n.
    • 21 |
    • 1 <= k <= n <= 104
    • 22 |
    • 0 <= Node.val <= 104
    • 23 |
    24 | 25 |

     

    26 | Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
    -------------------------------------------------------------------------------- /letter-combinations-of-a-phone-number/README.md: -------------------------------------------------------------------------------- 1 |

    17. Letter Combinations of a Phone Number

    Medium


    Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

    2 | 3 |

    A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

    4 | 5 |

    6 | 7 |

     

    8 |

    Example 1:

    9 | 10 |
    Input: digits = "23"
    11 | Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
    12 | 
    13 | 14 |

    Example 2:

    15 | 16 |
    Input: digits = ""
    17 | Output: []
    18 | 
    19 | 20 |

    Example 3:

    21 | 22 |
    Input: digits = "2"
    23 | Output: ["a","b","c"]
    24 | 
    25 | 26 |

     

    27 |

    Constraints:

    28 | 29 |
      30 |
    • 0 <= digits.length <= 4
    • 31 |
    • digits[i] is a digit in the range ['2', '9'].
    • 32 |
    33 |
    -------------------------------------------------------------------------------- /merge-intervals/merge-intervals.java: -------------------------------------------------------------------------------- 1 | // n = intervals.length 2 | // Time: O(n log n) 3 | // Space: O(n) 4 | class Solution { 5 | public int[][] merge(int[][] intervals) { 6 | int n = intervals.length; 7 | Arrays.sort(intervals, (a, b) -> a[0] - b[0]); 8 | List merged = new ArrayList<>(); 9 | int currStart = 0, currEnd = 0; 10 | boolean pastFirst = false; 11 | for (int i = 0; i < n; i++) { 12 | if (!pastFirst) { 13 | currStart = intervals[i][0]; 14 | currEnd = intervals[i][1]; 15 | pastFirst = true; 16 | } else if (intervals[i][0] <= currEnd) { 17 | currEnd = Math.max(currEnd, intervals[i][1]); 18 | } else if (intervals[i][0] > currEnd) { 19 | merged.add(new int[]{currStart, currEnd}); 20 | currStart = intervals[i][0]; 21 | currEnd = Math.max(currEnd, intervals[i][1]); 22 | } 23 | if (i == n - 1) { 24 | merged.add(new int[]{currStart, currEnd}); 25 | } 26 | } 27 | int resLen = merged.size(); 28 | int[][] result = new int[resLen][2]; 29 | for (int i = 0; i < resLen; i++) { 30 | result[i] = merged.get(i); 31 | } 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /maximum-value-after-insertion/maximum-value-after-insertion.java: -------------------------------------------------------------------------------- 1 | // n = n.length() 2 | // Time: O(n) 3 | // Space: O(1) 4 | class Solution { 5 | public String maxValue(String n, int x) { 6 | int len = n.length(); 7 | boolean isNeg = false; 8 | boolean placed = false; 9 | if (n.charAt(0) == '-') isNeg = true; 10 | 11 | StringBuilder sb = new StringBuilder(); 12 | if (!isNeg) { 13 | for (int i = 0; i < len; i++) { 14 | if (n.charAt(i) - '0' < x && !placed) { 15 | sb.append(x); 16 | sb.append(n.charAt(i)); 17 | placed = true; 18 | } else { 19 | sb.append(n.charAt(i)); 20 | } 21 | } 22 | if (!placed) sb.append(x); 23 | } else { 24 | for (int i = 1; i < len; i++) { 25 | if (n.charAt(i) - '0' > x && !placed) { 26 | sb.append(x); 27 | sb.append(n.charAt(i)); 28 | placed = true; 29 | } else { 30 | sb.append(n.charAt(i)); 31 | } 32 | } 33 | if (!placed) sb.append(x); 34 | } 35 | 36 | if (isNeg) sb.insert(0, '-'); 37 | return sb.toString(); 38 | } 39 | } -------------------------------------------------------------------------------- /invalid-transactions/invalid-transactions.java: -------------------------------------------------------------------------------- 1 | // n = transactions.length 2 | // Time: O(n^2) 3 | // Space: O(n) 4 | class Solution { 5 | public List invalidTransactions(String[] transactions) { 6 | int n = transactions.length; 7 | boolean[] marked = new boolean[n]; 8 | List result = new ArrayList<>(); 9 | Map> map = new HashMap<>(); 10 | 11 | for (int i = 0; i < n; i++) { 12 | String[] t = transactions[i].split(","); 13 | if (Integer.valueOf(t[2]) > 1000) { 14 | result.add(transactions[i]); 15 | marked[i] = true; 16 | } 17 | map.putIfAbsent(t[0], new ArrayList<>()); 18 | map.get(t[0]).add(new String[]{t[1], t[3]}); 19 | } 20 | 21 | for (int i = 0; i < n; i++) { 22 | if (marked[i]) continue; 23 | String[] t = transactions[i].split(","); 24 | for (String[] arr : map.get(t[0])) { 25 | if (Math.abs(Integer.valueOf(t[1]) - Integer.valueOf(arr[0])) <= 60 26 | && !t[3].equals(arr[1])) 27 | { 28 | result.add(transactions[i]); 29 | break; 30 | } 31 | } 32 | } 33 | 34 | return result; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /largest-rectangle-in-histogram/README.md: -------------------------------------------------------------------------------- 1 | [

    Click here for detailed solution

    ](https://www.danielleskosky.com/largest-rectangle-in-histogram/) 2 | 3 |

    84. Largest Rectangle in Histogram

    Hard


    Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

    4 | 5 |

     

    6 |

    Example 1:

    7 | 8 |
    Input: heights = [2,1,5,6,2,3]
     9 | Output: 10
    10 | Explanation: The above is a histogram where width of each bar is 1.
    11 | The largest rectangle is shown in the red area, which has an area = 10 units.
    12 | 
    13 | 14 |

    Example 2:

    15 | 16 |
    Input: heights = [2,4]
    17 | Output: 4
    18 | 
    19 | 20 |

     

    21 |

    Constraints:

    22 | 23 |
      24 |
    • 1 <= heights.length <= 105
    • 25 |
    • 0 <= heights[i] <= 104
    • 26 |
    27 |
    28 | -------------------------------------------------------------------------------- /reformat-phone-number/reformat-phone-number.java: -------------------------------------------------------------------------------- 1 | // n = number.length() 2 | // Time: O(n) 3 | // Space: O(n) 4 | class Solution { 5 | public String reformatNumber(String number) { 6 | StringBuilder sb1 = new StringBuilder(); 7 | for (char c : number.toCharArray()) { 8 | if (Character.isDigit(c)) { 9 | sb1.append(c); 10 | } 11 | } 12 | 13 | String parsed = sb1.toString(); 14 | StringBuilder sb2 = new StringBuilder(); 15 | int count = 0; 16 | for (int i = 0; i < parsed.length(); i++) { 17 | if (count == 0 && parsed.length() - i <= 4) { 18 | if (parsed.length() - i <= 3) { 19 | sb2.append(parsed.charAt(i)); 20 | } 21 | if (parsed.length() - i == 4) { 22 | sb2.append(parsed.charAt(i)); 23 | sb2.append(parsed.charAt(i + 1)); 24 | sb2.append('-'); 25 | i++; 26 | } 27 | } else { 28 | sb2.append(parsed.charAt(i)); 29 | count++; 30 | if (count == 3) { 31 | sb2.append('-'); 32 | count = 0; 33 | } 34 | } 35 | } 36 | 37 | return sb2.toString(); 38 | } 39 | } -------------------------------------------------------------------------------- /subsets/subsets.java: -------------------------------------------------------------------------------- 1 | // Cascading 2 | // n = nums.length 3 | // Time: O(n * 2^n) 4 | // Space: O(n * 2^n) 5 | class Solution { 6 | public List> subsets(int[] nums) { 7 | List> result = new ArrayList<>(); 8 | result.add(new ArrayList<>()); 9 | 10 | for (int num : nums) { 11 | int size = result.size(); 12 | for (int i = 0; i < size; i++) { 13 | List newList = new ArrayList<>(result.get(i)); 14 | newList.add(num); 15 | result.add(newList); 16 | } 17 | } 18 | 19 | return result; 20 | } 21 | } 22 | 23 | // Backtracking 24 | // n = nums.length 25 | // Time: O(n * 2^n) 26 | // Space: O(n) 27 | class Solution { 28 | List> result = new ArrayList<>(); 29 | 30 | public List> subsets(int[] nums) { 31 | backtrack(nums, 0, new ArrayList<>()); 32 | return result; 33 | } 34 | 35 | private void backtrack(int[] nums, int idx, List list) { 36 | result.add(new ArrayList<>(list)); 37 | 38 | for (int i = idx; i < nums.length; i++) { 39 | list.add(nums[i]); 40 | backtrack(nums, i + 1, new ArrayList<>(list)); 41 | list.remove(list.size() - 1); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /group-shifted-strings/README.md: -------------------------------------------------------------------------------- 1 |

    249. Group Shifted Strings

    Medium


    We can shift a string by shifting each of its letters to its successive letter.

    2 | 3 |
      4 |
    • For example, "abc" can be shifted to be "bcd".
    • 5 |
    6 | 7 |

    We can keep shifting the string to form a sequence.

    8 | 9 |
      10 |
    • For example, we can keep shifting "abc" to form the sequence: "abc" -> "bcd" -> ... -> "xyz".
    • 11 |
    12 | 13 |

    Given an array of strings strings, group all strings[i] that belong to the same shifting sequence. You may return the answer in any order.

    14 | 15 |

     

    16 |

    Example 1:

    17 |
    Input: strings = ["abc","bcd","acef","xyz","az","ba","a","z"]
    18 | Output: [["acef"],["a","z"],["abc","bcd","xyz"],["az","ba"]]
    19 | 

    Example 2:

    20 |
    Input: strings = ["a"]
    21 | Output: [["a"]]
    22 | 
    23 |

     

    24 |

    Constraints:

    25 | 26 |
      27 |
    • 1 <= strings.length <= 200
    • 28 |
    • 1 <= strings[i].length <= 50
    • 29 |
    • strings[i] consists of lowercase English letters.
    • 30 |
    31 |
    -------------------------------------------------------------------------------- /count-square-submatrices-with-all-ones/README.md: -------------------------------------------------------------------------------- 1 |

    1277. Count Square Submatrices with All Ones

    Medium


    Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: matrix =
     7 | [
     8 |   [0,1,1,1],
     9 |   [1,1,1,1],
    10 |   [0,1,1,1]
    11 | ]
    12 | Output: 15
    13 | Explanation: 
    14 | There are 10 squares of side 1.
    15 | There are 4 squares of side 2.
    16 | There is  1 square of side 3.
    17 | Total number of squares = 10 + 4 + 1 = 15.
    18 | 
    19 | 20 |

    Example 2:

    21 | 22 |
    Input: matrix = 
    23 | [
    24 |   [1,0,1],
    25 |   [1,1,0],
    26 |   [1,1,0]
    27 | ]
    28 | Output: 7
    29 | Explanation: 
    30 | There are 6 squares of side 1.  
    31 | There is 1 square of side 2. 
    32 | Total number of squares = 6 + 1 = 7.
    33 | 
    34 | 35 |

     

    36 |

    Constraints:

    37 | 38 |
      39 |
    • 1 <= arr.length <= 300
    • 40 |
    • 1 <= arr[0].length <= 300
    • 41 |
    • 0 <= arr[i][j] <= 1
    • 42 |
    43 |
    -------------------------------------------------------------------------------- /degree-of-an-array/degree-of-an-array.java: -------------------------------------------------------------------------------- 1 | // n = nums.length 2 | // Time: O(n) might be O(n^2) . . . depends who you ask 3 | // Space: O(n) 4 | class Solution { 5 | public int findShortestSubArray(int[] nums) { 6 | Map map = new HashMap<>(); 7 | for (int num : nums) 8 | map.put(num, map.getOrDefault(num, 0) + 1); 9 | 10 | int degree = 0; 11 | for (int key : map.keySet()) 12 | degree = Math.max(degree, map.get(key)); 13 | 14 | map.clear(); 15 | int minLen = Integer.MAX_VALUE; 16 | for (int i = 0, j = 0; i < nums.length; i++) { 17 | map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); 18 | while (degCount(map, degree) == 1) { 19 | minLen = Math.min(minLen, i - j + 1); 20 | map.put(nums[j], map.get(nums[j]) - 1); 21 | if (map.get(nums[j]) == 0) 22 | map.remove(nums[j]); 23 | j++; 24 | } 25 | } 26 | 27 | return minLen; 28 | } 29 | 30 | private int degCount(Map map, int degree) { 31 | int count = 0; 32 | for (int key : map.keySet()) { 33 | if (map.get(key) == degree) 34 | count++; 35 | } 36 | return count; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /maximum-distance-between-a-pair-of-values/maximum-distance-between-a-pair-of-values.java: -------------------------------------------------------------------------------- 1 | // Binary Search 2 | class Solution { 3 | public int maxDistance(int[] nums1, int[] nums2) { 4 | int n1 = nums1.length; 5 | int n2 = nums2.length; 6 | int max = 0; 7 | for (int i = 0; i < n1; i++) { 8 | int left = i; 9 | int right = n2 - 1; 10 | while (left <= right) { 11 | int mid = left + (right - left) / 2; 12 | if (nums1[i] <= nums2[mid]) { 13 | max = Math.max(max, mid - i); 14 | } 15 | if (nums1[i] <= nums2[mid]) { 16 | left = mid + 1; 17 | } else { 18 | right = mid - 1; 19 | } 20 | } 21 | } 22 | return max; 23 | } 24 | } 25 | 26 | // Brute Force 27 | class Solution { 28 | public int maxDistance(int[] nums1, int[] nums2) { 29 | int max = 0; 30 | for (int i = 0; i < nums1.length; i++) { 31 | for (int j = i; j < nums2.length; j++) { 32 | if (nums1[i] <= nums2[j]) { 33 | max = Math.max(max, j - i); 34 | } else { 35 | break; 36 | } 37 | } 38 | } 39 | 40 | return max; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /delete-nodes-and-return-forest/README.md: -------------------------------------------------------------------------------- 1 |

    1110. Delete Nodes And Return Forest

    Medium


    Given the root of a binary tree, each node in the tree has a distinct value.

    2 | 3 |

    After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

    4 | 5 |

    Return the roots of the trees in the remaining forest. You may return the result in any order.

    6 | 7 |

     

    8 |

    Example 1:

    9 | 10 |
    Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
    11 | Output: [[1,2,null,4],[6],[7]]
    12 | 
    13 | 14 |

    Example 2:

    15 | 16 |
    Input: root = [1,2,4,null,3], to_delete = [3]
    17 | Output: [[1,2,4]]
    18 | 
    19 | 20 |

     

    21 |

    Constraints:

    22 | 23 |
      24 |
    • The number of nodes in the given tree is at most 1000.
    • 25 |
    • Each node has a distinct value between 1 and 1000.
    • 26 |
    • to_delete.length <= 1000
    • 27 |
    • to_delete contains distinct values between 1 and 1000.
    • 28 |
    29 |
    -------------------------------------------------------------------------------- /longest-substring-without-repeating-characters/README.md: -------------------------------------------------------------------------------- 1 |

    3. Longest Substring Without Repeating Characters

    Medium


    Given a string s, find the length of the longest substring without repeating characters.

    2 | 3 |

     

    4 |

    Example 1:

    5 | 6 |
    Input: s = "abcabcbb"
     7 | Output: 3
     8 | Explanation: The answer is "abc", with the length of 3.
     9 | 
    10 | 11 |

    Example 2:

    12 | 13 |
    Input: s = "bbbbb"
    14 | Output: 1
    15 | Explanation: The answer is "b", with the length of 1.
    16 | 
    17 | 18 |

    Example 3:

    19 | 20 |
    Input: s = "pwwkew"
    21 | Output: 3
    22 | Explanation: The answer is "wke", with the length of 3.
    23 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
    24 | 
    25 | 26 |

    Example 4:

    27 | 28 |
    Input: s = ""
    29 | Output: 0
    30 | 
    31 | 32 |

     

    33 |

    Constraints:

    34 | 35 |
      36 |
    • 0 <= s.length <= 5 * 104
    • 37 |
    • s consists of English letters, digits, symbols and spaces.
    • 38 |
    39 |
    --------------------------------------------------------------------------------