├── .DS_Store ├── .gitbook └── assets │ ├── 011.png │ ├── 041.png │ ├── 084-1.png │ ├── 084-2.png │ ├── 174.PNG │ └── 723.png ├── .gitignore ├── README.md ├── SUMMARY.md ├── assets ├── 011.png ├── 041.png ├── 084-1.png ├── 084-2.png ├── 174.PNG └── 723.png ├── leetcode ├── .DS_Store ├── README.md ├── array │ ├── 001-two-sum.md │ ├── 004-median-of-two-sorted-arrays.md │ ├── 011-container-with-most-water.md │ ├── 015-3sum.md │ ├── 016-3sum-closest.md │ ├── 018-4sum.md │ ├── 026-remove-duplicates-from-sorted-array.md │ ├── 027-remove-element.md │ ├── 031-next-permutation.md │ ├── 033-search-in-rotated-sorted-array.md │ ├── 034-search-for-a-range.md │ ├── 035-search-insert-position.md │ ├── 039-combination-sum.md │ ├── 040-combination-sum-ii.md │ ├── 041-first-missing-positive.md │ ├── 042-trapping-rain-water.md │ ├── 045-jump-game-ii.md │ ├── 048-rotate-image.md │ ├── 053-maximum-subarray.md │ ├── 054-spiral-matrix.md │ ├── 055-jump-game.md │ ├── 056-merge-intervals.md │ ├── 057-insert-interval.md │ ├── 059-spiral-matrix-ii.md │ ├── 062-unique-paths.md │ ├── 063-unique-paths-ii.md │ ├── 064-minimum-path-sum.md │ ├── 066-plus-one.md │ ├── 073-set-matrix-zeroes.md │ ├── 074-search-a-2d-matrix.md │ ├── 075-sort-colors.md │ ├── 078-remove-duplicates-from-sorted-array-ii.md │ ├── 078-subsets.md │ ├── 079-word-search.md │ ├── 080-remove-duplicates-from-sorted-array-ii.md │ ├── 081-search-in-rotated-sorted-array-ii.md │ ├── 084-largest-rectangle-in-histogram.md │ ├── 085-maximal-rectangle.md │ ├── 088-merge-sorted-array.md │ ├── 090-subsets-ii.md │ ├── 105-construct-binary-tree-from-preorder-and-inorder-traversal.md │ ├── 106-construct-binary-tree-from-inorder-and-postorder-traversal.md │ ├── 118-pascals-triangle.md │ ├── 119-pascals-triangle-ii.md │ ├── 120-triangle.md │ ├── 121-best-time-to-buy-and-sell-stock.md │ ├── 122-best-time-to-buy-and-sell-stock-ii.md │ ├── 123-best-time-to-buy-and-sell-stock-iii.md │ ├── 126-word-ladder-ii.md │ ├── 128-longest-consecutive-sequence.md │ ├── 152-maximum-product-subarray.md │ └── README.md ├── binary-search │ ├── 153-find-minimum-in-rotated-sorted-array.md │ ├── 154-find-minimum-in-rotated-sorted-array-ii.md │ ├── 162-find-peak-element.md │ ├── 222-count-complete-tree-nodes.md │ ├── 230-kth-smallest-element-in-a-bst.md │ ├── 240-search-a-2d-matrix-ii.md │ ├── 270-closest-binary-search-tree-value.md │ ├── 275-h-index-ii.md │ ├── 278-first-bad-version.md │ ├── 300-longest-increasing-subsequence.md │ ├── 302-smallest-rectangle-enclosing-black-pixels.md │ ├── 349-intersection-of-two-arrays.md │ ├── 350-intersection-of-two-arrays-ii.md │ ├── 354-russian-doll-envelopes.md │ ├── 363-max-sum-of-rectangle-no-larger-than-k.md │ ├── 374-guess-number-higher-or-lower.md │ ├── 378-kth-smallest-element-in-a-sorted-matrix.md │ ├── 392-is-subsequence.md │ ├── 410-split-array-largest-sum.md │ ├── 436-find-right-interval.md │ ├── 441-arranging-coins.md │ ├── 454-4sum-ii.md │ ├── 475-heaters.md │ ├── 483-smallest-good-base.md │ ├── 497-random-point-in-non-overlapping-rectangles.md │ ├── 528-random-pick-with-weight.md │ ├── 644-maximum-average-subarray-ii.md │ ├── 658-find-k-closest-elements.md │ ├── 668-kth-smallest-number-in-multiplication-table.md │ ├── 702-search-in-a-sorted-array-of-unknown-size.md │ ├── 704-binary-search.md │ ├── 710-random-pick-with-blacklist.md │ ├── 718-maximum-length-of-repeated-subarray.md │ ├── 719-find-k-th-smallest-pair-distance.md │ ├── 744-find-smallest-letter-greater-than-target.md │ ├── 774-minimize-max-distance-to-gas-station.md │ ├── 778-swim-in-rising-water.md │ ├── 793-preimage-size-of-factorial-zeroes-function.md │ ├── 852-peak-index-in-a-mountain-array.md │ ├── 862-shortest-subarray-with-sum-at-least-k.md │ ├── 875-koko-eating-bananas.md │ ├── 878-nth-magical-number.md │ ├── 887-super-egg-drop.md │ ├── README.md │ └── untitled.md ├── bit-manipulation │ ├── 137-single-number-ii.md │ ├── 260-single-number-iii.md │ └── README.md ├── divide-and-conquer │ ├── 169-majority-element.md │ ├── 215-kth-largest-element-in-an-array.md │ ├── 218-the-skyline-problem.md │ ├── 241-different-ways-to-add-parentheses.md │ ├── 282-expression-add-operators.md │ ├── 426-convert-binary-search-tree-to-sorted-doubly-linked-list.md │ └── README.md ├── dynamic-programing │ ├── 174-dungeon-game.md │ └── README.md ├── hash-table │ ├── 003-longest-substring-without-repeating-characters.md │ ├── 030-substring-with-concatenation-of-all-words.md │ ├── 036-valid-sudoku.md │ ├── 037-sudoku-solver.md │ ├── 049-group-anagrams.md │ ├── 076-minimum-window-substring.md │ ├── 094-binary-tree-inorder-traversal.md │ ├── 136-single-number.md │ ├── 138-copy-list-with-random-pointer.md │ ├── 149-max-points-on-a-line.md │ ├── 159-longest-substring-with-at-most-two-distinct-characters.md │ ├── 166-fraction-to-recurring-decimal.md │ ├── 170-two-sum-iii-data-structure-design.md │ ├── 187-repeated-dna-sequences.md │ ├── 202-happy-number.md │ ├── 204-count-primes.md │ ├── 205-isomorphic-strings.md │ ├── 217-contains-duplicate.md │ ├── 219-contains-duplicate-ii.md │ ├── 242-valid-anagram.md │ ├── 244-shortest-word-distance-ii.md │ ├── 246-strobogrammatic-number.md │ ├── 249-group-shifted-strings.md │ ├── 266-palindrome-permutation.md │ ├── 274-h-index.md │ ├── 288-unique-word-abbreviation.md │ ├── 290-word-pattern.md │ ├── 299-bulls-and-cows.md │ ├── 311-sparse-matrix-multiplication.md │ ├── 314-binary-tree-vertical-order-traversal.md │ ├── 325-maximum-size-subarray-sum-equals-k.md │ ├── 336-palindrome-pairs.md │ ├── 340-longest-substring-with-at-most-k-distinct-characters.md │ ├── 347-top-k-frequent-elements.md │ ├── 356-line-reflection.md │ ├── 358-rearrange-string-k-distance-apart.md │ ├── 359-logger-rate-limiter.md │ ├── 380-insert-delete-getrandom-o1.md │ ├── 381-insert-delete-getrandom-o1-duplicates-allowed.md │ ├── 387-first-unique-character-in-a-string.md │ ├── 389-find-the-difference.md │ ├── 409-longest-palindrome.md │ ├── 438-find-all-anagrams-in-a-string.md │ ├── 447-number-of-boomerangs.md │ └── README.md ├── linked-list │ ├── 002-add-two-numbers.md │ ├── 019-remove-nth-node-from-end-of-list.md │ ├── 021-merge-two-sorted-lists.md │ ├── 023-merge-k-sorted-lists.md │ ├── 024-swap-nodes-in-pairs.md │ ├── 025-reverse-nodes-in-k-group.md │ ├── 061-rotate-list.md │ ├── 082-remove-duplicates-from-sorted-list-ii.md │ ├── 083-remove-duplicates-from-sorted-list.md │ ├── 086-partition-list.md │ ├── 092-reverse-linked-list-ii.md │ ├── 109-convert-sorted-list-to-binary-search-tree.md │ ├── 141-linked-list-cycle.md │ ├── 142-linked-list-cycle-ii.md │ ├── 143-reorder-list.md │ ├── 147-insertion-sort-list.md │ ├── 148-sort-list.md │ ├── 160-intersection-of-two-linked-lists.md │ ├── 203-remove-linked-list-elements.md │ ├── 206-reverse-linked-list.md │ ├── 234-palindrome-linked-list.md │ ├── 237-delete-node-in-a-linked-list.md │ ├── 328-odd-even-linked-list.md │ ├── 369-plus-one-linked-list.md │ ├── 379-design-phone-directory.md │ ├── 445-add-two-numbers-ii.md │ ├── 725-split-linked-list-in-parts.md │ └── README.md ├── math │ ├── 007-reverse-integer.md │ ├── 008-string-to-integer-atoi.md │ ├── 009-palindrome-number.md │ ├── 012-integer-to-roman.md │ ├── 013-roman-to-integer.md │ ├── 014-longest-common-prefix.md │ ├── 029-divide-two-integers.md │ ├── 043-multiply-strings.md │ ├── 050-powx-n.md │ ├── 060-permutation-sequence.md │ ├── 065-valid-number.md │ ├── 067-add-binary.md │ ├── 069-sqrtx.md │ ├── 168-excel-sheet-column-title.md │ ├── 171-excel-sheet-column-number.md │ ├── 223-rectangle-area.md │ ├── 224-basic-calculator.md │ ├── 247-strobogrammatic-number-ii.md │ ├── 248-strobogrammatic-number-iii.md │ ├── 258-add-digits.md │ ├── 263-ugly-number.md │ ├── 264-ugly-number-ii.md │ ├── 268-missing-number.md │ ├── 273-integer-to-english-words.md │ ├── 279-perfect-squares.md │ ├── 296-best-meeting-point.md │ ├── 313-super-ugly-number.md │ ├── 319-bulb-switcher.md │ ├── 326-power-of-three.md │ ├── 335-self-crossing.md │ ├── 343-integer-break.md │ ├── 357-count-numbers-with-unique-digits.md │ ├── 360-sort-transformed-array.md │ ├── 365-water-and-jug-problem.md │ ├── 367-valid-perfect-square.md │ ├── 368-largest-divisible-subset.md │ ├── 372-super-pow.md │ ├── 396-rotate-function.md │ ├── 397-integer-replacement.md │ ├── 400-nth-digit.md │ └── README.md ├── string │ ├── 005-longest-palindromic-substring.md │ ├── 006-zigzag-conversion.md │ ├── 010-regular-expression-matching.md │ ├── 014-longest-common-prefix.md │ ├── 017-letter-combinations-of-a-phone-number.md │ ├── 020-valid-parentheses.md │ ├── 022-generate-parentheses.md │ ├── 032-longest-valid-parentheses.md │ ├── 038-count-and-say.md │ ├── 043-wildcard-matching.md │ ├── 044-wildcard-matching.md │ ├── 058-length-of-last-word.md │ ├── 068-text-justification.md │ ├── 071-simplify-path.md │ ├── 072-edit-distance.md │ ├── 087-scramble-string.md │ ├── 091-decode-ways.md │ ├── 093-restore-ip-addresses.md │ ├── 097-interleaving-string.md │ ├── 115-distinct-subsequences.md │ ├── 151-reverse-words-in-a-string.md │ ├── 157-read-n-characters-given-read4.md │ ├── 158-read-n-characters-given-read4-ii-call-multiple-times.md │ ├── 161-one-edit-distance.md │ ├── 165-compare-version-numbers.md │ ├── 186-reverse-words-in-a-string-ii.md │ ├── 214-shortest-palindrome.md │ ├── 227-basic-calculator-ii.md │ ├── 271-encode-and-decode-strings.md │ ├── 293-flip-game.md │ ├── 344-reverse-string.md │ ├── 345-reverse-vowels-of-a-string.md │ ├── 383-ransom-note.md │ └── README.md └── two-pointers │ ├── 028-implement-strstr.md │ ├── 125-valid-palindrome.md │ ├── 167-two-sum-ii-input-array-is-sorted.md │ ├── 209-minimum-size-subarray-sum.md │ ├── 259-3sum-smaller.md │ ├── 283-move-zeroes.md │ ├── 287-find-the-duplicate-number.md │ ├── 344-reverse-string.md │ ├── 345-reverse-vowels-of-a-string.md │ ├── 349-intersection-of-two-arrays.md │ ├── 350-intersection-of-two-arrays-ii.md │ ├── 487-max-consecutive-ones-ii.md │ ├── 524-longest-word-in-dictionary-through-deleting.md │ ├── 532-k-diff-pairs-in-an-array.md │ ├── 567-permutation-in-string.md │ ├── 632-smallest-range.md │ ├── 713-subarray-product-less-than-k.md │ ├── 723-candy-crush.md │ ├── 763-partition-labels.md │ └── README.md ├── other ├── README.md ├── euclidean-algorithm.md ├── rabin-karp-rolling-hash.md └── summation-identities.md └── template ├── README.md └── leetcode.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/.DS_Store -------------------------------------------------------------------------------- /.gitbook/assets/011.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/.gitbook/assets/011.png -------------------------------------------------------------------------------- /.gitbook/assets/041.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/.gitbook/assets/041.png -------------------------------------------------------------------------------- /.gitbook/assets/084-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/.gitbook/assets/084-1.png -------------------------------------------------------------------------------- /.gitbook/assets/084-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/.gitbook/assets/084-2.png -------------------------------------------------------------------------------- /.gitbook/assets/174.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/.gitbook/assets/174.PNG -------------------------------------------------------------------------------- /.gitbook/assets/723.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/.gitbook/assets/723.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Node rules: 2 | ## Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 3 | .grunt 4 | 5 | ## Dependency directory 6 | ## Commenting this out is preferred by some people, see 7 | ## https://docs.npmjs.com/misc/faq#should-i-check-my-node_modules-folder-into-git 8 | node_modules 9 | 10 | # Book build output 11 | _book 12 | 13 | # eBook build output 14 | *.epub 15 | *.mobi 16 | *.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # README 2 | 3 | ## Getting Super Powers 4 | 5 | To clone the repo 6 | 7 | ``` 8 | git clone https://github.com/just4once/leetcode.git 9 | ``` 10 | 11 | To clone the repo with username 12 | 13 | ``` 14 | git clone https://username@github.com/username/repository.git 15 | ``` 16 | 17 | To clone the repo with username and password 18 | 19 | ``` 20 | git clone https://username:password@github.com/username/repository.git 21 | ``` 22 | 23 | -------------------------------------------------------------------------------- /assets/011.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/assets/011.png -------------------------------------------------------------------------------- /assets/041.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/assets/041.png -------------------------------------------------------------------------------- /assets/084-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/assets/084-1.png -------------------------------------------------------------------------------- /assets/084-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/assets/084-2.png -------------------------------------------------------------------------------- /assets/174.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/assets/174.PNG -------------------------------------------------------------------------------- /assets/723.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/assets/723.png -------------------------------------------------------------------------------- /leetcode/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/just4once/leetcode/e80874883cbacd9b9bd354717665caa4e44b7b1a/leetcode/.DS_Store -------------------------------------------------------------------------------- /leetcode/README.md: -------------------------------------------------------------------------------- 1 | # leetcode 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/array/001-two-sum.md: -------------------------------------------------------------------------------- 1 | # 001-two-sum 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/two-sum/description/](https://leetcode.com/problems/two-sum/description/) 6 | 7 | Given an array of integers, return **indices** of the two numbers such that they add up to a specific target. 8 | 9 | You may assume that each input would have **exactly** one solution, and you may not use the same element twice. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Given nums = [2, 7, 11, 15], target = 9, 15 | 16 | Because nums[0] + nums[1] = 2 + 7 = 9, 17 | return [0, 1]. 18 | ``` 19 | 20 | ## Thought Process {#thought-process} 21 | 22 | 1. Brute Force 23 | 1. Use every element as an anchor and search its right element 24 | 2. The time complexity is O\(n^2\) = \(n - 1\) + \(n - 2\) + ... + 1 25 | 3. The space complexity is O\(1\) 26 | 2. Optimal \(Hash Map\) 27 | 1. Leverage the power of hashmap and store the number and its index in the map 28 | 2. When the map contain target - curNum, we know the search is complete 29 | 3. The time complexity is O\(n\) 30 | 4. The space complexity is O\(n\) 31 | 32 | ## Solution {#solution} 33 | 34 | ```java 35 | class Solution { 36 | public int[] twoSum(int[] nums, int target) { 37 | if (nums == null) return null; 38 | int[] result = new int[2]; 39 | Map map = new HashMap<>(); 40 | for (int i = 0; i < nums.length; i++) { 41 | if (map.containsKey(target - nums[i])) { 42 | result[0] = map.get(target - nums[i]); 43 | result[1] = i; 44 | return result; 45 | } 46 | map.put(nums[i], i); 47 | } 48 | return result; 49 | } 50 | } 51 | ``` 52 | 53 | ## Additional {#additional} 54 | 55 | -------------------------------------------------------------------------------- /leetcode/array/011-container-with-most-water.md: -------------------------------------------------------------------------------- 1 | # 011-container-with-most-water 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/container-with-most-water/description/](https://leetcode.com/problems/container-with-most-water/description/) 6 | 7 | Given non-negative integers a1,a2, ...,an, where each represents a point at coordinate \(i,ai\).n vertical lines are drawn such that the two endpoints of line i is at \(i,ai\) and \(i, 0\). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 8 | 9 | Note: You may not slant the container and n is at least 2. 10 | 11 | **Example:** 12 | 13 | ![](../../.gitbook/assets/011.png) 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Brute Force 18 | 1. Start with each vertical line as the container's left boundary 19 | 2. Pick every one of the remaining vertical line as the right boundary 20 | 3. Volume = \(x2 - x1\) \* min\(y2, y1\) 21 | 4. Time complexity is O\(n\) 22 | 5. Space complexity is O\(1\) 23 | 2. Two pointers 24 | 1. Start with pointer at left and right, this could potentially by our largest container because the widest length 25 | 2. We compute the volume same way as before 26 | 3. Because only the larger height will be most useful in getting larger volume, we shrink the side that has lesser height 27 | 4. Time complexity is O\(n\) 28 | 5. Space complexity is O\(1\) 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public int maxArea(int[] height) { 35 | int maxArea = 0, l = 0, r = height.length - 1; 36 | while (l < r) { 37 | maxArea = Math.max(maxArea, Math.min(height[l], height[r]) * (r - l)); 38 | if (height[l] > height[r]) r--; 39 | else l++; 40 | } 41 | return maxArea; 42 | } 43 | } 44 | ``` 45 | 46 | ## Additional {#additional} 47 | 48 | -------------------------------------------------------------------------------- /leetcode/array/016-3sum-closest.md: -------------------------------------------------------------------------------- 1 | # 016-3sum-closest 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/3sum-closest/description/](https://leetcode.com/problems/3sum-closest/description/) 6 | 7 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 8 | 9 | **Example:** 10 | 11 | ```text 12 | For example, given array S = {-1 2 1 -4}, and target = 1. 13 | 14 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Very similar to Q015 [https://leetcode.com/problems/3sum/description/](https://leetcode.com/problems/3sum/description/) 20 | 21 | ## Solution 22 | 23 | ```java 24 | class Solution { 25 | public int threeSumClosest(int[] nums, int target) { 26 | if (nums == null || nums.length < 3) return 0; 27 | Arrays.sort(nums); 28 | int sum = 0; 29 | int closest = nums[0] + nums[1] + nums[2]; 30 | for (int i = 0; i < nums.length - 2; i++) { 31 | if (i > 1 && nums[i] == nums[i - 1]) continue; 32 | int lo = i + 1; 33 | int hi = nums.length - 1; 34 | while (lo < hi) { 35 | sum = nums[i] + nums[lo] + nums[hi]; 36 | if (sum == target) { 37 | return target; 38 | } else if (sum < target) { 39 | lo++; 40 | } else { 41 | hi--; 42 | } 43 | if (Math.abs(sum - target) < Math.abs(closest - target)) closest = sum; 44 | } 45 | 46 | } 47 | return closest; 48 | } 49 | } 50 | ``` 51 | 52 | ## Additional {#additional} 53 | 54 | -------------------------------------------------------------------------------- /leetcode/array/026-remove-duplicates-from-sorted-array.md: -------------------------------------------------------------------------------- 1 | # 026-remove-duplicates-from-sorted-array 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/) 6 | 7 | Given a sorted array, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each element appear only once and return the new length. 8 | 9 | Do not allocate extra space for another array, you must do this by **modifying the input array** [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) with O\(1\) extra memory. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Given nums = [1,1,2], 15 | 16 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 17 | It doesn't matter what you leave beyond the new length. 18 | ``` 19 | 20 | ## Thought Process {#thought-process} 21 | 22 | 1. Because the question ask we do it in place and return the new length, we have somehow scanning through the array and insert/discard the exploring element 23 | 2. This hint inspires the use of two pointers, where one points to the current element and the other points to the correct position that element should be reside 24 | 3. Time complexity O\(n\) 25 | 4. Space complexity O\(1\) 26 | 27 | ## Solution 28 | 29 | ```java 30 | class Solution { 31 | public int removeDuplicates(int[] nums) { 32 | if (nums.length <= 1) return nums.length; 33 | int id = 1; 34 | for (int i = 1; i < nums.length; i++) { 35 | if (nums[i] != nums[i-1]) { 36 | nums[id] = nums[i]; 37 | id++; 38 | } 39 | } 40 | return id; 41 | } 42 | } 43 | ``` 44 | 45 | ## Additional {#additional} 46 | 47 | -------------------------------------------------------------------------------- /leetcode/array/027-remove-element.md: -------------------------------------------------------------------------------- 1 | # 027-remove-element 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/remove-element/description/](https://leetcode.com/problems/remove-element/description/) 6 | 7 | Given an array and a value, remove all instances of that value [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) and return the new length. 8 | 9 | Do not allocate extra space for another array, you must do this by **modifying the input array** [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) with O\(1\) extra memory. 10 | 11 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 12 | 13 | **Example:** 14 | 15 | ```text 16 | Given nums = [3,2,2,3], val = 3, 17 | 18 | Your function should return length = 2, with the first two elements of nums being 2. 19 | ``` 20 | 21 | ## Thought Process {#thought-process} 22 | 23 | 1. Since we have to move non-targeted value to the front and target value to the back, we need two pointers. 24 | 2. One pointer track the location of non-targeted value from forward. T 25 | 3. The other points to the location of at the end where we can insert the target value. 26 | 4. Time complexity O\(n\) 27 | 5. Space complexity O\(1\) 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public int removeElement(int[] nums, int val) { 34 | int id = 0; 35 | for (int i = 0; i < nums.length; i++) { 36 | if (nums[i] != val) { 37 | nums[id++] = nums[i]; 38 | } 39 | } 40 | return id; 41 | } 42 | } 43 | ``` 44 | 45 | ## Additional {#additional} 46 | 47 | -------------------------------------------------------------------------------- /leetcode/array/031-next-permutation.md: -------------------------------------------------------------------------------- 1 | # 031-next-permutation 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/next-permutation/description/](https://leetcode.com/problems/next-permutation/description/) 6 | 7 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 8 | 9 | If such arrangement is not possible, it must rearrange it as the lowest possible order \(ie, sorted in ascending order\). 10 | 11 | The replacement must be in-place, do not allocate extra memory. 12 | 13 | **Example:** 14 | 15 | ```text 16 | 1,2,3 → 1,3,2 17 | 3,2,1 → 1,2,3 18 | 1,1,5 → 1,5,1 19 | ``` 20 | 21 | ## Thought Process {#thought-process} 22 | 23 | 1. Since we want the next greater number, we better scan from the back toward the front 24 | 2. When we find an element that is smaller than its right element\(s\) we know this location needs to be updated with a greater element, let's called this index i 25 | 3. However, we don't want any element that is greater. We want an element that is smallest among all the potential candidates. 26 | 4. To find that, we again scan from the back and locate that element and swap with index i 27 | 5. Now, all we have to make the remaining elements in ascending order by reversing 28 | 6. Time complexity O\(n\) 29 | 7. Space complexity O\(1\) 30 | 31 | ## Solution 32 | 33 | ```java 34 | class Solution { 35 | public void nextPermutation(int[] nums) { 36 | int i = nums.length - 2; 37 | while (i >= 0 && nums[i] >= nums[i+1]) i--; 38 | if (i >= 0){ 39 | int j = nums.length - 1; 40 | while(j >= 0 && nums[j] <= nums[i]) j--; 41 | swap(nums, i, j); 42 | } 43 | reverse(nums, i + 1); 44 | } 45 | 46 | public void swap(int[] nums, int i, int j){ 47 | int tmp = nums[i]; 48 | nums[i] = nums[j]; 49 | nums[j] = tmp; 50 | } 51 | 52 | public void reverse(int[] nums, int start){ 53 | int end = nums.length -1; 54 | while(start < end){ 55 | swap(nums, start++, end--); 56 | } 57 | } 58 | } 59 | ``` 60 | 61 | ## Additional {#additional} 62 | 63 | -------------------------------------------------------------------------------- /leetcode/array/035-search-insert-position.md: -------------------------------------------------------------------------------- 1 | # 035-search-insert-position 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/search-insert-position/description/](https://leetcode.com/problems/search-insert-position/description/) 6 | 7 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 8 | 9 | You may assume no duplicates in the array. 10 | 11 | **Example 1:** 12 | 13 | ```text 14 | Input: [1,3,5,6], 5 15 | Output: 2 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ```text 21 | Input: [1,3,5,6], 2 22 | Output: 1 23 | ``` 24 | 25 | ## Thought Process {#thought-process} 26 | 27 | 1. Basically this is regular binary search 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public int searchInsert(int[] nums, int target) { 34 | if(nums == null) return -1; 35 | int lo = 0, hi = nums.length - 1; 36 | while (lo <= hi){ 37 | int mid = lo + (hi - lo)/2; 38 | if (nums[mid] == target) return mid; 39 | else if (nums[mid] < target) lo = mid + 1; 40 | else hi = mid - 1; 41 | } 42 | return lo; 43 | } 44 | } 45 | ``` 46 | 47 | ## Additional {#additional} 48 | 49 | -------------------------------------------------------------------------------- /leetcode/array/039-combination-sum.md: -------------------------------------------------------------------------------- 1 | # 039-combination-sum 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/combination-sum/description/](https://leetcode.com/problems/combination-sum/description/) 6 | 7 | Given a **set** of candidate numbers \(**C**\)**\(without duplicates\)**and a target number \(**T**\), find all unique combinations in **C** where the candidate numbers sums to**T**. 8 | 9 | The **same** repeated number may be chosen from **C** unlimited number of times. 10 | 11 | **Note:** 12 | 13 | * All numbers \(including target\) will be positive integers. 14 | * The solution set must not contain duplicate combinations. 15 | 16 | **Example:** 17 | 18 | ```text 19 | Given candidate set [2, 3, 6, 7] and target 7, 20 | A solution set is: 21 | [ 22 | [7], 23 | [2, 2, 3] 24 | ] 25 | ``` 26 | 27 | ## Thought Process {#thought-process} 28 | 29 | 1. This is classic question asking for use of backtrack 30 | 2. We loop through every element, if adding this element will not exceed the target 31 | 3. If the target is equal to 0, we have find our solution along this path and we add this path to out solution 32 | 4. Time complexity O\(n^2\) 33 | 5. Space complexity O\(log n\) 34 | 35 | ## Solution 36 | 37 | ```java 38 | class Solution { 39 | public List> combinationSum(int[] candidates, int target) { 40 | List> res = new ArrayList<>(); 41 | Arrays.sort(candidates); 42 | backtrack(res, new ArrayList<>(), candidates, target, 0); 43 | return res; 44 | } 45 | 46 | public void backtrack(List> res, List sol, int[] candidates, int target, int start){ 47 | if (target < 0) return; 48 | else if (target == 0) res.add(new ArrayList<>(sol)); 49 | else { 50 | for (int i = start; i < candidates.length; i++){ 51 | sol.add(candidates[i]); 52 | backtrack(res, sol, candidates, target - candidates[i], i); 53 | sol.remove(sol.size() - 1); 54 | } 55 | } 56 | } 57 | } 58 | ``` 59 | 60 | ## Additional {#additional} 61 | 62 | -------------------------------------------------------------------------------- /leetcode/array/040-combination-sum-ii.md: -------------------------------------------------------------------------------- 1 | # 040-combination-sum-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/combination-sum-ii/description/](https://leetcode.com/problems/combination-sum-ii/description/) 6 | 7 | Given a collection of candidate numbers \(**C**\) and a target number \(**T**\), find all unique combinations in**C**where the candidate numbers sums to**T**. 8 | 9 | Each number in**C**may only be used**once**in the combination. 10 | 11 | **Note:** 12 | 13 | * All numbers \(including target\) will be positive integers. 14 | * The solution set must not contain duplicate combinations. 15 | 16 | **Example:** 17 | 18 | ```text 19 | For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, 20 | A solution set is: 21 | [ 22 | [1, 7], 23 | [1, 2, 5], 24 | [2, 6], 25 | [1, 1, 6] 26 | ] 27 | ``` 28 | 29 | ## Thought Process {#thought-process} 30 | 31 | 1. To avoid the duplicated solution, we have to sort the input 32 | 2. If the number is the same as the last number, we skip them 33 | 3. We also have to use backtrack to keep track of the number added 34 | 4. We could also break early if the current element will greater than the target since input was sorted at step 1 35 | 5. Time complexity O\(n^2\) 36 | 6. Space complexity O\(log n\) 37 | 38 | ## Solution 39 | 40 | ```java 41 | class Solution { 42 | public List> combinationSum2(int[] candidates, int target) { 43 | List> res = new ArrayList<>(); 44 | Arrays.sort(candidates); 45 | backtrack(res, new ArrayList<>(), candidates, target, 0); 46 | return res; 47 | } 48 | 49 | public void backtrack(List> res, List sol, int[] candidates, int target, int start){ 50 | if (target == 0) res.add(new ArrayList<>(sol)); 51 | else { 52 | for(int i = start; i < candidates.length; i++){ 53 | if(i > start && candidates[i] == candidates[i-1]) continue; 54 | if (candidates[i] > target) break; 55 | sol.add(candidates[i]); 56 | backtrack(res, sol, candidates, target - candidates[i], i + 1); 57 | sol.remove(sol.size() - 1); 58 | } 59 | } 60 | } 61 | } 62 | ``` 63 | 64 | ## Additional {#additional} 65 | 66 | -------------------------------------------------------------------------------- /leetcode/array/041-first-missing-positive.md: -------------------------------------------------------------------------------- 1 | # 041-first-missing-positive 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/first-missing-positive/description/](https://leetcode.com/problems/first-missing-positive/description/) 6 | 7 | Given an unsorted integer array, find the first missing positive integer. 8 | 9 | Your algorithm should run in O\(n\) time and uses constant space. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Given [1,2,0] return 3, 15 | and [3,4,-1,1] return 2. 16 | ``` 17 | 18 | ## Thought Process {#thought-process} 19 | 20 | 1. The restriction means what we cannot use any kind of cache, therefore we should do thing in place. 21 | 2. As we go through the array, we put the element in the correct spot at \(num - 1\) index 22 | 3. In the second pass, if the ith index is not equal to i + 1, we know this is the first missing positive 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public int firstMissingPositive(int[] nums) { 29 | int i = 0; 30 | while (i < nums.length) { 31 | if (nums[i] > 0 && nums[i] <= nums.length && nums[nums[i] - 1] != nums[i]) { 32 | swap(nums, nums[i] - 1, i); 33 | } else { 34 | i++; 35 | } 36 | } 37 | i = 0; 38 | while (i < nums.length) { 39 | if (nums[i] != i + 1) return i + 1; 40 | i++; 41 | } 42 | return nums.length + 1; 43 | } 44 | 45 | public void swap(int[] nums, int i, int j){ 46 | int tmp = nums[i]; 47 | nums[i] = nums[j]; 48 | nums[j] = tmp; 49 | } 50 | } 51 | ``` 52 | 53 | ## Additional {#additional} 54 | 55 | -------------------------------------------------------------------------------- /leetcode/array/053-maximum-subarray.md: -------------------------------------------------------------------------------- 1 | # 053-maximum-subarray 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/maximum-subarray/description/](https://leetcode.com/problems/maximum-subarray/description/) 6 | 7 | Find the contiguous subarray within an array \(containing at least one number\) which has the largest sum. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given the array [-2,1,-3,4,-1,2,1,-5,4], 13 | the contiguous subarray [4,-1,2,1] has the largest sum = 6. 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Typical maximum subarray problem 19 | 2. We add the element if it doesn't make the sum negative 20 | 3. If the sum goes negative, we reset the sum 21 | 22 | ## Solution 23 | 24 | ```java 25 | class Solution { 26 | public int maxSubArray(int[] nums) { 27 | if (nums == null || nums.length == 0) return -1; 28 | int maxSoFar = nums[0]; 29 | int maxCur = nums[0]; 30 | for (int i = 1; i < nums.length; i++) { 31 | maxCur = Math.max(maxCur + nums[i], nums[i]); 32 | maxSoFar = Math.max(maxSoFar, maxCur); 33 | } 34 | return maxSoFar; 35 | } 36 | } 37 | ``` 38 | 39 | ## Additional {#additional} 40 | 41 | -------------------------------------------------------------------------------- /leetcode/array/054-spiral-matrix.md: -------------------------------------------------------------------------------- 1 | # 054-spiral-matrix 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/spiral-matrix/description/](https://leetcode.com/problems/spiral-matrix/description/) 6 | 7 | Given a matrix of m x n elements \(m rows, n columns\), return all elements of the matrix in spiral order. 8 | 9 | **Example:** 10 | 11 | Given the following matrix: 12 | 13 | ```text 14 | [ 15 | [ 1, 2, 3 ], 16 | [ 4, 5, 6 ], 17 | [ 7, 8, 9 ] 18 | ] 19 | ``` 20 | 21 | You should return`[1,2,3,6,9,8,7,4,5]`. 22 | 23 | ## Thought Process {#thought-process} 24 | 25 | 1. Collect in the order top, right, bottom, left 26 | 2. We go from outer layer inward 27 | 3. Time complexity O\(n\) 28 | 4. Space complexity O\(n\), O\(1\) extra space 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public List spiralOrder(int[][] matrix) { 35 | List res = new ArrayList<>(); 36 | if (matrix == null || matrix.length == 0) return res; 37 | int m = matrix.length, n = matrix[0].length; 38 | int top = 0, bottom = m - 1; 39 | int left = 0, right = n - 1; 40 | while (top <= bottom && left <= right) { 41 | // collect the top row 42 | for (int c = left; c <= right; c++) res.add(matrix[top][c]); 43 | top++; 44 | // collect the right column 45 | for (int r = top; r <= bottom; r++) res.add(matrix[r][right]); 46 | right--; 47 | // collect the bottom row 48 | for (int c = right; c >= left; c--) res.add(matrix[bottom][c]); 49 | bottom--; 50 | // collect the left column 51 | for (int r = bottom; r >= top; r--) res.add(matrix[r][left]); 52 | left++; 53 | } 54 | return res; 55 | } 56 | } 57 | ``` 58 | 59 | ## Additional {#additional} 60 | 61 | -------------------------------------------------------------------------------- /leetcode/array/059-spiral-matrix-ii.md: -------------------------------------------------------------------------------- 1 | # 059-spiral-matrix-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/spiral-matrix-ii/description/](https://leetcode.com/problems/spiral-matrix-ii/description/) 6 | 7 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given n = 3, 13 | You should return the following matrix: 14 | [ 15 | [ 1, 2, 3 ], 16 | [ 8, 9, 4 ], 17 | [ 7, 6, 5 ] 18 | ] 19 | ``` 20 | 21 | ## Thought Process {#thought-process} 22 | 23 | 1. Very similar to [054-Spiral Matrix](054-spiral-matrix.md), we can reuse very much the same code 24 | 2. Fill the top, right, bottom, and left 25 | 3. Time complexity O\(n^2\) 26 | 4. Space complexity O\(n^2\), O\(1\) extra 27 | 28 | ## Solution 29 | 30 | ```java 31 | class Solution { 32 | public int[][] generateMatrix(int n) { 33 | int[][] result = new int[n][n]; 34 | int left = 0, right = n - 1; 35 | int top = 0, bottom = n - 1; 36 | int count = 1; 37 | while(left <=right && top <= bottom){ 38 | // fill the top 39 | for(int col = left; col <= right; col++){ 40 | result[top][col] = count++; 41 | } 42 | top++; 43 | // fill the right 44 | for(int row = top; row <= bottom; row++){ 45 | result[row][right] = count++; 46 | } 47 | right--; 48 | // fill the bottom 49 | for(int col = right; col >= left; col--){ 50 | result[bottom][col] = count++; 51 | } 52 | bottom--; 53 | // fill the left 54 | for(int row = bottom; row >= top; row--){ 55 | result[row][left] = count++; 56 | } 57 | left++; 58 | } 59 | return result; 60 | } 61 | } 62 | ``` 63 | 64 | ## Additional {#additional} 65 | 66 | -------------------------------------------------------------------------------- /leetcode/array/064-minimum-path-sum.md: -------------------------------------------------------------------------------- 1 | # 064-minimum-path-sum 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/minimum-path-sum/description/](https://leetcode.com/problems/minimum-path-sum/description/) 6 | 7 | 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. 8 | 9 | **Example:** 10 | 11 | ```text 12 | [[1,3,1], 13 | [1,5,1], 14 | [4,2,1]] 15 | 16 | Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Similar to the [062-Unique Paths](062-unique-paths.md) and [063-Unique Paths II ](063-unique-paths-ii.md)we can create two dimensional dp array and reduce to one dimentional 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public int minPathSum(int[][] grid) { 28 | if (grid == null || grid.length == 0) return 0; 29 | int m = grid.length, n = grid[0].length; 30 | int[] dp = new int[n + 1]; 31 | for (int c = 1; c <= n; c++) dp[c] = dp[c - 1] + grid[0][c - 1]; 32 | for (int r = 1; r < m; r++) { 33 | dp[0] = Integer.MAX_VALUE; 34 | for (int c = 1; c <= n; c++) { 35 | dp[c] = Math.min(dp[c], dp[c - 1]) + grid[r][c - 1]; 36 | } 37 | } 38 | return dp[n]; 39 | } 40 | } 41 | ``` 42 | 43 | ## Additional {#additional} 44 | 45 | -------------------------------------------------------------------------------- /leetcode/array/066-plus-one.md: -------------------------------------------------------------------------------- 1 | # 066-plus-one 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/plus-one/description/](https://leetcode.com/problems/plus-one/description/) 6 | 7 | Given a non-negative integer represented as a **non-empty** array of digits, plus one to the integer. 8 | 9 | You may assume the integer do not contain any leading zero, except the number 0 itself. 10 | 11 | The digits are stored such that the most significant digit is at the head of the list. 12 | 13 | **Example:** 14 | 15 | ```text 16 | 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Since the most significant digit is at the head, we need to go from back of the array 22 | 2. We can break fast if the current digit is smaller than 9, since adding one won't impact the rest front digit 23 | 3. Otherwise, we need to keep going forward 24 | 4. If we are able to reach to the head of the array, and still not returning, there is only one possibility that all digits are 9's, then we would need to create an array with number of digit + 1 and the first digit is 1 25 | 5. Time complexity O\(n\) 26 | 6. Space complexity O\(1\) or O\(n\) when all digits are 9 27 | 28 | ## Solution 29 | 30 | ```java 31 | class Solution { 32 | public int[] plusOne(int[] digits) { 33 | for(int i = digits.length - 1; i >= 0; i--){ 34 | if (digits[i]++ < 9) return digits; 35 | digits[i] = 0; 36 | } 37 | int[] result = new int[digits.length + 1]; 38 | result[0] = 1; 39 | return result; 40 | } 41 | } 42 | ``` 43 | 44 | ## Additional {#additional} 45 | 46 | -------------------------------------------------------------------------------- /leetcode/array/073-set-matrix-zeroes.md: -------------------------------------------------------------------------------- 1 | # 073-set-matrix-zeroes 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/set-matrix-zeroes/description/](https://leetcode.com/problems/set-matrix-zeroes/description/) 6 | 7 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. We can use an extra array in a separate array 18 | 1. Time complexity O\(mn\) 19 | 2. Space complexity O\(mn\) 20 | 2. We can directly record the state in the first row and first column, 21 | 1. The first record decide whether this column should be zero or not and first column decide whether current row should be zero or not 22 | 2. One thing that we need to keep in mind that, we need to keep one of indicator either the first row and first column in tact to preserve the information 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public void setZeroes(int[][] matrix) { 29 | if (matrix == null || matrix.length == 0) return; 30 | int m = matrix.length, n = matrix[0].length; 31 | boolean isFirstColZero = false; 32 | for (int r = 0; r < m; r++) { 33 | if (matrix[r][0] == 0) isFirstColZero = true; 34 | // skip the column 0 to save the info for each row 35 | for (int c = 1; c < n; c++) { 36 | if (matrix[r][c] == 0) { 37 | matrix[0][c] = matrix[r][0] = 0; 38 | } 39 | } 40 | } 41 | for (int r = m - 1; r >= 0; r--) { 42 | for (int c = n - 1; c > 0; c--) { 43 | if (matrix[0][c] == 0 || matrix[r][0] == 0) { 44 | matrix[r][c] = 0; 45 | } 46 | } 47 | if (isFirstColZero) matrix[r][0] = 0; 48 | } 49 | } 50 | } 51 | ``` 52 | 53 | ## Additional {#additional} 54 | 55 | -------------------------------------------------------------------------------- /leetcode/array/074-search-a-2d-matrix.md: -------------------------------------------------------------------------------- 1 | # 074-search-a-2d-matrix 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/search-a-2d-matrix/description/](https://leetcode.com/problems/search-a-2d-matrix/description/) 6 | 7 | Write an efficient algorithm that searches for a value in anmxnmatrix. This matrix has the following properties: 8 | 9 | * Integers in each row are sorted from left to right. 10 | * The first integer of each row is greater than the last integer of the previous row. 11 | 12 | **Example:** 13 | 14 | ```text 15 | [ 16 | [1, 3, 5, 7], 17 | [10, 11, 16, 20], 18 | [23, 30, 34, 50] 19 | ] 20 | Given target = 3, return true. 21 | ``` 22 | 23 | ## Thought Process {#thought-process} 24 | 25 | 1. We can treat this as one dimensional array, we can perform binary search as well 26 | 2. The only difference is the way to calculate the index 27 | 3. Time complexity O\(log \(mn\)\) 28 | 4. Space complexity O\(1\) 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public boolean searchMatrix(int[][] matrix, int target) { 35 | if (matrix == null || matrix.length == 0) return false; 36 | int rows = matrix.length, cols = matrix[0].length; 37 | int start = 0, end = rows * cols - 1; 38 | while (start <= end){ 39 | int mid = start + (end - start)/ 2; 40 | int value = matrix[mid / cols][mid % cols]; 41 | if(value == target) return true; 42 | else if(value < target) start = mid + 1; 43 | else end = mid - 1; 44 | } 45 | return false; 46 | } 47 | } 48 | ``` 49 | 50 | ## Additional {#additional} 51 | 52 | -------------------------------------------------------------------------------- /leetcode/array/078-remove-duplicates-from-sorted-array-ii.md: -------------------------------------------------------------------------------- 1 | # 078-remove-duplicates-from-sorted-array-ii 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/array/078-subsets.md: -------------------------------------------------------------------------------- 1 | # 078-subsets 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/subsets/description/](https://leetcode.com/problems/subsets/description/) 6 | 7 | Given a set of **distinct** integers, nums, return all possible subsets \(the power set\). 8 | 9 | **Note:**The solution set must not contain duplicate subsets. 10 | 11 | **Example:** 12 | 13 | ```text 14 | If nums = [1,2,3], a solution is: 15 | [ 16 | [3], 17 | [1], 18 | [2], 19 | [1,2,3], 20 | [1,3], 21 | [2,3], 22 | [1,2], 23 | [] 24 | ] 25 | ``` 26 | 27 | ## Thought Process {#thought-process} 28 | 29 | 1. For creating power set, there are 2^n possibilities, where n is number of elements, due to each element can be either in or out of particular set 30 | 2. To help create the set, we can have an additional array 31 | 32 | ## Solution 33 | 34 | ```java 35 | class Solution { 36 | public List> subsets(int[] nums) { 37 | List> res = new ArrayList<>(); 38 | backtrack(nums, res, new ArrayList<>(), 0); 39 | return res; 40 | } 41 | 42 | public void backtrack(int[] nums, List> res, List path, int start) { 43 | res.add(new ArrayList<>(path)); 44 | for (int i = start; i < nums.length; i++) { 45 | path.add(nums[i]); 46 | backtrack(nums, res, path, i + 1); 47 | path.remove(path.size() - 1); 48 | } 49 | } 50 | } 51 | ``` 52 | 53 | ```java 54 | class Solution { 55 | public List> subsets(int[] nums) { 56 | List> res = new ArrayList<>(); 57 | if (nums == null || nums.length == 0) return res; 58 | res.add(new ArrayList<>()); 59 | for (int i = 0; i < nums.length; i++) { 60 | int size = res.size(); 61 | for (int j = 0; j < size; j++) { 62 | List l = new ArrayList<>(res.get(j)); 63 | l.add(nums[i]); 64 | res.add(l); 65 | } 66 | } 67 | return res; 68 | } 69 | } 70 | ``` 71 | 72 | ## Additional {#additional} 73 | 74 | -------------------------------------------------------------------------------- /leetcode/array/080-remove-duplicates-from-sorted-array-ii.md: -------------------------------------------------------------------------------- 1 | # 080-remove-duplicates-from-sorted-array-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/) 6 | 7 | Follow up for "Remove Duplicates": 8 | 9 | What if duplicates are allowed at most twice? 10 | 11 | **Example:** 12 | 13 | ```text 14 | Given sorted array nums = [1,1,1,2,2,3], 15 | Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. 16 | ``` 17 | 18 | ## Thought Process {#thought-process} 19 | 20 | 1. Unlike [026-Remove Duplicates from Sorted Array ](026-remove-duplicates-from-sorted-array.md)where duplicates aren't allowed, this question allow to have 2 duplicates 21 | 2. We simply compare current ith element with the i - 2 element 22 | 1. We can have two pointers, one going forward and one keep track of last inserted index 23 | 2. We increment the last inserted index when the element is different, so we insert it directly to the array 24 | 3. Time complexity O\(n\) 25 | 4. Space complexity O\(1\) 26 | 27 | ## Solution 28 | 29 | ```java 30 | class Solution { 31 | public int removeDuplicates(int[] nums) { 32 | if (nums == null) return 0; 33 | if (nums.length < 3) return nums.length; 34 | int k = 2, id = 2; 35 | for (int i = 2; i < nums.length; i++) { 36 | if (nums[i] != nums[id - 2]) { 37 | nums[id] = nums[i]; 38 | id++; 39 | } 40 | } 41 | return id; 42 | } 43 | } 44 | ``` 45 | 46 | ## Additional {#additional} 47 | 48 | -------------------------------------------------------------------------------- /leetcode/array/085-maximal-rectangle.md: -------------------------------------------------------------------------------- 1 | # 085-maximal-rectangle 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/maximal-rectangle/description/](https://leetcode.com/problems/maximal-rectangle/description/) 6 | 7 | Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 1 0 1 0 0 13 | 1 0 1 1 1 14 | 1 1 1 1 1 15 | 1 0 0 1 0 16 | 17 | Return 6. 18 | ``` 19 | 20 | ## Thought Process {#thought-process} 21 | 22 | 1. This is very similar to , instead of giving heights directly to us, we have to computer row by row. Therefore we need an additional array to hold the heights of the column 23 | 2. Time complexity O\(n^2\) 24 | 3. Space complexity O\(n\) 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | public int maximalRectangle(char[][] matrix) { 31 | if (matrix == null || matrix.length == 0) return 0; 32 | int n = matrix[0].length; 33 | int[] heights = new int[n + 1]; 34 | int maxArea = 0; 35 | for (char[] row : matrix) { 36 | updateHeight(row, heights); 37 | maxArea = Math.max(maxArea, getMaxArea(heights)); 38 | } 39 | return maxArea; 40 | } 41 | 42 | private void updateHeight(char[] row, int[] heights) { 43 | for (int i = 0; i < row.length; i++) { 44 | if (row[i] == '1') heights[i]++; 45 | else heights[i] = 0; 46 | } 47 | } 48 | 49 | private int getMaxArea(int[] heights) { 50 | int n = heights.length; 51 | int[] stack = new int[n + 1]; 52 | int top = 0; 53 | stack[top] = -1; 54 | int maxArea = 0; 55 | for (int i = 0; i < n; i++) { 56 | while (top > 0 && heights[i] < heights[stack[top]]) { 57 | int h = heights[stack[top--]]; 58 | int w = i - stack[top] - 1; 59 | maxArea = Math.max(maxArea, h * w); 60 | } 61 | stack[++top] = i; 62 | } 63 | return maxArea; 64 | } 65 | } 66 | ``` 67 | 68 | ## Additional {#additional} 69 | 70 | -------------------------------------------------------------------------------- /leetcode/array/088-merge-sorted-array.md: -------------------------------------------------------------------------------- 1 | # 088-merge-sorted-array 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/merge-sorted-array/description/](https://leetcode.com/problems/merge-sorted-array/description/) 6 | 7 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 8 | 9 | **Note:** 10 | You may assume that nums1 has enough space \(size that is greater or equal to m + n\) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. 11 | 12 | **Example:** 13 | 14 | ```text 15 | 16 | ``` 17 | 18 | ## Thought Process {#thought-process} 19 | 20 | 1. Since array nums1 has enough space, we can put the the element directly into nums1 21 | 2. We can either start from beginning or the end 22 | 3. Starting from the end is better because we don't have tor swift the element 23 | 4. We can use two pointers to track the last index we fill while comparing these two arrays 24 | 5. Time complexity O\(n\) 25 | 6. Space complexity O\(1\) 26 | 27 | ## Solution 28 | 29 | ```java 30 | class Solution { 31 | public void merge(int[] nums1, int m, int[] nums2, int n) { 32 | int len = m + n; 33 | while (n > 0) { 34 | if (m > 0 && nums1[m - 1] > nums2[n - 1]) nums1[--len] = nums1[--m]; 35 | else nums1[--len] = nums2[--n]; 36 | } 37 | } 38 | } 39 | ``` 40 | 41 | ## Additional {#additional} 42 | 43 | -------------------------------------------------------------------------------- /leetcode/array/090-subsets-ii.md: -------------------------------------------------------------------------------- 1 | # 090-subsets-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/subsets-ii/description/](https://leetcode.com/problems/subsets-ii/description/) 6 | 7 | Given a collection of integers that might contain duplicates, **nums**, return all possible subsets \(the power set\). 8 | 9 | **Note:**The solution set must not contain duplicate subsets. 10 | 11 | **Example:** 12 | 13 | ```text 14 | If nums = [1,2,2], a solution is: 15 | [ 16 | [2], 17 | [1], 18 | [1,2,2], 19 | [2,2], 20 | [1,2], 21 | [] 22 | ] 23 | ``` 24 | 25 | ## Thought Process {#thought-process} 26 | 27 | 1. Similar to [078-Subsets](078-subsets.md), we need to generate the power sets 28 | 2. To remove the duplicate set, we have sort the input and make sure that that current element is not the same as previous element 29 | 3. Time complexity O\(2^n\) 30 | 4. Space complexity O\(n\) 31 | 32 | ## Solution 33 | 34 | ```java 35 | class Solution { 36 | public List> subsetsWithDup(int[] nums) { 37 | List> list = new ArrayList<>(); 38 | Arrays.sort(nums); 39 | backtrack(list, new ArrayList<>(), nums, 0); 40 | return list; 41 | } 42 | 43 | public void backtrack(List> list, List path, int[] nums, int start){ 44 | list.add(new ArrayList<>(path)); 45 | for(int i = start; i < nums.length; i++){ 46 | if(i > start && nums[i] == nums[i-1]) continue; 47 | path.add(nums[i]); 48 | backtrack(list, path, nums, i + 1); 49 | path.remove(path.size() - 1); 50 | } 51 | } 52 | } 53 | ``` 54 | 55 | ## Additional {#additional} 56 | 57 | -------------------------------------------------------------------------------- /leetcode/array/118-pascals-triangle.md: -------------------------------------------------------------------------------- 1 | # 118-pascals-triangle 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/pascals-triangle/description/](https://leetcode.com/problems/pascals-triangle/description/) 6 | 7 | Given numRows, generate the first numRows of Pascal's triangle. 8 | 9 | **Example:** 10 | 11 | ```text 12 | For example, given numRows = 5, 13 | Return 14 | 15 | [ 16 | [1], 17 | [1,1], 18 | [1,2,1], 19 | [1,3,3,1], 20 | [1,4,6,4,1] 21 | ] 22 | ``` 23 | 24 | ## Thought Process {#thought-process} 25 | 26 | 1. Each row in Pascal's triangle can be determined from previous row 27 | 2. For each column in the row, we can obtain the value by adding pascal\[i - 1\]\[j - 1\] and pascal\[i -1\]\[j\], where i denotes the ith row, and j denotes the jth column 28 | 3. Time complexity O\(n^2\) because summing from 1 to n -> n\(n +1\)/2 29 | 4. Space complexity O\(n^2\) 30 | 31 | ## Solution 32 | 33 | ```java 34 | class Solution { 35 | public List> generate(int numRows) { 36 | int[][] pascal = new int[numRows][]; 37 | for (int i = 0; i < numRows; i++){ 38 | int[] row = new int[i + 1]; 39 | row[0] = 1; 40 | row[i] = 1; 41 | for (int j = 1; j < i; j++){ 42 | row[j] = pascal[i - 1][j - 1] + pascal[i - 1][j]; 43 | } 44 | pascal[i] = row; 45 | } 46 | return (List)Arrays.asList(pascal); 47 | } 48 | } 49 | ``` 50 | 51 | ## Additional {#additional} 52 | 53 | -------------------------------------------------------------------------------- /leetcode/array/119-pascals-triangle-ii.md: -------------------------------------------------------------------------------- 1 | # 119-pascals-triangle-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/pascals-triangle-ii/description/](https://leetcode.com/problems/pascals-triangle-ii/description/) 6 | 7 | Given an index k, return the kth row of the Pascal's triangle. 8 | 9 | **Example:** 10 | 11 | ```text 12 | For example, given k = 3, 13 | Return [1,3,3,1]. 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. We have use Combination formula nCk = n! / \(n - k\)! k! 19 | 2. We have to be careful about potential integer overflow when multiplying, so we use long to store our intermediate answer 20 | 3. Time complexity O\(n\) 21 | 4. Space complexity O\(n\) 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public List getRow(int rowIndex) { 28 | List list = new ArrayList<>(rowIndex + 1); 29 | long res = 1; 30 | for(int i = 0; i <= rowIndex; i++){ 31 | list.add((int) res); 32 | res *= rowIndex - i; 33 | res /= i + 1; 34 | } 35 | return list; 36 | } 37 | } 38 | ``` 39 | 40 | ## Additional {#additional} 41 | 42 | -------------------------------------------------------------------------------- /leetcode/array/120-triangle.md: -------------------------------------------------------------------------------- 1 | # 120-triangle 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/triangle/description/](https://leetcode.com/problems/triangle/description/) 6 | 7 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 8 | 9 | For example, given the following triangle 10 | 11 | **Example:** 12 | 13 | ```text 14 | [ 15 | [2], 16 | [3,4], 17 | [6,5,7], 18 | [4,1,8,3] 19 | ] 20 | 21 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 22 | ``` 23 | 24 | ## Thought Process {#thought-process} 25 | 26 | 1. The triangle is very similar to a tree structure, where at each node, we can either travel left or right 27 | 2. However, there is overlap of the subproblem, where the siblings share same leaf node, i.e. the left sibling and right sibling share their right leaf and left leaf respectively 28 | 3. From above observation, we can cache the result for each node 29 | 4. The best route sum can be calculate from backward, where sum\[i\]\[j\] equals math.min\(sum\[i + 1\]\[j\], sum\[i + 1\]\[j + 1\]\) + value\[i\]\[j\] 30 | 5. We can reduce the space usage to one dimensional array, since current sum depends on the row below 31 | 6. Time complexity O\(n^2\), where n is number of rows 32 | 7. Space complexity O\(n\) 33 | 34 | ## Solution 35 | 36 | ```java 37 | class Solution { 38 | public int minimumTotal(List> triangle) { 39 | int n = triangle.size(); 40 | int[] dp = new int[n + 1]; 41 | for (int i = n - 1; i >= 0; i--) { 42 | for (int j = 0; j <= i; j++) { 43 | dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j); 44 | } 45 | } 46 | return dp[0]; 47 | } 48 | } 49 | ``` 50 | 51 | ## Additional {#additional} 52 | 53 | -------------------------------------------------------------------------------- /leetcode/array/122-best-time-to-buy-and-sell-stock-ii.md: -------------------------------------------------------------------------------- 1 | # 122-best-time-to-buy-and-sell-stock-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/) 6 | 7 | Say you have an array for which the ith element is the price of a given stock on day i. 8 | 9 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like \(ie, buy one and sell one share of the stock multiple times\). However, you may not engage in multiple transactions at the same time \(ie, you must sell the stock before you buy again\). 10 | 11 | **Example:** 12 | 13 | ```text 14 | 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. First we need to find the local min, then the next local max 20 | 1. repeat the local min and max process until we reach the end 21 | 2. Time complexity O\(n\) 22 | 3. Space complexity O\(1\) 23 | 2. Greedy approach 24 | 1. Instead of trying to find local min and local max, we can pretend that we can buy and sell at the same day, this transaction can be treated as gathering profit as we go 25 | 2. Anytime that the stock price is higher than the yesterday's, we gather out profit, this is essentially same as the buy at the lowest price and sell at the highest price 26 | 3. Time complexity O\(n\) 27 | 4. Space complexity O\(1\) 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public int maxProfit(int[] prices) { 34 | int profit = 0; 35 | for (int i = 1; i < prices.length; i++){ 36 | if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i -1]; 37 | } 38 | return profit; 39 | } 40 | } 41 | ``` 42 | 43 | ## Additional {#additional} 44 | 45 | -------------------------------------------------------------------------------- /leetcode/array/152-maximum-product-subarray.md: -------------------------------------------------------------------------------- 1 | # 152-maximum-product-subarray 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/maximum-product-subarray/description/](https://leetcode.com/problems/maximum-product-subarray/description/) 6 | 7 | Find the contiguous subarray within an array \(containing at least one number\) which has the largest product. 8 | 9 | **Example:** 10 | 11 | ```text 12 | For example, given the array [2,3,-2,4], 13 | the contiguous subarray [2,3] has the largest product = 6. 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Brute Force 19 | 1. Check the max product for every subsequence 20 | 2. Time complexity O\(n^2\) 21 | 3. Space complexity O\(1\) 22 | 2. Dynamic Programing 23 | 1. Because there is negative number, we need to keep track of the min product as well for the next negative that turn the sign back to positive 24 | 2. We need to have two dimensional array size of 2 x n for storing both min and max product. We need to compare the previous max and min product to current number, reset it when appropriate 25 | 3. Because we only depends on the previous value, we can reduce the two dimensional array to two variables 26 | 4. Time complexity O\(n\) 27 | 5. Space complexity O\(1\) 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public int maxProduct(int[] nums) { 34 | int r = nums[0]; 35 | // max and min stores the max/min product of subarray that ends with the current number 36 | for (int i = 1, min = r, max = r; i < nums.length; i++){ 37 | if (nums[i] < 0) { 38 | int tmp = max; 39 | max = min; 40 | min = tmp; 41 | } 42 | // the max and min are either previous number times cur or the cur itselft 43 | max = Math.max(max * nums[i], nums[i]); 44 | min = Math.min(min * nums[i], nums[i]); 45 | r = Math.max(r, max); 46 | } 47 | return r; 48 | } 49 | } 50 | ``` 51 | 52 | ## Additional {#additional} 53 | 54 | -------------------------------------------------------------------------------- /leetcode/array/README.md: -------------------------------------------------------------------------------- 1 | # array 2 | 3 | -------------------------------------------------------------------------------- /leetcode/binary-search/153-find-minimum-in-rotated-sorted-array.md: -------------------------------------------------------------------------------- 1 | # 153-find-minimum-in-rotated-sorted-array 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/) 6 | 7 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 8 | 9 | \(i.e., \[0,1,2,4,5,6,7\] might become \[4,5,6,7,0,1,2\]\). 10 | 11 | Find the minimum element. 12 | 13 | You may assume no duplicate exists in the array. 14 | 15 | **Example:** 16 | 17 | ```text 18 | Input: [3,4,5,1,2], 19 | Output: 1 20 | ``` 21 | 22 | ## Thought Process {#thought-process} 23 | 24 | 1. Two Pointers 25 | 1. We use two pointers to track the start and the end of the array 26 | 2. To determine the min is on left on right, we need to check the nums\[mid\] against nums\[lo\] or nums\[hi\] 27 | 3. If we check nums\[mid\] against nums\[lo\], and it's greater than nums\[lo\], the result is non-deterministic, because it could be on either side, i.e. \[2, 4, 6\] or \[4, 6, 2\] 28 | 4. However, if we check nums\[mid\] against nums\[hi\] and it's smaller than nums\[hi\], the min can definitely on the left including the mid element 29 | 5. Time complexity O\(log n\) 30 | 6. Space complexity O\(1\) 31 | 32 | ## Solution 33 | 34 | ```java 35 | class Solution { 36 | public int findMin(int[] nums) { 37 | int lo = 0, hi = nums.length - 1; 38 | while (lo < hi) { 39 | int mi = lo + (hi - lo) / 2; 40 | // we have already find the min on the right side 41 | // we narrow down to search the left 42 | if (nums[mi] < nums[hi]) hi = mi; 43 | else lo = mi + 1; 44 | } 45 | return nums[lo]; 46 | } 47 | } 48 | ``` 49 | 50 | ## Additional {#additional} 51 | 52 | -------------------------------------------------------------------------------- /leetcode/binary-search/154-find-minimum-in-rotated-sorted-array-ii.md: -------------------------------------------------------------------------------- 1 | # 154-find-minimum-in-rotated-sorted-array-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description/](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description/) 6 | 7 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 8 | 9 | \(i.e., \[0,1,2,4,5,6,7\] might become \[4,5,6,7,0,1,2\]\). 10 | 11 | Find the minimum element. 12 | 13 | The array may contain duplicates. 14 | 15 | **Example 1:** 16 | 17 | ```text 18 | Input: [1,3,5], 19 | Output: 1 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ```text 25 | Input: [2,2,2,0,1], 26 | Output: 0 27 | ``` 28 | 29 | **Note:** 30 | 31 | * This is a follow up for "[Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/)". 32 | * Would allow duplicates affect the run-time complexity? How and why? 33 | 34 | ## Thought Process {#thought-process} 35 | 36 | 1. Two Pointers 37 | 1. Similar to previous question, we need to find where to find our minium 38 | 2. We compare mid element to the end element 39 | 1. When nums\[mi\] < nums\[hi\], it's on the left, so we set hi = mi 40 | 2. When nums\[mi\] > nums\[hi\], is's on the right because the pivot point has to be on the right 41 | 3. Lastly, when nums\[mi\] == nums\[hi\], we decrease the hi and keep finding 42 | 3. Time complexity O\(n\) 43 | 4. Space complexity O\(1\) 44 | 45 | ## Solution 46 | 47 | ```java 48 | class Solution { 49 | public int findMin(int[] nums) { 50 | int lo = 0, hi = nums.length - 1; 51 | while (lo < hi) { 52 | int mi = lo + (hi - lo) / 2; 53 | if (nums[mi] < nums[hi]) hi = mi; 54 | else if (nums[mi] > nums[hi]) lo = mi + 1; 55 | else hi--; 56 | } 57 | return nums[lo]; 58 | } 59 | } 60 | ``` 61 | 62 | ## Additional {#additional} 63 | 64 | -------------------------------------------------------------------------------- /leetcode/binary-search/275-h-index-ii.md: -------------------------------------------------------------------------------- 1 | # 275-h-index-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/h-index-ii/description/](https://leetcode.com/problems/h-index-ii/description/) 6 | 7 | Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm? 8 | 9 | **Example:** 10 | 11 | ```text 12 | 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Binary Search 18 | 1. Since there are n index, we have h index range from 1 to n 19 | 2. Doing binary search, if the mid element is equal to n - mid, we have found our h index 20 | 3. The n - mid is number of publications that are greater than or equal to citations\[mid\] 21 | 4. Time complexity O\(logn\) 22 | 5. Space complexity O\(1\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public int hIndex(int[] citations) { 29 | int n = citations.length; 30 | if (n == 0) return 0; 31 | int lo = 0, hi = n - 1, mid; 32 | // If the citations and h index (n - mid) are equal, we reach the solution 33 | // Else if the citations is less than h, we move to right so less citation needed 34 | // Else move to left 35 | while (lo <= hi) { 36 | mid = lo + (hi -lo) / 2; 37 | if (citations[mid] == n - mid) return citations[mid]; 38 | else if (citations[mid] < n - mid) lo = mid + 1; 39 | else hi = mid - 1; 40 | } 41 | return n - (hi + 1); 42 | } 43 | } 44 | ``` 45 | 46 | ## Additional {#additional} 47 | 48 | -------------------------------------------------------------------------------- /leetcode/binary-search/278-first-bad-version.md: -------------------------------------------------------------------------------- 1 | # 278-first-bad-version 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/first-bad-version/description/](https://leetcode.com/problems/first-bad-version/description/) 6 | 7 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 8 | 9 | Suppose you have n versions \[1, 2, ..., n\] and you want to find out the first bad one, which causes all the following ones to be bad. 10 | 11 | You are given an API bool isBadVersion\(version\) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 12 | 13 | **Example:** 14 | 15 | ```text 16 | 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Binary Search 22 | 1. We test the mid version is bad or not 23 | 2. If it's bad, we move right pointer to mid, else we move left pointer to mid + 1 24 | 3. Notice we we should not use lo <= hi in the while condition, since it will stuck indefinitely 25 | 4. Time complexity O\(logn\) 26 | 5. Space complexity O\(1\) 27 | 28 | ## Solution 29 | 30 | ```java 31 | /* The isBadVersion API is defined in the parent class VersionControl. 32 | boolean isBadVersion(int version); */ 33 | 34 | public class Solution extends VersionControl { 35 | public int firstBadVersion(int n) { 36 | int lo = 1, hi = n, mi; 37 | while (lo < hi) { 38 | mi = lo + (hi - lo) / 2; 39 | if (isBadVersion(mi)) hi = mi; 40 | else lo = mi + 1; 41 | } 42 | return lo; 43 | } 44 | } 45 | ``` 46 | 47 | ## Additional {#additional} 48 | 49 | -------------------------------------------------------------------------------- /leetcode/binary-search/349-intersection-of-two-arrays.md: -------------------------------------------------------------------------------- 1 | # 349-intersection-of-two-arrays 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/intersection-of-two-arrays/description/](https://leetcode.com/problems/intersection-of-two-arrays/description/) 6 | 7 | Given two arrays, write a function to compute their intersection. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 13 | ``` 14 | 15 | **Note:** 16 | 17 | * Each element in the result must be unique. 18 | * The result can be in any order. 19 | 20 | ## Thought Process {#thought-process} 21 | 22 | 1. Set 23 | 1. Using set we can easily store the number we have seen in nums1 and compare with nums2 24 | 2. Time complexity O\(m + n\) 25 | 3. Space complexity O\(m\) or O\(min\(m, n\)\) 26 | 2. Binary Search 27 | 28 | ## Solution 29 | 30 | ```java 31 | class Solution { 32 | public int[] intersection(int[] nums1, int[] nums2) { 33 | Set set = new HashSet<>(); 34 | for (int num : nums1) set.add(num); 35 | Set res = new HashSet<>(); 36 | for (int num : nums2) { 37 | if (set.contains(num)) res.add(num); 38 | } 39 | int[] result = new int[res.size()]; 40 | int i = 0; 41 | for (int num : res) { 42 | result[i++] = num; 43 | } 44 | return result; 45 | } 46 | } 47 | ``` 48 | 49 | ## Additional {#additional} 50 | 51 | -------------------------------------------------------------------------------- /leetcode/binary-search/374-guess-number-higher-or-lower.md: -------------------------------------------------------------------------------- 1 | # 374-guess-number-higher-or-lower 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/guess-number-higher-or-lower/description/](https://leetcode.com/problems/guess-number-higher-or-lower/description/) 6 | 7 | We are playing the Guess Game. The game is as follows: 8 | 9 | I pick a number from 1 to n. You have to guess which number I picked. 10 | 11 | Every time you guess wrong, I'll tell you whether the number is higher or lower. 12 | 13 | You call a pre-defined API guess\(int num\) which returns 3 possible results \(-1, 1, or 0\): 14 | 15 | ```text 16 | -1 : My number is lower 17 | 1 : My number is higher 18 | 0 : Congrats! You got it! 19 | ``` 20 | 21 | **Example:** 22 | 23 | ```text 24 | n = 10, I pick 6. 25 | 26 | Return 6. 27 | ``` 28 | 29 | ## Thought Process {#thought-process} 30 | 31 | 1. Binary Search 32 | 1. Very Typical binary search, where we return when we get 0, search the lower half when we got -1 \(the solution is lower\), otherwise we search the higher half 33 | 2. Time complexity O\(nlogn\) 34 | 3. Space complexity O\(1\) 35 | 36 | ## Solution 37 | 38 | ```java 39 | /* The guess API is defined in the parent class GuessGame. 40 | @param num, your guess 41 | @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 42 | int guess(int num); */ 43 | 44 | public class Solution extends GuessGame { 45 | public int guessNumber(int n) { 46 | int lo = 0, hi = n; 47 | int mid; 48 | while (lo <= hi) { 49 | mid = lo + (hi - lo)/2; 50 | int g = guess(mid); 51 | if (g == 0) return mid; 52 | else if (g > 0) lo = mid + 1; 53 | else hi = mid - 1; 54 | } 55 | return -1; 56 | } 57 | } 58 | ``` 59 | 60 | ## Additional {#additional} 61 | 62 | -------------------------------------------------------------------------------- /leetcode/binary-search/702-search-in-a-sorted-array-of-unknown-size.md: -------------------------------------------------------------------------------- 1 | # 702-search-in-a-sorted-array-of-unknown-size 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/description/](https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/description/) 6 | 7 | Given an integer array sorted in ascending order, write a function to search`target`in`nums`. If`target`exists, then return its index, otherwise return`-1`.**However, the array size is unknown to you**. You may only access the array using an`ArrayReader` interface, where `ArrayReader.get(k)`returns the element of the array at index`k` \(0-indexed\). 8 | 9 | You may assume all integers in the array are less than `10000`, and if you access the array out of bounds,`ArrayReader.get`will return`2147483647`. 10 | 11 | **Example 1:** 12 | 13 | ```text 14 | Input: array = [-1,0,3,5,9,12], target = 9 15 | Output: 4 16 | Explanation: 9 exists in nums and its index is 4 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ```text 22 | Input: array = [-1,0,3,5,9,12], target = 2 23 | Output: -1 24 | Explanation: 2 does not exist in nums so return -1 25 | ``` 26 | 27 | **Note:** 28 | 29 | 1. You may assume that all elements in the array are unique. 30 | 2. The value of each element in the array will be in the range \[-9999, 9999\]. 31 | 32 | ## Thought Process {#thought-process} 33 | 34 | 1. Binary Search 35 | 1. We set our search index to be from 0 to 2147483647, named lo and hi 36 | 2. Our search ends when we hit our target or hi > lo 37 | 3. Time complexity O\(1\) from 32 times or search 38 | 4. Space complexity O\(1\) 39 | 40 | ## Solution 41 | 42 | ```java 43 | class Solution { 44 | public int search(ArrayReader reader, int target) { 45 | int lo = 0, hi = Integer.MAX_VALUE; 46 | while (lo <= hi) { 47 | int mi = lo + (hi - lo) / 2; 48 | int val = reader.get(mi); 49 | if (val == target) return mi; 50 | else if (val < target) lo = mi + 1; 51 | else hi = mi - 1; 52 | } 53 | return -1; 54 | } 55 | } 56 | ``` 57 | 58 | ## Additional {#additional} 59 | 60 | -------------------------------------------------------------------------------- /leetcode/binary-search/704-binary-search.md: -------------------------------------------------------------------------------- 1 | # 704-binary-search 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/binary-search/description/](https://leetcode.com/problems/binary-search/description/) 6 | 7 | Given a sorted \(in ascending order\) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. 8 | 9 | **Example 1:** 10 | 11 | ```text 12 | Input: nums = [-1,0,3,5,9,12], target = 9 13 | Output: 4 14 | Explanation: 9 exists in nums and its index is 4 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ```text 20 | Input: nums = [-1,0,3,5,9,12], target = 2 21 | Output: -1 22 | Explanation: 2 does not exist in nums so return -1 23 | ``` 24 | 25 | **Note:** 26 | 27 | 1. You may assume that all elements in nums are unique. 28 | 2. n will be in the range \[1, 10000\]. 29 | 3. The value of each element in nums will be in the range \[-9999, 9999\]. 30 | 31 | ## Thought Process {#thought-process} 32 | 33 | 1. Binary 34 | 1. Time complexity O\(logn\) 35 | 2. Space complexity O\(1\) 36 | 37 | ## Solution 38 | 39 | ```java 40 | class Solution { 41 | public int search(int[] nums, int target) { 42 | int lo = 0, hi = nums.length - 1; 43 | while (lo <= hi) { 44 | int mi = lo + (hi - lo) / 2; 45 | if (nums[mi] == target) return mi; 46 | else if (nums[mi] < target) lo = mi + 1; 47 | else hi = mi - 1; 48 | } 49 | return -1; 50 | } 51 | } 52 | ``` 53 | 54 | ## Additional {#additional} 55 | 56 | -------------------------------------------------------------------------------- /leetcode/binary-search/852-peak-index-in-a-mountain-array.md: -------------------------------------------------------------------------------- 1 | # 852-peak-index-in-a-mountain-array 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/peak-index-in-a-mountain-array/description/](https://leetcode.com/problems/peak-index-in-a-mountain-array/description/) 6 | 7 | Let's call an array A a mountain if the following properties hold: 8 | 9 | A.length >= 3 There exists some 0 < i < A.length - 1 such that A\[0\] < A\[1\] < ... A\[i-1\] < A\[i\] > A\[i+1\] > ... > A\[A.length - 1\] Given an array that is definitely a mountain, return any i such that A\[0\] < A\[1\] < ... A\[i-1\] < A\[i\] > A\[i+1\] > ... > A\[A.length - 1\]. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Input: [0,1,0] 15 | Output: 1 16 | 17 | Input: [0,2,1,0] 18 | Output: 1 19 | ``` 20 | 21 | **Note:** 22 | 23 | 3 <= A.length <= 10000 0 <= A\[i\] <= 10^6 A is a mountain, as defined above. 24 | 25 | ## Thought Process {#thought-process} 26 | 27 | 1. Binary Search 28 | 1. Since there is only one peak, we can use binary search to successively cut the search range by half 29 | 2. The boundaries are lo = 1, hi = A.length - 2 30 | 3. We compare A\[mi\] to A\[mi + 1\] 31 | 4. If A\[mi\] < A\[mi + 1\], the peak lies on the right, so lo = mi + 1 32 | 5. Else hi = mi 33 | 6. Time complexity O\(logn\) 34 | 7. Space complexity O\(1\) 35 | 36 | ## Solution 37 | 38 | ```java 39 | class Solution { 40 | public int peakIndexInMountainArray(int[] A) { 41 | int lo = 1, hi = A.length - 2; 42 | while (lo < hi) { 43 | int mi = lo + (hi - lo) / 2; 44 | if (A[mi] < A[mi + 1]) lo = mi + 1; 45 | else hi = mi; 46 | } 47 | return lo; 48 | } 49 | } 50 | ``` 51 | 52 | ## Additional {#additional} 53 | 54 | -------------------------------------------------------------------------------- /leetcode/binary-search/README.md: -------------------------------------------------------------------------------- 1 | # binary-search 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/137-single-number-ii.md: -------------------------------------------------------------------------------- 1 | # 137-single-number-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/single-number-ii/description/](https://leetcode.com/problems/single-number-ii/description/) 6 | 7 | Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 13 | ``` 14 | 15 | **Note:** 16 | 17 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Check Every Bit 22 | 1. We sum all the bit for current bit position, if the sum is divisible by 3, we know current bit is 0, otherwise is 1 23 | 2. Time complexity O\(n\) 24 | 3. Space complexity O\(1\) 25 | 2. asd 26 | 27 | ## Solution 28 | 29 | ```java 30 | class Solution { 31 | public int singleNumber(int[] nums) { 32 | int res = 0; 33 | for (int i = 0; i < 32; i++) { 34 | int mask = 1 << i; 35 | int sum = 0; 36 | for (int num : nums) { 37 | sum += (mask & num) == 0 ? 0 : 1; 38 | } 39 | res |= (sum % 3) << i; 40 | } 41 | return res; 42 | } 43 | } 44 | ``` 45 | 46 | ```java 47 | class Solution { 48 | public int singleNumber(int[] nums) { 49 | int one = 0, two = 0; 50 | for (int num : nums){ 51 | // xor num save the num, if one is set right now, 1, two is 0 52 | // the second time we see the number, one will become 0, because 53 | // two is set, where & ~two will unset it, then two will become set. 54 | one = (one ^ num) & ~two; 55 | two = (two ^ num) & ~one; 56 | } 57 | return one; 58 | } 59 | } 60 | ``` 61 | 62 | ## Additional {#additional} 63 | 64 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/260-single-number-iii.md: -------------------------------------------------------------------------------- 1 | # 260-single-number-iii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/single-number-iii/description/](https://leetcode.com/problems/single-number-iii/description/) 6 | 7 | Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. XOR 18 | 1. Initialize a variable call mask. after XOR with all the numbers, we have the XOR of target1 and target2 save 19 | 2. To distinguish between target1 and target2, we need to XOR mask with mask - 1, this will unset all the digits except the bit position that target1 and target2 differs 20 | 3. Now, we divide the numbers into two groups based on the that bit position, and XOR the numbers in that group only, we get the result 21 | 4. Time complexity O\(n\) 22 | 5. Space complexity O\(1\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public int[] singleNumber(int[] nums) { 29 | int[] result = new int[2]; 30 | int mask = 0; 31 | for (int num : nums) { 32 | mask ^= num; 33 | } 34 | // get the right most significant bit, i.e. [1,2,1,2,3,5] 35 | // mask = 6, 00110, -mask = 1..11010, mask & -mask = 0..010 36 | // becase 3 011 and 5 101 are differs at second bit, we can 37 | // run the process again and divide them into two groups. 38 | mask &= -mask; 39 | for (int num: nums) { 40 | if ((num & mask) == 0) result[0] ^= num; 41 | else result[1] ^= num; 42 | } 43 | return result; 44 | } 45 | } 46 | ``` 47 | 48 | ## Additional {#additional} 49 | 50 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/README.md: -------------------------------------------------------------------------------- 1 | # bit-manipulation 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/divide-and-conquer/README.md: -------------------------------------------------------------------------------- 1 | # divide-and-conquer 2 | 3 | -------------------------------------------------------------------------------- /leetcode/dynamic-programing/README.md: -------------------------------------------------------------------------------- 1 | # dynamic-programing 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/hash-table/036-valid-sudoku.md: -------------------------------------------------------------------------------- 1 | # 036-valid-sudoku 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/valid-sudoku/description/](https://leetcode.com/problems/valid-sudoku/description/) 6 | 7 | Determine if a Sudoku is valid, according to: [Sudoku Puzzles - The Rules](http://sudoku.com.au/TheRules.aspx). 8 | 9 | The Sudoku board could be partially filled, where empty cells are filled with the character`'.'`. 10 | 11 | **Example:** 12 | 13 | ```text 14 | 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Follow the rule 20 | 1. We simply follow the rule of the Sudoku, where we check all the row, column and boxes 21 | 2. Time complexity O\(n^2\), where n = 9 for common Sudoku 22 | 3. Space complexity O\(1\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public boolean isValidSudoku(char[][] board) { 29 | for (int i = 0; i < 9; i++) { 30 | if (!isValid(board, i, i, 0, 8)) return false; 31 | if (!isValid(board, 0, 8, i, i)) return false; 32 | if (!isValid(board, (i / 3) * 3, (i / 3) * 3 + 2, (i % 3) * 3, (i % 3) * 3 + 2)) return false; 33 | } 34 | return true; 35 | } 36 | 37 | public boolean isValid(char[][] board, int rStart, int rEnd, int cStart, int cEnd){ 38 | boolean[] contain = new boolean[9]; 39 | for (int row = rStart; row <= rEnd; row++) { 40 | for (int col = cStart; col <= cEnd; col++) { 41 | char c = board[row][col]; 42 | if(c != '.'){ 43 | if(contain[c - '1']) return false; 44 | else contain[c - '1'] = true; 45 | } 46 | } 47 | } 48 | return true; 49 | } 50 | } 51 | ``` 52 | 53 | ## Additional {#additional} 54 | 55 | -------------------------------------------------------------------------------- /leetcode/hash-table/037-sudoku-solver.md: -------------------------------------------------------------------------------- 1 | # 037-sudoku-solver 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/sudoku-solver/description/](https://leetcode.com/problems/sudoku-solver/description/) 6 | 7 | Write a program to solve a Sudoku puzzle by filling the empty cells. 8 | 9 | Empty cells are indicated by the character`'.'`. 10 | 11 | You may assume that there will be only one unique solution. 12 | 13 | **Example:** 14 | 15 | ```text 16 | 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Trial by Error and Backtrack 22 | 1. Time complexity O\(9^m\), where m is number of blank cells 23 | 2. Space complexity O\(m\) 24 | 25 | ## Solution 26 | 27 | ```java 28 | class Solution { 29 | public void solveSudoku(char[][] board) { 30 | if (board == null || board.length != 9) return; 31 | solve(board); 32 | } 33 | 34 | private boolean solve(char[][] board) { 35 | for (int r = 0; r < 9; r++) { 36 | for (int c = 0; c < 9; c++) { 37 | if (board[r][c] == '.') { 38 | for (char i = '1'; i <= '9'; i++) { 39 | if (isValid(board, r, c, i)) { 40 | board[r][c] = i; 41 | if (solve(board)) return true; 42 | else board[r][c] = '.'; 43 | } 44 | } 45 | return false; 46 | } 47 | } 48 | } 49 | return true; 50 | } 51 | 52 | private boolean isValid(char[][] board, int r, int c, char i) { 53 | for (int j = 0; j < 9; j++) { 54 | if (board[r][j] != '.' && board[r][j] == i) return false; 55 | if (board[j][c] != '.' && board[j][c] == i) return false; 56 | if (board[(r / 3) * 3 + j / 3][(c / 3) *3 + j % 3] != '.' && board[(r / 3) * 3 + j / 3][(c / 3) *3 + j % 3] == i) return false; 57 | } 58 | return true; 59 | } 60 | } 61 | ``` 62 | 63 | ## Additional {#additional} 64 | 65 | -------------------------------------------------------------------------------- /leetcode/hash-table/049-group-anagrams.md: -------------------------------------------------------------------------------- 1 | # 049-group-anagrams 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/group-anagrams/description/](https://leetcode.com/problems/group-anagrams/description/) 6 | 7 | Given an array of strings, group anagrams together. 8 | 9 | **Example:** 10 | 11 | ```text 12 | For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 13 | Return: 14 | 15 | [ 16 | ["ate", "eat","tea"], 17 | ["nat","tan"], 18 | ["bat"] 19 | ] 20 | ``` 21 | 22 | ## Thought Process {#thought-process} 23 | 24 | 1. Sort the character in Key 25 | 1. Time complexity O\(n w logw\), where n is number of words, and w is the average length of w 26 | 2. Space complexity O\(n\) 27 | 2. Key Hashing using Prime 28 | 1. We 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public List> groupAnagrams(String[] strs) { 35 | List> res = new ArrayList<>(); 36 | Map> map = new HashMap<>(); 37 | for (String str : strs) { 38 | char[] chars = str.toCharArray(); 39 | Arrays.sort(chars); 40 | map.computeIfAbsent(String.valueOf(chars), k -> new ArrayList<>()).add(str); 41 | } 42 | res.addAll(map.values()); 43 | return res; 44 | } 45 | } 46 | ``` 47 | 48 | ```java 49 | class Solution { 50 | public List> groupAnagrams(String[] strs) { 51 | int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101}; 52 | List> res = new ArrayList<>(); 53 | Map> map = new HashMap<>(); 54 | for (String str : strs) { 55 | int key = 1; 56 | for (char c : str.toCharArray()) { 57 | key *= primes[c - 'a']; 58 | } 59 | if (!map.containsKey(key)) map.put(key, new ArrayList<>()); 60 | map.get(key).add(str); 61 | } 62 | res.addAll(map.values()); 63 | return res; 64 | } 65 | } 66 | ``` 67 | 68 | ## Additional {#additional} 69 | 70 | -------------------------------------------------------------------------------- /leetcode/hash-table/076-minimum-window-substring.md: -------------------------------------------------------------------------------- 1 | # 076-minimum-window-substring 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/minimum-window-substring/description/](https://leetcode.com/problems/minimum-window-substring/description/) 6 | 7 | Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O\(n\). 8 | 9 | **Example:** 10 | 11 | ```text 12 | S = "ADOBECODEBANC" 13 | T = "ABC" 14 | Minimum window is "BANC". 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Brute Force 20 | 1. Try every possible subsequence 21 | 2. Time complexity O\(n^2\) 22 | 3. Space complexity O\(1\) 23 | 2. Sliding Window 24 | 1. Two pointers to track the start and end point of our window 25 | 2. Once we have include all the letter, we start shrinking the start pointers 26 | 3. Time complexity O\(n\) 27 | 4. Space complexity O\(1\) 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public String minWindow(String s, String t) { 34 | if (t.length() > s.length()) return ""; 35 | int[] counts = new int[256]; 36 | for (char c : t.toCharArray()) { 37 | counts[c]++; 38 | } 39 | int left = 0, right = 0, n = t.length(), start = 0, len = Integer.MAX_VALUE; 40 | char[] chars = s.toCharArray(); 41 | while (right < s.length()) { 42 | if (counts[chars[right++]]-- > 0) n--; 43 | while (n == 0) { 44 | if (right - left < len) { 45 | start = left; 46 | len = right - left; 47 | } 48 | if (counts[chars[left++]]++ >= 0) n++; 49 | } 50 | } 51 | len = len == Integer.MAX_VALUE ? 0 : len; 52 | return s.substring(start, start + len); 53 | } 54 | } 55 | ``` 56 | 57 | ## Additional {#additional} 58 | 59 | -------------------------------------------------------------------------------- /leetcode/hash-table/136-single-number.md: -------------------------------------------------------------------------------- 1 | # 136-single-number 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/single-number/description/](https://leetcode.com/problems/single-number/description/) 6 | 7 | Given an array of integers, every element appears twice except for one. Find that single one. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Hash Table 18 | 1. Use set to record the number, if we encounter the number again, we remove them, in the end there will be only 1 number left 19 | 2. Time complexity O\(n\) 20 | 3. Space complexity O\(n\) 21 | 2. XOR 22 | 1. Use the bit trick where xor a number twice cancel the number one 23 | 2. Time complexity O\(n\) 24 | 3. Space complexity O\(1\) 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | public int singleNumber(int[] nums) { 31 | Set set = new HashSet<>(); 32 | for (int num : nums){ 33 | if (!set.contains(num)) set.add(num); 34 | else set.remove(num); 35 | } 36 | return (int) set.iterator().next(); 37 | } 38 | } 39 | ``` 40 | 41 | ```java 42 | class Solution { 43 | public int singleNumber(int[] nums) { 44 | int res = 0; 45 | for (int num : nums){ 46 | res ^= num; 47 | } 48 | return res; 49 | } 50 | } 51 | ``` 52 | 53 | ## Additional {#additional} 54 | 55 | -------------------------------------------------------------------------------- /leetcode/hash-table/149-max-points-on-a-line.md: -------------------------------------------------------------------------------- 1 | # 149-max-points-on-a-line 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/max-points-on-a-line/description/](https://leetcode.com/problems/max-points-on-a-line/description/) 6 | 7 | Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Brute Force - HashMap 18 | 1. We simply create all possible pair of points, and calculate their slope and intercept 19 | 2. Use the string representation of slope 20 | 3. Time complexity O\(n^2\) 21 | 4. Space complexity O\(n^2\) 22 | 23 | ## Solution 24 | 25 | ```java 26 | /** 27 | * Definition for a point. 28 | * class Point { 29 | * int x; 30 | * int y; 31 | * Point() { x = 0; y = 0; } 32 | * Point(int a, int b) { x = a; y = b; } 33 | * } 34 | */ 35 | class Solution { 36 | public int maxPoints(Point[] points) { 37 | if (points.length <= 2) return points.length; 38 | int n = points.length; 39 | int res = 0; 40 | for (int i = 0; i < n - 1; i++) { 41 | int sameP = 0, max = 0; 42 | Map map = new HashMap<>(); 43 | for (int j = i + 1; j < n; j++) { 44 | int x = points[i].x - points[j].x; 45 | int y = points[i].y - points[j].y; 46 | if (x == 0 && y == 0) { 47 | sameP++; 48 | continue; 49 | } 50 | // divide by gcd to reduce the factor in slope 51 | int gcd = gcd(x, y); 52 | x /= gcd; 53 | y /= gcd; 54 | String key = y + "/" + x; 55 | map.put(key, map.getOrDefault(key, 0) + 1); 56 | max = Math.max(max, map.get(key)); 57 | } 58 | // +1 to include original point 59 | res = Math.max(res, max + sameP + 1); 60 | } 61 | return res; 62 | } 63 | 64 | private int gcd(int x, int y) { 65 | if (y == 0) return x; 66 | return gcd(y, x % y); 67 | } 68 | } 69 | ``` 70 | 71 | ## Additional {#additional} 72 | 73 | -------------------------------------------------------------------------------- /leetcode/hash-table/166-fraction-to-recurring-decimal.md: -------------------------------------------------------------------------------- 1 | # 166-fraction-to-recurring-decimal 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/fraction-to-recurring-decimal/description/](https://leetcode.com/problems/fraction-to-recurring-decimal/description/) 6 | 7 | Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. 8 | 9 | If the fractional part is repeating, enclose the repeating part in parentheses. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Given numerator = 1, denominator = 2, return "0.5". 15 | Given numerator = 2, denominator = 1, return "2". 16 | Given numerator = 2, denominator = 3, return "0.(6)". 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. StringBuilder and Map 22 | 1. Follow the rule of division, save the output to the string builder 23 | 2. The repeating part happens when we have visited the remainder before, then we need to insert the "\(" at the position provided by the map 24 | 3. Time com 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | public String fractionToDecimal(int numerator, int denominator) { 31 | if (numerator == 0) return "0"; 32 | String sign = (numerator > 0) ^ (denominator > 0) ? "-" : ""; 33 | long num = Math.abs((long) numerator); 34 | long den = Math.abs((long) denominator); 35 | StringBuilder sb = new StringBuilder(); 36 | sb.append(sign).append(num / den); 37 | num %= den; 38 | if (num == 0) return sb.toString(); 39 | sb.append("."); 40 | Map map = new HashMap<>(); 41 | int index = sb.length(); 42 | while (num != 0) { 43 | if (map.containsKey(num)) { 44 | sb.insert(map.get(num), "("); 45 | sb.append(")"); 46 | break; 47 | } 48 | map.put(num, index++); 49 | num *= 10; 50 | sb.append(num / den); 51 | num %= den; 52 | } 53 | return sb.toString(); 54 | } 55 | } 56 | ``` 57 | 58 | ## Additional {#additional} 59 | 60 | -------------------------------------------------------------------------------- /leetcode/hash-table/202-happy-number.md: -------------------------------------------------------------------------------- 1 | # 202-happy-number 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/happy-number/description/](https://leetcode.com/problems/happy-number/description/) 6 | 7 | Write an algorithm to determine if a number is "happy". 8 | 9 | A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 \(where it will stay\), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 10 | 11 | **Example:** 12 | 13 | ```text 14 | 19 is a happy number 15 | 16 | 1^2 + 9^2 = 82 17 | 8^2 + 2^2 = 68 18 | 6^2 + 8^2 = 100 19 | 1^2 + 0^2 + 0^2 = 1 20 | ``` 21 | 22 | ## Thought Process {#thought-process} 23 | 24 | 1. Brute Force - Set 25 | 1. Use set to record the squared sum through the process 26 | 2. If we have seen this number before, we know there is loop, and we cannot reach to 1 27 | 2. asd 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public boolean isHappy(int n) { 34 | Set set = new HashSet<>(); 35 | int res = 0; 36 | while (set.add(n)) { 37 | if (n == 1) return true; 38 | while (n > 0) { 39 | int d = n % 10; 40 | res += d * d; 41 | n /= 10; 42 | } 43 | n = res; 44 | res = 0; 45 | } 46 | return false; 47 | } 48 | } 49 | ``` 50 | 51 | ```java 52 | class Solution { 53 | public boolean isHappy(int n) { 54 | int slow = n, fast = n; 55 | do { 56 | slow = cal(slow); 57 | fast = cal(cal(fast)); 58 | } while (slow != fast); 59 | return slow == 1; 60 | } 61 | 62 | private int cal(int n) { 63 | int res = 0; 64 | while (n > 0) { 65 | int d = n % 10; 66 | res += d * d; 67 | n /= 10; 68 | } 69 | return res; 70 | } 71 | } 72 | ``` 73 | 74 | ## Additional {#additional} 75 | 76 | -------------------------------------------------------------------------------- /leetcode/hash-table/205-isomorphic-strings.md: -------------------------------------------------------------------------------- 1 | # 205-isomorphic-strings 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/isomorphic-strings/description/](https://leetcode.com/problems/isomorphic-strings/description/) 6 | 7 | Given two strings **s** and **t**, determine if they are isomorphic. 8 | 9 | Two strings are isomorphic if the characters in **s** can be replaced to get **t**. 10 | 11 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 12 | 13 | **Example:** 14 | 15 | ```text 16 | Given "egg", "add", return true. 17 | 18 | Given "foo", "bar", return false. 19 | 20 | Given "paper", "title", return true. 21 | ``` 22 | 23 | ## Thought Process {#thought-process} 24 | 25 | 1. Hash Table and Boolean 26 | 1. Use hashtable to track the mapping of characters and boolean to track whether a character has been used already 27 | 2. Time complexity O\(n\) 28 | 3. Space complexity O\(1\) 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public boolean isIsomorphic(String s, String t) { 35 | if (s.length() != t.length()) return false; 36 | char[] map = new char[256]; 37 | boolean[] used = new boolean[256]; 38 | char[] sc = s.toCharArray(); 39 | char[] tc = t.toCharArray(); 40 | for (int i = 0; i < sc.length; i++) { 41 | // if this character has not been mapped 42 | if (map[sc[i]] == 0) { 43 | if (used[tc[i]]) return false; 44 | map[sc[i]] = tc[i]; 45 | used[tc[i]] = true; 46 | } else if (map[sc[i]] != tc[i]) { 47 | return false; 48 | } 49 | } 50 | return true; 51 | } 52 | } 53 | ``` 54 | 55 | ## Additional {#additional} 56 | 57 | -------------------------------------------------------------------------------- /leetcode/hash-table/217-contains-duplicate.md: -------------------------------------------------------------------------------- 1 | # 217-contains-duplicate 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/contains-duplicate/description/](https://leetcode.com/problems/contains-duplicate/description/) 6 | 7 | Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Sort 18 | 1. Time complexity O\(n logn\) 19 | 2. Space complexity O\(1\) or O\(n\) depends on if we can temper the original array 20 | 2. Hash Table - Set 21 | 1. Time complexity O\(n\) 22 | 2. Space complexity O\(n\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public boolean containsDuplicate(int[] nums) { 29 | Arrays.sort(nums); 30 | for (int i = 1; i < nums.length; i++) { 31 | if (nums[i] == nums[i - 1]) return true; 32 | } 33 | return false; 34 | } 35 | } 36 | ``` 37 | 38 | ```java 39 | class Solution { 40 | public boolean containsDuplicate(int[] nums) { 41 | Set set = new HashSet<>(); 42 | for (int num : nums){ 43 | if (!set.add(num)) return true; 44 | } 45 | return false; 46 | } 47 | } 48 | ``` 49 | 50 | ## Additional {#additional} 51 | 52 | -------------------------------------------------------------------------------- /leetcode/hash-table/242-valid-anagram.md: -------------------------------------------------------------------------------- 1 | # 242-valid-anagram 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/valid-anagram/description/](https://leetcode.com/problems/valid-anagram/description/) 6 | 7 | Given two strings s and t, write a function to determine if t is an anagram of s. 8 | 9 | **Example:** 10 | 11 | ```text 12 | s = "anagram", t = "nagaram", return true. 13 | s = "rat", t = "car", return false. 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Hash Table 19 | 1. Store the frequency in the map 20 | 2. If the count reach 0 when encounter a particular character, we know we don't have enough character from the String s 21 | 3. Time complexity O\(n\) 22 | 4. Space complexity O\(1\), at most 256 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public boolean isAnagram(String s, String t) { 29 | if (s.length() != t.length()) return false; 30 | char[] map = new char[256]; 31 | for (char c : s.toCharArray()) { 32 | map[c]++; 33 | } 34 | for (char c: t.toCharArray()) { 35 | if (map[c] == 0) return false; 36 | map[c]--; 37 | } 38 | return true; 39 | } 40 | } 41 | ``` 42 | 43 | ## Additional {#additional} 44 | 45 | -------------------------------------------------------------------------------- /leetcode/hash-table/249-group-shifted-strings.md: -------------------------------------------------------------------------------- 1 | # 249-group-shifted-strings 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/group-shifted-strings/description/](https://leetcode.com/problems/group-shifted-strings/description/) 6 | 7 | Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: 8 | 9 | "abc" -> "bcd" -> ... -> "xyz" 10 | 11 | Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. 12 | 13 | **Example:** 14 | 15 | ```text 16 | For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], 17 | A solution is: 18 | [ 19 | ["abc","bcd","xyz"], 20 | ["az","ba"], 21 | ["acef"], 22 | ["a","z"] 23 | ] 24 | ``` 25 | 26 | ## Thought Process {#thought-process} 27 | 28 | 1. Hash Table - Normalized Key 29 | 1. Using the first character as gauge and make the first character 'a', and normalize the rest of characters accordingly 30 | 2. Time complexity O\(nw\), where n is number of word, w is the average width of the word 31 | 3. Space complexity O\(nw\) 32 | 33 | ## Solution 34 | 35 | ```java 36 | class Solution { 37 | public List> groupStrings(String[] strings) { 38 | List> res = new ArrayList<>(); 39 | if (strings == null || strings.length == 0) return res; 40 | Map> map = new HashMap<>(); 41 | for (String str : strings) { 42 | String key = normalize(str); 43 | if (!map.containsKey(key)) map.put(key, new ArrayList<>()); 44 | map.get(key).add(str); 45 | } 46 | res.addAll(map.values()); 47 | return res; 48 | } 49 | 50 | private String normalize(String s) { 51 | if (s.length() == 0 || s.charAt(0) == 'a') return s; 52 | char[] chars = s.toCharArray(); 53 | int diff = chars[0] - 'a'; 54 | for (int i = 0; i < chars.length; i++) { 55 | chars[i] -= diff; 56 | if (chars[i] < 'a') chars[i] += 26; 57 | } 58 | return String.valueOf(chars); 59 | } 60 | } 61 | ``` 62 | 63 | ## Additional {#additional} 64 | 65 | -------------------------------------------------------------------------------- /leetcode/hash-table/266-palindrome-permutation.md: -------------------------------------------------------------------------------- 1 | # 266-palindrome-permutation 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/palindrome-permutation/description/](https://leetcode.com/problems/palindrome-permutation/description/) 6 | 7 | Given a string, determine if a permutation of the string could form a palindrome. 8 | 9 | **Example:** 10 | 11 | ```text 12 | "code" -> False, "aab" -> True, "carerac" -> True. 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Hash Table - Two passes 18 | 1. Use map to store the frequency of character, if we have seen odd frequency more than once, we can't make a permutation that is palindrom 19 | 2. Time complexity O\(n\) 20 | 3. Space complexity O\(n\) 21 | 2. Hash Table - One pass 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public boolean canPermutePalindrome(String s) { 28 | if (s.length() <= 1) return true; 29 | int[] map = new int[128]; 30 | char[] chars = s.toCharArray(); 31 | for (char c : chars) map[c]++; 32 | boolean oddSeen = false; 33 | for (char a = 0; a < 128; a++) { 34 | if (map[a] % 2 == 1) { 35 | if (oddSeen) return false; 36 | oddSeen = true; 37 | } 38 | } 39 | return true; 40 | } 41 | } 42 | ``` 43 | 44 | ```java 45 | class Solution { 46 | public boolean canPermutePalindrome(String s) { 47 | if (s.length() <= 1) return true; 48 | int[] map = new int[128]; 49 | int oddCnt = 0; 50 | for (char c : s.toCharArray()) { 51 | map[c]++; 52 | if (map[c] % 2 == 1) oddCnt++; 53 | else oddCnt--; 54 | } 55 | return oddCnt <= 1 ? true : false; 56 | } 57 | } 58 | ``` 59 | 60 | ## Additional {#additional} 61 | 62 | -------------------------------------------------------------------------------- /leetcode/hash-table/290-word-pattern.md: -------------------------------------------------------------------------------- 1 | # 290-word-pattern 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/word-pattern/description/](https://leetcode.com/problems/word-pattern/description/) 6 | 7 | Given a pattern and a string str, find if str follows the same pattern. 8 | 9 | Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. 10 | 11 | **Example:** 12 | 13 | ```text 14 | pattern = "abba", str = "dog cat cat dog" should return true. 15 | pattern = "abba", str = "dog cat cat fish" should return false. 16 | pattern = "aaaa", str = "dog cat cat dog" should return false. 17 | pattern = "abba", str = "dog dog dog dog" should return false. 18 | ``` 19 | 20 | ## Thought Process {#thought-process} 21 | 22 | 1. Hash Table 23 | 1. Use two hash table to store the index of each character and word mapping 24 | 2. At any time if the index are different for the same word, we know the pattern and string don't match 25 | 3. We can take advantage of the return value of put function for java Hashmap, where it return value of the old mapping or null when the key is new 26 | 4. Time complexity O\(n\) 27 | 5. Space complexity O\(n\) 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public boolean wordPattern(String pattern, String str) { 34 | char[] chars = pattern.toCharArray(); 35 | String[] strs = str.split(" "); 36 | if (chars.length != strs.length) return false; 37 | Map cmap = new HashMap<>(); 38 | Map smap = new HashMap<>(); 39 | for (Integer i = 0; i < chars.length; i++) { 40 | if (cmap.put(chars[i], i) != smap.put(strs[i], i)) return false; 41 | } 42 | return true; 43 | } 44 | } 45 | ``` 46 | 47 | ## Additional {#additional} 48 | 49 | -------------------------------------------------------------------------------- /leetcode/hash-table/356-line-reflection.md: -------------------------------------------------------------------------------- 1 | # 356-line-reflection 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/line-reflection/description/](https://leetcode.com/problems/line-reflection/description/) 6 | 7 | Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given points = [[1,1],[-1,1]], return true. 13 | Given points = [[1,1],[-1,-1]], return false. 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Hash Table - Two pass 19 | 1. The reflection line has to be in the middle, meaning xref = \(xmin + xmax\) / 2 20 | 2. Then we search if the there is reflected counterpart by searching point \[\(xmin + xmax\) - x, y\] 21 | 3. Time complexity O\(n\) 22 | 4. Space complexity O\(n\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public boolean isReflected(int[][] points) { 29 | int xMin = Integer.MAX_VALUE, xMax = Integer.MIN_VALUE; 30 | Set set = new HashSet<>(); 31 | for (int[] point : points) { 32 | xMin = Math.min(xMin, point[0]); 33 | xMax = Math.max(xMax, point[0]); 34 | set.add(point[0] + "," + point[1]); 35 | } 36 | int xSum = xMin + xMax; 37 | for (int[] point : points) { 38 | if (!set.contains((xSum - point[0]) + "," + point[1])) return false; 39 | } 40 | return true; 41 | } 42 | } 43 | ``` 44 | 45 | ```java 46 | class Solution { 47 | public boolean isReflected(int[][] points) { 48 | int xMin = Integer.MAX_VALUE, xMax = Integer.MIN_VALUE; 49 | Set set = new HashSet<>(); 50 | for (int[] point : points) { 51 | xMin = Math.min(xMin, point[0]); 52 | xMax = Math.max(xMax, point[0]); 53 | set.add(Arrays.hashCode(point)); 54 | } 55 | int xSum = xMin + xMax; 56 | for (int[] point : points) { 57 | int[] pRef = {xSum - point[0], point[1]}; 58 | if (!set.contains(Arrays.hashCode(pRef))) return false; 59 | } 60 | return true; 61 | } 62 | } 63 | ``` 64 | 65 | ## Additional {#additional} 66 | 67 | -------------------------------------------------------------------------------- /leetcode/hash-table/387-first-unique-character-in-a-string.md: -------------------------------------------------------------------------------- 1 | # 387-first-unique-character-in-a-string 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/first-unique-character-in-a-string/description/](https://leetcode.com/problems/first-unique-character-in-a-string/description/) 6 | 7 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 8 | 9 | **Example:** 10 | 11 | ```text 12 | s = "leetcode" 13 | return 0. 14 | 15 | s = "loveleetcode", 16 | return 2. 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Hash Map 22 | 1. Store the count for each character 23 | 2. When we first encounter a character that has 1 count, w return the index 24 | 3. Time complexity O\(n\) 25 | 4. Space complexity O\(1\) 26 | 2. String index of 27 | 1. Use indexOf and lastIndexOf function from string, if the index is the same and not -1, we know there is exactly one count for this character 28 | 2. Time complexity O\(1\) 29 | 3. Space complexity O\(1\) 30 | 31 | ## Solution 32 | 33 | ```java 34 | class Solution { 35 | public int firstUniqChar(String s) { 36 | int[] counts = new int[256]; 37 | char[] chars = s.toCharArray(); 38 | for (int i = 0; i < chars.length; i++) { 39 | counts[chars[i]]++; 40 | } 41 | for (int i = 0; i < chars.length; i++) { 42 | if (counts[chars[i]] == 1) return i; 43 | } 44 | return -1; 45 | } 46 | } 47 | ``` 48 | 49 | ```java 50 | class Solution { 51 | public int firstUniqChar(String s) { 52 | int res = s.length(); 53 | for (char c = 'a'; c <= 'z'; c++) { 54 | int id = s.indexOf(c); 55 | if (id != -1 && id == s.lastIndexOf(c)) { 56 | res = Math.min(id, res); 57 | } 58 | } 59 | return res == s.length() ? -1 : res; 60 | } 61 | } 62 | ``` 63 | 64 | ## Additional {#additional} 65 | 66 | -------------------------------------------------------------------------------- /leetcode/hash-table/447-number-of-boomerangs.md: -------------------------------------------------------------------------------- 1 | # 447-number-of-boomerangs 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/number-of-boomerangs/description/](https://leetcode.com/problems/number-of-boomerangs/description/) 6 | 7 | Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points \(i, j, k\) such that the distance between i and j equals the distance between i and k \(the order of the tuple matters\). 8 | 9 | Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range \[-10000, 10000\] \(inclusive\). 10 | 11 | **Example:** 12 | 13 | ```text 14 | Input: 15 | [[0,0],[1,0],[2,0]] 16 | 17 | Output: 18 | 2 19 | 20 | Explanation: 21 | The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]] 22 | ``` 23 | 24 | ## Thought Process {#thought-process} 25 | 26 | 1. Hash Table 27 | 1. Use map to record the count of point that are equidistance to current point 28 | 2. To calculate the count, we simply use the recorded count times count - 1, based on the permutation formula, nPk 29 | 3. Time complexity O\(n^2\) 30 | 4. Space complexity O\(n\) 31 | 32 | ## Solution 33 | 34 | ```java 35 | class Solution { 36 | public int numberOfBoomerangs(int[][] points) { 37 | int res = 0; 38 | Map map = new HashMap<>(); 39 | for (int i = 0; i < points.length; i++) { 40 | for (int j = 0; j < points.length; j++) { 41 | if (i == j) continue; 42 | int d = distance(points[i], points[j]); 43 | map.put(d, map.getOrDefault(d, 0) + 1); 44 | } 45 | for (int val : map.values()) { 46 | res += val * (val - 1); 47 | } 48 | map.clear(); 49 | } 50 | return res; 51 | } 52 | 53 | private int distance(int[] p, int[] q) { 54 | int dx = p[0] - q[0]; 55 | int dy = p[1] - q[1]; 56 | return dx * dx + dy * dy; 57 | } 58 | } 59 | ``` 60 | 61 | ## Additional {#additional} 62 | 63 | -------------------------------------------------------------------------------- /leetcode/hash-table/README.md: -------------------------------------------------------------------------------- 1 | # hash-table 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/linked-list/002-add-two-numbers.md: -------------------------------------------------------------------------------- 1 | # 002-add-two-numbers 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/add-two-numbers/description/](https://leetcode.com/problems/add-two-numbers/description/) 6 | 7 | You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order** and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 8 | 9 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 15 | Output: 7 -> 0 -> 8 16 | Explanation: 342 + 465 = 807. 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Since the digits are stored in reverse order, the solution is pretty straight forward. The only thing we need to be careful about is the possibility of carry over. 22 | 2. Dummy node is helpful to return the head of the linked list \(the "last" digit of the number\). 23 | 3. Time complexity is O\(n\) 24 | 4. Space complexity is O\(n\) for creating new linked list or O\(1\) for reusing one of the input 25 | 26 | ## Solution {#solution} 27 | 28 | ```java 29 | class Solution { 30 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 31 | ListNode dummy = new ListNode(-1); 32 | ListNode cur = dummy; 33 | int sum = 0; 34 | while(l1!=null || l2!=null){ 35 | sum /= 10; 36 | if(l1!=null){ 37 | sum+=l1.val; 38 | l1 = l1.next; 39 | } 40 | if(l2!=null){ 41 | sum+=l2.val; 42 | l2 = l2.next; 43 | } 44 | cur.next = new ListNode(sum%10); 45 | cur = cur.next; 46 | } 47 | if(sum >= 10){ 48 | cur.next = new ListNode(1); 49 | } 50 | return dummy.next; 51 | } 52 | } 53 | ``` 54 | 55 | ## Additional {#additional} 56 | 57 | -------------------------------------------------------------------------------- /leetcode/linked-list/024-swap-nodes-in-pairs.md: -------------------------------------------------------------------------------- 1 | # 024-swap-nodes-in-pairs 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/swap-nodes-in-pairs/description/](https://leetcode.com/problems/swap-nodes-in-pairs/description/) 6 | 7 | Given a linked list, swap every two adjacent nodes and return its head. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given 1->2->3->4, you should return the list as 2->1->4->3. 13 | ``` 14 | 15 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Iterative 20 | 1. Make sure we have next two nodes available to swap the position 21 | 2. Time complexity O\(n\) 22 | 3. Space complexity O\(1\) 23 | 2. Recursion 24 | 1. Time complexity O\(n\) 25 | 2. Space complexity O\(n\) for recursion stack 26 | 27 | ## Solution 28 | 29 | ```java 30 | class Solution { 31 | public ListNode swapPairs(ListNode head) { 32 | ListNode dummy = new ListNode(0); 33 | dummy.next = head; 34 | ListNode cur = dummy; 35 | while (cur.next != null && cur.next.next != null) { 36 | ListNode next = cur.next; 37 | cur.next = next.next; 38 | next.next = cur.next.next; 39 | cur.next.next = next; 40 | cur = next; 41 | } 42 | return dummy.next; 43 | } 44 | } 45 | ``` 46 | 47 | ```java 48 | class Solution { 49 | public ListNode swapPairs(ListNode head) { 50 | if (head == null || head.next == null) return head; 51 | ListNode newHead = head.next; 52 | head.next = swapPairs(newHead.next); 53 | newHead.next = head; 54 | return newHead; 55 | } 56 | } 57 | ``` 58 | 59 | ## Additional {#additional} 60 | 61 | -------------------------------------------------------------------------------- /leetcode/linked-list/061-rotate-list.md: -------------------------------------------------------------------------------- 1 | # 061-rotate-list 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/rotate-list/description/](https://leetcode.com/problems/rotate-list/description/) 6 | 7 | Given a list, rotate the list to the right by k places, where k is non-negative. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given 1->2->3->4->5->NULL and k = 2, 13 | 14 | return 4->5->1->2->3->NULL. 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Circular Linked List 20 | 1. Count the size of linked list, create the link between the tail and the first node 21 | 2. Mod the k with the size, since a full size rotation goes back to the same list 22 | 3. Move the pointer, pointed at the old tail right now, size - k steps forward to point at the new tail 23 | 4. Unset the link and return the newHead 24 | 5. Time complexity O\(n\) 25 | 6. Space complexity O\(1\) 26 | 27 | ## Solution 28 | 29 | ```java 30 | class Solution { 31 | public ListNode rotateRight(ListNode head, int k) { 32 | if(head == null) return head; 33 | int size = 1; 34 | ListNode cur = head; 35 | while(cur.next != null){ 36 | size++; 37 | cur = cur.next; 38 | } 39 | k %= size; 40 | if(k == 0) return head; 41 | cur.next = head; //circular ListNode 42 | while (size-- > k) cur = cur.next; 43 | head = cur.next; 44 | cur.next = null; 45 | return head; 46 | } 47 | } 48 | ``` 49 | 50 | ## Additional {#additional} 51 | 52 | -------------------------------------------------------------------------------- /leetcode/linked-list/082-remove-duplicates-from-sorted-list-ii.md: -------------------------------------------------------------------------------- 1 | # 082-remove-duplicates-from-sorted-list-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/) 6 | 7 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given 1->2->3->3->4->4->5, return 1->2->5. 13 | Given 1->1->1->2->3, return 2->3. 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Compare Next Node 19 | 1. Simply compare every node to its next node, move the pointers forward if the cur node's value is same as next 20 | 2. If the previous node's next node is still same as current, we haven't move the pointer forward, which means the node has no duplicate 21 | 3. Time complexity O\(n\) 22 | 4. Space complexity O\(1\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public ListNode deleteDuplicates(ListNode head) { 29 | ListNode dummy = new ListNode(0); 30 | dummy.next = head; 31 | ListNode pre = dummy, cur = head; 32 | while(cur != null){ 33 | while (cur.next != null && cur.next.val == cur.val) { 34 | cur = cur.next; 35 | } 36 | if (pre.next == cur) pre = pre.next; 37 | else pre.next = cur.next; 38 | cur = cur.next; 39 | } 40 | return dummy.next; 41 | } 42 | } 43 | ``` 44 | 45 | ## Additional {#additional} 46 | 47 | -------------------------------------------------------------------------------- /leetcode/linked-list/083-remove-duplicates-from-sorted-list.md: -------------------------------------------------------------------------------- 1 | # 083-remove-duplicates-from-sorted-list 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/) 6 | 7 | Given a sorted linked list, delete all duplicates such that each element appear only once. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given 1->1->2, return 1->2. 13 | Given 1->1->2->3->3, return 1->2->3. 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Compare next node 19 | 1. Link the cur node to next.next if same as current 20 | 2. Time complexity O\(n\) 21 | 3. Space complexity O\(1\) 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public ListNode deleteDuplicates(ListNode head) { 28 | ListNode cur = head; 29 | while(cur != null && cur.next != null){ 30 | if(cur.val == cur.next.val) cur.next = cur.next.next; 31 | else cur = cur.next; 32 | } 33 | return head; 34 | } 35 | } 36 | ``` 37 | 38 | ## Additional {#additional} 39 | 40 | -------------------------------------------------------------------------------- /leetcode/linked-list/086-partition-list.md: -------------------------------------------------------------------------------- 1 | # 086-partition-list 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/partition-list/description/](https://leetcode.com/problems/partition-list/description/) 6 | 7 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given 1->4->3->2->5->2 and x = 3, 13 | return 1->2->2->4->3->5. 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Two Pointers 19 | 1. Save the vale into different pointers 20 | 2. Link the two pointers at the end 21 | 3. Time complexity O\(n\) 22 | 4. Space complexity O\(1\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public ListNode partition(ListNode head, int x) { 29 | ListNode less = new ListNode(-1), greater = new ListNode(0); 30 | ListNode dummyLess = less, dummyGreater = greater; 31 | while (head != null){ 32 | if (head.val < x){ 33 | less.next = head; 34 | less = head; 35 | } else { 36 | greater.next = head; 37 | greater = head; 38 | } 39 | head = head.next; 40 | } 41 | greater.next = null; 42 | less.next = dummyGreater.next; 43 | return dummyLess.next; 44 | } 45 | } 46 | ``` 47 | 48 | ## Additional {#additional} 49 | 50 | -------------------------------------------------------------------------------- /leetcode/linked-list/092-reverse-linked-list-ii.md: -------------------------------------------------------------------------------- 1 | # 092-reverse-linked-list-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reverse-linked-list-ii/description/](https://leetcode.com/problems/reverse-linked-list-ii/description/) 6 | 7 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 13 | 14 | return 1->4->3->2->5->NULL. 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Move Pointer 20 | 1. Move pointer to the mth position, then reverse 21 | 2. Time complexity O\(n\) 22 | 3. Space complexity O\(1\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public ListNode reverseBetween(ListNode head, int m, int n) { 29 | if (head == null || m == n) return head; 30 | int len = n - m; 31 | ListNode dummy = new ListNode(0); 32 | dummy.next = head; 33 | ListNode pre = dummy; 34 | while(m > 1){ 35 | pre = pre.next; 36 | m--; 37 | } 38 | ListNode cur = pre.next, remain = cur.next; 39 | while(len-- > 0){ 40 | cur.next = remain.next; 41 | remain.next = pre.next; 42 | pre.next = remain; 43 | remain = cur.next; 44 | } 45 | return dummy.next; 46 | } 47 | } 48 | ``` 49 | 50 | ## Additional {#additional} 51 | 52 | -------------------------------------------------------------------------------- /leetcode/linked-list/141-linked-list-cycle.md: -------------------------------------------------------------------------------- 1 | # 141-linked-list-cycle 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/linked-list-cycle/description/](https://leetcode.com/problems/linked-list-cycle/description/) 6 | 7 | Given a linked list, determine if it has a cycle in it. 8 | 9 | Follow up: 10 | 11 | Can you solve it without using extra space? 12 | 13 | **Example:** 14 | 15 | ```text 16 | 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Hash Table 22 | 1. Use hash table to record the node visited 23 | 2. Time complexity O\(n\) 24 | 3. Space complexity O\(n\) 25 | 2. Two Pointer 26 | 1. Classic Tortoise and Hare Algorithm or Floyd's Cycle detection algorithm 27 | 2. Slow pointer move at the pace of 1 and fast pointer moves at the pace of 2 28 | 3. Fast pointer is the one who catch up with slow 29 | 4. If slow and fast meet, we know there is cycle 30 | 5. Time complexity O\(n\) 31 | 6. Space complexity O\(1\) 32 | 33 | ## Solution 34 | 35 | ```java 36 | public class Solution { 37 | public boolean hasCycle(ListNode head) { 38 | ListNode slow = head, fast = head; 39 | while (fast!= null && fast.next != null){ 40 | slow = slow.next; 41 | fast = fast.next.next; 42 | if (slow == fast) return true; 43 | } 44 | return false; 45 | } 46 | } 47 | ``` 48 | 49 | ## Additional {#additional} 50 | 51 | -------------------------------------------------------------------------------- /leetcode/linked-list/143-reorder-list.md: -------------------------------------------------------------------------------- 1 | # 143-reorder-list 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reorder-list/description/](https://leetcode.com/problems/reorder-list/description/) 6 | 7 | Given a singly linked listL:L0→L1→…→Ln-1→Ln, 8 | reorder it to:L0→Ln→L1→Ln-1→L2→Ln-2→… 9 | 10 | You must do this in-place without altering the nodes' values. 11 | 12 | **Example:** 13 | 14 | ```text 15 | Given {1,2,3,4}, reorder it to {1,4,2,3}. 16 | ``` 17 | 18 | ## Thought Process {#thought-process} 19 | 20 | 1. Reverse and Link 21 | 1. Reverse the second half of linked list and then relink 22 | 2. Time complexity O\(n\) 23 | 3. Space complexity O\(1\) 24 | 25 | ## Solution 26 | 27 | ```java 28 | class Solution { 29 | public void reorderList(ListNode head) { 30 | if (head == null || head.next == null) return; 31 | ListNode slow = head, fast = head; 32 | while (fast.next != null && fast.next.next != null) { 33 | slow = slow.next; 34 | fast = fast.next.next; 35 | } 36 | // split the list into two equal parts, left has one extra 37 | // element when the length is odd 38 | ListNode rightHead = reverse(slow.next); 39 | slow.next = null; 40 | ListNode left = head, right = rightHead; 41 | while (right != null) { 42 | ListNode nLeft = left.next; 43 | left.next = right; 44 | right = right.next; 45 | left.next.next = nLeft; 46 | left = nLeft; 47 | } 48 | } 49 | 50 | private ListNode reverse(ListNode head) { 51 | ListNode dummy = new ListNode(0); 52 | dummy.next = head; 53 | ListNode pre = dummy, cur = head; 54 | while (cur.next != null) { 55 | ListNode newHead = cur.next; 56 | cur.next = newHead.next; 57 | newHead.next = pre.next; 58 | pre.next = newHead; 59 | } 60 | return dummy.next; 61 | } 62 | } 63 | ``` 64 | 65 | ## Additional {#additional} 66 | 67 | -------------------------------------------------------------------------------- /leetcode/linked-list/147-insertion-sort-list.md: -------------------------------------------------------------------------------- 1 | # 147-insertion-sort-list 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/insertion-sort-list/description/](https://leetcode.com/problems/insertion-sort-list/description/) 6 | 7 | Sort a linked list using insertion sort. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Pointer 18 | 1. Use dummy variable to point to head and a another variable track the progress the variable 19 | 2. We need to find the node that the current node is greater than its next node, and that's where we insert the current node 20 | 3. Time complexity O\(n^2\) 21 | 4. Space complexity O\(1\) 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public ListNode insertionSortList(ListNode head) { 28 | ListNode dummy = new ListNode(Integer.MIN_VALUE); 29 | ListNode pre = dummy; 30 | while (head != null) { 31 | ListNode next = head.next; 32 | if (head.val < pre.val) pre = dummy; 33 | while (pre.next != null && head.val > pre.next.val) pre = pre.next; 34 | head.next = pre.next; 35 | pre.next = head; 36 | head = next; 37 | } 38 | return dummy.next; 39 | } 40 | } 41 | ``` 42 | 43 | ## Additional {#additional} 44 | 45 | -------------------------------------------------------------------------------- /leetcode/linked-list/203-remove-linked-list-elements.md: -------------------------------------------------------------------------------- 1 | # 203-remove-linked-list-elements 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/remove-linked-list-elements/description/](https://leetcode.com/problems/remove-linked-list-elements/description/) 6 | 7 | Remove all elements from a linked list of integers that have value **val**. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 13 | Return: 1 --> 2 --> 3 --> 4 --> 5 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Iterative 19 | 1. Time complexity O\(n\) 20 | 2. Space complexity O\(1\) 21 | 2. Recursion 22 | 1. Time complexity O\(n\) 23 | 2. Space complexity O\(1\) 24 | 25 | ## Solution 26 | 27 | ```java 28 | class Solution { 29 | public ListNode removeElements(ListNode head, int val) { 30 | ListNode dummy = new ListNode(0); 31 | dummy.next = head; 32 | ListNode pre = dummy; 33 | while (pre.next != null){ 34 | if (pre.next.val == val){ 35 | pre.next = pre.next.next; 36 | } else { 37 | pre = pre.next; 38 | } 39 | } 40 | return dummy.next; 41 | } 42 | } 43 | ``` 44 | 45 | ```java 46 | class Solution { 47 | public ListNode removeElements(ListNode head, int val) { 48 | if (head == null) return null; 49 | head.next = removeElements(head.next, val); 50 | return head.val == val ? head.next : head; 51 | } 52 | } 53 | ``` 54 | 55 | ## Additional {#additional} 56 | 57 | -------------------------------------------------------------------------------- /leetcode/linked-list/206-reverse-linked-list.md: -------------------------------------------------------------------------------- 1 | # 206-reverse-linked-list 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reverse-linked-list/description/](https://leetcode.com/problems/reverse-linked-list/description/) 6 | 7 | Reverse a singly linked list. 8 | 9 | A linked list can be reversed either iteratively or recursively. Could you implement both? 10 | 11 | **Example:** 12 | 13 | ```text 14 | 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Iterative 20 | 1. Time complexity O\(n\) 21 | 2. Space complexity O\(1\) 22 | 2. Recursion 23 | 1. Time complexity O\(n\) 24 | 2. Space complexity O\(1\) or O\(n\) due to recursion stack 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | public ListNode reverseList(ListNode head) { 31 | if (head == null) return null; 32 | ListNode dummy = new ListNode(0); 33 | dummy.next = head; 34 | ListNode pre = dummy, cur = pre.next, next = null; 35 | while (cur.next != null) { 36 | next = cur.next; 37 | cur.next = next.next; 38 | next.next = pre.next; 39 | pre.next = next; 40 | } 41 | return dummy.next; 42 | } 43 | } 44 | ``` 45 | 46 | ```text 47 | class Solution { 48 | public ListNode reverseList(ListNode head) { 49 | return revert(head, null); 50 | } 51 | 52 | private ListNode revert(ListNode head, ListNode tail) { 53 | if (head == null) return tail; 54 | ListNode next = head.next; 55 | head.next = tail; 56 | return revert(next, head); 57 | } 58 | } 59 | ``` 60 | 61 | ## Additional {#additional} 62 | 63 | -------------------------------------------------------------------------------- /leetcode/linked-list/237-delete-node-in-a-linked-list.md: -------------------------------------------------------------------------------- 1 | # 237-delete-node-in-a-linked-list 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/delete-node-in-a-linked-list/description/](https://leetcode.com/problems/delete-node-in-a-linked-list/description/) 6 | 7 | Write a function to delete a node \(except the tail\) in a singly linked list, given only access to that node. 8 | 9 | Supposed the linked list is`1 -> 2 -> 3 -> 4`and you are given the third node with value`3`, the linked list should become`1 -> 2 -> 4`after calling your function. 10 | 11 | **Example:** 12 | 13 | ```text 14 | 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Copy val 20 | 1. Since we don't have access to the previous node, we have to do something with current node 21 | 2. By copying the value of next, we are able to "delete" current node and link current to next's next 22 | 3. Time complexity O\(1\) 23 | 4. Space complexity O\(1\) 24 | 25 | ## Solution 26 | 27 | ```java 28 | class Solution { 29 | public void deleteNode(ListNode node) { 30 | node.val = node.next.val; 31 | node.next = node.next.next; 32 | } 33 | } 34 | ``` 35 | 36 | ## Additional {#additional} 37 | 38 | -------------------------------------------------------------------------------- /leetcode/linked-list/328-odd-even-linked-list.md: -------------------------------------------------------------------------------- 1 | # 328-odd-even-linked-list 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/odd-even-linked-list/description/](https://leetcode.com/problems/odd-even-linked-list/description/) 6 | 7 | Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. 8 | 9 | You should try to do it in place. The program should run in O\(1\) space complexity and O\(nodes\) time complexity. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Given 1->2->3->4->5->NULL, 15 | return 1->3->5->2->4->NULL. 16 | ``` 17 | 18 | **Note:** 19 | 20 | The relative order inside both the even and odd groups should remain as it was in the input. 21 | 22 | The first node is considered odd, the second node even and so on ... 23 | 24 | ## Thought Process {#thought-process} 25 | 26 | 1. Two pointers 27 | 1. Time complexity O\(n\) 28 | 2. Space complexity O\(1\) 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public ListNode oddEvenList(ListNode head) { 35 | if (head == null) return null; 36 | ListNode odd = head, even = head.next, evenHead = even; 37 | while (even != null && even.next != null) { 38 | odd.next = even.next; 39 | odd = odd.next; 40 | even.next = odd.next; 41 | even = even.next; 42 | } 43 | odd.next = evenHead; 44 | return head; 45 | } 46 | } 47 | ``` 48 | 49 | ## Additional {#additional} 50 | 51 | -------------------------------------------------------------------------------- /leetcode/linked-list/445-add-two-numbers-ii.md: -------------------------------------------------------------------------------- 1 | # 445-add-two-numbers-ii 2 | 3 | ## Question {#question} 4 | 5 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 6 | 7 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 8 | 9 | **Follow up:** 10 | What if you cannot modify the input lists? In other words, reversing the lists is not allowed. 11 | 12 | **Example:** 13 | 14 | ```text 15 | Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 16 | Output: 7 -> 8 -> 0 -> 7 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Reverse and Add 22 | 1. Time complexity O\(n\) 23 | 2. Space complexity O\(1\) 24 | 2. Stack 25 | 1. By adding the val to the stack, we get the values in reverse, which means we create the tail first and then adding the head one by one 26 | 2. Time complexity O\(n\) 27 | 3. Space complexity O\(n\) 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 34 | Stack stack1 = getVal(l1); 35 | Stack stack2 = getVal(l2); 36 | ListNode cur = new ListNode(0); 37 | int sum = 0; 38 | while (!stack1.isEmpty() || !stack2.isEmpty()) { 39 | if (!stack1.isEmpty()) sum += stack1.pop(); 40 | if (!stack2.isEmpty()) sum += stack2.pop(); 41 | cur.val = sum % 10; 42 | sum /= 10; //carry 43 | ListNode head = new ListNode(sum); 44 | head.next = cur; 45 | cur = head; 46 | } 47 | return cur.val == 0 ? cur.next : cur; 48 | } 49 | 50 | private Stack getVal(ListNode l) { 51 | Stack stack = new Stack<>(); 52 | while (l != null) { 53 | stack.push(l.val); 54 | l = l.next; 55 | } 56 | return stack; 57 | } 58 | } 59 | ``` 60 | 61 | ## Additional {#additional} 62 | 63 | -------------------------------------------------------------------------------- /leetcode/linked-list/README.md: -------------------------------------------------------------------------------- 1 | # linked-list 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/math/007-reverse-integer.md: -------------------------------------------------------------------------------- 1 | # 007-reverse-integer 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reverse-integer/description/](https://leetcode.com/problems/reverse-integer/description/) 6 | 7 | Given a 32-bit signed integer, reverse digits of an integer. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Input: 123 13 | Output: 321 14 | 15 | Input: -123 16 | Output: -321 17 | 18 | Input: 120 19 | Output: 21 20 | ``` 21 | 22 | ## Thought Process {#thought-process} 23 | 24 | 1. Reverse digit by digit 25 | 1. Check for potential overflow as we obtain the result 26 | 2. Time complexity O\(d\), where d is number of digits 27 | 3. Space complexity O\(1\) 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public int reverse(int x) { 34 | long res = 0; 35 | while(x != 0){ 36 | res = res * 10 + x % 10; 37 | if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0; 38 | x /= 10; 39 | } 40 | return (int) res; 41 | } 42 | } 43 | ``` 44 | 45 | ```java 46 | class Solution { 47 | public int reverse(int x) { 48 | int res = 0; 49 | while(x != 0){ 50 | int tmp = res * 10 + x % 10; 51 | if (tmp / 10 != res) return 0; 52 | res = tmp; 53 | x /= 10; 54 | } 55 | return res; 56 | } 57 | } 58 | ``` 59 | 60 | ## Additional {#additional} 61 | 62 | -------------------------------------------------------------------------------- /leetcode/math/009-palindrome-number.md: -------------------------------------------------------------------------------- 1 | # 009-palindrome-number 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/palindrome-number/description/](https://leetcode.com/problems/palindrome-number/description/) 6 | 7 | Determine whether an integer is a palindrome. Do this without extra space. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Revert Half 18 | 1. Create the reverse of right half of the number 19 | 2. Check the equivalence of x and its reverse or x and its reverse / 10 20 | 3. Time complexity O\(log n\) 21 | 4. Space complexity O\(1\) 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public boolean isPalindrome(int x) { 28 | if(x < 0 || (x != 0 && x % 10 == 0)) return false; 29 | int rev = 0; 30 | while (x > rev) { 31 | rev = rev * 10 + x % 10; 32 | x /= 10; 33 | } 34 | return x == rev || x == rev / 10; 35 | } 36 | } 37 | ``` 38 | 39 | ## Additional {#additional} 40 | 41 | -------------------------------------------------------------------------------- /leetcode/math/029-divide-two-integers.md: -------------------------------------------------------------------------------- 1 | # 029-divide-two-integers 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/divide-two-integers/description/](https://leetcode.com/problems/divide-two-integers/description/) 6 | 7 | Divide two integers without using multiplication, division and mod operator. 8 | 9 | If it is overflow, return MAX\_INT. 10 | 11 | **Example:** 12 | 13 | ```text 14 | 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Convert to Long 20 | 1. Use two variables to check the accumulative sum and multiplier 21 | 2. While the dividend is still greater than divisor, we can increase out count 22 | 3. We can speed up the count by multiplying by 2 using right shift 23 | 4. Time complexity O\(log n\) 24 | 5. Space complexity O\(1\) 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | public int divide(int dividend, int divisor) { 31 | if (divisor == 1) return dividend; 32 | if (divisor == -1) { 33 | return dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : -dividend; 34 | } 35 | int ret = 0; 36 | boolean isNegative = (dividend < 0) ^ (divisor < 0) ? true : false; 37 | long ldividend = Math.abs((long) dividend); 38 | long ldivisor = Math.abs((long) divisor); 39 | while (ldividend >= ldivisor) { 40 | long multiple = 1, accum = ldivisor; 41 | while (ldividend >= (accum << 1)) { 42 | accum <<= 1; 43 | multiple <<= 1; 44 | } 45 | ret += multiple; 46 | ldividend -= accum; 47 | } 48 | return isNegative ? -ret : ret; 49 | } 50 | } 51 | ``` 52 | 53 | ## Additional {#additional} 54 | 55 | -------------------------------------------------------------------------------- /leetcode/math/043-multiply-strings.md: -------------------------------------------------------------------------------- 1 | # 043-multiply-strings 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/multiply-strings/description/](https://leetcode.com/problems/multiply-strings/description/) 6 | 7 | Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. 8 | 9 | **Note:** 10 | 11 | 1. The length of both num1 and num2 is < 110. 12 | 2. Both num1 and num2 contains only digits 0-9. 13 | 3. Both num1 and num2 does not contain any leading zero. 14 | 4. You must not use any built-in BigInteger library or convert the inputs to integer directly. 15 | 16 | **Example:** 17 | 18 | ```text 19 | 20 | ``` 21 | 22 | ## Thought Process {#thought-process} 23 | 24 | 1. Multiply from Back 25 | 1. Start the multiplication from the back, each time we will have at most 2 digits 26 | 2. We need 27 | 28 | ## Solution 29 | 30 | ```java 31 | class Solution { 32 | public String multiply(String num1, String num2) { 33 | if (num1.equals("0") || num2.equals("0")) return "0"; 34 | int m = num1.length(), n = num2.length(); 35 | int[] pos = new int[m + n]; 36 | char[] n1 = num1.toCharArray(), n2 = num2.toCharArray(); 37 | for (int i = m - 1; i >= 0; i--){ 38 | for (int j = n - 1; j >= 0; j--){ 39 | int mul = (n1[i] - '0') * (n2[j] - '0'); 40 | int p1 = i + j, p2 = i + j + 1; 41 | int sum = mul + pos[p2]; 42 | pos[p1] += sum /10; 43 | pos[p2] = sum % 10; 44 | } 45 | } 46 | StringBuilder sb = new StringBuilder(); 47 | int i = 0; 48 | while (pos[i] == 0) i++; 49 | while (i < pos.length) sb.append(pos[i++]); 50 | return sb.toString(); 51 | } 52 | } 53 | ``` 54 | 55 | ## Additional {#additional} 56 | 57 | -------------------------------------------------------------------------------- /leetcode/math/050-powx-n.md: -------------------------------------------------------------------------------- 1 | # 050-powx-n 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/powx-n/description/](https://leetcode.com/problems/powx-n/description/) 6 | 7 | Implement pow\(x, n\). 8 | 9 | **Example:** 10 | 11 | ```text 12 | Input: 2.00000, 10 13 | Output: 1024.00000 14 | ``` 15 | 16 | ```text 17 | Input: 2.10000, 3 18 | Output: 9.26100 19 | ``` 20 | 21 | ## Thought Process {#thought-process} 22 | 23 | 1. Recurision 24 | 1. We can multiply the x by itself and reduce the power by 2 25 | 2. If the power is odd we need to multiply by the result of x \* x and n / 2 power by x 26 | 3. Time complexity O\(log n\) 27 | 4. Space complexity O\(log n\) due to recursion stack 28 | 2. Iterative 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public double myPow(double x, int n) { 35 | if (n == 0) return 1; 36 | if (n == Integer.MIN_VALUE) { 37 | x *= x; 38 | n /= 2; 39 | } 40 | if (n < 0) { 41 | x = 1/ x; 42 | n = -n; 43 | } 44 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 45 | } 46 | } 47 | ``` 48 | 49 | ```java 50 | class Solution { 51 | public double myPow(double x, int n) { 52 | if (x == 0) return 0; 53 | if (n == 0) return 1; 54 | if (n == Integer.MIN_VALUE) { 55 | x *= x; 56 | n /= 2; 57 | } 58 | if (n < 0) { 59 | x = 1/ x; 60 | n = -n; 61 | } 62 | double res = 1; 63 | while (n > 0) { 64 | if ((n & 1) == 1) res *= x; 65 | x *= x; 66 | n /= 2; 67 | } 68 | return res; 69 | } 70 | } 71 | ``` 72 | 73 | ## Additional {#additional} 74 | 75 | -------------------------------------------------------------------------------- /leetcode/math/060-permutation-sequence.md: -------------------------------------------------------------------------------- 1 | # 060-permutation-sequence 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/permutation-sequence/description/](https://leetcode.com/problems/permutation-sequence/description/) 6 | 7 | The set \[1,2,3,…,n\] contains a total of n! unique permutations. 8 | 9 | By listing and labeling all of the permutations in order, 10 | 11 | We get the following sequence \(ie, for n = 3\): 12 | 13 | 1. "123" 14 | 2. "132" 15 | 3. "213" 16 | 4. "231" 17 | 5. "312" 18 | 6. "321" 19 | 20 | Given n and k, return the kth permutation sequence. 21 | 22 | **Note:** Given n will be between 1 and 9 inclusive. 23 | 24 | **Example:** 25 | 26 | ```text 27 | 28 | ``` 29 | 30 | ## Thought Process {#thought-process} 31 | 32 | 1. Find Pattern 33 | 1. The number of permutation is n! 34 | 2. Each digit of the permutation can be determined by the k, using the formula k / \(n - 1\) 35 | 3. As we find out the number we want, \(technically index in this case\), we remove the number from the list 36 | 4. The k need to be mod as well to find the new relative position without each group 37 | 5. Time complexity O\(n^2\) 38 | 6. Space complexity O\(n\) 39 | 40 | ## Solution 41 | 42 | ```java 43 | class Solution { 44 | public String getPermutation(int n, int k) { 45 | /* 1 2 3 4 2 1 3 4 3 1 2 4 4 1 2 3 46 | 1 2 4 3 2 1 4 3 3 1 4 2 4 1 3 2 47 | 1 3 2 4 2 3 1 4 3 2 1 4 4 2 1 3 48 | 1 3 4 2 2 3 4 1 3 2 4 1 4 2 3 1 49 | 1 4 2 3 2 4 1 3 3 4 1 2 4 3 1 2 50 | 1 4 3 2 2 4 3 1 3 4 2 1 4 3 2 1*/ 51 | int weight = 1; 52 | List nums = new LinkedList<>(); 53 | StringBuilder sb = new StringBuilder(); 54 | for (int i = 1; i <= n; i++) { 55 | nums.add(i); 56 | weight *= i; 57 | } 58 | k--; 59 | for (int i = n; i > 0; i--) { 60 | weight /= i; 61 | int id = k / weight; 62 | sb.append(nums.get(id)); 63 | nums.remove(id); 64 | k %= weight; 65 | } 66 | return sb.toString(); 67 | } 68 | } 69 | ``` 70 | 71 | ## Additional {#additional} 72 | 73 | -------------------------------------------------------------------------------- /leetcode/math/067-add-binary.md: -------------------------------------------------------------------------------- 1 | # 067-add-binary 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/add-binary/description/](https://leetcode.com/problems/add-binary/description/) 6 | 7 | Given two binary strings, return their sum \(also a binary string\). 8 | 9 | **Example:** 10 | 11 | ```text 12 | a = "11" 13 | b = "1" 14 | Return "100". 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Scan Backward 20 | 1. At the number from the back 21 | 2. When the character is the same, we simply append the carry and update the carry accordingly 22 | 3. When the character is different, we append the opposite of the carry 23 | 4. At the end, we reverse the string builder 24 | 25 | ## Solution 26 | 27 | ```java 28 | class Solution { 29 | public String addBinary(String a, String b) { 30 | int m = a.length() - 1, n = b.length() - 1; 31 | StringBuilder sb = new StringBuilder(); 32 | char prev = '0'; 33 | while(m >= 0 || n >= 0){ 34 | char c1 = m < 0 ? '0' : a.charAt(m); 35 | char c2 = n < 0 ? '0' :b.charAt(n); 36 | if(c1 == c2){ 37 | sb.append(prev); 38 | prev = c1; 39 | } else if (prev == '1'){ 40 | sb.append('0'); 41 | } else{ 42 | sb.append('1'); 43 | } 44 | m--; 45 | n--; 46 | } 47 | if(prev == '1') sb.append('1'); 48 | return sb.reverse().toString(); 49 | } 50 | } 51 | ``` 52 | 53 | ## Additional {#additional} 54 | 55 | -------------------------------------------------------------------------------- /leetcode/math/069-sqrtx.md: -------------------------------------------------------------------------------- 1 | # 069-sqrtx 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/sqrtx/description/](https://leetcode.com/problems/sqrtx/description/) 6 | 7 | Implement int sqrt\(int x\). 8 | 9 | Compute and return the square root of x. 10 | 11 | x is guaranteed to be a non-negative integer. 12 | 13 | **Example:** 14 | 15 | ```text 16 | Input: 4 17 | Output: 2 18 | ``` 19 | 20 | ```text 21 | Input: 8 22 | Output: 2 23 | Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated. 24 | ``` 25 | 26 | ## Thought Process {#thought-process} 27 | 28 | 1. Binary Search 29 | 1. Use lo and hi to track the possible range of root 30 | 2. We return right 31 | 3. Time complexity O\(log x\) 32 | 4. Space 33 | 2. Newton's method 34 | 1. We can guess a root and gradually refine the root until the new guessis very close to the previous guess 35 | 2. r1 = r - f\(r\) /f'\(r\) 36 | 3. f\(r\) = r^2 - x 37 | 4. f'\(r\) = 2r 38 | 5. r1 = r - \(r^2 - x\) / 2r = \(r + x/r\) /2 39 | 6. Time complexity ?? 40 | 7. Space complexity ??? 41 | 42 | ## Solution 43 | 44 | ```java 45 | class Solution { 46 | public int mySqrt(int x) { 47 | if (x == 0) return 0; 48 | int lo = 1, hi = x; 49 | while (lo <= hi) { 50 | int mi = lo + (hi - lo) / 2; 51 | if (mi == x / mi) return mi; 52 | else if (mi < x / mi) lo = mi + 1; 53 | else hi = mi - 1; 54 | } 55 | return hi; 56 | } 57 | } 58 | ``` 59 | 60 | ```java 61 | class Solution { 62 | public int mySqrt(int x) { 63 | long r = x; 64 | while (r * r > x) { 65 | r = (r + x / r) / 2; 66 | } 67 | return (int) r; 68 | } 69 | } 70 | ``` 71 | 72 | ## Additional 73 | 74 | -------------------------------------------------------------------------------- /leetcode/math/168-excel-sheet-column-title.md: -------------------------------------------------------------------------------- 1 | # 168-excel-sheet-column-title 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/excel-sheet-column-title/description/](https://leetcode.com/problems/excel-sheet-column-title/description/) 6 | 7 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 1 -> A 13 | 2 -> B 14 | 3 -> C 15 | ... 16 | 26 -> Z 17 | 27 -> AA 18 | 28 -> AB 19 | ``` 20 | 21 | ## Thought Process {#thought-process} 22 | 23 | 1. Mod 24 | 1. we need to use mod to get the correct character 25 | 2. Reverse the string at the end 26 | 3. Time complexity O\(log n\) 27 | 4. Space complexity O\(1\) 28 | 29 | ## Solution 30 | 31 | ```java 32 | class Solution { 33 | public String convertToTitle(int n) { 34 | StringBuilder sb = new StringBuilder(); 35 | while (n > 0){ 36 | n--; 37 | sb.append((char)('A' + n % 26)); 38 | n /= 26; 39 | } 40 | return sb.reverse().toString(); 41 | } 42 | } 43 | ``` 44 | 45 | ## Additional {#additional} 46 | 47 | -------------------------------------------------------------------------------- /leetcode/math/171-excel-sheet-column-number.md: -------------------------------------------------------------------------------- 1 | # 171-excel-sheet-column-number 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/excel-sheet-column-number/description/](https://leetcode.com/problems/excel-sheet-column-number/description/) 6 | 7 | Related to question [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) 8 | 9 | Given a column title as appear in an Excel sheet, return its corresponding column number. 10 | 11 | **Example:** 12 | 13 | ```text 14 | A -> 1 15 | B -> 2 16 | C -> 3 17 | ... 18 | Z -> 26 19 | AA -> 27 20 | AB -> 28 21 | ``` 22 | 23 | ## Thought Process {#thought-process} 24 | 25 | 1. Reverse of Mod 26 | 1. Just multiply and add 27 | 2. Time complexity O\(n\) 28 | 3. Space complexity O\(1\) 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public int titleToNumber(String s) { 35 | char[] chars = s.toCharArray(); 36 | int res = 0; 37 | for (int i = 0; i < chars.length; i++){ 38 | res = res * 26 + chars[i] - 'A' + 1; 39 | } 40 | return res; 41 | } 42 | } 43 | ``` 44 | 45 | ## Additional {#additional} 46 | 47 | -------------------------------------------------------------------------------- /leetcode/math/223-rectangle-area.md: -------------------------------------------------------------------------------- 1 | # 223-rectangle-area 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/rectangle-area/description/](https://leetcode.com/problems/rectangle-area/description/) 6 | 7 | Find the total area covered by two **rectilinear** rectangles in a **2D** plane. 8 | 9 | Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 10 | 11 | **Example:** 12 | 13 | ```text 14 | 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Check Overlap 20 | 1. If there is no overlap, we know the total area is the sum of areas 21 | 2. The overlap can be check if any of indices fall in the range of other, if any of the indices is outside of the range, there is no overlap 22 | 3. Time complexity O\(1\) 23 | 4. Space complexity O\(1\) 24 | 25 | ## Solution 26 | 27 | ```java 28 | class Solution { 29 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 30 | // if one side of one rectangle lies outside the boundary of the other, the overlap is 0. 31 | int overlap; 32 | if (C <= E || A >= G || B >= H || D <= F) { 33 | overlap = 0; 34 | } else { 35 | // the width is the the minimum of right boundary - minimum of left boundary 36 | int width = Math.min(C, G) - Math.max(A, E); 37 | // the height is the minimum of the top boundary - maximum of bottom boundary 38 | int height = Math.min(D, H) - Math.max(B, F); 39 | overlap = width * height; 40 | } 41 | return (C - A) * (D - B) + (G - E) * (H - F) - overlap; 42 | } 43 | } 44 | ``` 45 | 46 | ## Additional {#additional} 47 | 48 | -------------------------------------------------------------------------------- /leetcode/math/224-basic-calculator.md: -------------------------------------------------------------------------------- 1 | # 224-basic-calculator 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/basic-calculator/description/](https://leetcode.com/problems/basic-calculator/description/) 6 | 7 | Implement a basic calculator to evaluate a simple expression string. 8 | 9 | The expression string may contain open \( and closing parentheses \), the plus + or minus sign -, non-negative integers and empty spaces . 10 | 11 | You may assume that the given expression is always valid. 12 | 13 | **Example:** 14 | 15 | ```text 16 | "1 + 1" = 2 17 | " 2-1 + 2 " = 3 18 | "(1+(4+5+2)-3)+(6+8)" = 23 19 | ``` 20 | 21 | ## Thought Process {#thought-process} 22 | 23 | 1. Stack 24 | 1. Use variable to keep track of the number, using num = num \* 10 + curVal 25 | 2. When we see a operator, + and -, its time to evaluate previous expression, update the sign and reset num 26 | 3. We also need another variable, sign, to simply the formula 27 | 4. Time complexity O\(n\) 28 | 5. Space complexity O\(n\) 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public int calculate(String s) { 35 | char[] chars = s.toCharArray(); 36 | int result = 0, sign = 1, num = 0; 37 | Stack stack = new Stack<>(); 38 | stack.push(sign); 39 | for (int i = 0; i < chars.length; i++) { 40 | if (chars[i] >= '0' && chars[i] <= '9') { 41 | num = num * 10 + chars[i] - '0'; 42 | } else if (chars[i] == '+' || chars[i] == '-') { 43 | result += sign * num; 44 | sign = stack.peek() * (chars[i] == '+' ? 1 : -1); 45 | num = 0; 46 | } else if (chars[i] == '(') { 47 | stack.push(sign); 48 | } else if (chars[i] == ')') { 49 | stack.pop(); 50 | } 51 | } 52 | result += sign * num; 53 | return result; 54 | } 55 | } 56 | ``` 57 | 58 | ## Additional {#additional} 59 | 60 | -------------------------------------------------------------------------------- /leetcode/math/258-add-digits.md: -------------------------------------------------------------------------------- 1 | # 258-add-digits 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/add-digits/description/](https://leetcode.com/problems/add-digits/description/) 6 | 7 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Loop 18 | 1. While the num > 9, we compute 19 | 2. The computation simply add all the digt 20 | 3. Time complexity O\(d\) 21 | 4. Space complexity O\(1\) 22 | 2. Find pattern 23 | 1. If you observe the cycle repeats from 1 to 9 for range of 9, such as 1 to 9, 10 - 18, 19 to 27, and etc 24 | 2. Time complexity 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | public int addDigits(int num) { 31 | int tmp; 32 | while (num > 9) { 33 | tmp = 0; 34 | while (num > 0) { 35 | tmp += num % 10; 36 | num /= 10; 37 | } 38 | num = tmp; 39 | } 40 | return num; 41 | } 42 | } 43 | ``` 44 | 45 | ```java 46 | class Solution { 47 | public int addDigits(int num) { 48 | return 1 + (num - 1) % 9; 49 | } 50 | } 51 | ``` 52 | 53 | ## Additional {#additional} 54 | 55 | -------------------------------------------------------------------------------- /leetcode/math/263-ugly-number.md: -------------------------------------------------------------------------------- 1 | # 263-ugly-number 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/ugly-number/description/](https://leetcode.com/problems/ugly-number/description/) 6 | 7 | Write a program to check whether a given number is an ugly number. 8 | 9 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 10 | 11 | Note that 1 is typically treated as an ugly number. 12 | 13 | **Example:** 14 | 15 | ```text 16 | 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Divide All Factors 22 | 1. While we can divide an factor perfectly, we divide 23 | 2. At the end, we compare the final num to 1 24 | 25 | ## Solution 26 | 27 | ```java 28 | class Solution { 29 | public boolean isUgly(int num) { 30 | if (num <= 0) return false; 31 | while (num % 2 == 0) num /= 2; 32 | while (num % 3 == 0) num /= 3; 33 | while (num % 5 == 0) num /= 5; 34 | return num == 1; 35 | } 36 | } 37 | ``` 38 | 39 | ## Additional {#additional} 40 | 41 | -------------------------------------------------------------------------------- /leetcode/math/268-missing-number.md: -------------------------------------------------------------------------------- 1 | # 268-missing-number 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/missing-number/description/](https://leetcode.com/problems/missing-number/description/) 6 | 7 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Input: [3,0,1] 13 | Output: 2 14 | ``` 15 | 16 | ```text 17 | Input: [9,6,4,2,3,5,7,0,1] 18 | Output: 8 19 | ``` 20 | 21 | ## Thought Process {#thought-process} 22 | 23 | 1. Sort 24 | 1. Sort the array, if the number is not equal to i, we know this index is the missing number 25 | 2. Time complexity O\(n logn\) 26 | 3. Space complexity O\(1\) 27 | 2. Hash Set 28 | 1. We use hashset to store the number 29 | 2. Time complexity O\(n\) 30 | 3. Space complexity O\(n\) 31 | 3. XOR 32 | 1. We can leverage the fact that XOR of same number twice will 0 33 | 2. We XOR all the numbers and the index 34 | 3. The final result is the missing number 35 | 4. Time complexity O\(n\) 36 | 5. Space complexity O\(1\) 37 | 38 | ## Solution 39 | 40 | ```java 41 | class Solution { 42 | public int missingNumber(int[] nums) { 43 | Arrays.sort(nums); 44 | int n = nums.length; 45 | for (int i = 0; i < n; i++) { 46 | if (nums[i] != i) return i; 47 | } 48 | return n; 49 | } 50 | } 51 | ``` 52 | 53 | ```java 54 | class Solution { 55 | public int missingNumber(int[] nums) { 56 | Set set = new HashSet<>(); 57 | for (int num : nums) { 58 | set.add(num); 59 | } 60 | int n = nums.length; 61 | for (int i = 0; i < n; i++) { 62 | if (!set.contains(i)) return i; 63 | } 64 | return n; 65 | } 66 | } 67 | ``` 68 | 69 | ```java 70 | class Solution { 71 | public int missingNumber(int[] nums) { 72 | int res = nums.length; 73 | for (int i = 0; i < nums.length; i++) { 74 | res ^= i ^ nums[i]; 75 | } 76 | return res; 77 | } 78 | } 79 | ``` 80 | 81 | ## Additional {#additional} 82 | 83 | -------------------------------------------------------------------------------- /leetcode/math/313-super-ugly-number.md: -------------------------------------------------------------------------------- 1 | # 313-super-ugly-number 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/super-ugly-number/description/](https://leetcode.com/problems/super-ugly-number/description/) 6 | 7 | Write a program to find the nth super ugly number. 8 | 9 | Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. 10 | 11 | **Example:** 12 | 13 | ```text 14 | [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers 15 | Given primes = [2, 7, 13, 19] of size 4. 16 | ``` 17 | 18 | 1. 1 is a super ugly number for any given primes. 19 | 2. The given numbers in primes are in ascending order. 20 | 3. 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes\[i\] < 1000. 21 | 4. The nth super ugly number is guaranteed to fit in a 32-bit signed integer. 22 | 23 | ## Thought Process {#thought-process} 24 | 25 | 1. Array 26 | 1. Similar to [264-Ugly Number II](264-ugly-number-ii.md), we just have to loop through all the prime and update its id accordingly 27 | 2. Time complexity O\(np\) 28 | 3. Space complexity O\(n + p\) 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public int nthSuperUglyNumber(int n, int[] primes) { 35 | int[] ugly = new int[n]; 36 | int[] pid = new int[primes.length]; 37 | ugly[0] = 1; 38 | int nextUgly, id; 39 | for (int i = 1; i < n; i++) { 40 | nextUgly = Integer.MAX_VALUE; 41 | id = 0; 42 | for (int p = 0; p < pid.length; p++) { 43 | int possible = ugly[pid[p]] * primes[p]; 44 | if (possible < nextUgly) { 45 | nextUgly = possible; 46 | id = p; 47 | } else if (possible == nextUgly) { 48 | pid[p]++; 49 | } 50 | } 51 | ugly[i] = nextUgly; 52 | pid[id]++; 53 | } 54 | return ugly[n - 1]; 55 | } 56 | } 57 | ``` 58 | 59 | ## Additional {#additional} 60 | 61 | -------------------------------------------------------------------------------- /leetcode/math/319-bulb-switcher.md: -------------------------------------------------------------------------------- 1 | # 319-bulb-switcher 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/bulb-switcher/description/](https://leetcode.com/problems/bulb-switcher/description/) 6 | 7 | There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb \(turning on if it's off or turning off if it's on\). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds. 8 | 9 | **Example:** 10 | 11 | ```text 12 | 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Perfect Square 18 | 1. Observe that only perfect square will be switched odd number of times, resulting "on" status 19 | 2. Total number of time will be the sqrt of input 20 | 3. Time complexity O\(1\) 21 | 4. Space complexity O\(1\) 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public int bulbSwitch(int n) { 28 | return (int) Math.sqrt(n); 29 | } 30 | } 31 | ``` 32 | 33 | ## Additional {#additional} 34 | 35 | -------------------------------------------------------------------------------- /leetcode/math/343-integer-break.md: -------------------------------------------------------------------------------- 1 | # 343-integer-break 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/integer-break/description/](https://leetcode.com/problems/integer-break/description/) 6 | 7 | Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. 8 | 9 | For example, given n = 2, return 1 \(2 = 1 + 1\); given n = 10, return 36 \(10 = 3 + 3 + 4\). 10 | 11 | **Note:** You may assume that n is not less than 2 and not larger than 58. 12 | 13 | **Example:** 14 | 15 | ```text 16 | 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Observe Pattern 22 | 1. n = 1 2 3 4 5 6 7 8 9 10 23 | 2. s = 0 1 2 4 6 9 12 18 27 36 24 | 3. Starting from 7, the number repeat as multiple of 3 of num\[i - 3\] 25 | 4. Time complexity O\(n\) 26 | 5. Space complexity O\(1\) 27 | 2. Math 28 | 1. We can use the built-in pow function to return result directly 29 | 2. Time complexity O\(1\)??? 30 | 3. Space complexity O\(1\) 31 | 32 | ## Solution 33 | 34 | ```java 35 | class Solution { 36 | public int integerBreak(int n) { 37 | if (n < 4) return n - 1; 38 | int res = 1; 39 | while (n > 4) { 40 | res *= 3; 41 | n -= 3; 42 | } 43 | res *= n; 44 | return res; 45 | } 46 | } 47 | ``` 48 | 49 | ```java 50 | class Solution { 51 | public int integerBreak(int n) { 52 | if (n < 4) return n - 1; 53 | int cof = 1, p = (n + 1) / 3 - 1; 54 | if (n % 3 == 1) cof = 4; 55 | else if (n % 3 == 2) cof = 2; 56 | else cof = 3; 57 | return cof * (int) Math.pow(3, p); 58 | } 59 | } 60 | ``` 61 | 62 | ## Additional {#additional} 63 | 64 | -------------------------------------------------------------------------------- /leetcode/math/357-count-numbers-with-unique-digits.md: -------------------------------------------------------------------------------- 1 | # 357-count-numbers-with-unique-digits 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/count-numbers-with-unique-digits/description/](https://leetcode.com/problems/count-numbers-with-unique-digits/description/) 6 | 7 | Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given n = 2, return 91. 13 | (The answer should be the total numbers in the range of 0 ≤ x < 100, 14 | excluding [11,22,33,44,55,66,77,88,99]) 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. DP 20 | 1. Start from n = 1, we have 10 choices 21 | 2. For n = 2, we can only have 9 choice for the first digit \(excluding 0\), and 9 choices for the second digit \(avoiding the same number\), 9 \* 9 unique 2 digits number in additional to the 10 before 22 | 3. For n = 3, we have 9, 9, and 8 choice for each digit, 9 \*9 \* 8 in additional to 91 before 23 | 4. Time complexity O\(n\) or O\(10\) at most 24 | 5. Space complexity O\(1\) 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | public int countNumbersWithUniqueDigits(int n) { 31 | int res = 1; 32 | int choice = 9, available = 9; 33 | while (n-- >= 1 && available > 0) { 34 | res += choice; 35 | choice *= available; 36 | available--; 37 | } 38 | return res; 39 | } 40 | } 41 | ``` 42 | 43 | ## Additional {#additional} 44 | 45 | -------------------------------------------------------------------------------- /leetcode/math/365-water-and-jug-problem.md: -------------------------------------------------------------------------------- 1 | # 365-water-and-jug-problem 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/water-and-jug-problem/description/](https://leetcode.com/problems/water-and-jug-problem/description/) 6 | 7 | You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactlyzlitres using these two jugs. 8 | 9 | If z liters of water is measurable, you must havezliters of water contained within **one or both buckets** by the end. 10 | 11 | Operations allowed: 12 | 13 | * Fill any of the jugs completely with water. 14 | * Empty any of the jugs. 15 | * Pour water from one jug into another till the other jug is completely full or the first jug itself is empty. 16 | 17 | **Example:** 18 | 19 | ```text 20 | Input: x = 3, y = 5, z = 4 21 | Output: True 22 | ``` 23 | 24 | ```text 25 | Input: x = 2, y = 6, z = 5 26 | Output: False 27 | ``` 28 | 29 | ## Thought Process {#thought-process} 30 | 31 | 1. GCD 32 | 1. We can eliminate the z volume that is greater than x + y 33 | 2. We can return true for z = x or y, or z = x + y 34 | 3. The problem can be summarized as ax + by = z, where positive a and b means filling jugs a or b times, negative a and b means emptying 35 | 4. This can be solved by \[Bézout’s identity\]\([https://en.wikipedia.org/wiki/Bézout's\_identity](https://en.wikipedia.org/wiki/Bézout's_identity)\), where we check z is multiple of GCD\(x, y\) 36 | 37 | ## Solution 38 | 39 | ```java 40 | class Solution { 41 | public boolean canMeasureWater(int x, int y, int z) { 42 | if (x + y < z) return false; 43 | if (x == z || y == z || (x + y) == z) return true; 44 | return z % GCD(x, y) == 0; 45 | } 46 | 47 | private int GCD(int x, int y) { 48 | int tmp; 49 | while (y != 0) { 50 | tmp = y; 51 | y = x % y; 52 | x = tmp; 53 | } 54 | return x; 55 | } 56 | 57 | private int GCD2(int x, int y) { 58 | if (y == 0) return x; 59 | return GCD(y, x % y); 60 | } 61 | } 62 | ``` 63 | 64 | ## Additional {#additional} 65 | 66 | -------------------------------------------------------------------------------- /leetcode/math/367-valid-perfect-square.md: -------------------------------------------------------------------------------- 1 | # 367-valid-perfect-square 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/valid-perfect-square/description/](https://leetcode.com/problems/valid-perfect-square/description/) 6 | 7 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Input: 16 13 | Returns: True 14 | 15 | Input: 14 16 | Returns: False 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Binary Search 22 | 1. We choose the mid and adjust low and high accordingly 23 | 2. Time complexity O\(log n\) 24 | 3. Space complexity O\(1\) 25 | 2. Newton's Method 26 | 1. We can refer to [Newton Method](https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division), where we want to solve x^2 - n = 0 27 | 2. $$x_1 = x_0 - f(x_0)/f'(x_0)$$ 28 | 3. $$x_1 = (x_0 + n / x_0) / 2$$ 29 | 4. Time complexity O\(log n\) 30 | 5. Space complexity O\(1\) 31 | 32 | ## Solution 33 | 34 | ```java 35 | class Solution { 36 | public boolean isPerfectSquare(int num) { 37 | long lo = 1, hi = num; 38 | while (lo <= hi) { 39 | long mi = lo + (hi - lo) / 2; 40 | if (mi * mi == num) return true; 41 | else if (mi * mi < num) lo = mi + 1; 42 | else hi = mi - 1; 43 | } 44 | return false; 45 | } 46 | } 47 | ``` 48 | 49 | ```java 50 | class Solution { 51 | public boolean isPerfectSquare(int num) { 52 | long x = num; 53 | while (x * x > num) { 54 | x = (x + num / x) / 2; 55 | } 56 | return x * x == num; 57 | } 58 | } 59 | ``` 60 | 61 | ## Additional {#additional} 62 | 63 | -------------------------------------------------------------------------------- /leetcode/math/368-largest-divisible-subset.md: -------------------------------------------------------------------------------- 1 | # 368-largest-divisible-subset 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/largest-divisible-subset/description/](https://leetcode.com/problems/largest-divisible-subset/description/) 6 | 7 | Given a set of distinct positive integers, find the largest subset such that every pair \(Si, Sj\) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. 8 | 9 | If there are multiple solutions, return any subset is fine. 10 | 11 | **Example:** 12 | 13 | ```text 14 | nums: [1,2,3] 15 | 16 | Result: [1,2] (of course, [1,3] will also be ok) 17 | ``` 18 | 19 | ```text 20 | nums: [1,2,4,8] 21 | 22 | Result: [1,2,4,8] 23 | ``` 24 | 25 | ## Thought Process {#thought-process} 26 | 27 | 1. Parent Array and Count Array 28 | 1. Use parent array to keep track of each number's parent, and count array to keep track of the length of sequence ending on current number 29 | 2. Time complexity O\(n^2\) 30 | 3. Space complexity O\(n\) 31 | 32 | ## Solution 33 | 34 | ```java 35 | class Solution { 36 | public List largestDivisibleSubset(int[] nums) { 37 | Arrays.sort(nums); 38 | int n = nums.length; 39 | int[] count = new int[n], pre = new int[n]; 40 | int max = 0, index = -1; 41 | for (int i = 0; i < n; i++) { 42 | count[i] = 1; 43 | pre[i] = -1; 44 | for (int j = i - 1; j >= 0; j--) { 45 | if (nums[i] % nums[j] == 0 && 1 + count[j] > count[i]) { 46 | count[i] = count[j] + 1; 47 | pre[i] = j; 48 | } 49 | } 50 | if (count[i] > max) { 51 | max = count[i]; 52 | index = i; 53 | } 54 | } 55 | LinkedList list = new LinkedList<>(); 56 | while (index != -1) { 57 | list.addFirst(nums[index]); 58 | index = pre[index]; 59 | } 60 | return list; 61 | } 62 | } 63 | ``` 64 | 65 | ## Additional {#additional} 66 | 67 | -------------------------------------------------------------------------------- /leetcode/math/396-rotate-function.md: -------------------------------------------------------------------------------- 1 | # 396-rotate-function 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/rotate-function/description/](https://leetcode.com/problems/rotate-function/description/) 6 | 7 | Given an array of integers A and let n to be its length. 8 | 9 | Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow: 10 | 11 | F\(k\) = 0 \* Bk\[0\] + 1 \* Bk\[1\] + ... + \(n-1\) \* Bk\[n-1\]. 12 | 13 | Calculate the maximum value of F\(0\), F\(1\), ..., F\(n-1\). 14 | 15 | **Example:** 16 | 17 | ```text 18 | A = [4, 3, 2, 6] 19 | 20 | F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 21 | F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 22 | F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 23 | F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 24 | 25 | So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. 26 | ``` 27 | 28 | ## Thought Process {#thought-process} 29 | 30 | 1. Math 31 | 1. As we rotate the number clockwise, the value is increased by sum - the length \* preLastNum 32 | 2. We start from the back, since every rotation will move the last element to the first 33 | 3. Time complexity O\(n\) 34 | 4. Space complexity O\(1\) 35 | 36 | ## Solution 37 | 38 | ```java 39 | class Solution { 40 | public int maxRotateFunction(int[] A) { 41 | // F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1] 42 | // F(k+1) = 0 * Bk+1[0] + 1 * Bk+1[1] + ... + (n-1) * Bk+1[n-1] 43 | // = 0 * Bk[n - 1] + 1 * Bk[0] + ... + (n -1) * Bk[n-2] 44 | // F(k+1) - F(k) = Bk[0] + Bk[1] + .. Bk[n -2] - (n-1) * Bk[n-1] 45 | // = sum(0 to n - 1) - n * Bk[n - 1] 46 | int sum = 0, F = 0, n = A.length; 47 | for (int i = 0; i < n; i++) { 48 | sum += A[i]; 49 | F += i * A[i]; 50 | } 51 | int max = F; 52 | for (int i = n - 1; i > 0; i--) { 53 | F = F + sum - n * A[i]; 54 | max = Math.max(max, F); 55 | } 56 | return max; 57 | } 58 | } 59 | ``` 60 | 61 | ## Additional {#additional} 62 | 63 | -------------------------------------------------------------------------------- /leetcode/math/397-integer-replacement.md: -------------------------------------------------------------------------------- 1 | # 397-integer-replacement 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/integer-replacement/description/](https://leetcode.com/problems/integer-replacement/description/) 6 | 7 | Given a positive integer n and you can do operations as follow: 8 | 9 | 1. If n is even, replace n with n/2. 10 | 2. If n is odd, you can replace n with either n + 1 or n - 1. 11 | 12 | What is the minimum number of replacements needed for n to become 1? 13 | 14 | **Example:** 15 | 16 | ```text 17 | Input: 18 | 8 19 | 20 | Output: 21 | 3 22 | 23 | Explanation: 24 | 8 -> 4 -> 2 -> 1 25 | ``` 26 | 27 | ```text 28 | Input: 29 | 7 30 | 31 | Output: 32 | 4 33 | 34 | Explanation: 35 | 7 -> 8 -> 4 -> 2 -> 1 36 | or 37 | 7 -> 6 -> 3 -> 2 -> 1 38 | ``` 39 | 40 | ## Thought Process {#thought-process} 41 | 42 | 1. Pattern Finding 43 | 1. Three cases 44 | 1. If n is even, we just follow the rule 45 | 2. If n is odd we need to look at the second last digit, if it is 1, adding 1 will be able to remove two 1s, otherwise we can just decrement it 46 | 3. One exception is 3, which we should decrement by 1 47 | 2. Time complexity O\(log n\) 48 | 3. Space complexity O\(1\) 49 | 50 | ## Solution 51 | 52 | ```java 53 | class Solution { 54 | public int integerReplacement(int n) { 55 | int count = 0; 56 | while (n != 1) { 57 | count++; 58 | if (n % 2 == 0) n >>>= 1; 59 | else if (n == 3 || ((n >>> 1) & 1) == 0) n -= 1; 60 | else n += 1; 61 | } 62 | return count; 63 | } 64 | } 65 | ``` 66 | 67 | ## Additional {#additional} 68 | 69 | -------------------------------------------------------------------------------- /leetcode/math/400-nth-digit.md: -------------------------------------------------------------------------------- 1 | # 400-nth-digit 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/nth-digit/description/](https://leetcode.com/problems/nth-digit/description/) 6 | 7 | Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 8 | 9 | **Example:** 10 | 11 | ```text 12 | Input: 13 | 3 14 | 15 | Output: 16 | 3 17 | ``` 18 | 19 | ```text 20 | Input: 21 | 11 22 | 23 | Output: 24 | 0 25 | 26 | Explanation: 27 | The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. 28 | ``` 29 | 30 | ## Thought Process {#thought-process} 31 | 32 | 1. Math 33 | 1. The problem can be break down into different group based on the digits, 1 - 9, 10 - 99, where the count is 9, 90, and etc 34 | 2. Time complexity O\(log n\) 35 | 3. Space complexity O\(1\) 36 | 37 | ## Solution 38 | 39 | ```java 40 | class Solution { 41 | public int findNthDigit(int n) { 42 | int len = 1; 43 | long count = 9; 44 | int start = 1; 45 | while (n > len * count) { 46 | n -= len * count; 47 | count *= 10; 48 | start *= 10; 49 | len++; 50 | } 51 | start += (n - 1) / len; 52 | return Integer.toString(start).charAt((n - 1) % len) - '0'; 53 | } 54 | } 55 | ``` 56 | 57 | ## Additional {#additional} 58 | 59 | -------------------------------------------------------------------------------- /leetcode/math/README.md: -------------------------------------------------------------------------------- 1 | # math 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/string/006-zigzag-conversion.md: -------------------------------------------------------------------------------- 1 | # 006-zigzag-conversion 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/zigzag-conversion/description/](https://leetcode.com/problems/zigzag-conversion/description/) 6 | 7 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: \(you may want to display this pattern in a fixed font for better legibility\) 8 | 9 | **Example:** 10 | 11 | ```text 12 | P A H N 13 | A P L S I I G 14 | Y I R 15 | 16 | And then read line by line: "PAHNAPLSIIGYIR" 17 | ``` 18 | 19 | Write the code that will take a string and make this conversion given a number of rows: 20 | 21 | convert\("PAYPALISHIRING", 3\) should return "PAHNAPLSIIGYIR". 22 | 23 | ## Thought Process {#thought-process} 24 | 25 | 1. Magic Number 26 | 1. The first row and last row always insert next 2 \* num - 2th position, or referred as num in the code \(excluding the character in the middle\) 27 | 2. In the middle, we increase the next position by alternating between diff and num - diff 28 | 3. Time complexity O\(n\) 29 | 4. Space complexity O\(n\) 30 | 31 | ## Solution 32 | 33 | ```java 34 | class Solution { 35 | public String convert(String s, int numRows) { 36 | if(numRows==1) return s; 37 | char[] chars = s.toCharArray(); 38 | int n = chars.length; 39 | StringBuilder sb = new StringBuilder(); 40 | int num = numRows * 2 - 2; 41 | for(int i = 0; i < numRows; i++){ 42 | int j = i; 43 | int diff = i * 2; 44 | while(j < n){ 45 | sb.append(chars[j]); 46 | diff = (diff == num) ? num : num - diff; 47 | j += diff; 48 | } 49 | } 50 | return sb.toString(); 51 | } 52 | } 53 | ``` 54 | 55 | ## Additional {#additional} 56 | 57 | -------------------------------------------------------------------------------- /leetcode/string/017-letter-combinations-of-a-phone-number.md: -------------------------------------------------------------------------------- 1 | # 017-letter-combinations-of-a-phone-number 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/](https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/) 6 | 7 | Given a digit string, return all possible letter combinations that the number could represent. 8 | 9 | A mapping of digit to letters \(just like on the telephone buttons\) is given below. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Input:Digit string "23" 15 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 16 | ``` 17 | 18 | ## Thought Process {#thought-process} 19 | 20 | 1. Permutation 21 | 1. 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public List letterCombinations(String digits) { 28 | LinkedList result = new LinkedList(); 29 | if (digits == null || digits.length() == 0) return result; 30 | String[] map = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 31 | result.add(""); 32 | result.add(""); 33 | char[] chars = digits.toCharArray(); 34 | for (int i = 0; i < chars.length; i++) { 35 | while (result.peek().length() == i) { 36 | String top = result.poll(); 37 | String letters = map[chars[i] - '0']; 38 | for (char c : letters.toCharArray()) { 39 | result.add(top + c); 40 | } 41 | } 42 | } 43 | return result; 44 | } 45 | } 46 | ``` 47 | 48 | ## Additional {#additional} 49 | 50 | -------------------------------------------------------------------------------- /leetcode/string/020-valid-parentheses.md: -------------------------------------------------------------------------------- 1 | # 020-valid-parentheses 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/valid-parentheses/description/](https://leetcode.com/problems/valid-parentheses/description/) 6 | 7 | Given a string containing just the characters '\(', '\)', '{', '}', '\[' and '\]', determine if the input string is valid. 8 | 9 | The brackets must close in the correct order, "\(\)" and "\(\)\[\]{}" are all valid but "\(\]" and "\(\[\)\]" are not. 10 | 11 | **Example:** 12 | 13 | ```text 14 | 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. AAAAAA 20 | 21 | ## Solution 22 | 23 | ```java 24 | 25 | ``` 26 | 27 | ## Additional {#additional} 28 | 29 | -------------------------------------------------------------------------------- /leetcode/string/022-generate-parentheses.md: -------------------------------------------------------------------------------- 1 | # 022-generate-parentheses 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/generate-parentheses/description/](https://leetcode.com/problems/generate-parentheses/description/) 6 | 7 | Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses. 8 | 9 | For example, givenn= 3, a solution set is: 10 | 11 | **Example:** 12 | 13 | ```text 14 | [ 15 | "((()))", 16 | "(()())", 17 | "(())()", 18 | "()(())", 19 | "()()()" 20 | ] 21 | ``` 22 | 23 | ## Thought Process {#thought-process} 24 | 25 | 1. Backtrack 26 | 1. Use two variable to keep track left bracket and right bracket, open and close 27 | 2. Increase the count until we open + close == 2 \* n 28 | 3. As long we have more room to add left, we add left bracket first 29 | 4. And then we add right bracket when right bracket usage is less than the left 30 | 5. Time complexity O\(4^n/sqrt\(n\)\) 31 | 6. Space complexity O\(4^n/sqrt\(n\)\) 32 | 33 | ## Solution 34 | 35 | ```java 36 | class Solution { 37 | public List generateParenthesis(int n) { 38 | List result = new ArrayList<>(); 39 | char[] chars = new char[n * 2]; 40 | backtrack(result, chars, 0, 0); 41 | return result; 42 | } 43 | 44 | public void backtrack(List result, char[] chars, int open, int close) { 45 | if (open + close == chars.length) { 46 | result.add(new String(chars)); 47 | return; 48 | } 49 | if (open < chars.length / 2) { 50 | chars[open + close] = '('; 51 | backtrack(result, chars, open + 1, close); 52 | } 53 | if (close < open) { 54 | chars[open + close] = ')'; 55 | backtrack(result, chars, open, close + 1); 56 | } 57 | } 58 | } 59 | ``` 60 | 61 | ## Additional {#additional} 62 | 63 | -------------------------------------------------------------------------------- /leetcode/string/038-count-and-say.md: -------------------------------------------------------------------------------- 1 | # 038-count-and-say 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/count-and-say/description/](https://leetcode.com/problems/count-and-say/description/) 6 | 7 | The count-and-say sequence is the sequence of integers with the first five terms as following: 8 | 9 | ```text 10 | 1. 1 11 | 2. 11 12 | 3. 21 13 | 4. 1211 14 | 5. 111221 15 | ``` 16 | 17 | 1 is read off as "one 1" or 11. 18 | 19 | 11 is read off as "two 1s" or 21. 20 | 21 | 21 is read off as "one 2, then one 1" or 1211. 22 | 23 | **Example:** 24 | 25 | ## Thought Process {#thought-process} 26 | 27 | 1. Recursion 28 | 1. Get the previous string and then start count and append 29 | 2. Time complexity ?????? 30 | 3. Space complexity O\(n\) due to recursion stack and O\(n\) ??? for storage 31 | 2. Iterative 32 | 1. We can also write iterative approach 33 | 34 | ## Solution 35 | 36 | ```java 37 | class Solution { 38 | public String countAndSay(int n) { 39 | if(n <= 1) return "1"; 40 | String prev = countAndSay(n -1); 41 | StringBuilder sb = new StringBuilder(); 42 | char[] chars = prev.toCharArray(); 43 | char prevC = chars[0]; 44 | int count = 1; 45 | for(int i = 1; i < chars.length; i++){ 46 | if (chars[i] == prevC){ 47 | count++; 48 | } else{ 49 | sb.append(count).append(prevC); 50 | prevC = chars[i]; 51 | count = 1; 52 | } 53 | } 54 | sb.append(count).append(prevC); 55 | return sb.toString(); 56 | } 57 | } 58 | ``` 59 | 60 | ## Additional {#additional} 61 | 62 | -------------------------------------------------------------------------------- /leetcode/string/043-wildcard-matching.md: -------------------------------------------------------------------------------- 1 | # 043-wildcard-matching 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/string/058-length-of-last-word.md: -------------------------------------------------------------------------------- 1 | # 058-length-of-last-word 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/length-of-last-word/description/](https://leetcode.com/problems/length-of-last-word/description/) 6 | 7 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 8 | 9 | If the last word does not exist, return 0. 10 | 11 | **Note:** 12 | 13 | A word is defined as a character sequence consists of non-space characters only. 14 | 15 | **Example:** 16 | 17 | ```text 18 | Input: "Hello World" 19 | Output: 5 20 | ``` 21 | 22 | ## Thought Process {#thought-process} 23 | 24 | 1. Scanning Backward 25 | 1. Having a pointer points at the end of the string and move forward the string if it's a space 26 | 2. Then we stop at the end of the last word 27 | 3. Increase the length as long as the character is not a space 28 | 4. Time complexity O\(n\) 29 | 5. Space complexity O\(1\) 30 | 31 | ## Solution 32 | 33 | ```java 34 | class Solution { 35 | public int lengthOfLastWord(String s) { 36 | int len = 0, tail = s.length() - 1; 37 | while(tail >= 0 && s.charAt(tail) == ' ') tail--; 38 | while(tail >= 0 && s.charAt(tail) != ' '){ 39 | len++; 40 | tail--; 41 | } 42 | return len; 43 | } 44 | } 45 | ``` 46 | 47 | ## Additional {#additional} 48 | 49 | -------------------------------------------------------------------------------- /leetcode/string/071-simplify-path.md: -------------------------------------------------------------------------------- 1 | # 071-simplify-path 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/simplify-path/description/](https://leetcode.com/problems/simplify-path/description/) 6 | 7 | Given an absolute path for a file \(Unix-style\), simplify it. 8 | 9 | **Example:** 10 | 11 | ```text 12 | path = "/home/", => "/home" 13 | path = "/a/./b/../../c/", => "/c" 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Deque 19 | 1. Use deque to store the directories 20 | 2. When we encounter "." or "" we continue to next 21 | 3. When we encounter "..", we should pop the last inserted element, just like traveling up the folder 22 | 4. Otherwise, we should save this directory into our queue 23 | 5. Time complexity O\(d\), where d is number of directories 24 | 6. Space complexity O\(n\), where n is the length of path 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | 31 | public String simplifyPath(String path) { 32 | Deque queue = new LinkedList<>(); 33 | for (String dir : path.split("/")) { 34 | if (dir.equals(".") || dir.equals("")) continue; 35 | else if (dir.equals("..")) queue.pollLast(); 36 | else queue.add(dir); 37 | } 38 | StringBuilder sb = new StringBuilder(); 39 | for (String dir : queue) { 40 | sb.append("/").append(dir); 41 | } 42 | return queue.isEmpty() ? "/" : sb.toString(); 43 | } 44 | } 45 | ``` 46 | 47 | ## Additional {#additional} 48 | 49 | -------------------------------------------------------------------------------- /leetcode/string/091-decode-ways.md: -------------------------------------------------------------------------------- 1 | # 091-decode-ways 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/decode-ways/description/](https://leetcode.com/problems/decode-ways/description/) 6 | 7 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 8 | 9 | ```text 10 | 'A' -> 1 11 | 'B' -> 2 12 | ... 13 | 'Z' -> 26 14 | ``` 15 | 16 | Given an encoded message containing digits, determine the total number of ways to decode it. 17 | 18 | ```text 19 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 20 | The number of ways decoding "12" is 2. 21 | ``` 22 | 23 | ## Thought Process {#thought-process} 24 | 25 | 1. Dynamic Programing 26 | 1. For every character we are exploring, we need to check it along with previous character 27 | 2. We create an array of dp\[n + 1\] to store the number ways of deciphering, and dp\[i\] store the result for ith character 28 | 3. if the character is 0, it has to be use in conjunction with previous character 29 | 4. If the character is non 0, it has to be at least as dp\[i - 1\] 30 | 5. if the character combine with previous character is between 10 and 26 inclusive, we need to add dp\[i - 2\] 31 | 6. Time complexity O\(n\) 32 | 7. Space complexity O\(n\) 33 | 2. Dynamic Programing - Space Reduction 34 | 1. If we observe closely, we can see that the dp only depends on i - 1 and i - 2, so we just need two variables 35 | 2. pre1 and pre2 36 | 3. Time complexity O\(n\) 37 | 4. Space complexity O\(1\) 38 | 39 | ## Solution 40 | 41 | ```java 42 | class Solution { 43 | public int numDecodings(String s) { 44 | if (s == null || s.length() == 0 || s.charAt(0) == '0') return 0; 45 | char[] chars = s.toCharArray(); 46 | int n = chars.length; 47 | // dp[i] store the ith character 48 | int[] dp = new int[n + 1]; 49 | dp[0] = 1; 50 | dp[1] = 1; 51 | for (int i = 2; i < dp.length; i++) { 52 | int cur = chars[i - 1] - '0'; 53 | int pre = (chars[i - 2] - '0' ) * 10 + cur; 54 | if (cur != 0) dp[i] = dp[i - 1]; 55 | if (pre >= 10 && pre <= 26) dp[i] += dp[i - 2]; 56 | } 57 | return dp[n]; 58 | } 59 | } 60 | ``` 61 | 62 | ## Additional {#additional} 63 | 64 | -------------------------------------------------------------------------------- /leetcode/string/151-reverse-words-in-a-string.md: -------------------------------------------------------------------------------- 1 | # 151-reverse-words-in-a-string 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reverse-words-in-a-string/description/](https://leetcode.com/problems/reverse-words-in-a-string/description/) 6 | 7 | Given an input string, reverse the string word by word. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given s = "the sky is blue", 13 | return "blue is sky the". 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Split by Space 19 | 1. We can choose to trim the space or not, then we split by space 20 | 2. Then start from the end of the string array, we start building word by word 21 | 3. Time complexity O\(n\) 22 | 4. Space complexity O\(n\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | public class Solution { 28 | public String reverseWords(String s) { 29 | String[] words = s.trim().split("\\s+"); 30 | if (words.length == 0) return ""; 31 | StringBuilder sb = new StringBuilder(); 32 | for (int i = words.length - 1; i > 0; i--){ 33 | sb.append(words[i]).append(" "); 34 | } 35 | sb.append(words[0]); 36 | return sb.toString(); 37 | } 38 | } 39 | ``` 40 | 41 | ```java 42 | public class Solution { 43 | public String reverseWords(String s) { 44 | String[] words = s.split(" "); 45 | StringBuilder sb = new StringBuilder(); 46 | for (int i = words.length - 1; i >= 0; i--){ 47 | if (words[i].length() > 0) sb.append(words[i]).append(" "); 48 | } 49 | if (sb.length() > 0) sb.setLength(sb.length() - 1); 50 | return sb.toString(); 51 | } 52 | } 53 | ``` 54 | 55 | ## Additional {#additional} 56 | 57 | -------------------------------------------------------------------------------- /leetcode/string/157-read-n-characters-given-read4.md: -------------------------------------------------------------------------------- 1 | # 157-read-n-characters-given-read4 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/read-n-characters-given-read4/description/](https://leetcode.com/problems/read-n-characters-given-read4/description/) 6 | 7 | The API: int read4\(char \*buf\) reads 4 characters at a time from a file. 8 | 9 | The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. 10 | 11 | By using the read4 API, implement the function int read\(char \*buf, int n\) that reads n characters from the file. 12 | 13 | **Example:** 14 | 15 | ```text 16 | 17 | ``` 18 | 19 | **Note:** 20 | 21 | The read function will only be called once for each test case. 22 | 23 | ## Thought Process 24 | 25 | 1. Extra Buffer Array and Pointer 26 | 1. Read and store the characters in a temporary buffer 27 | 2. Then append the character until we reach the end of file or the nth character 28 | 3. Time complexity O\(n\) 29 | 4. Space complexity O\(1\) 30 | 31 | ## Solution 32 | 33 | ```java 34 | /* The read4 API is defined in the parent class Reader4. 35 | int read4(char[] buf); */ 36 | 37 | public class Solution extends Reader4 { 38 | /** 39 | * @param buf Destination buffer 40 | * @param n Maximum number of characters to read 41 | * @return The number of characters read 42 | */ 43 | public int read(char[] buf, int n) { 44 | char[] tmp = new char[4]; 45 | int total = 0; 46 | while (total < n) { 47 | int count = read4(tmp); 48 | int len = Math.min(count, n - total); 49 | for (int i = 0; i < len; i++) { 50 | buf[total++] = tmp[i]; 51 | } 52 | if (count < 4) break; 53 | } 54 | return total; 55 | } 56 | }Additional 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /leetcode/string/161-one-edit-distance.md: -------------------------------------------------------------------------------- 1 | # 161-one-edit-distance 2 | 3 | ## Question {#question} 4 | 5 | Given two strings S and T, determine if they are both one edit distance apart. 6 | 7 | **Example:** 8 | 9 | ```text 10 | 11 | ``` 12 | 13 | ## Thought Process {#thought-process} 14 | 15 | 1. DP \(TLE\) 16 | 1. Typical DP where we store the edit distance in dp, where dp\[i\]\[j\] means the edit distance up to ith character of s and jth character of t 17 | 2. Time complexity O\(mn\) 18 | 3. Space complexity O\(mn\) 19 | 2. Two Pointers 20 | 1. Using two pointers i and j to track the index of s and t respectively 21 | 2. Another variable to check the difference we have encountered 22 | 3. At the end, we just need to check whether the diff == 1 or diff == 0 && m != n 23 | 4. Time complexity O\(m\) 24 | 5. Space complexity O\(1\) 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | public boolean isOneEditDistance(String s, String t) { 31 | int m = s.length(), n = t.length(); 32 | int[][] dp = new int[m + 1][n + 1]; 33 | char[] sc = s.toCharArray(), tc = t.toCharArray(); 34 | for (int j = 1; j <= n; j++) dp[0][j] = j; 35 | for (int i = 1; i <= m; i++) dp[i][0] = i; 36 | for (int i = 1; i <= m; i++) { 37 | for (int j = 1; j <= n; j++) { 38 | if (sc[i - 1] == tc[j - 1]) dp[i][j] = dp[i - 1][j - 1]; 39 | else dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; 40 | } 41 | } 42 | return dp[m][n] == 1; 43 | } 44 | } 45 | ``` 46 | 47 | ## Additional {#additional} 48 | 49 | -------------------------------------------------------------------------------- /leetcode/string/165-compare-version-numbers.md: -------------------------------------------------------------------------------- 1 | # 165-compare-version-numbers 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/compare-version-numbers/description/](https://leetcode.com/problems/compare-version-numbers/description/) 6 | 7 | Compare two version numbers version1 and version2. 8 | 9 | If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. 10 | 11 | You may assume that the version strings are non-empty and contain only digits and the . character. 12 | 13 | The . character does not represent a decimal point and is used to separate number sequences. 14 | 15 | For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. 16 | 17 | **Example:** 18 | 19 | ```text 20 | 0.1 < 1.1 < 1.2 < 13.37 21 | ``` 22 | 23 | ## Thought Process {#thought-process} 24 | 25 | 1. Split and Compare 26 | 1. Start from the first field until we reach the end or the numbers are different 27 | 2. Time complexity O\(n\), where n is number of fields 28 | 3. Space complexity O\(n\) 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public int compareVersion(String version1, String version2) { 35 | String[] ver1 = version1.split("\\."); 36 | String[] ver2 = version2.split("\\."); 37 | int n = Math.max(ver1.length, ver2.length); 38 | for (int i = 0; i < n; i++){ 39 | int v1 = i >= ver1.length ? 0 : Integer.parseInt(ver1[i]); 40 | int v2 = i >= ver2.length ? 0 : Integer.parseInt(ver2[i]); 41 | int cmp = Integer.compare(v1, v2); 42 | if (cmp != 0) return cmp; 43 | } 44 | return 0; 45 | } 46 | } 47 | ``` 48 | 49 | ## Additional {#additional} 50 | 51 | -------------------------------------------------------------------------------- /leetcode/string/186-reverse-words-in-a-string-ii.md: -------------------------------------------------------------------------------- 1 | # 186-reverse-words-in-a-string-ii 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reverse-words-in-a-string-ii/description/](https://leetcode.com/problems/reverse-words-in-a-string-ii/description/) 6 | 7 | Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. 8 | 9 | The input string does not contain leading or trailing spaces and the words are always separated by a single space. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Given s = "the sky is blue", 15 | return "blue is sky the". 16 | ``` 17 | 18 | Could you do it in-place without allocating extra space? 19 | 20 | ## Thought Process {#thought-process} 21 | 22 | 1. Reverse and Two Pointers 23 | 1. We first reverse the whole string 24 | 2. Then when we encounter a space, we reverse the start to the last position, so we "correct" the order 25 | 3. Time complexity O\(n\) 26 | 4. Space complexity O\(1\) 27 | 28 | ## Solution 29 | 30 | ```java 31 | class Solution { 32 | public void reverseWords(char[] str) { 33 | int n = str.length; 34 | reverse(str, 0, n - 1); 35 | int start = 0, end = 0; 36 | while (end < n) { 37 | if (str[end] == ' ') { 38 | reverse(str, start, end - 1); 39 | start = end + 1; 40 | } 41 | end++; 42 | } 43 | reverse(str, start, end - 1); 44 | } 45 | 46 | private void reverse(char[] str, int i, int j) { 47 | while (i < j) { 48 | char tmp = str[i]; 49 | str[i] = str[j]; 50 | str[j] = tmp; 51 | i++; 52 | j--; 53 | } 54 | } 55 | } 56 | ``` 57 | 58 | ## Additional {#additional} 59 | 60 | -------------------------------------------------------------------------------- /leetcode/string/293-flip-game.md: -------------------------------------------------------------------------------- 1 | # 293-flip-game 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/flip-game/description/](https://leetcode.com/problems/flip-game/description/) 6 | 7 | You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner. 8 | 9 | Write a function to compute all possible states of the string after one valid move. 10 | 11 | **Example:** 12 | 13 | ```text 14 | given s = "++++", after one move, it may become one of the following states: 15 | 16 | [ 17 | "--++", 18 | "+--+", 19 | "++--" 20 | ] 21 | 22 | If there is no valid move, return an empty list []. 23 | ``` 24 | 25 | ## Thought Process {#thought-process} 26 | 27 | 1. Check Character Pair 28 | 1. Starting from index 1, we need to make sure the current character and previous character are both '+' 29 | 2. We flip and add the result to the list, then reset 30 | 3. Time complexity O\(n\) 31 | 4. Space complexity O\(1\) 32 | 33 | ## Solution 34 | 35 | ```java 36 | class Solution { 37 | public List generatePossibleNextMoves(String s) { 38 | List res = new ArrayList<>(); 39 | char[] path = s.toCharArray(); 40 | for (int i = 1; i < path.length; i++) { 41 | if (path[i - 1] == '+' && path[i] == '+') { 42 | path[i - 1] = path[i] = '-'; 43 | res.add(String.valueOf(path)); 44 | path[i - 1] = path[i] = '+'; 45 | } 46 | } 47 | return res; 48 | } 49 | } 50 | ``` 51 | 52 | ## Additional {#additional} 53 | 54 | -------------------------------------------------------------------------------- /leetcode/string/344-reverse-string.md: -------------------------------------------------------------------------------- 1 | # 344-reverse-string 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reverse-string/description/](https://leetcode.com/problems/reverse-string/description/) 6 | 7 | Write a function that takes a string as input and returns the string reversed. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given s = "hello", return "olleh". 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Two Pointers 18 | 1. Start from the ends of the string and swap the pair as we increment left pointer and decrement right pointer 19 | 2. Time complexity O\(n\) 20 | 3. Space complexity O\(1\) 21 | 22 | ## Solution 23 | 24 | ```java 25 | class Solution { 26 | public String reverseString(String s) { 27 | char[] chars = s.toCharArray(); 28 | int i = 0, j = chars.length - 1; 29 | while (i < j) swap(chars, i++, j--); 30 | return String.valueOf(chars); 31 | } 32 | 33 | private void swap(char[] chars, int i, int j) { 34 | char tmp = chars[i]; 35 | chars[i] = chars[j]; 36 | chars[j] = tmp; 37 | } 38 | } 39 | ``` 40 | 41 | ## Additional {#additional} 42 | 43 | -------------------------------------------------------------------------------- /leetcode/string/345-reverse-vowels-of-a-string.md: -------------------------------------------------------------------------------- 1 | # 345-reverse-vowels-of-a-string 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reverse-vowels-of-a-string/description/](https://leetcode.com/problems/reverse-vowels-of-a-string/description/) 6 | 7 | Write a function that takes a string as input and reverse only the vowels of a string. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given s = "hello", return "holle". 13 | 14 | Given s = "leetcode", return "leotcede". 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Two Pointers 20 | 1. Start again with two pointers from left and right 21 | 2. Skip all the non-vowel character, then we switch the vowels pair 22 | 3. Time complexity O\(n\) 23 | 4. Space complexity O\(1\) 24 | 25 | ## Solution 26 | 27 | ```java 28 | class Solution { 29 | public String reverseVowels(String s) { 30 | if (s == null || s.length() <= 1) return s; 31 | Set vowels = new HashSet<>(); 32 | vowels.add('a'); 33 | vowels.add('e'); 34 | vowels.add('i'); 35 | vowels.add('o'); 36 | vowels.add('u'); 37 | vowels.add('A'); 38 | vowels.add('E'); 39 | vowels.add('I'); 40 | vowels.add('O'); 41 | vowels.add('U'); 42 | char[] chars = s.toCharArray(); 43 | int i = 0, j = chars.length - 1; 44 | while (i < j) { 45 | while (i < j && !vowels.contains(chars[i])) i++; 46 | while (i < j && !vowels.contains(chars[j])) j--; 47 | if (i >= j) break; 48 | char tmp = chars[i]; 49 | chars[i] = chars[j]; 50 | chars[j] = tmp; 51 | i++; 52 | j--; 53 | } 54 | return String.valueOf(chars); 55 | } 56 | } 57 | ``` 58 | 59 | ## Additional {#additional} 60 | 61 | -------------------------------------------------------------------------------- /leetcode/string/383-ransom-note.md: -------------------------------------------------------------------------------- 1 | # 383-ransom-note 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/ransom-note/description/](https://leetcode.com/problems/ransom-note/description/) 6 | 7 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 8 | 9 | Each letter in the magazine string can only be used once in your ransom note. 10 | 11 | **Example:** 12 | 13 | ```text 14 | canConstruct("a", "b") -> false 15 | canConstruct("aa", "ab") -> false 16 | canConstruct("aa", "aab") -> true 17 | ``` 18 | 19 | ## Thought Process {#thought-process} 20 | 21 | 1. Map 22 | 1. Use separate map to store the frequency of all characters 23 | 2. Any time we run into character that has count == 0, we know we can't construct the note 24 | 3. Time complexity O\(n\) 25 | 4. Space complexity O\(256\) or O\(1\) 26 | 27 | ## Solution 28 | 29 | ```java 30 | class Solution { 31 | public boolean canConstruct(String ransomNote, String magazine) { 32 | int[] count = new int[256]; 33 | for (char c : magazine.toCharArray()) { 34 | count[c]++; 35 | } 36 | for (char c : ransomNote.toCharArray()) { 37 | if (count[c]-- == 0) return false; 38 | } 39 | return true; 40 | } 41 | } 42 | ``` 43 | 44 | ## Additional {#additional} 45 | 46 | -------------------------------------------------------------------------------- /leetcode/string/README.md: -------------------------------------------------------------------------------- 1 | # string 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /leetcode/two-pointers/028-implement-strstr.md: -------------------------------------------------------------------------------- 1 | # 028-implement-strstr 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/implement-strstr/description/](https://leetcode.com/problems/implement-strstr/description/) 6 | 7 | Implement [strStr\(\)](http://www.cplusplus.com/reference/cstring/strstr/). 8 | 9 | Return the index of the first occurrence of needle in haystack, or **-1** if needle is not part of haystack. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Input: haystack = "hello", needle = "ll" 15 | Output: 2 16 | 17 | Input: haystack = "aaaaa", needle = "bba" 18 | Output: -1 19 | ``` 20 | 21 | ## Thought Process {#thought-process} 22 | 23 | 1. Two Pointers 24 | 1. At each position, we simply compare the letter matches 25 | 2. Time complexity O\(hn\), where h is the length of haystack and n is length of needle 26 | 3. Space complexity O\(1\) 27 | 28 | ## Solution 29 | 30 | ```java 31 | class Solution { 32 | public int strStr(String haystack, String needle) { 33 | if(haystack.length() < needle.length()) return -1; 34 | if(needle.length() == 0) return 0; 35 | char[] hc = haystack.toCharArray(); 36 | char[] nc = needle.toCharArray(); 37 | int id = -1; 38 | for(int i = 0; i <= hc.length - nc.length; i++){ 39 | if(match(hc, i, nc)){ 40 | return i; 41 | } 42 | } 43 | return id; 44 | } 45 | 46 | public boolean match(char[] hc, int start, char[] nc){ 47 | for(int i = 0; i < nc.length; i++){ 48 | if(hc[start++] != nc[i]) return false; 49 | } 50 | return true; 51 | } 52 | } 53 | ``` 54 | 55 | ## Additional {#additional} 56 | 57 | -------------------------------------------------------------------------------- /leetcode/two-pointers/125-valid-palindrome.md: -------------------------------------------------------------------------------- 1 | # 125-valid-palindrome 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/valid-palindrome/description/](https://leetcode.com/problems/valid-palindrome/description/) 6 | 7 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 8 | 9 | **Example:** 10 | 11 | ```text 12 | "A man, a plan, a canal: Panama" is a palindrome. 13 | "race a car" is not a palindrome. 14 | ``` 15 | 16 | ## Thought Process {#thought-process} 17 | 18 | 1. Two Pointers 19 | 1. Having two pointer at the ends of the string, we can compare character by character 20 | 2. Time complexity O\(n\) 21 | 3. Space complexity O\(1\) 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public boolean isPalindrome(String s) { 28 | int i = 0, j = s.length() - 1; 29 | while (i < j){ 30 | if (!Character.isLetterOrDigit(s.charAt(i))){ 31 | i++; 32 | } else if (!Character.isLetterOrDigit(s.charAt(j))){ 33 | j--; 34 | } else { 35 | if (Character.toLowerCase(s.charAt(i)) 36 | != Character.toLowerCase(s.charAt(j))) return false; 37 | i++; 38 | j--; 39 | } 40 | } 41 | return true; 42 | } 43 | } 44 | ``` 45 | 46 | ## Additional {#additional} 47 | 48 | -------------------------------------------------------------------------------- /leetcode/two-pointers/167-two-sum-ii-input-array-is-sorted.md: -------------------------------------------------------------------------------- 1 | # 167-two-sum-ii-input-array-is-sorted 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/) 6 | 7 | Given an array of integers that is already **sorted in ascending order**, find two numbers such that they add up to a specific target number. 8 | 9 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers \(both index1 and index2\) are not zero-based. 10 | 11 | You may assume that each input would have exactly one solution and you may not use the same element twice. 12 | 13 | **Example:** 14 | 15 | ```text 16 | Input: numbers={2, 7, 11, 15}, target=9 17 | Output: index1=1, index2=2 18 | ``` 19 | 20 | ## Thought Process {#thought-process} 21 | 22 | 1. Two Pointers 23 | 1. Using two pointers to track the start and end of array 24 | 2. Adjust the start and end pointers accordingly by comparing their sum and the target 25 | 3. Time complexity O\(n\) 26 | 4. Space complexity O\(1\) 27 | 28 | ## Solution 29 | 30 | ```java 31 | class Solution { 32 | public int[] twoSum(int[] numbers, int target) { 33 | int lo = 0, hi = numbers.length - 1; 34 | int[] indices = new int[2]; 35 | while (lo < hi){ 36 | int sum = numbers[lo] + numbers[hi]; 37 | if (sum < target){ 38 | lo++; 39 | } else if (sum > target){ 40 | hi--; 41 | } else { 42 | indices[0] = lo + 1; 43 | indices[1] = hi + 1; 44 | break; 45 | } 46 | } 47 | return indices; 48 | } 49 | } 50 | ``` 51 | 52 | ## Additional {#additional} 53 | 54 | -------------------------------------------------------------------------------- /leetcode/two-pointers/283-move-zeroes.md: -------------------------------------------------------------------------------- 1 | # 283-move-zeroes 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/move-zeroes/description/](https://leetcode.com/problems/move-zeroes/description/) 6 | 7 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given nums = [0, 1, 0, 3, 12], 13 | after calling your function, 14 | nums should be [1, 3, 12, 0, 0]. 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Two Pointers 20 | 1. Use one pointer to keep track the last inserted position 21 | 2. Anther pointer moves forward as we progress the element 22 | 3. Insert the element if it is not equal to 0 23 | 4. Time complexity O\(n\) 24 | 5. Space complexity O\(1\) 25 | 26 | ## Solution 27 | 28 | ```java 29 | class Solution { 30 | public void moveZeroes(int[] nums) { 31 | int id = 0; 32 | for (int i = 0; i < nums.length; i++) { 33 | if (nums[i] != 0) nums[id++] = nums[i]; 34 | } 35 | while (id < nums.length) nums[id++] = 0; 36 | } 37 | } 38 | ``` 39 | 40 | ## Additional {#additional} 41 | 42 | -------------------------------------------------------------------------------- /leetcode/two-pointers/344-reverse-string.md: -------------------------------------------------------------------------------- 1 | # 344-reverse-string 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reverse-string/description/](https://leetcode.com/problems/reverse-string/description/) 6 | 7 | Write a function that takes a string as input and returns the string reversed. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given s = "hello", return "olleh". 13 | ``` 14 | 15 | ## Thought Process {#thought-process} 16 | 17 | 1. Two Pointers 18 | 1. Use two pointer to track the start and end of string 19 | 2. Swap the character at each pointer and then shrink toward the center 20 | 3. Time complexity O\(n\) 21 | 4. Space complexity O\(1\) 22 | 23 | ## Solution 24 | 25 | ```java 26 | class Solution { 27 | public String reverseString(String s) { 28 | char[] chars = s.toCharArray(); 29 | int i = 0, j = chars.length - 1; 30 | while (i < j) swap(chars, i++, j--); 31 | return String.valueOf(chars); 32 | } 33 | 34 | private void swap(char[] chars, int i, int j) { 35 | char tmp = chars[i]; 36 | chars[i] = chars[j]; 37 | chars[j] = tmp; 38 | } 39 | } 40 | ``` 41 | 42 | ## Additional {#additional} 43 | 44 | -------------------------------------------------------------------------------- /leetcode/two-pointers/345-reverse-vowels-of-a-string.md: -------------------------------------------------------------------------------- 1 | # 345-reverse-vowels-of-a-string 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/reverse-vowels-of-a-string/description/](https://leetcode.com/problems/reverse-vowels-of-a-string/description/) 6 | 7 | Write a function that takes a string as input and reverse only the vowels of a string. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Given s = "hello", return "holle". 13 | 14 | Given s = "leetcode", return "leotcede". 15 | ``` 16 | 17 | ## Thought Process {#thought-process} 18 | 19 | 1. Two Pointers 20 | 1. Scan the first vowels from each side and then swap 21 | 2. Time complexity O\(n\) 22 | 3. Space complexity O\(1\) 23 | 24 | ## Solution 25 | 26 | ```java 27 | class Solution { 28 | public String reverseVowels(String s) { 29 | if (s == null || s.length() <= 1) return s; 30 | Set vowels = new HashSet<>(); 31 | vowels.add('a'); 32 | vowels.add('e'); 33 | vowels.add('i'); 34 | vowels.add('o'); 35 | vowels.add('u'); 36 | vowels.add('A'); 37 | vowels.add('E'); 38 | vowels.add('I'); 39 | vowels.add('O'); 40 | vowels.add('U'); 41 | char[] chars = s.toCharArray(); 42 | int i = 0, j = chars.length - 1; 43 | while (i < j) { 44 | while (i < j && !vowels.contains(chars[i])) i++; 45 | while (i < j && !vowels.contains(chars[j])) j--; 46 | if (i >= j) break; 47 | char tmp = chars[i]; 48 | chars[i] = chars[j]; 49 | chars[j] = tmp; 50 | i++; 51 | j--; 52 | } 53 | return String.valueOf(chars); 54 | } 55 | } 56 | ``` 57 | 58 | ## Additional {#additional} 59 | 60 | -------------------------------------------------------------------------------- /leetcode/two-pointers/567-permutation-in-string.md: -------------------------------------------------------------------------------- 1 | # 567-permutation-in-string 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/permutation-in-string/description/](https://leetcode.com/problems/permutation-in-string/description/) 6 | 7 | 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. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Input:s1 = "ab" s2 = "eidbaooo" 13 | Output:True 14 | Explanation: s2 contains one permutation of s1 ("ba"). 15 | ``` 16 | 17 | ```text 18 | Input:s1= "ab" s2 = "eidboaoo" 19 | Output: False 20 | ``` 21 | 22 | ## Thought Process {#thought-process} 23 | 24 | 1. Two Pointers 25 | 1. Scanning left to right with sliding window 26 | 2. When all the characters from s1 are used up, we have to make sure the sliding window is exactly the length of s1 27 | 3. Time complexity O\(n\) 28 | 4. Space complexity O\( 29 | 30 | ## Solution 31 | 32 | ```java 33 | class Solution { 34 | public boolean checkInclusion(String s1, String s2) { 35 | int[] map = new int[128]; 36 | for (char c : s1.toCharArray()) { 37 | map[c]++; 38 | } 39 | int count = s1.length(); 40 | char[] chars = s2.toCharArray(); 41 | int left = 0, right = 0; 42 | while (right < chars.length) { 43 | if (map[chars[right++]]-- > 0) count--; 44 | while (count == 0) { 45 | if (right - left == s1.length()) return true; 46 | if (++map[chars[left++]] > 0) count++; 47 | } 48 | } 49 | return false; 50 | } 51 | } 52 | ``` 53 | 54 | ## Additional {#additional} 55 | 56 | -------------------------------------------------------------------------------- /leetcode/two-pointers/713-subarray-product-less-than-k.md: -------------------------------------------------------------------------------- 1 | # 713-subarray-product-less-than-k 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/subarray-product-less-than-k/description/](https://leetcode.com/problems/subarray-product-less-than-k/description/) 6 | 7 | Your are given an array of positive integers nums. 8 | 9 | Count and print the number of \(contiguous\) subarrays where the product of all the elements in the subarray is less than k. 10 | 11 | **Example:** 12 | 13 | ```text 14 | Input: nums = [10, 5, 2, 6], k = 100 15 | Output: 8 16 | Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]. 17 | Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. 18 | ``` 19 | 20 | **Note:** 21 | 22 | * 0 < nums.length <= 50000. 23 | * 0 < nums\[i\] < 1000. 24 | * 0 <= k < 10^6. 25 | 26 | ## Thought Process {#thought-process} 27 | 28 | 1. Two Pointers 29 | 1. Since the multiplication will not overflow, we can use one variable to store the product 30 | 2. We multiply the current number and adjust the left pointer until we have product smaller than k 31 | 3. Then the number of product less than k is equal to current - left + 1 32 | 4. Time complexity O\(n\) 33 | 5. Space complexity O\(1\) 34 | 35 | ## Solution 36 | 37 | ```java 38 | class Solution { 39 | public int numSubarrayProductLessThanK(int[] nums, int k) { 40 | if (k <= 1) return 0; 41 | int prod = 1; 42 | int count = 0, left = 0; 43 | for (int i = 0; i < nums.length; i++) { 44 | prod *= nums[i]; 45 | while (prod >= k) prod /= nums[left++]; 46 | count += i - left + 1; 47 | } 48 | return count; 49 | } 50 | } 51 | ``` 52 | 53 | ## Additional {#additional} 54 | 55 | -------------------------------------------------------------------------------- /leetcode/two-pointers/763-partition-labels.md: -------------------------------------------------------------------------------- 1 | # 763-partition-labels 2 | 3 | ## Question {#question} 4 | 5 | [https://leetcode.com/problems/partition-labels/description/](https://leetcode.com/problems/partition-labels/description/) 6 | 7 | A string S of lowercase 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. 8 | 9 | **Example:** 10 | 11 | ```text 12 | Input: S = "ababcbacadefegdehijhklij" 13 | Output: [9,7,8] 14 | Explanation: 15 | The partition is "ababcbaca", "defegde", "hijhklij". 16 | This is a partition so that each letter appears in at most one part. 17 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. 18 | ``` 19 | 20 | **Note:** 21 | 22 | 1. S will have length in range \[1, 500\]. 23 | 2. S will consist of lowercase letters \('a' to 'z'\) only. 24 | 25 | ## Thought Process {#thought-process} 26 | 27 | 1. Two Pointers 28 | 1. For each character, we need to find the rightest index for it, then within this range, we need to further expand the right boundary 29 | 2. Use map to facilitate the search rightest index and also use two pointers to find the length 30 | 3. Time complexity O\(n\) 31 | 4. Space complexity O\(128\) or O\(1\) 32 | 33 | ## Solution 34 | 35 | ```java 36 | class Solution { 37 | public List partitionLabels(String S) { 38 | int[] map = new int[128]; 39 | char[] chars = S.toCharArray(); 40 | for (int i = 0; i < chars.length; i++) map[chars[i]] = i; 41 | int left = 0, right = 0; 42 | List res = new ArrayList<>(); 43 | while (left < chars.length) { 44 | right = map[chars[left]]; 45 | for (int i = left; i < right; i++) right = Math.max(right, map[chars[i]]); 46 | res.add(right - left + 1); 47 | left = right + 1; 48 | } 49 | return res; 50 | } 51 | } 52 | ``` 53 | 54 | ## Additional {#additional} 55 | 56 | -------------------------------------------------------------------------------- /leetcode/two-pointers/README.md: -------------------------------------------------------------------------------- 1 | # two-pointers 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /other/README.md: -------------------------------------------------------------------------------- 1 | # other 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /other/euclidean-algorithm.md: -------------------------------------------------------------------------------- 1 | # euclidean-algorithm 2 | 3 | [https://en.wikipedia.org/wiki/Euclidean\_algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) 4 | 5 | This algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. 6 | 7 | For example, 21 is the GCD of 252 and 105 \(as 252 = 21 × 12 and 105 = 21 × 5\), and the same number 21 is also the GCD of 105 and 252 − 105 = 147. 8 | 9 | By reversing the steps, the GCD can be expressed as sum two numbers, i.e. 21 = 5 x 105 + \(-2\) x 252. 10 | 11 | -------------------------------------------------------------------------------- /other/rabin-karp-rolling-hash.md: -------------------------------------------------------------------------------- 1 | # rabin-karp-rolling-hash 2 | 3 | Rolling Hash 4 | 5 | [http://blog.teamleadnet.com/2012/10/rabin-karp-rolling-hash-dynamic-sized.html](http://blog.teamleadnet.com/2012/10/rabin-karp-rolling-hash-dynamic-sized.html) 6 | 7 | Modular Multiplicative Inverse 8 | 9 | [https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/](https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/) 10 | 11 | -------------------------------------------------------------------------------- /other/summation-identities.md: -------------------------------------------------------------------------------- 1 | # summation-identities 2 | 3 | [https://www.math.uh.edu/~ilya/class/useful\_summations.pdf](https://www.math.uh.edu/~ilya/class/useful_summations.pdf) 4 | 5 | [http://www.cs.uml.edu/~jannunzi/91.404/classNotes/ch3/3.1%20Summation%20Formulas%20and%20Properties.html](http://www.cs.uml.edu/~jannunzi/91.404/classNotes/ch3/3.1%20Summation%20Formulas%20and%20Properties.html) 6 | 7 | -------------------------------------------------------------------------------- /template/README.md: -------------------------------------------------------------------------------- 1 | # template 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /template/leetcode.md: -------------------------------------------------------------------------------- 1 | # leetcode 2 | 3 | ## Question {#question} 4 | 5 | 6 | 7 | 8 | 9 | ## Thought Process {#thought-process} 10 | 11 | 1. a 12 | 13 | ## Solution 14 | 15 | ```java 16 | 17 | ``` 18 | 19 | ## Additional {#additional} 20 | 21 | 22 | 23 | --------------------------------------------------------------------------------