├── .github
├── FUNDING.yml
└── workflows
│ └── README_Generator.yml
├── Swift
├── reverse_string.swift
├── add-two-integers.swift
├── xor-operation-in-an-array.swift
├── a-number-after-a-double-reversal.swift
├── richest-customer-wealth.swift
├── power-of-two.swift
├── longest-uncommon-subsequence-i.swift
├── ugly-number.swift
├── count-all-valid-pickup-and-delivery-options.swift
├── broken-calculator.swift
├── reverse-string.swift
├── running-sum-of-1d-array.swift
├── best-time-to-buy-and-sell-stock-ii.swift
├── count-elements-with-strictly-smaller-and-greater-elements.swift
├── distribute-candies.swift
├── contains-duplicate.swift
├── largest-number-at-least-twice-of-others.swift
├── transpose-matrix.swift
├── number-of-equivalent-domino-pairs.swift
├── minimum-value-to-get-positive-step-by-step-sum.swift
├── max-consecutive-ones.swift
├── k-closest-points-to-origin.swift
├── minimum-consecutive-cards-to-pick-up.swift
├── fibonacci-number.swift
├── partitioning-into-minimum-number-of-deci-binary-numbers.swift
├── range-addition-ii.swift
├── sum-of-square-numbers.swift
├── total-hamming-distance.swift
├── fizz-buzz.swift
├── smallest-integer-divisible-by-k.swift
├── best-time-to-buy-and-sell-stock.swift
├── kth-missing-positive-number.swift
├── palindrome-number.swift
├── determine-if-string-halves-are-alike.swift
├── water-bottles.swift
├── left-and-right-sum-differences.swift
├── maximum-split-of-positive-even-integers.swift
├── remove-all-adjacent-duplicates-in-string.swift
├── short-encoding-of-words.swift
├── meeting-rooms.swift
├── number-complement.swift
├── concatenation-of-consecutive-binary-numbers.swift
├── task-scheduler.swift
├── happy-number.swift
├── length-of-last-word.swift
├── check-array-formation-through-concatenation.swift
├── power-of-three.swift
├── number-of-segments-in-a-string.swift
├── h-index-ii.swift
├── longest-harmonious-subsequence.swift
├── orderly-queue.swift
├── boats-to-save-people.swift
├── set-mismatch.swift
├── valid-perfect-square.swift
├── next-greater-element-i.swift
├── angle-between-hands-of-a-clock.swift
├── max-number-of-k-sum-pairs.swift
├── binary-search.swift
├── validate-stack-sequences.swift
├── jewels-and-stones.swift
├── n-th-tribonacci-number.swift
├── reverse-bits.swift
├── check-if-all-1s-are-at-least-length-k-places-away.swift
├── domino-and-tromino-tiling.swift
├── h-index.swift
├── brick-wall.swift
├── find-the-divisibility-array-of-a-string.swift
├── perfect-squares.swift
├── meeting-rooms-ii.swift
├── shifting-letters.swift
├── array-of-doubled-pairs.swift
├── find-the-most-competitive-subsequence.swift
├── max-consecutive-ones-iii.swift
├── minimum-flips-to-make-a-or-b-equal-to-c.swift
├── majority-element-ii.swift
├── stone-game-viii.swift
├── coin-change-2.swift
├── implement-strstr.swift
├── jump-game.swift
├── largest-number.swift
├── pascals-triangle.swift
├── reduce-array-size-to-the-half.swift
├── remove-digit-from-number-to-maximize-result.swift
├── repeated-dna-sequences.swift
├── maximum-subarray-sum-with-one-deletion.swift
├── rank-transform-of-an-array.swift
├── teemo-attacking.swift
├── battleships-in-a-board.swift
├── check-if-every-row-and-column-contains-all-numbers.swift
├── delete-and-earn.swift
├── longest-continuous-increasing-subsequence.swift
├── consecutive-characters.swift
├── contiguous-array.swift
├── keys-and-rooms.swift
├── smallest-string-with-a-given-numeric-value.swift
├── reverse-only-letters.swift
├── search-insert-position.swift
├── maximum-points-you-can-obtain-from-cards.swift
├── advantage-shuffle.swift
├── check-if-a-string-contains-all-binary-codes-of-size-k.swift
├── excel-sheet-column-number.swift
├── flip-string-to-monotone-increasing.swift
├── minimum-moves-to-equal-array-elements.swift
├── find-the-smallest-divisor-given-a-threshold.swift
├── flipping-an-image.swift
├── minimum-operations-to-make-array-equal.swift
├── distribute-candies-to-people.swift
├── container-with-most-water.swift
├── unique-paths.swift
├── majority-element.swift
├── powerful-integers.swift
├── find-peak-element.swift
├── longest-palindrome.swift
├── maximum-score-after-splitting-a-string.swift
├── minimum-size-subarray-sum.swift
├── patching-array.swift
├── unique-morse-code-words.swift
├── reverse-integer.swift
├── complex-number-multiplication.swift
├── first-bad-version.swift
├── remove-covered-intervals.swift
├── logger-rate-limiter.swift
├── missing-number.swift
├── subsets-ii.swift
├── 3sum.swift
├── find-missing-and-repeated-values.swift
├── longest-nice-subarray.swift
├── maximum-length-of-repeated-subarray.swift
├── break-a-palindrome.swift
├── linked-list-cycle.swift
├── super-pow.swift
├── valid-anagram.swift
├── factorial-trailing-zeroes.swift
├── k-diff-pairs-in-an-array.swift
├── sliding-window-maximum.swift
├── nth-magical-number.swift
├── divide-a-string-into-groups-of-size-k.swift
├── slowest-key.swift
├── can-place-flowers.swift
├── find-k-closest-elements.swift
├── longest-turbulent-subarray.swift
├── get-maximum-in-generated-array.swift
├── non-overlapping-intervals.swift
├── shortest-subarray-with-sum-at-least-k.swift
├── baseball-game.swift
├── beautiful-arrangement-ii.swift
├── combination-sum-iv.swift
├── intersection-of-two-arrays.swift
├── number-of-subarrays-with-bounded-maximum.swift
├── online-stock-span.swift
├── partition-labels.swift
├── maximum-number-of-balloons.swift
├── number-of-steps-to-reduce-a-number-to-zero.swift
├── reverse-vowels-of-a-string.swift
├── combinations.swift
├── decode-ways.swift
├── bitwise-and-of-numbers-range.swift
├── first-missing-positive.swift
├── maximum-subarray.swift
├── minimum-cost-to-move-chips-to-the-same-position.swift
├── maximum-erasure-value.swift
├── reshape-the-matrix.swift
├── goat-latin.swift
├── element-appearing-more-than-25-in-sorted-array.swift
├── number-of-recent-calls.swift
├── beautiful-arrangement.swift
├── maximum-sum-circular-subarray.swift
├── minimum-cost-for-tickets.swift
├── set-matrix-zeroes.swift
├── two-city-scheduling.swift
├── wiggle-subsequence.swift
├── convert-binary-number-in-a-linked-list-to-integer.swift
├── maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.swift
├── rotate-image.swift
├── jump-game-iii.swift
├── decode-string.swift
├── determine-if-two-strings-are-close.swift
├── four-divisors.swift
├── partition-equal-subset-sum.swift
├── array-nesting.swift
├── binary-trees-with-factors.swift
├── unique-paths-ii.swift
├── minimum-moves-to-equal-array-elements-ii.swift
├── remove-k-digits.swift
├── single-number-ii.swift
├── valid-square.swift
├── copy-list-with-random-pointer.swift
├── word-pattern.swift
├── 4sum-ii.swift
├── verifying-an-alien-dictionary.swift
├── 3sum-closest.swift
├── maximum-units-on-a-truck.swift
├── minimum-operations-to-reduce-x-to-zero.swift
└── delete-operation-for-two-strings.swift
├── GenREADME
├── .swiftpm
│ └── xcode
│ │ └── package.xcworkspace
│ │ └── contents.xcworkspacedata
├── Sources
│ ├── GenREADME.swift
│ └── Language.swift
├── Package.resolved
└── Package.swift
├── Java
├── power-of-two.java
├── single-number.java
├── ugly-number.java
├── missing-number.java
├── excel-sheet-column-number.java
├── find-minimum-in-rotated-sorted-array.java
├── find-minimum-in-rotated-sorted-array_ii.java
├── nim-game.java
├── find-minimum-in-rotated-sorted-array-ii.java
├── unique-paths.java
├── valid-anagram.java
├── H-Index.java
├── add-digits.java
├── delete-node-in-a-linked-list.java
├── number-of-1-bits.java
├── house-robber.java
├── length-of-last-word.java
├── remove-duplicates-from-sorted-array.java
├── powx-n.java
├── single-number-ii.java
├── find-peak-element.java
├── h-index-ii.java
├── majority-element.java
├── jump-game.java
├── product-of-array-except-self.java
├── contains-duplicate.java
├── rectangle-area.java
├── remove-element.java
├── remove-duplicates-from-sorted-array-ii.java
├── maximum-depth-of-binary-tree.java
├── happy-number.java
├── search-insert-position.java
├── generate-parentheses.java
├── longest-valid-parentheses.java
├── find-the-duplicate-number.java
├── same-tree.java
├── count-primes.java
├── reverse-bits.java
├── move-zeroes.java
├── longest-common-prefix.java
├── reverse-integer.java
├── reverse-words-in-a-string.java
├── invert-binary-tree.java
├── remove-duplicates-from-sorted-list.java
├── climbing-stairs.java
├── summary-ranges.java
├── unique-binary-search-trees.java
├── ugly-number-ii.java
├── lowest-common-ancestor-of-a-binary-tree.java
├── best-time-to-buy-and-sell-stock.java
├── candy.java
├── minimum-path-sum.java
├── merge-sorted-array.java
├── lowest-common-ancestor-of-a-binary-search-tree.java
├── single-number-iii.java
├── balanced-binary-tree.java
├── unique-paths-ii.java
├── roman-to-integer.java
├── spiral-matrix-ii.java
├── perfect-squares.java
├── search-a-2d-matrix-ii.java
├── best-time-to-buy-and-sell-stock-ii.java
├── first-bad-version.java
├── minimum-depth-of-binary-tree.java
├── remove-linked-list-elements.java
├── sum-root-to-leaf-numbers.java
├── implement-queue-using-stacks.java
├── restore-ip-addresses.java
├── Combinations.java
├── pascal-triangle.java
├── word-pattern.java
├── longest-consecutive-sequence.java
├── linked-list-cycle.java
├── search-a-2d-matrix.java
└── binary-tree-preorder-traversal.java
├── push_with_msg.sh
├── _config.yml
└── Python
├── palindrome-number.py
└── two-sum.py
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: antonio081014
4 |
--------------------------------------------------------------------------------
/Swift/reverse_string.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func reverseString(s: String) -> String {
3 | return String(s.characters.reverse())
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/Swift/add-two-integers.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func sum(_ num1: Int, _ num2: Int) -> Int {
3 | if num2 == 0 { return num1 }
4 | return sum(num1 ^ num2, (num1 & num2) << 1)
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/GenREADME/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Java/power-of-two.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public boolean isPowerOfTwo(int n) {
3 | if(n == 0) return false;
4 | int base = (int)(Math.log(1.0 * n) / Math.log(2.0));
5 | return n == (int)Math.pow(2.0, base);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/Swift/xor-operation-in-an-array.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func xorOperation(_ n: Int, _ start: Int) -> Int {
3 | var result = 0
4 | for index in 0 ..< n {
5 | result ^= start + 2 * index
6 | }
7 | return result
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/push_with_msg.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | COMMIT_MSG='AC ...'
4 |
5 | if [ $# -gt 0 ]; then
6 | COMMIT_MSG=$1
7 | fi
8 |
9 | echo "- Add changed/new files."
10 | git add .
11 |
12 | echo "- Commit"
13 | git commit -m "${COMMIT_MSG}"
14 |
15 | echo "- Push to origin HEAD"
16 | git push origin HEAD
17 |
--------------------------------------------------------------------------------
/Java/single-number.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/single-number/
3 | */
4 |
5 | public class Solution {
6 | public int singleNumber(int[] nums) {
7 | int ret = 0;
8 | for(int x : nums) {
9 | ret ^= x;
10 | }
11 | return ret;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Swift/a-number-after-a-double-reversal.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/a-number-after-a-double-reversal/
3 | *
4 | *
5 | */
6 | // Date: Fri Jan 21 19:43:50 PST 2022
7 | class Solution {
8 | func isSameAfterReversals(_ num: Int) -> Bool {
9 | return num == 0 || num % 10 != 0
10 | }
11 | }
--------------------------------------------------------------------------------
/Java/ugly-number.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public boolean isUgly(int num) {
3 | if (num <= 0) {
4 | return false;
5 | }
6 | while(num % 2 == 0) num/=2;
7 | while(num % 3 == 0) num/=3;
8 | while(num % 5 == 0) num/=5;
9 | return num == 1;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Swift/richest-customer-wealth.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func maximumWealth(_ accounts: [[Int]]) -> Int {
3 | var result = 0
4 | for acc in accounts {
5 | let wealth = acc.reduce(0) { $0 + $1 }
6 | result = max(result, wealth)
7 | }
8 | return result
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | title: LeetCode Source Code
2 | # description: This repo presents all the solution I passed on LeeCode, should be used AS a Reference for study purpose.
3 | show_downloads: false
4 | is_project_page: true
5 | google_analytics:
6 | markdown: kramdown
7 | theme: jekyll-theme-cayman
8 |
9 | gems:
10 | - jekyll-mentions
11 |
--------------------------------------------------------------------------------
/Java/missing-number.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/missing-number/
3 | */
4 |
5 | public class Solution {
6 | public int missingNumber(int[] nums) {
7 | int n = nums.length;
8 | int sum = (n) * (n + 1) / 2;
9 | for(int i=0; i Bool {
8 | var n = n
9 | while n > 1 {
10 | if n % 2 != 0 { return false }
11 | n /= 2
12 | }
13 | return n == 1
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Swift/longest-uncommon-subsequence-i.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/longest-uncommon-subsequence-i/
3 | *
4 | *
5 | */
6 | // Date: Sun Aug 29 13:37:15 PDT 2021
7 | class Solution {
8 | func findLUSlength(_ a: String, _ b: String) -> Int {
9 | if a == b { return -1 }
10 | return max(a.count, b.count)
11 | }
12 | }
--------------------------------------------------------------------------------
/Java/excel-sheet-column-number.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/excel-sheet-column-number/
3 | */
4 | public class Solution {
5 | public int titleToNumber(String s) {
6 | int sum = 0;
7 | for(int i=0; i nums[i+1]) return nums[i+1];
8 | }
9 | return nums[0];
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Java/find-minimum-in-rotated-sorted-array_ii.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
3 | *
4 | */
5 | public class Solution {
6 | public int findMin(int[] nums) {
7 | for(int i=0; i+1 nums[i+1]) return nums[i+1];
9 | }
10 | return nums[0];
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Swift/ugly-number.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/ugly-number/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func isUgly(_ num: Int) -> Bool {
8 | var num = num
9 | while num > 1, num % 2 == 0 { num /= 2 }
10 | while num > 1, num % 3 == 0 { num /= 3 }
11 | while num > 1, num % 5 == 0 { num /= 5 }
12 | return num == 1
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Java/nim-game.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/nim-game/
3 | *
4 | * When n∈[1,3],Win.
5 | *
6 | * When n == 4,Lose.
7 | *
8 | * When n∈[5,7],Win.
9 | *
10 | * When n == 8, Lose.
11 | *
12 | * So, whenever n % 4 == 0, Fail.
13 | */
14 |
15 | public class Solution {
16 | public boolean canWinNim(int n) {
17 | return n % 4 != 0;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Java/find-minimum-in-rotated-sorted-array-ii.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii
3 | *
4 | *
5 | */
6 |
7 | public class Solution {
8 | public int findMin(int[] nums) {
9 | for(int i=0; i+1 nums[i+1]) return nums[i+1];
11 | }
12 | return nums[0];
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Swift/count-all-valid-pickup-and-delivery-options.swift:
--------------------------------------------------------------------------------
1 | // Date: Mon Mar 7 17:31:50 PST 2022
2 | class Solution {
3 | func countOrders(_ n: Int) -> Int {
4 | let MOD = 1000000007
5 | var result = 1
6 | for index in 1 ... n {
7 | result *= index
8 | result = result * ( 2 * index - 1)
9 | result %= MOD
10 | }
11 | return result
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Swift/broken-calculator.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/broken-calculator/
3 | *
4 | *
5 | */
6 | // Date: Sun Feb 21 13:55:30 PST 2021
7 | class Solution {
8 | func brokenCalc(_ X: Int, _ Y: Int) -> Int {
9 | var steps = 0
10 | var y = Y
11 | while X < y {
12 | steps += 1
13 | y = y % 2 == 0 ? y / 2 : y + 1
14 | }
15 | return steps + X - y
16 | }
17 | }
--------------------------------------------------------------------------------
/Swift/reverse-string.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/reverse-string/
3 | *
4 | *
5 | */
6 | // Date: Sun May 3 15:27:06 PDT 2020
7 | class Solution {
8 | func reverseString(_ s: inout [Character]) {
9 | var start = 0
10 | var end = s.count - 1
11 | while start < end {
12 | s.swapAt(start, end)
13 | start += 1
14 | end -= 1
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Swift/running-sum-of-1d-array.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/running-sum-of-1d-array/
3 | *
4 | *
5 | */
6 | // Date: Mon May 3 13:10:40 PDT 2021
7 | class Solution {
8 | func runningSum(_ nums: [Int]) -> [Int] {
9 | var sum = 0
10 | var result: [Int] = []
11 | for n in nums {
12 | sum += n
13 | result.append(sum)
14 | }
15 | return result
16 | }
17 | }
--------------------------------------------------------------------------------
/Java/unique-paths.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public int uniquePaths(int m, int n) {
3 | int[][] count = new int[m][n];
4 | count[0][0] = 1;
5 | for(int i=0; i0) count[i][j] += count[i-1][j];
8 | if(j>0) count[i][j] += count[i][j-1];
9 | }
10 | }
11 | return count[m-1][n-1];
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Java/valid-anagram.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/valid-anagram/
3 | */
4 | public class Solution {
5 | public boolean isAnagram(String s, String t) {
6 | return sortedString(s).compareTo(sortedString(t)) == 0;
7 | }
8 |
9 | private String sortedString(String s) {
10 | char[] array = s.toCharArray();
11 | Arrays.sort(array);
12 | return new String(array);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Java/H-Index.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/h-index/
3 | */
4 |
5 | public class Solution {
6 | public int hIndex(int[] citations) {
7 | Arrays.sort(citations);
8 | int h = 0;
9 | int i = 0;
10 | for(i=citations.length-1; i>=0; i--){
11 | if(citations[i] <= h || citations[i] == 0) break;
12 | h++;
13 | }
14 |
15 | return h;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Java/add-digits.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/add-digits/
3 | * Recursively call this method until the num is smaller than 10.
4 | **/
5 | public class Solution {
6 | public int addDigits(int num) {
7 | if(num < 10) return num;
8 | int sum = 0;
9 | while(num > 0) {
10 | sum += num % 10;
11 | num /= 10;
12 | }
13 | return addDigits(sum);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Swift/best-time-to-buy-and-sell-stock-ii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func maxProfit(_ prices: [Int]) -> Int {
8 | var profit = 0
9 | if prices.isEmpty { return profit }
10 | for index in 1 ..< prices.count {
11 | profit += max(0, prices[index] - prices[index - 1])
12 | }
13 | return profit
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Swift/count-elements-with-strictly-smaller-and-greater-elements.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/
3 | *
4 | *
5 | */
6 | // Date: Mon Jan 24 11:44:59 PST 2022
7 |
8 | class Solution {
9 | func countElements(_ nums: [Int]) -> Int {
10 | let maxN = nums.max()!
11 | let minN = nums.min()!
12 | return nums.filter { $0 > minN && $0 < maxN }.count
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Swift/distribute-candies.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/distribute-candies/
3 | *
4 | *
5 | */
6 | // Date: Mon Mar 1 11:31:09 PST 2021
7 | class Solution {
8 | func distributeCandies(_ candyType: [Int]) -> Int {
9 | var count: [Int : Int] = [:]
10 | for candy in candyType {
11 | count[candy, default: 0] += 1
12 | }
13 | return min(count.keys.count, candyType.count / 2)
14 | }
15 | }
16 |
17 |
--------------------------------------------------------------------------------
/Swift/contains-duplicate.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/contains-duplicate/
3 | *
4 | *
5 | */
6 | // Date: Sat May 2 12:45:51 PDT 2020
7 | class Solution {
8 | func containsDuplicate(_ nums: [Int]) -> Bool {
9 | var set: Set = []
10 | for n in nums {
11 | if set.contains(n) {
12 | return true
13 | }
14 | set.insert(n)
15 | }
16 | return false
17 | }
18 | }
--------------------------------------------------------------------------------
/Swift/largest-number-at-least-twice-of-others.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func dominantIndex(_ nums: [Int]) -> Int {
3 | guard let largest = nums.max() else { return -1 }
4 | var index = -1
5 | for idx in 0 ..< nums.count {
6 | if nums[idx] < largest {
7 | if nums[idx] * 2 > largest { return -1 }
8 | } else if nums[idx] == largest { index = idx }
9 | }
10 | return index
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Swift/transpose-matrix.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func transpose(_ matrix: [[Int]]) -> [[Int]] {
3 | let n = matrix.count
4 | guard let m = matrix.first?.count else { return [] }
5 | var result = Array(repeating: Array(repeating: -1, count: n), count: m)
6 | for x in 0 ..< n {
7 | for y in 0 ..< m {
8 | result[y][x] = matrix[x][y]
9 | }
10 | }
11 | return result
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/GenREADME/Sources/GenREADME.swift:
--------------------------------------------------------------------------------
1 | // The Swift Programming Language
2 | // https://docs.swift.org/swift-book
3 | //
4 | // Swift Argument Parser
5 | // https://swiftpackageindex.com/apple/swift-argument-parser/documentation
6 |
7 | import ArgumentParser
8 |
9 | @main
10 | struct GenREADME: AsyncParsableCommand {
11 | mutating func run() async throws {
12 |
13 | let coreLogic = CoreLogic()
14 | try await coreLogic.coreFucntion()
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Java/delete-node-in-a-linked-list.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * public class ListNode {
4 | * int val;
5 | * ListNode next;
6 | * ListNode(int x) { val = x; }
7 | * }
8 | */
9 | public class Solution {
10 | public void deleteNode(ListNode node) {
11 | if(node.next == null) node = null;
12 | else {
13 | node.val = node.next.val;
14 | node.next = node.next.next;
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Java/number-of-1-bits.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/number-of-1-bits/
3 | *
4 | * n & (n-1) will remove the first '1' bit from right.
5 | */
6 |
7 | public class Solution {
8 | // you need to treat n as an unsigned value
9 | public int hammingWeight(int n) {
10 | int count = 0;
11 | while(n != 0){
12 | n = n & (n-1);
13 | count++;
14 | }
15 | return count;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Java/house-robber.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public int rob(int[] nums) {
3 | int n = nums.length;
4 | int[] cost = new int[n+1];
5 | int max = 0;
6 | for(int i=1; i<=n; i++) {
7 | if(i==1) cost[i] = nums[i-1];
8 | else {
9 | cost[i] = Math.max(cost[i-1], nums[i-1] + cost[i-2]);
10 | }
11 | max = Math.max(max, cost[i]);
12 | }
13 | return max;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Swift/number-of-equivalent-domino-pairs.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func numEquivDominoPairs(_ dominoes: [[Int]]) -> Int {
3 | var count: [[Int] : Int] = [:]
4 | dominoes.map { count[[min($0[0], $0[1]), max($0[0], $0[1])], default:0] += 1 }
5 |
6 | var result = 0
7 | for v in count.values {
8 | if v > 1 {
9 | result += v * (v - 1) / 2
10 | }
11 | }
12 | return result
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Java/length-of-last-word.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/length-of-last-word/
3 | *
4 | */
5 | public class Solution {
6 | public int lengthOfLastWord(String s) {
7 | int len = 0;
8 | s = s.trim();
9 | for(int i=s.length() - 1; i>=0; i--){
10 | if(s.charAt(i) == ' ') {
11 | break;
12 | } else {
13 | len++;
14 | }
15 | }
16 | return len;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Swift/minimum-value-to-get-positive-step-by-step-sum.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/
3 | *
4 | *
5 | */
6 | // Date: Sat Nov 27 09:08:39 PST 2021
7 | class Solution {
8 | func minStartValue(_ nums: [Int]) -> Int {
9 | var start = 0
10 | var sum = 0
11 | for n in nums {
12 | sum += n
13 | start = min(start, sum)
14 | }
15 | return -start + 1
16 | }
17 | }
--------------------------------------------------------------------------------
/GenREADME/Package.resolved:
--------------------------------------------------------------------------------
1 | {
2 | "originHash" : "7b13cb344ff533df802cd7179bd4d364b955f394d154c6e8bb2e4f310d05cabe",
3 | "pins" : [
4 | {
5 | "identity" : "swift-argument-parser",
6 | "kind" : "remoteSourceControl",
7 | "location" : "https://github.com/apple/swift-argument-parser.git",
8 | "state" : {
9 | "revision" : "41982a3656a71c768319979febd796c6fd111d5c",
10 | "version" : "1.5.0"
11 | }
12 | }
13 | ],
14 | "version" : 3
15 | }
16 |
--------------------------------------------------------------------------------
/Python/palindrome-number.py:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/palindrome-number/
3 | *
4 | *
5 | */
6 | // Date: Thu Mar 27 17:04:19 PDT 2025
7 | class Solution:
8 | def isPalindrome(self, x: int) -> bool:
9 | text = str(x)
10 | start = 0
11 | end = len(text) - 1
12 | while start < end:
13 | if text[start] != text[end]:
14 | return False
15 | start += 1
16 | end -= 1
17 | return True
18 |
--------------------------------------------------------------------------------
/Java/remove-duplicates-from-sorted-array.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
3 | */
4 | public class Solution {
5 | public int removeDuplicates(int[] nums) {
6 | if(nums.length == 0) return 0;
7 | int len = 0;
8 | for(int i=1; i Int {
9 | var result = 0
10 | var count = 0
11 | for n in nums {
12 | if n == 0 { count = 0 }
13 | else { count += 1 }
14 | result = max(count, result)
15 | }
16 | return result
17 | }
18 | }
--------------------------------------------------------------------------------
/Swift/k-closest-points-to-origin.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/k-closest-points-to-origin/
3 | *
4 | *
5 | */
6 | // Date: Sat May 30 09:18:01 PDT 2020
7 | class Solution {
8 | func kClosest(_ points: [[Int]], _ K: Int) -> [[Int]] {
9 | let p = points.sorted(by: { p1, p2 in
10 | return p1[0]*p1[0] + p1[1]*p1[1] < p2[0]*p2[0] + p2[1]*p2[1]
11 | })
12 | return Array(p[0 ..< K])
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Swift/minimum-consecutive-cards-to-pick-up.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func minimumCardPickup(_ cards: [Int]) -> Int {
3 | var result = cards.count + 1
4 | var record = [Int : Int]()
5 | for (index, c) in cards.enumerated() {
6 | if let lastIndex = record[c] {
7 | result = min(result, index - lastIndex + 1)
8 | }
9 | record[c] = index
10 | }
11 | return result == (cards.count + 1) ? -1 : result
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Java/powx-n.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public double myPow(double x, int n) {
3 | if(n < 0) return 1.0 / pow(x, -n);
4 | return pow(x, n);
5 | }
6 |
7 | private double pow(double x, int n) {
8 | if (x == 0) return 0;
9 | if (n == 0) return 1;
10 | if (n == 1) return x;
11 |
12 | double value = myPow(x, n/2);
13 |
14 | if(n % 2 == 0) return value * value;
15 | else return x * value * value;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Java/single-number-ii.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/single-number-ii/
3 | * x, y 两个变量。
4 | * 当同一个数第一次出现的时候,x 被设为那个数。
5 | * 当第二次出现的时候,x被清0,y被设置为那个数。
6 | * 当第三次出现的时候,y被清0。
7 | * 因为有一个数只出现一次,所以最后x就是那个数.
8 | */
9 |
10 | public class Solution {
11 | public int singleNumber(int[] nums) {
12 | int x = 0x0;
13 | int y = 0x0;
14 | for(int n : nums) {
15 | x ^= ~y & n;
16 | y ^= ~x & n;
17 | }
18 | return x;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Swift/fibonacci-number.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/fibonacci-number/
3 | *
4 | *
5 | */
6 | // Date: Thu Apr 15 11:44:25 PDT 2021
7 | class Solution {
8 |
9 | var fibNumber: [Int : Int] = [:]
10 |
11 | func fib(_ n: Int) -> Int {
12 | if let val = fibNumber[n] { return val }
13 | if n < 2 {
14 | fibNumber[n] = n
15 | return n
16 | }
17 | fibNumber[n] = fib(n - 1) + fib(n - 2)
18 | return fibNumber[n]!
19 | }
20 | }
--------------------------------------------------------------------------------
/Swift/partitioning-into-minimum-number-of-deci-binary-numbers.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/
3 | *
4 | *
5 | */
6 | // Date: Wed May 26 08:29:45 PDT 2021
7 | class Solution {
8 | func minPartitions(_ n: String) -> Int {
9 | var result = 0
10 | for c in n {
11 | if let val = Int(String(c)) {
12 | result = max(val, result)
13 | }
14 | }
15 | return result
16 | }
17 | }
--------------------------------------------------------------------------------
/Swift/range-addition-ii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/range-addition-ii/
3 | *
4 | *
5 | */
6 | // Date: Mon Aug 30 08:08:47 PDT 2021
7 | class Solution {
8 | func maxCount(_ m: Int, _ n: Int, _ ops: [[Int]]) -> Int {
9 | if ops.count == 0 { return m * n }
10 | var xmin = Int.max
11 | var ymin = Int.max
12 | for op in ops {
13 | xmin = min(xmin, op[0])
14 | ymin = min(ymin, op[1])
15 | }
16 | return xmin * ymin
17 | }
18 | }
--------------------------------------------------------------------------------
/Swift/sum-of-square-numbers.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/sum-of-square-numbers/
3 | *
4 | *
5 | */
6 | // Date: Wed Aug 25 08:57:11 PDT 2021
7 | class Solution {
8 | func judgeSquareSum(_ c: Int) -> Bool {
9 | if c <= 1 { return true }
10 | for a in 1 ... Int(sqrt(Double(c))) {
11 | if c < a * a { continue }
12 | let b = Int(sqrt(Double(c - a * a)))
13 | if a * a + b * b == c { return true }
14 | }
15 | return false
16 | }
17 | }
--------------------------------------------------------------------------------
/Swift/total-hamming-distance.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/total-hamming-distance/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func totalHammingDistance(_ nums: [Int]) -> Int {
8 | let n = nums.count
9 | var total = 0
10 | for bit in 0..<32 {
11 | var ones = 0
12 | for i in 0..> bit) & 1)
14 | }
15 | total += ones * (n - ones)
16 | }
17 | return total
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Java/find-peak-element.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Find the up trend or down trend.
3 | */
4 | public class Solution {
5 | public int findPeakElement(int[] num) {
6 | int left=0,right=num.length-1;
7 | while(left<=right){
8 | if(left==right)
9 | return left;
10 | int mid=(left+right)/2;
11 | if(num[mid] [String] {
7 | var result = [String]()
8 | for i in 1...n {
9 | var s = ""
10 | if i % 3 == 0 {
11 | s += "Fizz"
12 | }
13 | if i % 5 == 0 {
14 | s += "Buzz"
15 | }
16 | result.append(s.characters.count > 0 ? s : "\(i)")
17 | }
18 | return result
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Swift/smallest-integer-divisible-by-k.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/smallest-integer-divisible-by-k/
3 | *
4 | *
5 | */
6 | // Date: Wed Nov 25 10:54:40 PST 2020
7 | class Solution {
8 | func smallestRepunitDivByK(_ K: Int) -> Int {
9 | if K % 2 == 0 { return -1 }
10 | var len = 1
11 | var num = 1
12 | while num % K != 0 {
13 | len += 1
14 | num = (num * 10 + 1) % K
15 | if len > K { return -1 }
16 | }
17 | return len
18 | }
19 | }
--------------------------------------------------------------------------------
/Swift/best-time-to-buy-and-sell-stock.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func maxProfit(_ prices: [Int]) -> Int {
8 | guard prices.count > 0 else {return 0}
9 | let n = prices.count
10 | var maxp = 0
11 | var profit = 0
12 | for i in 0.. Int {
9 | let list = Set(arr)
10 | var count = 0
11 | for x in 1 ... 2001 {
12 | if list.contains(x) == false {
13 | count += 1
14 | }
15 | if count == k { return x }
16 | }
17 | return -1
18 | }
19 | }
--------------------------------------------------------------------------------
/Swift/palindrome-number.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/palindrome-number/
3 | *
4 | *
5 | */
6 |
7 | class Solution {
8 | func isPalindrome(_ x: Int) -> Bool {
9 | if x < 0 || (x != 0 && x % 10 == 0) {
10 | return false
11 | }
12 | var xx = x
13 | var yy = 0
14 | while (xx > yy) {
15 | let c = xx % 10
16 | yy = yy * 10 + c
17 | xx /= 10
18 | }
19 | return xx == yy || (xx == yy / 10)
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Swift/determine-if-string-halves-are-alike.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/determine-if-string-halves-are-alike/
3 | *
4 | *
5 | */
6 | // Date: Wed Apr 7 09:22:32 PDT 2021
7 | class Solution {
8 | func halvesAreAlike(_ s: String) -> Bool {
9 | let n = s.count
10 | var count = 0
11 | for (index, c) in s.lowercased().enumerated() {
12 | if "aeiou".contains(c) {
13 | count += index < n / 2 ? 1 : -1
14 | }
15 | }
16 | return count == 0
17 | }
18 | }
--------------------------------------------------------------------------------
/Swift/water-bottles.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func numWaterBottles(_ numBottles: Int, _ numExchange: Int) -> Int {
3 | var full = numBottles
4 | var empty = 0
5 | var result = 0
6 | while full > 0 || empty >= numExchange {
7 | let refill = empty / numExchange
8 | empty -= refill * numExchange
9 | full += refill
10 | result += full
11 |
12 | empty += full
13 | full = 0
14 | }
15 | return result
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Swift/left-and-right-sum-differences.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/left-and-right-sum-differences/
3 | *
4 | *
5 | */
6 | // Date: Sun Feb 26 11:27:54 PST 2023
7 | class Solution {
8 | func leftRigthDifference(_ nums: [Int]) -> [Int] {
9 | let sum = nums.reduce(0) { $0 + $1 }
10 | var leftSum = 0
11 | var result = [Int]()
12 | for n in nums {
13 | result.append(abs(sum - n - leftSum - leftSum))
14 | leftSum += n
15 | }
16 | return result
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Java/h-index-ii.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/h-index-ii/
3 | */
4 |
5 | public class Solution {
6 | public int hIndex(int[] citations) {
7 | if(citations.length == 0) return 0;
8 | int left = 0;
9 | int right = citations.length - 1;
10 | while(left <= right) {
11 | int mid = (left + right) / 2;
12 | if(citations[mid] >= citations.length - mid) right =mid-1;
13 | else left = mid + 1;
14 | }
15 | return citations.length - left;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Java/majority-element.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/majority-element/
3 | */
4 |
5 | public class Solution {
6 | public int majorityElement(int[] nums) {
7 | int result = 0;
8 | int count = 0;
9 |
10 | for(int i=0; i [Int] {
3 | guard finalSum % 2 == 0 else { return [] }
4 | var result = [Int]()
5 | var sum = 0
6 | var inc = 2
7 | while (sum + inc) <= finalSum {
8 | result.append(inc)
9 | sum += inc
10 | inc += 2
11 | }
12 | if sum < finalSum {
13 | result[result.count - 1] += finalSum - sum
14 | }
15 | return result
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Java/jump-game.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/jump-game/
3 | * Solution: Greedy to find out if the end could be reached.
4 | * Using BFS could find the path with minimum steps to reach the end.
5 | */
6 | public class Solution {
7 | public boolean canJump(int[] nums) {
8 | int max = 0;
9 | for(int i=0; i max) max = i + nums[i];
12 | }
13 | return max >= nums.length - 1;
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/Java/product-of-array-except-self.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public int[] productExceptSelf(int[] nums) {
3 | int[] result = new int[nums.length];
4 | result[result.length-1] = 1;
5 |
6 | for(int i=nums.length-2; i>=0; i--) {
7 | result[i] = result[i+1] * nums[i+1];
8 | }
9 |
10 | int left = 1;
11 | for(int i=0; i String {
9 | var result = ""
10 | for c in S {
11 | if let last = result.last, last == c {
12 | result.removeLast()
13 | } else {
14 | result.append(c)
15 | }
16 | }
17 | return result
18 | }
19 | }
--------------------------------------------------------------------------------
/Swift/short-encoding-of-words.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/short-encoding-of-words/
3 | *
4 | *
5 | */
6 | // Date: Mon Mar 8 17:30:53 PST 2021
7 | class Solution {
8 | func minimumLengthEncoding(_ words: [String]) -> Int {
9 | var count = 0
10 | let array:[String] = words.map({String($0.reversed())}).sorted()
11 | for i in 0.. set = new HashSet();
13 | for(int x : nums) {
14 | if(set.contains(x)) return true;
15 | set.add(x);
16 | }
17 | return false;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Java/rectangle-area.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
3 | if(C 0 && nums[len-1] == val) len--;
10 | if(len > i) {
11 | nums[i] = nums[len - 1];
12 | len--;
13 | }
14 | }
15 | }
16 | return len;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Swift/meeting-rooms.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func canAttendMeetings(_ intervals: [[Int]]) -> Bool {
3 | let sortedIntervals = intervals.sorted { itvA, itvB in
4 | if itvA[0] == itvB[0] { return itvA[1] > itvB[1] }
5 | return itvA[0] < itvB[0]
6 | }
7 |
8 | for index in stride(from: 1, to: sortedIntervals.count, by: 1) {
9 | if sortedIntervals[index][0] >= sortedIntervals[index - 1][1] { continue }
10 | else { return false }
11 | }
12 | return true
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Swift/number-complement.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/number-complement/
3 | *
4 | *
5 | */
6 | // Date: Mon May 4 08:59:44 PDT 2020
7 | class Solution {
8 | func findComplement(_ num: Int) -> Int {
9 | if num == 0 { return 1 }
10 | var ret = 0
11 | var num = num
12 | var bit = 0
13 | while num > 0 {
14 | if num % 2 == 0 {
15 | ret += (1 << bit)
16 | }
17 | num /= 2
18 | bit += 1
19 | }
20 | return ret
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Swift/concatenation-of-consecutive-binary-numbers.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/
3 | *
4 | *
5 | */
6 | // Date: Wed Jan 27 14:05:46 PST 2021
7 | class Solution {
8 | // f(n) = f(n-1) * 2^(n_binary_length) + n
9 | func concatenatedBinary(_ n: Int) -> Int {
10 | let d = 1_000_000_007
11 | var x = 0
12 | for i in stride(from: 1, through: n, by: 1) {
13 | x = ((x << (i.bitWidth - i.leadingZeroBitCount)) + i) % d
14 | }
15 | return x
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Swift/task-scheduler.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/task-scheduler/
3 | *
4 | *
5 | */
6 | // Date: Tue Jul 28 22:41:23 PDT 2020
7 | class Solution {
8 | func leastInterval(_ tasks: [Character], _ n: Int) -> Int {
9 | var dict = [Character : Int]()
10 | for task in tasks {
11 | dict[task, default : 0] += 1
12 | }
13 | let maxV = dict.values.max()!
14 | let numsOfMax = dict.values.filter { $0 == maxV }.count
15 | return max(tasks.count, (maxV - 1) * (n + 1) + numsOfMax)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Swift/happy-number.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/happy-number/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func isHappy(_ n: Int) -> Bool {
8 | var n = n
9 | var list: Set = [n]
10 | while n > 1 {
11 | var sum = 0
12 | while n > 0 {
13 | sum += (n % 10) * (n % 10)
14 | n /= 10
15 | }
16 | if list.contains(sum) { return false }
17 | list.insert(sum)
18 | n = sum
19 | }
20 | return true
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Swift/length-of-last-word.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/length-of-last-word/
3 | *
4 | *
5 | *
6 | */
7 |
8 | class Solution {
9 | func lengthOfLastWord(_ s: String) -> Int {
10 | var len = 0
11 | let rev = String(s.trimmingCharacters(in: .whitespacesAndNewlines).characters.reversed())
12 | for c in rev.characters {
13 | if String(c) == " " {
14 | return len
15 | } else {
16 | len += 1
17 | }
18 | }
19 | return len
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Java/remove-duplicates-from-sorted-array-ii.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public int removeDuplicates(int[] nums) {
3 | if(nums.length == 0) return 0;
4 | boolean added = false;
5 | int index = 1;
6 | for(int i=1; i Bool {
10 | var dict: [Int : [Int]] = [:]
11 | for x in pieces {
12 | dict[x[0]] = x
13 | }
14 | var result = [Int]()
15 | for x in arr {
16 | result += dict[x, default: []]
17 | }
18 | return result == arr
19 | }
20 | }
--------------------------------------------------------------------------------
/Java/maximum-depth-of-binary-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/maximum-depth-of-binary-tree/
3 | * Solution: Find the Height of Binary Tree.
4 | *
5 | *
6 | * Definition for a binary tree node.
7 | * public class TreeNode {
8 | * int val;
9 | * TreeNode left;
10 | * TreeNode right;
11 | * TreeNode(int x) { val = x; }
12 | * }
13 | */
14 | public class Solution {
15 | public int maxDepth(TreeNode root) {
16 | if(root == null) return 0;
17 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Swift/power-of-three.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/power-of-three/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func isPowerOfThree(_ n: Int) -> Bool {
8 | var n = n
9 | while n > 1 {
10 | if n % 3 != 0 { return false }
11 | n /= 3
12 | }
13 | return n == 1
14 | }
15 | }
16 |
17 | /// 3 ^ (⌊log3MaxInt⌋) = 3 ^ ⌊19.56⌋ =3^19 =1162261467
18 | /// This is a very mathematica way.
19 | class Solution {
20 | func isPowerOfThree(_ n: Int) -> Bool {
21 | return n > 0 && 1162261467 % n == 0
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Java/happy-number.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/happy-number/
3 | */
4 |
5 | public class Solution {
6 | public boolean isHappy(int n) {
7 | return isHappy(n, new HashSet());
8 | }
9 |
10 | private boolean isHappy(int n, HashSet set) {
11 | if(set.contains(n)) return false;
12 | if(n == 1) return true;
13 | set.add(n);
14 | int sum = 0;
15 | while(n > 0) {
16 | sum += (n%10) * (n%10);
17 | n /= 10;
18 | }
19 | return isHappy(sum, set);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Swift/number-of-segments-in-a-string.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/number-of-segments-in-a-string/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func countSegments(_ s: String) -> Int {
8 | var count = 0
9 | var flag = false
10 | for c in s.lowercased().characters {
11 | if " " != String(c) {
12 | flag = true
13 | } else {
14 | if flag { count += 1 }
15 | flag = false
16 | }
17 | }
18 | if flag { count += 1 }
19 | return count
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Java/search-insert-position.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/search-insert-position/
3 | */
4 | public class Solution {
5 | public int searchInsert(int[] nums, int target) {
6 | int left = 0;
7 | int right = nums.length-1;
8 | while(left Int {
9 | var left = 0
10 | var right = citations.count
11 | while left < right {
12 | let mid = left + (right - left) / 2
13 | if citations[mid] < (citations.count - mid) {
14 | left = mid + 1
15 | } else {
16 | right = mid
17 | }
18 | }
19 | return citations.count - left
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Swift/longest-harmonious-subsequence.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/longest-harmonious-subsequence/
3 | *
4 | *
5 | */
6 | // Date: Thu Feb 4 13:57:16 PST 2021
7 | class Solution {
8 | func findLHS(_ nums: [Int]) -> Int {
9 | var map: [Int : Int] = [:]
10 | for x in nums {
11 | map[x, default: 0] += 1
12 | }
13 | var result = 0
14 | for key in map.keys {
15 | if let x = map[key], let y = map[key + 1] {
16 | result = max(result, x + y)
17 | }
18 | }
19 | return result
20 | }
21 | }
--------------------------------------------------------------------------------
/Swift/orderly-queue.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/orderly-queue/
3 | *
4 | *
5 | */
6 | // Date: Mon Sep 6 18:33:39 PDT 2021
7 | class Solution {
8 | func orderlyQueue(_ s: String, _ k: Int) -> String {
9 | if k > 1 { return String(s.sorted()) }
10 | var minS = s
11 | let s = Array(s)
12 | for index in stride(from: 1, to: s.count, by: 1) {
13 | let text = String(s[index ..< s.count] + s[0 ..< index])
14 |
15 | if minS > text {
16 | minS = text
17 | }
18 | }
19 | return minS
20 | }
21 | }
--------------------------------------------------------------------------------
/Swift/boats-to-save-people.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/boats-to-save-people/
3 | *
4 | *
5 | */
6 | // Date: Wed Jan 13 09:32:10 PST 2021
7 | class Solution {
8 | func numRescueBoats(_ people: [Int], _ limit: Int) -> Int {
9 | let p = people.sorted()
10 | var left = 0
11 | var right = p.count - 1
12 | var result = 0
13 | while left <= right {
14 | result += 1
15 | if p[left] + p[right] <= limit {
16 | left += 1
17 | }
18 | right -= 1
19 | }
20 | return result
21 | }
22 | }
--------------------------------------------------------------------------------
/Swift/set-mismatch.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/set-mismatch/
3 | *
4 | *
5 | */
6 | // Date: Tue Mar 2 13:53:28 PST 2021
7 | class Solution {
8 | func findErrorNums(_ nums: [Int]) -> [Int] {
9 | var cand: Set = []
10 | var missing = -1
11 | var sum = (1 + nums.count) * nums.count / 2
12 | for x in nums {
13 | if cand.contains(x) == false{
14 | cand.insert(x)
15 | sum -= x
16 | } else {
17 | missing = x
18 | }
19 | }
20 | return [missing, sum]
21 | }
22 | }
--------------------------------------------------------------------------------
/Swift/valid-perfect-square.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/valid-perfect-square/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func isPerfectSquare(_ num: Int) -> Bool {
8 | var left = 1
9 | var right = num
10 | while left <= right {
11 | let mid = left + (right - left) / 2
12 | if mid * mid == num {
13 | return true
14 | } else if mid * mid > num {
15 | right = mid - 1
16 | } else {
17 | left = mid + 1
18 | }
19 | }
20 | return false
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Swift/next-greater-element-i.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/next-greater-element-i/
3 | *
4 | *
5 | */
6 | // Date: Tue Dec 1 11:13:44 PST 2020
7 | class Solution {
8 | func nextGreaterElement(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
9 | var map: [Int : Int] = [:]
10 | var stack: [Int] = []
11 | for n in nums2 {
12 | while let last = stack.last, last < n {
13 | map[last] = n
14 | stack.removeLast()
15 | }
16 | stack.append(n)
17 | }
18 | return nums1.map { map[$0, default: -1] }
19 | }
20 | }
--------------------------------------------------------------------------------
/Swift/angle-between-hands-of-a-clock.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/angle-between-hands-of-a-clock/
3 | *
4 | *
5 | */
6 | // Date: Tue Jul 14 07:13:21 PDT 2020
7 | class Solution {
8 | /// With the exp of making app: https://apps.apple.com/us/app/spclock/id1233980440
9 | /// This one is quite similar.
10 | func angleClock(_ hour: Int, _ minutes: Int) -> Double {
11 | let minAngle = Double(minutes) * 6
12 | let hourAngle = Double(hour % 12) * 30 + Double(minutes) / 2
13 | let offset = abs(minAngle - hourAngle)
14 | return min(offset, 360.0 - offset)
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Swift/max-number-of-k-sum-pairs.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/max-number-of-k-sum-pairs/
3 | *
4 | *
5 | */
6 | // Date: Mon Jan 18 08:52:06 PST 2021
7 | class Solution {
8 | func maxOperations(_ nums: [Int], _ k: Int) -> Int {
9 | var result = 0
10 | var visited: [Int : Int] = [:]
11 | for x in nums {
12 | if let c = visited[k - x], c > 0 {
13 | result += 1
14 | visited[k - x] = c - 1
15 | } else {
16 | visited[x] = 1 + visited[x, default: 0]
17 | }
18 | }
19 | return result
20 | }
21 | }
--------------------------------------------------------------------------------
/Swift/binary-search.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/binary-search/
3 | *
4 | *
5 | */
6 | // Date: Thu Oct 8 08:54:13 PDT 2020
7 | class Solution {
8 | func search(_ nums: [Int], _ target: Int) -> Int {
9 | var left = 0
10 | var right = nums.count - 1
11 | while left <= right {
12 | let mid = left + (right - left) / 2
13 | if nums[mid] == target { return mid }
14 | if nums[mid] > target {
15 | right = mid - 1
16 | } else {
17 | left = mid + 1
18 | }
19 | }
20 | return -1
21 | }
22 | }
--------------------------------------------------------------------------------
/Swift/validate-stack-sequences.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/validate-stack-sequences/
3 | *
4 | *
5 | */
6 | // Date: Tue Mar 2 14:23:09 PST 2021
7 | class Solution {
8 | func validateStackSequences(_ pushed: [Int], _ popped: [Int]) -> Bool {
9 | var simulStack: [Int] = []
10 | var index = 0
11 | for x in pushed {
12 | simulStack.append(x)
13 | while let last = simulStack.last, popped[index] == last {
14 | simulStack.removeLast()
15 | index += 1
16 | }
17 | }
18 | return index == pushed.count
19 | }
20 | }
--------------------------------------------------------------------------------
/.github/workflows/README_Generator.yml:
--------------------------------------------------------------------------------
1 | name: README Generator
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | jobs:
10 | build:
11 |
12 | runs-on: macos-latest
13 |
14 | steps:
15 | - uses: actions/checkout@v2
16 | - name: Regenerate README.md
17 | run: swift readme_gen.swift > README.md
18 | - name: Check if README updated
19 | run: |
20 | ! git diff --quiet
21 | - name: Push and Save
22 | if: ${{ success() }}
23 | run: |
24 | git add README.md
25 | git commit -m "Regenerate README file."
26 | git push
27 |
--------------------------------------------------------------------------------
/Swift/jewels-and-stones.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/jewels-and-stones/
3 | *
4 | *
5 | */
6 | // Date: Sat May 2 12:59:05 PDT 2020
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(len(J) + len(S))
10 | /// - Space: O(len(J))
11 | ///
12 | func numJewelsInStones(_ J: String, _ S: String) -> Int {
13 | let jews = Set(Array(J).map { String($0) })
14 | var count = 0
15 | for c in S {
16 | if jews.contains(String(c)) {
17 | count += 1
18 | }
19 | }
20 | return count
21 |
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/n-th-tribonacci-number.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/n-th-tribonacci-number/
3 | *
4 | *
5 | */
6 | // Date: Fri Sep 24 00:24:13 PDT 2021
7 | class Solution {
8 | func tribonacci(_ n: Int) -> Int {
9 | if n == 0 { return 0 }
10 | if n == 1 { return 1 }
11 | if n == 2 { return 1 }
12 |
13 | var a = 0
14 | var b = 1
15 | var c = 1
16 |
17 | for x in stride(from: 3, through: n, by: 1) {
18 | let next = a + b + c
19 | a = b
20 | b = c
21 | c = next
22 | }
23 | return c
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/reverse-bits.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/reverse-bits/
3 | *
4 | *
5 | */
6 | class Solution {
7 | /// n is 32 bit integer.
8 | /// Thus,
9 | /// - Complexity: O(32) = O(1)
10 | ///
11 | func reverseBits(_ n: Int) -> Int {
12 | var n = n
13 | var sum = 0
14 | var count = 32
15 | while n > 0 || count > 0 {
16 | if n > 0 {
17 | sum = (sum << 1) + n % 2
18 | n /= 2
19 | } else {
20 | sum = sum << 1
21 | }
22 | count -= 1
23 | }
24 | return sum
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Swift/check-if-all-1s-are-at-least-length-k-places-away.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/
3 | *
4 | *
5 | */
6 | // Date: Mon Jan 25 10:13:51 PST 2021
7 | class Solution {
8 | func kLengthApart(_ nums: [Int], _ k: Int) -> Bool {
9 | var lastIndex: Int? = nil
10 | for index in 0 ..< nums.count {
11 | if nums[index] == 1 {
12 | if let last = lastIndex, index - last <= k {
13 | return false
14 | }
15 | lastIndex = index
16 | }
17 | }
18 | return true
19 | }
20 | }
--------------------------------------------------------------------------------
/Java/generate-parentheses.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 |
3 | private List list;
4 | public List generateParenthesis(int n) {
5 | list = new ArrayList();
6 | backtrack(n, 0, 0, "");
7 | return list;
8 | }
9 |
10 | private void backtrack(int n, int left, int right, String ret) {
11 | if(n == left && n == right) {
12 | list.add(ret);
13 | return;
14 | }
15 |
16 | if(left < n)
17 | backtrack(n, left + 1, right, ret+"(");
18 | if(left > right)
19 | backtrack(n, left, right+1, ret+")");
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Java/longest-valid-parentheses.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public int longestValidParentheses(String s) {
3 | int n = s.length();
4 | int[] mark = new int[n+1];
5 | mark[0] = 0;
6 | int maxLen = 0;
7 | for(int i=1; i<=n; i++) {
8 | mark[i] = 0;
9 | if(s.charAt(i-1) == ')') {
10 | int j = i - 2 - mark[i-1];
11 | if(j >= 0 && s.charAt(j) == '(') {
12 | mark[i] = mark[i-1] + mark[j] + 2;
13 | }
14 | }
15 | maxLen = Math.max(maxLen, mark[i]);
16 | }
17 | return maxLen;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Swift/domino-and-tromino-tiling.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | // Ref: https://leetcode.com/problems/domino-and-tromino-tiling/discuss/116581/Detail-and-explanation-of-O(n)-solution-why-dpn2*dn-1%2Bdpn-3
3 | func numTilings(_ n: Int) -> Int {
4 | let MOD = 1000000007
5 | var cache = Array(repeating: -1, count: 1001)
6 | cache[0] = 0
7 | cache[1] = 1
8 | cache[2] = 2
9 | cache[3] = 5
10 | if n <= 3 { return cache[n] }
11 | for x in 4 ... n {
12 | cache[x] = 2 * cache[x - 1] + cache[x - 3]
13 | cache[x] %= MOD
14 | }
15 | return cache[n]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Swift/h-index.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/h-index/
3 | *
4 | *
5 | */
6 | // Date: Tue Aug 11 10:24:05 PDT 2020
7 | class Solution {
8 | func hIndex(_ citations: [Int]) -> Int {
9 | let n = citations.count
10 | var bucket = Array(repeating: 0, count: n + 1)
11 | for c in citations {
12 | bucket[min(c, n)] += 1
13 | }
14 | var count = 0
15 | for index in stride(from: n, through: 0, by: -1) {
16 | count += bucket[index]
17 | if count >= index {
18 | return index
19 | }
20 | }
21 | return 0
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Java/find-the-duplicate-number.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/find-the-duplicate-number/
3 | *
4 | * Binary Search.
5 | */
6 |
7 | public class Solution {
8 | public int findDuplicate(int[] nums) {
9 | int left = 1;
10 | int right = nums.length - 1;
11 | while(left < right) {
12 | int mid = (left + right) / 2;
13 | int g = 0;
14 | for(int i=0; i Int {
9 | var count: [Int : Int] = [:]
10 | for row in wall {
11 | var index = 0
12 | for brick in row.dropLast() {
13 | index += brick
14 | count[index, default: 0] += 1
15 | }
16 | }
17 | var result = wall.count
18 | for num in count.values {
19 | result = min(result, wall.count - num)
20 | }
21 | return result
22 | }
23 | }
--------------------------------------------------------------------------------
/Swift/find-the-divisibility-array-of-a-string.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/find-the-divisibility-array-of-a-string/
3 | *
4 | *
5 | */
6 | // Date: Sun Feb 26 11:24:24 PST 2023
7 | class Solution {
8 | func divisibilityArray(_ word: String, _ m: Int) -> [Int] {
9 | var rem = 0
10 | var result = [Int]()
11 | for x in word {
12 | rem = rem * 10 + Int(String(x))!
13 | if rem % m == 0 {
14 | result.append(1)
15 | } else {
16 | result.append(0)
17 | }
18 | rem = rem % m
19 | }
20 | return result
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Swift/perfect-squares.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/perfect-squares/
3 | *
4 | *
5 | */
6 | // Date: Sat Jun 27 11:19:12 PDT 2020
7 | class Solution {
8 | func numSquares(_ n: Int) -> Int {
9 | var steps = Array(repeating: Int.max, count: n + 1)
10 | steps[0] = 0
11 | for x in 1 ... n {
12 | var minStep = steps[x]
13 | var dx = 1
14 | while (x - dx * dx) >= 0 {
15 | minStep = min(minStep, 1 + steps[x - dx * dx])
16 | dx += 1
17 | }
18 | steps[x] = minStep
19 | }
20 |
21 | return steps[n]
22 | }
23 | }
--------------------------------------------------------------------------------
/Swift/meeting-rooms-ii.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func minMeetingRooms(_ intervals: [[Int]]) -> Int {
3 | var start = [Int]()
4 | var end = [Int]()
5 | for intv in intervals {
6 | start.append(intv[0])
7 | end.append(intv[1])
8 | }
9 | start.sort()
10 | end.sort()
11 |
12 | var result = 0
13 | var lastEnd = 0
14 | for index in 0 ..< start.count {
15 | if start[index] < end[lastEnd] {
16 | result += 1
17 | } else {
18 | lastEnd += 1
19 | }
20 | }
21 | return result
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/shifting-letters.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/shifting-letters/
3 | *
4 | *
5 | */
6 | // Date: Wed Sep 8 21:47:54 PDT 2021
7 | class Solution {
8 | func shiftingLetters(_ s: String, _ shifts: [Int]) -> String {
9 | let s = Array(s)
10 | var sum = 0
11 | var result = ""
12 | for index in stride(from: s.count - 1, through: 0, by: -1) {
13 | sum += shifts[index]
14 | let a = (Int(s[index].asciiValue!) - 97 + sum) % 26 + 97
15 | let c = Character(Unicode.Scalar(UInt8(a)))
16 | result = String(c) + result
17 | }
18 | return result
19 | }
20 | }
--------------------------------------------------------------------------------
/Java/same-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/same-tree/
3 | *
4 | * Definition for a binary tree node.
5 | * public class TreeNode {
6 | * int val;
7 | * TreeNode left;
8 | * TreeNode right;
9 | * TreeNode(int x) { val = x; }
10 | * }
11 | */
12 | public class Solution {
13 | public boolean isSameTree(TreeNode p, TreeNode q) {
14 | if(p == null && q == null) return true;
15 | if(p == null && q != null) return false;
16 | if(p != null && q == null) return false;
17 | if(p.val != q.val) return false;
18 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Swift/array-of-doubled-pairs.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/array-of-doubled-pairs/
3 | *
4 | *
5 | */
6 | // Date: Wed Aug 11 16:53:37 PDT 2021
7 | class Solution {
8 | func canReorderDoubled(_ arr: [Int]) -> Bool {
9 | var count: [Int : Int] = [:]
10 | for n in arr {
11 | count[n, default: 0] += 1
12 | }
13 |
14 | let keys = count.keys.sorted { abs($0) < abs($1) }
15 |
16 | for key in keys {
17 | if count[key, default: 0] > count[key * 2, default: 0] { return false }
18 | count[key * 2, default: 0] -= count[key, default: 0]
19 | }
20 | return true
21 | }
22 | }
--------------------------------------------------------------------------------
/Swift/find-the-most-competitive-subsequence.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/find-the-most-competitive-subsequence/
3 | *
4 | *
5 | */
6 | // Date: Thu Jan 21 13:05:04 PST 2021
7 | class Solution {
8 | func mostCompetitive(_ nums: [Int], _ k: Int) -> [Int] {
9 | var result = [Int]()
10 | for index in 0 ..< nums.count {
11 | while let last = result.last, last > nums[index], nums.count - index + result.count > k {
12 | result.removeLast()
13 | }
14 | if result.count < k {
15 | result.append(nums[index])
16 | }
17 | }
18 | return result
19 | }
20 | }
--------------------------------------------------------------------------------
/Java/count-primes.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/count-primes/
3 | */
4 | public class Solution {
5 | public int countPrimes(int n) {
6 | int count = 0;
7 | for(int i=1; i> i) & 1;
16 | int aj = (n >> j) & 1;
17 | return n + (aj - ai) * ((1< Int {
9 | var start = 0
10 | var result = 0
11 | var K = 0
12 | for end in 0 ..< nums.count {
13 | if nums[end] == 0 { K += 1 }
14 | if K > k {
15 | if nums[start] == 0 { K -= 1 }
16 | start += 1
17 | }
18 | print(start, end)
19 | result = max(result, end - start + 1)
20 | }
21 | return result
22 | }
23 | }
--------------------------------------------------------------------------------
/Swift/minimum-flips-to-make-a-or-b-equal-to-c.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func minFlips(_ a: Int, _ b: Int, _ c: Int) -> Int {
8 | var count = 0
9 | var a = a
10 | var b = b
11 | var c = c
12 | while a > 0 || b > 0 || c > 0 {
13 | if c % 2 == 1 {
14 | count += 1 - ((a % 2) | (b % 2))
15 | } else {
16 | count += (a % 2) + (b % 2)
17 | }
18 | c /= 2
19 | b /= 2
20 | a /= 2
21 | }
22 | return count
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Java/move-zeroes.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/move-zeroes/
3 | */
4 |
5 | public class Solution {
6 | public void moveZeroes(int[] nums) {
7 | int z = 0;
8 | while(z < nums.length && nums[z] != 0) z++;
9 | if(z == nums.length) return;
10 | for(int i=0; i z) {
12 | int tmp = nums[i];
13 | nums[i] = nums[z];
14 | nums[z] = tmp;
15 | z++;
16 | while(z < nums.length && nums[z] != 0) z++;
17 | if(z == nums.length) break;
18 | }
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Swift/majority-element-ii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/majority-element-ii/
3 | *
4 | *
5 | */
6 | // Date: Tue Sep 22 09:48:02 PDT 2020
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(n)
10 | /// - Space: O(n)
11 | func majorityElement(_ nums: [Int]) -> [Int] {
12 | var count: [Int : Int] = [:]
13 | let n = nums.count
14 | var result: Set = []
15 | for num in nums {
16 | count[num] = count[num, default: 0] + 1
17 | if count[num, default: 0] > n / 3 {
18 | result.insert(num)
19 | }
20 | }
21 | return Array(result)
22 | }
23 | }
--------------------------------------------------------------------------------
/Swift/stone-game-viii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/stone-game-viii/
3 | *
4 | *
5 | */
6 | // Date: Sun Aug 29 16:30:41 PDT 2021
7 | class Solution {
8 | func stoneGameVIII(_ stones: [Int]) -> Int {
9 | let n = stones.count
10 | var sums = Array(repeating: 0, count: n)
11 | for index in 0 ..< n {
12 | sums[index] = stones[index] + (index > 0 ? sums[index - 1] : 0)
13 | }
14 |
15 | // print(sums)
16 | var result = sums[n - 1]
17 | for index in stride(from: n - 1, to: 1, by: -1) {
18 | result = max(result, sums[index - 1] - result)
19 | }
20 | return result
21 | }
22 | }
--------------------------------------------------------------------------------
/Java/longest-common-prefix.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/longest-common-prefix/
3 | */
4 | public class Solution {
5 | public String longestCommonPrefix(String[] strs) {
6 | if(strs.length == 0) return "";
7 | int len = 0;
8 | while(len < strs[0].length()) {
9 | char c = strs[0].charAt(len);
10 | for(int i=0; i= strs[i].length() || c != strs[i].charAt(len)) {
12 | return strs[0].substring(0, len);
13 | }
14 | }
15 | len ++;
16 | }
17 | return strs[0].substring(0, len);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Swift/coin-change-2.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/coin-change-2/
3 | *
4 | *
5 | */
6 | // Date: Sun Jun 7 11:13:38 PDT 2020
7 | class Solution {
8 | func change(_ amount: Int, _ coins: [Int]) -> Int {
9 | let coins = coins.sorted()
10 | var dp = Array(repeating: 0, count: amount + 1)
11 | dp[0] = 1
12 | for index in 0 ..< coins.count {
13 | if amount >= coins[index] {
14 | for total in coins[index] ... amount {
15 | dp[total] += dp[total - coins[index]]
16 | }
17 | }
18 | }
19 | print("\(dp)")
20 | return dp[amount]
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Swift/implement-strstr.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/implement-strstr/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func strStr(_ haystack: String, _ needle: String) -> Int {
8 | let hay = haystack.characters.map() {"\($0)"}
9 | let pat = needle.characters.map() {"\($0)"}
10 | var i = 0
11 | while true {
12 | var j = 0
13 | while true {
14 | if j == pat.count {return i}
15 | if i+j==hay.count {return -1}
16 | if hay[i+j] != pat[j] { break }
17 | j += 1
18 | }
19 | i += 1
20 | }
21 | return 0
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/jump-game.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/jump-game/
3 | *
4 | *
5 | */
6 | // Date: Sat Apr 25 11:12:14 PDT 2020
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(n), where n is the number of elements in the array.
10 | /// - Space: O(1).
11 | ///
12 | func canJump(_ nums: [Int]) -> Bool {
13 | guard nums.count > 0 else { return true }
14 | var far = nums[0]
15 | for index in 1 ..< nums.count {
16 | if index > far {
17 | return false
18 | }
19 | far = max(far, index + nums[index])
20 | }
21 | return far >= nums.count - 1
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/largest-number.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/largest-number/
3 | *
4 | *
5 | */
6 | // Date: Fri Sep 25 09:36:51 PDT 2020
7 | class Solution {
8 | func largestNumber(_ nums: [Int]) -> String {
9 | let nums = nums.map { String($0) }.sorted(by: {
10 | let n1 = Int($0 + $1)!
11 | let n2 = Int($1 + $0)!
12 | return n1 > n2
13 | })
14 | var result = nums.joined()
15 | while result.count > 1 {
16 | if let first = result.first, let n = Int(String(first)), n == 0 {
17 | result.removeFirst()
18 | } else { break }
19 | }
20 | return result
21 | }
22 | }
--------------------------------------------------------------------------------
/Swift/pascals-triangle.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/pascals-triangle/
3 | *
4 | *
5 | */
6 | // Date: Tue Apr 21 14:02:24 PDT 2020
7 | class Solution {
8 | func generate(_ numRows: Int) -> [[Int]] {
9 | var result: [[Int]] = []
10 | for row in 0 ..< numRows {
11 | var list = [1]
12 | if let last = result.last {
13 | for index in 0 ..< row {
14 | let sum = last[index] + (index + 1 < last.count ? last[index + 1] : 0)
15 | list.append(sum)
16 | }
17 | }
18 | result.append(list)
19 | }
20 | return result
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Swift/reduce-array-size-to-the-half.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/reduce-array-size-to-the-half/
3 | *
4 | *
5 | */
6 | // Date: Tue Jul 6 08:06:50 PDT 2021
7 | class Solution {
8 | func minSetSize(_ arr: [Int]) -> Int {
9 | var count: [Int : Int] = [:]
10 | for n in arr {
11 | count[n, default: 0] += 1
12 | }
13 | var n = arr.count
14 | let values = count.values.sorted { $0 > $1 }
15 | for index in stride(from: 0, to: values.count, by: 1) {
16 | n -= values[index]
17 | if n * 2 <= arr.count { return index + 1 }
18 | }
19 | return values.count
20 | }
21 | }
22 |
23 |
--------------------------------------------------------------------------------
/Swift/remove-digit-from-number-to-maximize-result.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func removeDigit(_ number: String, _ digit: Character) -> String {
3 | var num = Array(number)
4 | for (index, c) in number.enumerated() {
5 | if c == digit, index < num.count - 1, num[index + 1] > c {
6 | num.remove(at: index)
7 | return String(num)
8 | }
9 | }
10 | for index in stride(from: number.count - 1, through: 0, by: -1) {
11 | if num[index] == digit {
12 | num.remove(at: index)
13 | return String(num)
14 | }
15 | }
16 | return ""
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Swift/repeated-dna-sequences.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/repeated-dna-sequences/
3 | *
4 | *
5 | */
6 | // Date: Thu Oct 29 10:54:27 PDT 2020
7 | class Solution {
8 | func findRepeatedDnaSequences(_ s: String) -> [String] {
9 | var result: Set = []
10 | var visited: Set = []
11 | let list = Array(s)
12 | for index in stride(from: 9, to: list.count, by: 1) {
13 | let text = String(list[index - 9 ... index])
14 | if visited.contains(text) {
15 | result.insert(text)
16 | }
17 | visited.insert(text)
18 | }
19 | return Array(result)
20 | }
21 | }
--------------------------------------------------------------------------------
/Swift/maximum-subarray-sum-with-one-deletion.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/
3 | *
4 | *
5 | */
6 | // Date: Tue May 26 13:48:29 PDT 2020
7 | class Solution {
8 | func maximumSum(_ arr: [Int]) -> Int {
9 | guard arr.count > 0 else { return 0 }
10 | var maxsum = arr[0]
11 | var delsum = arr[0]
12 | var keepsum = arr[0]
13 | for index in 1 ..< arr.count {
14 | delsum = max(keepsum, delsum + arr[index])
15 | keepsum = max(keepsum + arr[index], arr[index])
16 | maxsum = max(maxsum, max(delsum, keepsum))
17 | }
18 | return maxsum
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Swift/rank-transform-of-an-array.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/rank-transform-of-an-array/
3 | *
4 | *
5 | */
6 | // Date: Mon Aug 9 16:53:13 PDT 2021
7 | class Solution {
8 | func arrayRankTransform(_ arr: [Int]) -> [Int] {
9 | let sorted = arr.sorted()
10 | var map: [Int : Int] = [:]
11 | var rank = 1
12 | for n in sorted {
13 | if map[n] == nil {
14 | map[n] = rank
15 | rank += 1
16 | }
17 | }
18 |
19 | var result = [Int]()
20 | for n in arr {
21 | result.append(map[n, default: -1])
22 | }
23 | return result
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/teemo-attacking.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/teemo-attacking/
3 | *
4 | *
5 | */
6 | // Date: Tue Sep 29 16:09:15 PDT 2020
7 | class Solution {
8 | func findPoisonedDuration(_ timeSeries: [Int], _ duration: Int) -> Int {
9 | guard let startTimestamp = timeSeries.first else { return 0 }
10 | var endTimestamp = startTimestamp + duration - 1
11 | var result = duration
12 | for index in stride(from: 1, to: timeSeries.count, by: 1) {
13 | let end = timeSeries[index] + duration - 1
14 | result += min(duration, end - endTimestamp)
15 | endTimestamp = end
16 | }
17 | return result
18 | }
19 | }
--------------------------------------------------------------------------------
/Java/reverse-integer.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/reverse-integer/
3 | *
4 | * Very tricky problem, requires checking result boundary before returning.
5 | */
6 |
7 | public class Solution {
8 | public int reverse(int x) {
9 | long ret = rev(x);
10 | if(ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) return 0;
11 | return (int)ret;
12 | }
13 |
14 | private long rev(long x) {
15 | boolean flag = x < 0;
16 | x = x < 0 ? -x : x;
17 | long p = 0;
18 | while(x > 0) {
19 | p = p * 10 + x % 10;
20 | x /= 10;
21 | }
22 | return flag ? -p : p;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Swift/battleships-in-a-board.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/battleships-in-a-board/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func countBattleships(_ board: [[Character]]) -> Int {
8 | let n = board.count
9 | guard n > 0 else { return 0}
10 | let m = board[0].count
11 | var count = 0
12 | for i in 0..0, String(board[i-1][j])=="X" {continue}
16 | if j>0, String(board[i][j-1])=="X" {continue}
17 | count += 1
18 | }
19 | }
20 | return count
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Swift/check-if-every-row-and-column-contains-all-numbers.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/
3 | *
4 | *
5 | */
6 | // Date: Fri Jan 21 19:44:31 PST 2022
7 | class Solution {
8 | func checkValid(_ matrix: [[Int]]) -> Bool {
9 | let n = matrix.count
10 | for x in 0 ..< n {
11 | var rows = Set()
12 | var cols = Set()
13 | for y in 0 ..< n {
14 | rows.insert(matrix[x][y])
15 | cols.insert(matrix[y][x])
16 | }
17 | if rows.count != n || cols.count != n { return false }
18 | }
19 | return true
20 | }
21 | }
--------------------------------------------------------------------------------
/Swift/delete-and-earn.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/delete-and-earn/
3 | *
4 | *
5 | */
6 | // Date: Sat Mar 5 15:00:12 PST 2022
7 | class Solution {
8 | func deleteAndEarn(_ nums: [Int]) -> Int {
9 | let n = 10000
10 | var sum = [Int : Int]()
11 | for n in nums {
12 | sum[n, default: 0] += n
13 | }
14 | var usedSum = 0
15 | var skipSum = 0
16 | for key in 1 ... n {
17 | let taken = skipSum + sum[key, default: 0]
18 | let skipMax = max(usedSum, skipSum)
19 | usedSum = taken
20 | skipSum = skipMax
21 | }
22 | return max(usedSum, skipSum)
23 | }
24 | }
--------------------------------------------------------------------------------
/Swift/longest-continuous-increasing-subsequence.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/longest-continuous-increasing-subsequence/
3 | *
4 | *
5 | */
6 | // Date: Tue Nov 3 09:32:56 PST 2020
7 | class Solution {
8 | func findLengthOfLCIS(_ nums: [Int]) -> Int {
9 | guard nums.count > 0 else { return 0 }
10 | var count = 1
11 | var result = 1
12 | for index in stride(from: 1, to: nums.count, by: 1) {
13 | if nums[index] > nums[index - 1] {
14 | count += 1
15 | } else {
16 | count = 1
17 | }
18 | result = max(result, count)
19 | }
20 | return result
21 | }
22 | }
--------------------------------------------------------------------------------
/Swift/consecutive-characters.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/consecutive-characters/
3 | *
4 | *
5 | */
6 | // Date: Tue Nov 3 09:28:39 PST 2020
7 | class Solution {
8 | func maxPower(_ s: String) -> Int {
9 | var lastCharacter: Character? = nil
10 | var count = 0
11 | var result = 1
12 | for c in s {
13 | if let last = lastCharacter {
14 | if last == c {
15 | count += 1
16 | result = max(result, count)
17 | continue
18 | }
19 | }
20 | lastCharacter = c
21 | count = 1
22 | }
23 | return result
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/contiguous-array.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/contiguous-array/
3 | *
4 | *
5 | */
6 | class Solution {
7 | /// - Complexity: O(n), n is the number of elements in the array.
8 | func findMaxLength(_ nums: [Int]) -> Int {
9 | var maxLen = 0
10 | var sum = 0
11 | var map: [Int : Int] = [0 : -1]
12 | for index in 0 ..< nums.count {
13 | sum += nums[index] == 1 ? 1 : -1
14 | if let firstPosition = map[sum] {
15 | maxLen = max(maxLen, index - firstPosition)
16 | } else {
17 | map[sum] = index
18 | }
19 | }
20 |
21 | return maxLen
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/keys-and-rooms.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/keys-and-rooms/
3 | *
4 | *
5 | */
6 | // Date: Fri Mar 19 09:28:49 PDT 2021
7 | class Solution {
8 | func canVisitAllRooms(_ rooms: [[Int]]) -> Bool {
9 | var visited: Set = [0]
10 | var queue = [0]
11 | while queue.isEmpty == false {
12 | let room = queue.removeFirst()
13 | for accessRoom in rooms[room] {
14 | if visited.contains(accessRoom) == false {
15 | queue.append(accessRoom)
16 | visited.insert(accessRoom)
17 | }
18 | }
19 | }
20 | return visited.count == rooms.count
21 | }
22 | }
--------------------------------------------------------------------------------
/Swift/smallest-string-with-a-given-numeric-value.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/
3 | *
4 | *
5 | */
6 | // Date: Thu Jan 28 11:09:41 PST 2021
7 | class Solution {
8 | func getSmallestString(_ n: Int, _ k: Int) -> String {
9 | var list = Array(repeating: 0, count: n)
10 | var k = k - n
11 | var n = n
12 | while n > 0 {
13 | list[n - 1] = min(25, k)
14 | k -= min(25, k)
15 | n -= 1
16 | }
17 | var result: String = ""
18 | for x in list {
19 | result.append(Character(UnicodeScalar(x + 97)!))
20 | }
21 | return result
22 | }
23 | }
--------------------------------------------------------------------------------
/Java/reverse-words-in-a-string.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/reverse-words-in-a-string/
3 | */
4 |
5 | public class Solution {
6 | public String reverseWords(String s) {
7 | if (s == null || s.length() == 0) {
8 | return "";
9 | }
10 |
11 | // split to words by space
12 | String[] arr = s.split(" ");
13 | StringBuilder sb = new StringBuilder();
14 | for (int i = arr.length - 1; i >= 0; --i) {
15 | if (!arr[i].equals("")) {
16 | sb.append(arr[i]).append(" ");
17 | }
18 | }
19 | return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Swift/reverse-only-letters.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/reverse-only-letters/
3 | *
4 | *
5 | */
6 | // Date: Wed Sep 15 23:30:41 PDT 2021
7 | class Solution {
8 | func reverseOnlyLetters(_ s: String) -> String {
9 | var s = Array(s)
10 | var start = 0
11 | var end = s.count - 1
12 | while start < end {
13 | while start < end, s[start].isLetter == false { start += 1 }
14 | while start < end, s[end].isLetter == false { end -= 1 }
15 | let tmp = s[start]
16 | s[start] = s[end]
17 | s[end] = tmp
18 | start += 1
19 | end -= 1
20 | }
21 | return String(s)
22 | }
23 | }
--------------------------------------------------------------------------------
/Swift/search-insert-position.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/search-insert-position/
3 | *
4 | *
5 | */
6 | // Date: Wed Jun 10 15:08:02 PDT 2020
7 | class Solution {
8 | func searchInsert(_ nums: [Int], _ target: Int) -> Int {
9 | // guard let last = nums.last else { return 0 }
10 | // if last < target { return nums.count }
11 | var left = 0
12 | var right = nums.count
13 | while left < right {
14 | let mid = left + (right - left) / 2
15 | if nums[mid] < target {
16 | left = mid + 1
17 | } else {
18 | right = mid
19 | }
20 | }
21 | return left
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Java/invert-binary-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/invert-binary-tree/
3 | *
4 | * Definition for a binary tree node.
5 | * public class TreeNode {
6 | * int val;
7 | * TreeNode left;
8 | * TreeNode right;
9 | * TreeNode(int x) { val = x; }
10 | * }
11 | */
12 | public class Solution {
13 | public TreeNode invertTree(TreeNode root) {
14 | if(root == null) return root;
15 | TreeNode tmp = root.left;
16 | root.left = root.right;
17 | root.right = tmp;
18 | if(root.left != null) root.left = invertTree(root.left);
19 | if(root.right != null) root.right = invertTree(root.right);
20 | return root;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Java/remove-duplicates-from-sorted-list.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link:
3 | * https://leetcode.com/problems/remove-duplicates-from-sorted-list/
4 | * Definition for singly-linked list.
5 | * public class ListNode {
6 | * int val;
7 | * ListNode next;
8 | * ListNode(int x) { val = x; }
9 | * }
10 | */
11 | public class Solution {
12 | public ListNode deleteDuplicates(ListNode head) {
13 | ListNode tmp = head;
14 | while(tmp != null && tmp.next != null) {
15 | if(tmp.val == tmp.next.val) {
16 | tmp.next = tmp.next.next;
17 | } else {
18 | tmp = tmp.next;
19 | }
20 | }
21 | return head;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/maximum-points-you-can-obtain-from-cards.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/
3 | *
4 | *
5 | */
6 | // Date: Tue May 11 13:15:23 PDT 2021
7 | class Solution {
8 | func maxScore(_ cardPoints: [Int], _ k: Int) -> Int {
9 | var sum = [0]
10 | for p in cardPoints {
11 | sum.append((sum.last ?? 0) + p)
12 | }
13 | // print(sum)
14 | var maxScore = max(sum[k], sum[cardPoints.count] - sum[cardPoints.count - k])
15 | for index in 1 ..< k {
16 | maxScore = max(maxScore, sum[index] + sum[cardPoints.count] - sum[cardPoints.count - k + index])
17 | }
18 | return maxScore
19 | }
20 | }
--------------------------------------------------------------------------------
/Java/climbing-stairs.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/climbing-stairs/
3 | *
4 | * Solution: Easy dynamic programming problem with memorization.
5 | */
6 |
7 | public class Solution {
8 | private int[] choices;
9 | public int climbStairs(int n) {
10 | choices = new int[n+1];
11 | for(int i=0; i<=n; i++) choices[i] = -1;
12 | return solve(n);
13 | }
14 |
15 | private int solve(int x) {
16 | if(choices[x] != -1) return choices[x];
17 | if(x == 0) return choices[x] = 1;
18 | choices[x] = 0;
19 | if(x >= 1) choices[x] += solve(x-1);
20 | if(x >= 2) choices[x] += solve(x-2);
21 | return choices[x];
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/advantage-shuffle.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/advantage-shuffle/
3 | *
4 | *
5 | */
6 | // Date: Wed Mar 24 08:54:50 PDT 2021
7 | class Solution {
8 | func advantageCount(_ A: [Int], _ B: [Int]) -> [Int] {
9 | let a = A.sorted()
10 | let b = B.enumerated().sorted { $0.1 < $1.1 }
11 | var result = A
12 | var start = 0
13 | var end = A.count - 1
14 | for num in a {
15 | if num > b[start].1 {
16 | result[b[start].0] = num
17 | start += 1
18 | } else {
19 | result[b[end].0] = num
20 | end -= 1
21 | }
22 | }
23 | return result
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/check-if-a-string-contains-all-binary-codes-of-size-k.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/
3 | *
4 | *
5 | */
6 | // Date: Fri Mar 12 11:25:30 PST 2021
7 | class Solution {
8 | func hasAllCodes(_ s: String, _ k: Int) -> Bool {
9 | var list: Set = []
10 | var cand: [Character] = []
11 | for c in s {
12 | cand.append(c)
13 | if cand.count == k {
14 | list.insert(String(cand))
15 | cand.removeFirst()
16 | }
17 | }
18 | var expected = 1
19 | for _ in 0 ..< k { expected *= 2 }
20 | return list.count == expected
21 | }
22 | }
--------------------------------------------------------------------------------
/Java/summary-ranges.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/summary-ranges/
3 | */
4 |
5 | public class Solution {
6 | public List summaryRanges(int[] nums) {
7 | List list = new ArrayList();
8 | for(int i=0; i" + nums[j-1]);
18 | }
19 | i = j;
20 | }
21 | return list;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Java/unique-binary-search-trees.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/unique-binary-search-trees/
3 | *
4 | */
5 | public class Solution {
6 | private int[] mark;
7 | public int numTrees(int n) {
8 | mark = new int[n+1];
9 | for(int i=0; i<=n; i++) mark[i] = -1;
10 | return solve(n);
11 | }
12 |
13 | private int solve(int n) {
14 | if(mark[n] >= 0) return mark[n];
15 | if(n == 0) return 1;
16 | if(n == 1) return 1;
17 | if(n == 2) return 2;
18 | mark[n] = 0;
19 | for(int left = 0; left < n; left++){
20 | mark[n] += solve(left) * solve(n-left-1);
21 | }
22 | return mark[n];
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Swift/excel-sheet-column-number.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/excel-sheet-column-number/
3 | *
4 | *
5 | */
6 | // Date: Mon Aug 10 10:16:08 PDT 2020
7 | class Solution {
8 | func titleToNumber(_ s: String) -> Int {
9 | var result = 0
10 | for c in s.unicodeScalars {
11 | result = result * 26 + Int(c.value) - 64
12 | }
13 | return result
14 | }
15 | }
16 | /**
17 | * https://leetcode.com/problems/excel-sheet-column-number/
18 | *
19 | *
20 | */
21 | // Date: Mon Aug 10 10:18:33 PDT 2020
22 | class Solution {
23 | func titleToNumber(_ s: String) -> Int {
24 | return s.unicodeScalars.reduce(0) { $0 * 26 + Int($1.value) - 64 }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Swift/flip-string-to-monotone-increasing.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/flip-string-to-monotone-increasing/
3 | *
4 | *
5 | */
6 | // Date: Wed Aug 11 17:12:14 PDT 2021
7 | class Solution {
8 | func minFlipsMonoIncr(_ s: String) -> Int {
9 | let len = s.count
10 | var count = Array(repeating: 0, count: len + 1)
11 | for (index, c) in s.enumerated() {
12 | let n = c == Character("0") ? 0 : 1
13 | count[index + 1] = count[index] + n
14 | }
15 | var result = Int.max
16 | for index in 0 ... len {
17 | result = min(result, count[index] + len - index - count[len] + count[index])
18 | }
19 | return result
20 | }
21 | }
--------------------------------------------------------------------------------
/Swift/minimum-moves-to-equal-array-elements.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
3 | *
4 | *
5 | */
6 | /**
7 | * Adding 1 to n - 1 elements is the same as subtracting 1 from one element,
8 | * w.r.t goal of making the elements in the array equal.
9 | * So, best way to do this is make all the elements in the array equal to the min element.
10 | * sum(array) - n * minimum
11 | */
12 | class Solution {
13 | func minMoves(_ nums: [Int]) -> Int {
14 | var minx = Int.max
15 | var total = 0
16 | for n in nums {
17 | minx = min(minx, n)
18 | total += n
19 | }
20 | return total - nums.count * minx
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Java/ugly-number-ii.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public int nthUglyNumber(int n) {
3 | int x = 0;
4 | int y = 0;
5 | int z = 0;
6 | int[] result = new int[n];
7 | result[0] = 1;
8 |
9 | for(int i=1; i Int {
9 | var right = 1 + nums.reduce(0) { $0 + $1 }
10 | var left = 1
11 | while left < right {
12 | let mid = left + (right - left) / 2
13 | let sum = nums.reduce(0) { $0 + (( $1 + mid - 1) / mid) }
14 | if sum <= threshold {
15 | right = mid
16 | } else {
17 | left = mid + 1
18 | }
19 | }
20 | return left
21 | }
22 | }
--------------------------------------------------------------------------------
/Swift/flipping-an-image.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/flipping-an-image/
3 | *
4 | *
5 | */
6 | // Date: Tue Nov 10 09:03:11 PST 2020
7 | class Solution {
8 | func flipAndInvertImage(_ A: [[Int]]) -> [[Int]] {
9 | let n = A.count
10 | guard let m = A.first?.count else { return [] }
11 | var B = A
12 | for x in 0 ..< n {
13 | var start = 0
14 | var end = m - 1
15 | while start <= end {
16 | let tmp = 1 - B[x][start]
17 | B[x][start] = 1 - B[x][end]
18 | B[x][end] = tmp
19 | start += 1
20 | end -= 1
21 | }
22 | }
23 | return B
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/minimum-operations-to-make-array-equal.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/minimum-operations-to-make-array-equal/
3 | *
4 | *
5 | */
6 | // Date: Tue Apr 6 09:26:36 PDT 2021
7 | class Solution {
8 | func minOperations(_ n: Int) -> Int {
9 | var result = 0
10 | for x in stride(from: 1, to: n, by: 2) {
11 | result += n - x
12 | }
13 | return result
14 | }
15 | }/**
16 | * https://leetcode.com/problems/minimum-operations-to-make-array-equal/
17 | *
18 | *
19 | */
20 | // Date: Tue Apr 6 09:48:08 PDT 2021
21 | class Solution {
22 | func minOperations(_ n: Int) -> Int {
23 | return n % 2 == 1 ? n / 2 * ( n / 2 + 1 ) : n / 2 * n / 2
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/distribute-candies-to-people.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/distribute-candies-to-people/
3 | *
4 | *
5 | */
6 | // Date: Tue Aug 18 08:53:34 PDT 2020
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(sqrt(candies))
10 | /// - Space: O(1)
11 | ///
12 | func distributeCandies(_ candies: Int, _ n: Int) -> [Int] {
13 | var c = candies
14 | var result = Array(repeating: 0, count: n)
15 | var index = 0
16 | var candy = 1
17 | while c > 0 {
18 | result[index] += min(c, candy)
19 | index = (index + 1) % n
20 | c -= candy
21 | candy += 1
22 | }
23 | return result
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Swift/container-with-most-water.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/container-with-most-water/
3 | *
4 | *
5 | */
6 |
7 | class Solution {
8 | func maxArea(_ height: [Int]) -> Int {
9 | var water = 0
10 | var left = 0
11 | var right = height.count - 1
12 | while left < right {
13 | let h = min(height[left], height[right])
14 | let w = h * (right - left)
15 | water = max(water, w)
16 | while height[left] <= h, left < right {
17 | left += 1
18 | }
19 | while height[right] <= h, left < right {
20 | right -= 1
21 | }
22 | }
23 | return water
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Swift/unique-paths.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/unique-paths/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func uniquePaths(_ m: Int, _ n: Int) -> Int {
8 | var count:[[Int]] = Array(repeating: Array(repeating: 0, count: m), count: n)
9 | count[0][0] = 1
10 | for i in 0 ..< n {
11 | for j in 0 ..< m {
12 | if i > 0 || j > 0 {
13 | if i > 0 {
14 | count[i][j] += count[i-1][j]
15 | }
16 | if j > 0 {
17 | count[i][j] += count[i][j-1]
18 | }
19 | }
20 | }
21 | }
22 | return count[n - 1][m - 1]
23 | }
24 | }
--------------------------------------------------------------------------------
/Java/lowest-common-ancestor-of-a-binary-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode(int x) { val = x; }
8 | * }
9 | */
10 | public class Solution {
11 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12 | if(root == null) return null;
13 | if(root == p || root == q) return root;
14 |
15 | TreeNode left = lowestCommonAncestor(root.left, p, q);
16 | TreeNode right = lowestCommonAncestor(root.right, p, q);
17 |
18 | if(left != null && right != null) return root;
19 | return left == null ? right : left;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Swift/majority-element.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/majority-element/
3 | *
4 | *
5 | */
6 | // Date: Tue Sep 22 09:28:10 PDT 2020
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(n)
10 | /// - Space: O(1)
11 | func majorityElement(_ nums: [Int]) -> Int {
12 | var result = nums[0]
13 | var count = 1
14 | for index in stride(from: 1, to: nums.count, by: 1) {
15 | if count == 0 {
16 | result = nums[index]
17 | count = 1
18 | } else if result == nums[index] {
19 | count += 1
20 | } else {
21 | count -= 1
22 | }
23 | }
24 | return result
25 | }
26 | }
--------------------------------------------------------------------------------
/Swift/powerful-integers.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/powerful-integers/
3 | *
4 | *
5 | */
6 | // Date: Fri Apr 30 11:44:05 PDT 2021
7 | class Solution {
8 | func powerfulIntegers(_ x: Int, _ y: Int, _ bound: Int) -> [Int] {
9 |
10 | var result: Set = []
11 |
12 | var a = 1
13 | while a <= bound {
14 | var b = 1
15 | while b <= bound {
16 | if a + b <= bound {
17 | result.insert(a + b)
18 | }
19 | b *= y
20 | if y == 1 { break }
21 | }
22 | a *= x
23 | if x == 1 { break }
24 | }
25 |
26 | return Array(result)
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Java/best-time-to-buy-and-sell-stock.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
3 | *
4 | */
5 | public class Solution {
6 | public int maxProfit(int[] prices) {
7 | if(prices == null || prices.length < 2){
8 | return 0;
9 | }
10 | int n = prices.length;
11 | int profit = 0;
12 | int[] buy = new int[n];
13 | for(int i=0; i ratings[i-1]) candies[i] = 1 + candies[i-1];
13 | else candies[i] = 1;
14 | }
15 |
16 | int ret = candies[n-1];
17 | for(int i=n-2; i>=0; i--) {
18 | if(ratings[i] > ratings[i+1]) {
19 | candies[i] = Math.max(candies[i], candies[i+1] + 1);
20 | }
21 | ret += candies[i];
22 | }
23 | return ret;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Java/minimum-path-sum.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/minimum-path-sum/
3 | *
4 | * Dynamic Programming.
5 | */
6 | public class Solution {
7 | public int minPathSum(int[][] grid) {
8 | int m = grid.length;
9 | int n = grid[0].length;
10 | int[][] cost = new int[m][n];
11 | for(int i=0; i 0) c = Math.min(c, cost[i-1][j]);
15 | if(j > 0) c = Math.min(c, cost[i][j-1]);
16 | if(c == Integer.MAX_VALUE) c = 0;
17 | cost[i][j] = grid[i][j] + c;
18 | }
19 | }
20 | return cost[m-1][n-1];
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Swift/find-peak-element.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/find-peak-element/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func findPeakElement(_ nums: [Int]) -> Int {
8 | let nums = [Int.min] + nums + [Int.min]
9 | var left = 0
10 | var right = nums.count - 1
11 | while left <= right {
12 | let mid = left + (right - left) / 2
13 | if mid > 0, nums[mid] > nums[mid - 1], mid + 1 < nums.count, nums[mid] > nums[mid + 1] {
14 | return mid - 1
15 | } else if mid > 0, nums[mid] < nums[mid - 1] {
16 | right = mid - 1
17 | } else {
18 | left = mid + 1
19 | }
20 | }
21 | return -1
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/longest-palindrome.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/longest-palindrome/
3 | *
4 | *
5 | */
6 | // Date: Fri Aug 14 10:21:35 PDT 2020
7 | /// - Complexity:
8 | /// - Time: O(n), n is the length of s.
9 | /// - Space: O(n), n is the length of s.
10 | ///
11 | class Solution {
12 | func longestPalindrome(_ s: String) -> Int {
13 | var visited: Set = []
14 | var count = 0
15 | for c in s {
16 | if visited.contains(c) {
17 | count += 2
18 | visited.remove(c)
19 | } else {
20 | visited.insert(c)
21 | }
22 | }
23 | if visited.isEmpty == false { count += 1 }
24 | return count
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Java/merge-sorted-array.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public void merge(int[] nums1, int m, int[] nums2, int n) {
3 | int index = m+n-1;
4 | while(index>=0) {
5 | if(m>0 && n>0) {
6 | if(nums1[m-1] > nums2[n-1]) {
7 | nums1[index] = nums1[m-1];
8 | m--;
9 | } else {
10 | nums1[index] = nums2[n-1];
11 | n--;
12 | }
13 | } else if(m > 0) {
14 | nums1[index] = nums1[m-1];
15 | m--;
16 | } else if(n > 0) {
17 | nums1[index] = nums2[n-1];
18 | n--;
19 | }
20 | index--;
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/maximum-score-after-splitting-a-string.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-score-after-splitting-a-string/
3 | *
4 | *
5 | */
6 | // Date: Sat Apr 25 23:29:33 PDT 2020
7 | class Solution {
8 | func maxScore(_ s: String) -> Int {
9 | var zeros = [Int]()
10 | for c in s {
11 | if String(c) == "0" {
12 | zeros.append((zeros.last ?? 0) + 1)
13 | } else {
14 | zeros.append((zeros.last ?? 0))
15 | }
16 | }
17 | var maxSum = 0
18 | for split in 1 ..< s.count {
19 | maxSum = max(maxSum, zeros[split - 1] + s.count - split - (zeros[s.count - 1] - zeros[split - 1]))
20 | }
21 | return maxSum
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/GenREADME/Sources/Language.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Language.swift
3 | // GenREADME
4 | //
5 | // Created by Antonio081014 on 2025-03-23.
6 | //
7 |
8 | import Foundation
9 |
10 | enum Language {
11 | case Swift
12 | case Java
13 | case Python
14 |
15 | var extensionString: String {
16 | switch self {
17 | case .Swift:
18 | return "swift"
19 | case .Java:
20 | return "java"
21 | case .Python:
22 | return "py"
23 | }
24 | }
25 |
26 | var description: String {
27 | switch self {
28 | case .Swift:
29 | "Swift"
30 | case .Java:
31 | "Java"
32 | case .Python:
33 | "Python"
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Java/lowest-common-ancestor-of-a-binary-search-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode(int x) { val = x; }
8 | * }
9 | */
10 | public class Solution {
11 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12 | if(root.val > p.val && root.val < q.val){
13 | return root;
14 | }else if(root.val>p.val && root.val > q.val){
15 | return lowestCommonAncestor(root.left, p, q);
16 | }else if(root.val map = new HashMap();
11 | for(int x : nums) {
12 | if(map.get(x) == null) map.put(x, 0);
13 | map.put(x, map.get(x) + 1);
14 | }
15 |
16 | for(int k : map.keySet()){
17 | if(map.get(k) % 2 !=0){
18 | ret[idx] = k;
19 | idx++;
20 | }
21 | }
22 | return ret;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Swift/minimum-size-subarray-sum.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/minimum-size-subarray-sum/
3 | *
4 | *
5 | */
6 | // Date: Wed Dec 9 11:55:41 PST 2020
7 | class Solution {
8 | func minSubArrayLen(_ K: Int, _ A: [Int]) -> Int {
9 | var sum = 0
10 | var window: [Int] = []
11 | var result = A.count + 1
12 | for n in A {
13 | window.append(n)
14 | sum += n
15 | while let first = window.first, sum - first >= K {
16 | window.removeFirst()
17 | sum -= first
18 | }
19 | if sum >= K {
20 | result = min(result, window.count)
21 | }
22 | }
23 | return result > A.count ? 0 : result
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/patching-array.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/patching-array/
3 | *
4 | *
5 | */
6 | // Date: Sun Aug 29 13:23:29 PDT 2021
7 | class Solution {
8 | func minPatches(_ nums: [Int], _ n: Int) -> Int {
9 | var missingNumber = 1
10 | var count = 0
11 | var index = 0
12 | while missingNumber <= n {
13 | if index < nums.count, nums[index] <= missingNumber {
14 | // Extend the covered area.
15 | missingNumber += nums[index]
16 | index += 1
17 | } else {
18 | // Add missing number
19 | count += 1
20 | missingNumber += missingNumber
21 | }
22 | }
23 | return count
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/unique-morse-code-words.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/unique-morse-code-words/
3 | *
4 | *
5 | */
6 | // Date: Sun Nov 22 09:16:51 PST 2020
7 | class Solution {
8 | func uniqueMorseRepresentations(_ words: [String]) -> Int {
9 | let code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
10 | var result: Set = []
11 |
12 | for word in words {
13 | var codeText = ""
14 | for c in word.unicodeScalars {
15 | codeText += code[Int(c.value) - 97]
16 | }
17 | result.insert(codeText)
18 | }
19 | return result.count
20 | }
21 | }
--------------------------------------------------------------------------------
/Swift/reverse-integer.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/reverse-integer/
3 | *
4 | *
5 | */
6 |
7 | class Solution {
8 | func reverse(_ x: Int) -> Int {
9 | let neg = x < 0
10 | let n = convert(abs(x))
11 | return (neg ? -1 : 1) * n
12 | }
13 |
14 | private func convert(_ nn: Int) -> Int {
15 | var n = nn
16 | var res = 0
17 | while n > 0 {
18 | // We are reversing a signed integer, so here we only have 31 bits for valid number, 1 bit for the sign.
19 | if (res * 10 + n % 10) > (1<<31-1) {
20 | return 0
21 | }
22 | res = res * 10 + n % 10
23 | n /= 10
24 | }
25 | return res
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Swift/complex-number-multiplication.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/complex-number-multiplication/
3 | *
4 | *
5 | */
6 | // Date: Tue Aug 24 09:33:43 PDT 2021
7 | class Solution {
8 | func complexNumberMultiply(_ num1: String, _ num2: String) -> String {
9 | func split(_ text: String) -> (Int, Int)? {
10 | let comp = text.split(separator: Character("+"))
11 | guard let anum = comp.first, let a = Int(anum) else { return nil }
12 | guard let bnum = comp.last?.dropLast(), let b = Int(bnum) else { return nil }
13 | return (a, b)
14 | }
15 |
16 | guard let (a, b) = split(num1), let (c, d) = split(num2) else { return "" }
17 | return "\(a * c - b * d)+\(b * c + a * d)i"
18 | }
19 | }
--------------------------------------------------------------------------------
/Swift/first-bad-version.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/first-bad-version/
3 | *
4 | *
5 | */
6 | /**
7 | * The knows API is defined in the parent class VersionControl.
8 | * func isBadVersion(_ version: Int) -> Bool{}
9 | */
10 |
11 | class Solution : VersionControl {
12 | func firstBadVersion(_ n: Int) -> Int {
13 | var left = 1
14 | var right = n
15 | // left will be the index of first element with satisfied requirements.
16 | while left < right {
17 | let mid = left + (right - left) / 2
18 | if isBadVersion(mid) == false {
19 | left = mid + 1
20 | } else {
21 | right = mid
22 | }
23 | }
24 | return left
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Swift/remove-covered-intervals.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/remove-covered-intervals/
3 | *
4 | *
5 | */
6 | // Date: Sun Oct 4 10:24:29 PDT 2020
7 | class Solution {
8 | func removeCoveredIntervals(_ inter: [[Int]]) -> Int {
9 | let intervals = inter.sorted { (a, b) in
10 | if a[0] == b[0] { return a[1] >= b[1] }
11 | return a[0] < b[0]
12 | }
13 | // print("\(intervals)")
14 | var rightEnd = 0
15 | var result = 1
16 | for index in stride(from: 1, to: intervals.count, by: 1) {
17 | if intervals[index][1] > intervals[rightEnd][1] {
18 | result += 1
19 | rightEnd = index
20 | }
21 | }
22 | return result
23 | }
24 | }
--------------------------------------------------------------------------------
/Swift/logger-rate-limiter.swift:
--------------------------------------------------------------------------------
1 |
2 | class Logger {
3 |
4 | private var logging: [String : Int]
5 | init() {
6 | self.logging = [:]
7 | }
8 |
9 | func shouldPrintMessage(_ timestamp: Int, _ message: String) -> Bool {
10 | if let lastTime = logging[message] {
11 | if timestamp - lastTime >= 10 {
12 | logging[message] = timestamp
13 | return true
14 | } else {
15 | return false
16 | }
17 | }
18 | logging[message] = timestamp
19 | return true
20 | }
21 | }
22 |
23 | /**
24 | * Your Logger object will be instantiated and called as such:
25 | * let obj = Logger()
26 | * let ret_1: Bool = obj.shouldPrintMessage(timestamp, message)
27 | */
28 |
--------------------------------------------------------------------------------
/Swift/missing-number.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/missing-number/
3 | *
4 | *
5 | */
6 | // Date: Fri May 8 14:05:52 PDT 2020
7 | class Solution {
8 | func missingNumber(_ nums: [Int]) -> Int {
9 | let n = nums.count
10 | var total = n * (n + 1) / 2
11 | for x in nums {
12 | total -= x
13 | }
14 | return total
15 | }
16 | }
17 | /**
18 | * https://leetcode.com/problems/missing-number/
19 | *
20 | *
21 | */
22 | // Date: Wed Mar 3 15:44:22 PST 2021
23 | class Solution {
24 | func missingNumber(_ nums: [Int]) -> Int {
25 | let n = nums.count
26 | var sum = (1 + n) * n / 2
27 | for x in nums {
28 | sum -= x
29 | }
30 | return sum
31 | }
32 | }
--------------------------------------------------------------------------------
/Swift/subsets-ii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/subsets-ii/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func subsetsWithDup(_ nums: [Int]) -> [[Int]] {
8 | let nums = nums.sorted()
9 | var ret: Set<[Int]> = []
10 | process(&ret, [], nums, 0)
11 | return Array(ret)
12 | }
13 |
14 | fileprivate func process(_ solution: inout Set<[Int]>, _ result: [Int], _ candidate: [Int], _ currentIndex: Int) {
15 | if currentIndex >= candidate.count {
16 | solution.insert(result)
17 | return
18 | }
19 | process(&solution, result + [candidate[currentIndex]], candidate, currentIndex + 1)
20 | process(&solution, result, candidate, currentIndex + 1)
21 |
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/3sum.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func threeSum(_ nums: [Int]) -> [[Int]] {
3 | var result: Set<[Int]> = []
4 | let sortedNums = nums.sorted()
5 | for index1 in 0.. 0 && sortedNums[index1] == sortedNums[index1 - 1] { continue }
7 | let target = 0 - sortedNums[index1]
8 | var dict: Set = []
9 | for index2 in (index1+1) ..< sortedNums.count {
10 | if dict.contains(target - sortedNums[index2]) {
11 | result.insert([sortedNums[index1], target - sortedNums[index2], sortedNums[index2]])
12 | }
13 | dict.insert(sortedNums[index2])
14 | }
15 | }
16 | return Array(result)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Java/balanced-binary-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode(int x) { val = x; }
8 | * }
9 | */
10 | public class Solution {
11 | public boolean isBalanced(TreeNode root) {
12 | if(root == null) return true;
13 | if(height(root) == -1) return false;
14 | return true;
15 | }
16 |
17 | private int height(TreeNode root) {
18 | if(root == null) return 0;
19 | int left = height(root.left);
20 | int right = height(root.right);
21 | if(left == -1 || right == -1) return -1;
22 | if(Math.abs(left - right) > 1) return -1;
23 | return Math.max(left, right) + 1;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Java/unique-paths-ii.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/unique-paths-ii/
3 | */
4 | public class Solution {
5 | public int uniquePathsWithObstacles(int[][] grid) {
6 | int n = grid.length;
7 | int m = grid[0].length;
8 | int[][] cost = new int[n][m];
9 | cost[0][0] = grid[0][0] == 0 ? 1 : 0;
10 | for(int i=0; i 0) cost[i][j] += cost[i-1][j];
14 | if(j > 0) cost[i][j] += cost[i][j-1];
15 | }
16 | else {
17 | cost[i][j] = 0;
18 | }
19 | }
20 | }
21 | return cost[n-1][m-1];
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/find-missing-and-repeated-values.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/find-missing-and-repeated-values/
3 | *
4 | *
5 | */
6 | // Date: Wed Mar 19 17:15:24 PDT 2025
7 | class Solution {
8 | func findMissingAndRepeatedValues(_ grid: [[Int]]) -> [Int] {
9 | var visited = Set()
10 | let n = grid.count
11 | var sum = n * n * (n * n + 1) / 2
12 | var dup = 0
13 | for x in 0 ..< n {
14 | for y in 0 ..< n {
15 | if visited.contains(grid[x][y]) {
16 | dup = grid[x][y]
17 | } else {
18 | sum -= grid[x][y]
19 | visited.insert(grid[x][y])
20 | }
21 | }
22 | }
23 | return [dup, sum]
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Swift/longest-nice-subarray.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/longest-nice-subarray/
3 | *
4 | *
5 | */
6 | // Date: Wed Mar 19 16:51:42 PDT 2025
7 | class Solution {
8 | func longestNiceSubarray(_ nums: [Int]) -> Int {
9 | var maxLength = 0
10 | var usedBits = 0
11 | var start = 0
12 | for end in 0 ..< nums.count {
13 | // Remove all the elements could have conflicts with current/end element.
14 | while (usedBits & nums[end]) != 0 {
15 | usedBits ^= nums[start]
16 | start += 1
17 | }
18 | // print(start, end)
19 | usedBits |= nums[end]
20 | maxLength = max(maxLength, end - start + 1)
21 | }
22 | return maxLength
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Swift/maximum-length-of-repeated-subarray.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-length-of-repeated-subarray/
3 | *
4 | *
5 | */
6 | // Date: Thu Jul 8 13:42:30 PDT 2021
7 | class Solution {
8 | func findLength(_ nums1: [Int], _ nums2: [Int]) -> Int {
9 | let n = nums1.count
10 | let m = nums2.count
11 | var result = 0
12 | var cost = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
13 | for x in 0 ..< n {
14 | for y in 0 ..< m {
15 | if nums1[x] == nums2[y] {
16 | cost[x + 1][y + 1] = cost[x][y] + 1
17 | }
18 | result = max(result, cost[x + 1][y + 1])
19 | }
20 | }
21 |
22 | return result
23 | }
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/Swift/break-a-palindrome.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/break-a-palindrome/
3 | *
4 | *
5 | */
6 | // Date: Thu Sep 23 23:39:59 PDT 2021
7 | class Solution {
8 | func breakPalindrome(_ palindrome: String) -> String {
9 | guard palindrome.count > 1 else { return "" }
10 | var p = Array(palindrome)
11 | for index in 0 ..< p.count {
12 | if p[index] != Character("a") {
13 | let c = p[index]
14 | p[index] = Character("a")
15 | if Set(p).count > 1 { return String(p) }
16 | p[index] = c
17 | p[p.count - 1] = Character("b")
18 | return String(p)
19 | }
20 | }
21 | p[p.count - 1] = Character("b")
22 | return String(p)
23 | }
24 | }
--------------------------------------------------------------------------------
/Swift/linked-list-cycle.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/linked-list-cycle/
3 | *
4 | *
5 | */
6 | // Date: Tue May 5 13:30:25 PDT 2020
7 | /**
8 | * Definition for singly-linked list.
9 | * public class ListNode {
10 | * public var val: Int
11 | * public var next: ListNode?
12 | * public init(_ val: Int) {
13 | * self.val = val
14 | * self.next = nil
15 | * }
16 | * }
17 | */
18 |
19 | class Solution {
20 | func hasCycle(_ head: ListNode?) -> Bool {
21 | var fast = head?.next
22 | var slow = head
23 | while fast != nil, fast?.next != nil {
24 | if fast === slow { return true }
25 | slow = slow?.next
26 | fast = fast?.next?.next
27 | }
28 | return false
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Swift/super-pow.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/super-pow/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func superPow(_ a: Int, _ b: [Int]) -> Int {
8 | if b.isEmpty { return 1 }
9 | var b = b
10 | let last = b.removeLast()
11 | return powerWithMode(a, last) * powerWithMode(superPow(a, b), 10) % 1337
12 | }
13 |
14 | fileprivate func powerWithMode(_ a: Int, _ b: Int, _ mod: Int = 1337) -> Int {
15 | if b == 0 { return 1 }
16 | if b == 1 { return a % mod }
17 | if b % 2 == 0 {
18 | let p = powerWithMode(a, b / 2, mod)
19 | return (p * p) % mod
20 | } else {
21 | let p = powerWithMode(a, b / 2, mod)
22 | return ((p * p) % mod * a) % mod
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Swift/valid-anagram.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/valid-anagram/
3 | *
4 | *
5 | */
6 | // Date: Sun May 3 15:42:05 PDT 2020
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(max(s.count, t.count))
10 | /// - Space: O(26)
11 | ///
12 | func isAnagram(_ s: String, _ t: String) -> Bool {
13 | if s.count != t.count { return false }
14 | var count: [String : Int] = [:]
15 | for c in s {
16 | count[String(c)] = 1 + count[String(c), default: 0]
17 | }
18 |
19 | for c in t {
20 | count[String(c)] = count[String(c), default: 0] - 1
21 | if count[String(c)]! < 0 {
22 | return false
23 | }
24 | }
25 | return true
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Java/roman-to-integer.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/roman-to-integer/
3 | */
4 |
5 | public class Solution {
6 | public int romanToInt(String s) {
7 | HashMap map = new HashMap();
8 | map.put('I', 1);
9 | map.put('V', 5);
10 | map.put('X', 10);
11 | map.put('L', 50);
12 | map.put('C', 100);
13 | map.put('D', 500);
14 | map.put('M', 1000);
15 |
16 | int sum = map.get(s.charAt(0));
17 | for(int i=1; i map.get(s.charAt(i-1))) {
20 | sum -= map.get(s.charAt(i-1)) * 2;
21 | }
22 | }
23 | return sum;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Java/spiral-matrix-ii.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem link: https://leetcode.com/problems/spiral-matrix-ii/
3 | */
4 |
5 | public class Solution {
6 | int[] dx = {0, 1, 0, -1};
7 | int[] dy = {1, 0, -1, 0};
8 |
9 | public int[][] generateMatrix(int n) {
10 | int[][] mat = new int[n][n];
11 | int dir = 0;
12 | for(int x=0,y=0,i=1; i<=n*n; i++) {
13 | mat[x][y] = i;
14 | int xx = x + dx[dir];
15 | int yy = y + dy[dir];
16 | if(xx < 0 || xx >= n || yy < 0 || yy >= n || mat[xx][yy] > 0) {
17 | dir = (dir + 1) % dx.length;
18 | xx = x + dx[dir];
19 | yy = y + dy[dir];
20 | }
21 | x = xx;
22 | y = yy;
23 | }
24 | return mat;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Swift/factorial-trailing-zeroes.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/factorial-trailing-zeroes/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func trailingZeroes(_ n: Int) -> Int {
8 | var base = 5
9 | var x = n
10 | var count = 0
11 | while x >= base {
12 | count += x / base
13 | base *= 5
14 | }
15 | return count
16 | }
17 | }
18 | /**
19 | * https://leetcode.com/problems/factorial-trailing-zeroes/
20 | *
21 | *
22 | */
23 | // Date: Fri Jul 10 16:12:12 PDT 2020
24 | class Solution {
25 | func trailingZeroes(_ n: Int) -> Int {
26 | var n = n
27 | var count = 0
28 | while n > 0 {
29 | n /= 5
30 | count += n
31 | }
32 | return count
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Swift/k-diff-pairs-in-an-array.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/k-diff-pairs-in-an-array/
3 | *
4 | *
5 | */
6 | // Date: Sat Oct 3 17:20:56 PDT 2020
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(n), n is nums.count
10 | /// - Space: O(n), n is nums.count
11 | func findPairs(_ nums: [Int], _ k: Int) -> Int {
12 | var result: Set = []
13 | var set: Set = []
14 | for index in 0 ..< nums.count {
15 | if set.contains(nums[index] - k) {
16 | result.insert(nums[index] - k)
17 | }
18 | if set.contains(nums[index] + k) {
19 | result.insert(nums[index])
20 | }
21 | set.insert(nums[index])
22 | }
23 | return result.count
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/sliding-window-maximum.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/sliding-window-maximum/
3 | *
4 | *
5 | */
6 | // Date: Sun Nov 29 11:30:11 PST 2020
7 | class Solution {
8 | func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
9 | var queue: [Int] = []
10 | var result: [Int] = []
11 | for index in 0 ..< nums.count {
12 | while let first = queue.first, first + k <= index {
13 | queue.removeFirst()
14 | }
15 | while let last = queue.last, nums[last] < nums[index] {
16 | queue.removeLast()
17 | }
18 | queue.append(index)
19 | if index >= k - 1 {
20 | result.append(nums[queue.first!])
21 | }
22 | }
23 | return result
24 | }
25 | }
--------------------------------------------------------------------------------
/Java/perfect-squares.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/perfect-squares/
3 | */
4 | public class Solution {
5 |
6 | private int[] mark;
7 |
8 | public int numSquares(int n) {
9 | int x = (int)Math.sqrt(n);
10 | mark = new int[n+1];
11 | for(int i=0; i<=n; i++) mark[i] = -1;
12 | for(int i = (int)Math.sqrt(n); i >= 1; i--) {
13 | mark[i*i] = 1;
14 | }
15 | return square(n);
16 | }
17 |
18 | private int square(int left) {
19 | if(mark[left] != -1) return mark[left];
20 | mark[left] = Integer.MAX_VALUE;
21 | for(int x = (int)Math.sqrt(left); x >=1; x--){
22 | mark[left] = Math.min(mark[left], 1 + square(left - x * x));
23 | }
24 | return mark[left];
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Swift/nth-magical-number.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/nth-magical-number/
3 | *
4 | *
5 | */
6 | // Date: Sun Apr 24 12:39:53 PDT 2022
7 | class Solution {
8 | func nthMagicalNumber(_ n: Int, _ a: Int, _ b: Int) -> Int {
9 | let MOD = 1_000_000_007
10 | let L = a / gcd(a, b) * b
11 |
12 | var lo = 0
13 | var hi = n * min(a, b)
14 | while lo < hi {
15 | let mid = lo + (hi - lo) / 2
16 | if (mid / a + mid / b - mid / L) < n {
17 | lo = mid + 1
18 | } else {
19 | hi = mid
20 | }
21 | }
22 | return lo % MOD
23 | }
24 |
25 | private func gcd(_ a: Int, _ b: Int) -> Int {
26 | if a == 0 { return b }
27 | return gcd(b % a, a)
28 | }
29 | }
--------------------------------------------------------------------------------
/Swift/divide-a-string-into-groups-of-size-k.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/
3 | *
4 | *
5 | */
6 | // Date: Fri Jan 21 19:44:12 PST 2022
7 | class Solution {
8 | func divideString(_ s: String, _ k: Int, _ fill: Character) -> [String] {
9 | var s = s
10 | if s.count % k != 0 {
11 | s.append(contentsOf: Array(repeating: fill, count: k - (s.count % k)))
12 | }
13 | var result = [String]()
14 | var tmp = ""
15 | var count = 0
16 | for c in s {
17 | tmp.append(c)
18 | count += 1
19 | if count == k {
20 | result.append(tmp)
21 | tmp = ""
22 | count = 0
23 | }
24 | }
25 | return result
26 | }
27 | }
--------------------------------------------------------------------------------
/Swift/slowest-key.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/slowest-key/
3 | *
4 | *
5 | */
6 | // Date: Mon Sep 6 18:19:08 PDT 2021
7 | class Solution {
8 | func slowestKey(_ releaseTimes: [Int], _ keysPressed: String) -> Character {
9 | var longest = 0
10 | var result = Character("a")
11 | var last = 0
12 | let keys = Array(keysPressed)
13 | for index in 0 ..< releaseTimes.count {
14 | let duration = releaseTimes[index] - last
15 | last = releaseTimes[index]
16 | if duration > longest {
17 | longest = duration
18 | result = keys[index]
19 | } else if duration == longest {
20 | result = max(result, keys[index])
21 | }
22 | }
23 | return result
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/can-place-flowers.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/can-place-flowers/
3 | *
4 | *
5 | */
6 | // Date: Mon Dec 7 15:50:55 PST 2020
7 | class Solution {
8 | func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool {
9 | var flowerbed = flowerbed
10 | var index = 0
11 | var result = 0
12 | while index < flowerbed.count {
13 | if flowerbed[index] == 0, (index == 0 || flowerbed[index - 1] == 0), (index + 1 == flowerbed.count || flowerbed[index + 1] == 0) {
14 | flowerbed[index] = 1
15 | result += 1
16 |
17 | if result >= n { return true }
18 | }
19 | if result >= n { return true }
20 |
21 | index += 1
22 | }
23 | return false
24 | }
25 | }
--------------------------------------------------------------------------------
/Swift/find-k-closest-elements.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/find-k-closest-elements/
3 | *
4 | *
5 | */
6 | class Solution {
7 | ///
8 | /// In this problem, we are trying to find the a window with minimum diff between x and those boundaries,
9 | /// since the array are dealing with is a sorted array.
10 | ///
11 | func findClosestElements(_ arr: [Int], _ k: Int, _ x: Int) -> [Int] {
12 | var left = 0
13 | var right = arr.count - k
14 | while left < right {
15 | let mid = left + (right - left) / 2
16 | if x - arr[mid] > arr[mid + k] - x {
17 | left = mid + 1
18 | } else {
19 | right = mid
20 | }
21 | }
22 |
23 | return Array(arr[(left)..<(left + k)])
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Swift/longest-turbulent-subarray.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/longest-turbulent-subarray/
3 | *
4 | *
5 | */
6 | // Date: Wed Sep 15 23:23:37 PDT 2021
7 | class Solution {
8 | func maxTurbulenceSize(_ arr: [Int]) -> Int {
9 | guard arr.count > 2 else { return Set(arr).count }
10 | var index = 1
11 | var result = 0
12 | var start = 0
13 | while index < arr.count {
14 | if arr[index] == arr[index - 1] {
15 | start = index
16 | } else if index >= 2, (arr[index - 1] - arr[index - 2]) * (arr[index] - arr[index - 1]) > 0 {
17 | start = index - 1
18 | }
19 | result = max(result, index - start + 1)
20 | index += 1
21 | }
22 |
23 | return result
24 | }
25 | }
--------------------------------------------------------------------------------
/Java/search-a-2d-matrix-ii.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/search-a-2d-matrix-ii/
3 | *
4 | * Search from bottom left to top right.
5 | * Since strictly ascending in any row or column,
6 | * use current position(r, c) as the bottom right boundary of the matrix search.
7 | *
8 | */
9 |
10 | public class Solution {
11 | public boolean searchMatrix(int[][] matrix, int target) {
12 | int m = matrix.length;
13 | int n = matrix[0].length;
14 |
15 | int r = m-1;
16 | int c = 0;
17 | while(r >= 0 && c < n) {
18 | if(matrix[r][c] == target) return true;
19 | else if(target > matrix[r][c]) {
20 | c++;
21 | } else {
22 | r--;
23 | }
24 | }
25 | return false;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Swift/get-maximum-in-generated-array.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/get-maximum-in-generated-array/
3 | *
4 | *
5 | */
6 | // Date: Fri Jan 15 09:15:06 PST 2021
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(n)
10 | /// - Space: O(n)
11 | func getMaximumGenerated(_ n: Int) -> Int {
12 | var result = Array(repeating: -1, count: n + 2)
13 | result[0] = 0
14 | result[1] = 1
15 | var maxNumber = Int.min
16 | for x in stride(from: 0, through: n, by: 1) {
17 | if x % 2 == 0 {
18 | result[x] = result[x / 2]
19 | } else {
20 | result[x] = result[x / 2] + result[x / 2 + 1]
21 | }
22 | maxNumber = max(maxNumber, result[x])
23 | }
24 | return maxNumber
25 | }
26 | }
--------------------------------------------------------------------------------
/Swift/non-overlapping-intervals.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/non-overlapping-intervals/
3 | *
4 | *
5 | */
6 | // Date: Sat Aug 15 12:06:17 PDT 2020
7 | class Solution {
8 | func eraseOverlapIntervals(_ intervals: [[Int]]) -> Int {
9 | guard intervals.count > 0 else { return 0 }
10 | let intervals = intervals.sorted(by: {
11 | if $0[1] == $1[1] {
12 | return $0[0] < $1[0]
13 | }
14 | return $0[1] < $1[1]
15 | })
16 | var count = 1
17 | var end = intervals[0][1]
18 | for index in 1 ..< intervals.count {
19 | if end <= intervals[index][0] {
20 | count += 1
21 | end = intervals[index][1]
22 | }
23 | }
24 | return intervals.count - count
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Swift/shortest-subarray-with-sum-at-least-k.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func shortestSubarray(_ nums: [Int], _ k: Int) -> Int {
3 | var sum: [Int] = [0]
4 | let len = nums.count
5 | for n in nums {
6 | sum.append(sum.last! + n)
7 | }
8 | var result = len + 1
9 |
10 | var queue = [Int]()
11 | for index in 0 ..< len + 1 {
12 | while let first = queue.first, sum[index] - sum[first] >= k {
13 | result = min(result, index - first)
14 | queue.removeFirst()
15 | }
16 | while let last = queue.last, sum[index] <= sum[last] {
17 | queue.removeLast()
18 | }
19 | queue.append(index)
20 | }
21 |
22 | return result > len ? -1 : result
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Java/best-time-to-buy-and-sell-stock-ii.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
3 | *
4 | */
5 | public class Solution {
6 | public int maxProfit(int[] prices) {
7 | int profit = 0;
8 | int buy = Integer.MAX_VALUE;
9 | int n = prices.length;
10 | for(int i=0; i prices[i+1] && buy != Integer.MAX_VALUE) {
14 | profit += prices[i] - buy;
15 | buy = Integer.MAX_VALUE;
16 | }
17 | }
18 | if(buy != Integer.MAX_VALUE && prices[n-1] >= prices[n-2]) {
19 | profit += prices[n-1] - buy;
20 | }
21 | return profit;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/baseball-game.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/baseball-game/
3 | *
4 | *
5 | */
6 | // Date: Sat Apr 9 23:27:59 PDT 2022
7 | class Solution {
8 | func calPoints(_ ops: [String]) -> Int {
9 | var result = [Int]()
10 | for op in ops {
11 | if op == "+" {
12 | let n = result.count
13 | let sum = result[n - 1] + result[n - 2]
14 | result.append(sum)
15 | } else if op == "D" {
16 | let d = result[result.count - 1] * 2
17 | result.append(d)
18 | } else if op == "C" {
19 | result.removeLast()
20 | } else {
21 | result.append(Int(op)!)
22 | }
23 | // print(result)
24 | }
25 | return result.reduce(0) { $0 + $1 }
26 | }
27 | }
--------------------------------------------------------------------------------
/Swift/beautiful-arrangement-ii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/beautiful-arrangement-ii/
3 | *
4 | *
5 | */
6 | // Date: Mon Apr 12 17:09:50 PDT 2021
7 | class Solution {
8 | func constructArray(_ n: Int, _ k: Int) -> [Int] {
9 | var result = [Int]()
10 | var k = k
11 | var start = 1
12 | var end = n
13 | while start <= end {
14 | if k > 1 {
15 | if k % 2 == 0 {
16 | result.append(end)
17 | end -= 1
18 | } else {
19 | result.append(start)
20 | start += 1
21 | }
22 | k -= 1
23 | } else {
24 | result.append(start)
25 | start += 1
26 | }
27 | }
28 | return result
29 | }
30 | }
--------------------------------------------------------------------------------
/Swift/combination-sum-iv.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/combination-sum-iv/
3 | *
4 | *
5 | */
6 | // Date: Mon Oct 5 16:02:29 PDT 2020
7 | class Solution {
8 | /// count[sum]: number of ways to add numbers to sum.
9 | /// count[sum] = sum(count[sum - n]), n is the candidates in nums.
10 | ///
11 | /// - Complexity:
12 | /// - Time: O(target * n)
13 | /// - Space: O(target)
14 | func combinationSum4(_ nums: [Int], _ target: Int) -> Int {
15 | var count = Array(repeating: 0, count: target + 1)
16 | count[0] = 1
17 | for sum in 1 ... target {
18 | for n in nums {
19 | if sum - n >= 0 {
20 | count[sum] = count[sum] &+ count[sum - n]
21 | }
22 | }
23 | }
24 | return count[target]
25 | }
26 | }
--------------------------------------------------------------------------------
/Swift/intersection-of-two-arrays.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/intersection-of-two-arrays/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
8 | var ret: Set = []
9 | let nums2 = nums2.sorted()
10 | for n in nums1 {
11 | var left = 0
12 | var right = nums2.count - 1
13 | while left <= right {
14 | let mid = left + (right - left) / 2
15 | if nums2[mid] == n {
16 | ret.insert(n)
17 | break
18 | } else if nums2[mid] > n {
19 | right = mid - 1
20 | } else {
21 | left = mid + 1
22 | }
23 | }
24 | }
25 | return Array(ret)
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Swift/number-of-subarrays-with-bounded-maximum.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/
3 | *
4 | *
5 | */
6 | // Date: Thu Jun 17 11:20:35 PDT 2021
7 | class Solution {
8 | func numSubarrayBoundedMax(_ nums: [Int], _ left: Int, _ right: Int) -> Int {
9 | var result = 0
10 | var dp = 0
11 | var prev = -1
12 | for index in 0 ..< nums.count {
13 | if nums[index] < left, index > 0 {
14 | result += dp
15 | }
16 | if nums[index] > right {
17 | dp = 0
18 | prev = index
19 | }
20 | if nums[index] >= left, nums[index] <= right {
21 | dp = index - prev
22 | result += dp
23 | }
24 | }
25 | return result
26 | }
27 | }
--------------------------------------------------------------------------------
/Swift/online-stock-span.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/online-stock-span/
3 | *
4 | *
5 | */
6 | // Date: Tue May 19 22:26:42 PDT 2020
7 | class StockSpanner {
8 |
9 | private var prices: [Int]
10 | private var count: [Int]
11 |
12 | init() {
13 | self.prices = []
14 | self.count = []
15 | }
16 |
17 | func next(_ price: Int) -> Int {
18 | var c = 1
19 | while let last = self.prices.last, last <= price {
20 | self.prices.removeLast()
21 | c += count.removeLast()
22 | }
23 | self.prices.append(price)
24 | self.count.append(c)
25 | return c
26 | }
27 | }
28 |
29 | /**
30 | * Your StockSpanner object will be instantiated and called as such:
31 | * let obj = StockSpanner()
32 | * let ret_1: Int = obj.next(price)
33 | */
34 |
--------------------------------------------------------------------------------
/Swift/partition-labels.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/partition-labels/
3 | *
4 | *
5 | */
6 | // Date: Fri Sep 4 22:04:17 PDT 2020
7 | /// - Complexity:
8 | /// - Time: O(n), n is the length of S.
9 | /// - Space: O(26), a - z.
10 | class Solution {
11 | func partitionLabels(_ S: String) -> [Int] {
12 | var lastIndex: [Character : Int] = [:]
13 | for (index, c) in S.enumerated() {
14 | lastIndex[c] = index
15 | }
16 | var result = [Int]()
17 | var start = 0
18 | var end = 0
19 | for (index, c) in S.enumerated() {
20 | end = max(end, lastIndex[c, default: -1])
21 | if index == end {
22 | result.append(end - start + 1)
23 | start = end + 1
24 | }
25 | }
26 | return result
27 | }
28 | }
--------------------------------------------------------------------------------
/Java/first-bad-version.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/first-bad-version/
3 | * Binary Search to find the first one which isBadVersion(x) is true.
4 | *
5 | * Reference: https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/
6 | */
7 |
8 | /* The isBadVersion API is defined in the parent class VersionControl.
9 | boolean isBadVersion(int version); */
10 |
11 | public class Solution extends VersionControl {
12 | public int firstBadVersion(int n) {
13 | int left = 1;
14 | int right = n;
15 | while(left < right) {
16 | int mid = left + (right - left) / 2;
17 | if(isBadVersion(mid)) {
18 | right = mid;
19 | } else {
20 | left = mid + 1;
21 | }
22 | }
23 | return left;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Java/minimum-depth-of-binary-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/minimum-depth-of-binary-tree/
3 | *
4 | * Solution: Recursively Find the depth of the tree.
5 | * PS: Only leaf node could be considered as the end of the tree branch.
6 | * Definition for a binary tree node.
7 | * public class TreeNode {
8 | * int val;
9 | * TreeNode left;
10 | * TreeNode right;
11 | * TreeNode(int x) { val = x; }
12 | * }
13 | */
14 | public class Solution {
15 | public int minDepth(TreeNode root) {
16 | if (root == null) return 0;
17 | if(root.left == null && root.right == null) return 1;
18 | if(root.left == null) return 1 + minDepth(root.right);
19 | if(root.right == null) return 1 + minDepth(root.left);
20 | return 1 + Math.min(minDepth(root.left), minDepth(root.right));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Swift/maximum-number-of-balloons.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-number-of-balloons/
3 | *
4 | *
5 | */
6 | // Date: Mon Sep 13 23:32:17 PDT 2021
7 | class Solution {
8 | func maxNumberOfBalloons(_ text: String) -> Int {
9 | let s = "balloon"
10 | var count: [Character : Int] = [:]
11 | for c in text {
12 | if s.contains(c) {
13 | count[c, default: 0] += 1
14 | }
15 | }
16 | var result = text.count
17 | for c in s {
18 | let key = c
19 | let val = count[c, default: 0]
20 | if key == Character("l") || key == Character("o") {
21 | result = min(result, val / 2)
22 | } else {
23 | result = min(result, val)
24 | }
25 | }
26 | return result
27 | }
28 | }
--------------------------------------------------------------------------------
/Swift/number-of-steps-to-reduce-a-number-to-zero.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
3 | *
4 | *
5 | */
6 | // Date: Fri Feb 12 13:31:46 PST 2021
7 | class Solution {
8 | func numberOfSteps (_ num: Int) -> Int {
9 | var num = num
10 | var result = 0
11 | while num > 0 {
12 | num = num % 2 == 0 ? num / 2 : num - 1
13 | result += 1
14 | }
15 | return result
16 | }
17 | }
18 |
19 |
20 | class Solution {
21 | func numberOfSteps (_ num: Int) -> Int {
22 | return max(0, num.bitWidth - num.leadingZeroBitCount + num.nonzeroBitCount - 1)
23 | }
24 | }
25 |
26 | class Solution {
27 | func numberOfSteps (_ num: Int) -> Int {
28 | if num < 2 { return num }
29 | return numberOfSteps(num / 2) + 1 + num % 2
30 | }
31 | }
--------------------------------------------------------------------------------
/Swift/reverse-vowels-of-a-string.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/reverse-vowels-of-a-string/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func reverseVowels(_ s: String) -> String {
8 | var list = s.characters.map() {"\($0)"}
9 | var left = 0
10 | var right = list.count-1
11 | while left < right {
12 | if !isVowel(list[left]) {left += 1}
13 | else if !isVowel(list[right]) {right -= 1}
14 | else {
15 | let tmp = list[left]
16 | list[left] = list[right]
17 | list[right] = tmp
18 | left += 1
19 | right -= 1
20 | }
21 | }
22 | return list.joined()
23 | }
24 |
25 | private func isVowel(_ c: String) -> Bool {
26 | return "aeiouAEIOU".contains(c)
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/GenREADME/Package.swift:
--------------------------------------------------------------------------------
1 | // swift-tools-version: 6.0
2 | // The swift-tools-version declares the minimum version of Swift required to build this package.
3 |
4 | import PackageDescription
5 |
6 | let package = Package(
7 | name: "GenREADME",
8 | platforms: [.macOS(.v13), .iOS(.v16)],
9 | dependencies: [
10 | .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.2.0"),
11 | ],
12 | targets: [
13 | // Targets are the basic building blocks of a package, defining a module or a test suite.
14 | // Targets can depend on other targets in this package and products from dependencies.
15 | .executableTarget(
16 | name: "GenREADME",
17 | dependencies: [
18 | .product(name: "ArgumentParser", package: "swift-argument-parser"),
19 | ]
20 | ),
21 | ]
22 | )
23 |
--------------------------------------------------------------------------------
/Swift/combinations.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/combinations/
3 | *
4 | *
5 | */
6 | // Date: Thu Jun 18 11:14:48 PDT 2020
7 | class Solution {
8 | func combine(_ n: Int, _ k: Int) -> [[Int]] {
9 | var solution: [[Int]] = []
10 |
11 | func choose(from nums: [Int], _ start: Int, _ left: Int, _ result: inout [Int]) {
12 | if left == 0 {
13 | solution.append(result)
14 | return
15 | }
16 | for index in start ..< nums.count {
17 | result.append(nums[index])
18 | choose(from: nums, index + 1, left - 1, &result)
19 | result.removeLast()
20 | }
21 | }
22 |
23 | var result: [Int] = []
24 | choose(from: Array((1...n)), 0, k, &result)
25 | return solution
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Java/remove-linked-list-elements.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/remove-linked-list-elements/
3 | *
4 | * Iterate every elements in the list, then remove the node with val equals to val.
5 | *
6 | * Definition for singly-linked list.
7 | * public class ListNode {
8 | * int val;
9 | * ListNode next;
10 | * ListNode(int x) { val = x; }
11 | * }
12 | */
13 | public class Solution {
14 | public ListNode removeElements(ListNode head, int val) {
15 | while(head != null && head.val == val) head = head.next;
16 | ListNode next = head;
17 | while(next != null && next.next != null) {
18 | if(next.next.val == val) {
19 | next.next = next.next.next;
20 | } else {
21 | next = next.next;
22 | }
23 | }
24 | return head;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Swift/decode-ways.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func numDecodings(s: String) -> Int {
3 | let array = Array(("0" + s).characters)
4 | let n = array.count
5 | if n <= 1 {
6 | return 0
7 | }
8 | var count = [Int](count: n, repeatedValue: 0)
9 | count[0] = 1
10 | for i in 1.. 1 && (array[i-1]=="1" || array[i-1]=="2"){
13 | count[i] = count[i-2]
14 | } else {
15 | return 0
16 | }
17 | } else {
18 | count[i] = count[i-1]
19 | if array[i-1] == "1" || (array[i-1]=="2" && array[i] <= "6") {
20 | count[i] += count[i-2]
21 | }
22 | }
23 | }
24 | return count[n-1]
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Swift/bitwise-and-of-numbers-range.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/bitwise-and-of-numbers-range/
3 | *
4 | *
5 | */
6 | // Date: Thu Apr 23 07:34:11 PDT 2020
7 |
8 | /// The idea is very simple:
9 | ///
10 | /// 1. last bit of (odd number & even number) is 0.
11 | /// 2. when m != n, There is at least an odd number and an even number, so the last bit position result is 0.
12 | /// 3. Move m and n rigth a position.
13 | ///
14 | /// Keep doing step 1,2,3 until m equal to n, use a factor to record the iteration time.
15 |
16 | class Solution {
17 | func rangeBitwiseAnd(_ m: Int, _ n: Int) -> Int {
18 | if m == 0 { return 0 }
19 | var m = m
20 | var n = n
21 | var bit = 0
22 | while m != n {
23 | m /= 2
24 | n /= 2
25 | bit += 1
26 | }
27 | return m << bit
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Swift/first-missing-positive.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/first-missing-positive/
3 | *
4 | *
5 | */
6 | // Date: Wed Sep 30 10:14:43 PDT 2020
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(n), n is the length of `nums`
10 | /// - Space: O(n), n is the length of `nums`
11 | func firstMissingPositive(_ nums: [Int]) -> Int {
12 | var nums = nums + [0]
13 | let n = nums.count
14 | for index in 0 ..< n {
15 | if nums[index] < 0 || nums[index] >= n {
16 | nums[index] = 0
17 | }
18 | }
19 | for index in 0 ..< n {
20 | nums[nums[index] % n] += n
21 | }
22 | for index in 1 ..< n {
23 | if nums[index] / n == 0 {
24 | return index
25 | }
26 | }
27 | return n
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Swift/maximum-subarray.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-subarray/
3 | *
4 | *
5 | */
6 | class Solution {
7 | /// - Complexity: O(n), n is the number of elements in the array.
8 | ///
9 | /// - Description:
10 | /// Here,
11 | /// 1. sum is the maximum sum ending with element n, inclusive.
12 | /// 2. compare the maxSum with current sum ending with element n.
13 | /// 3. if sum is negtive, it will not be helpful for the maximum possible element ending with next element. Then, clear it to zero, 0.
14 | ///
15 | ///
16 | func maxSubArray(_ nums: [Int]) -> Int {
17 | var sum = 0
18 | var maxSum = Int.min
19 | for n in nums {
20 | sum += n
21 | maxSum = max(maxSum, sum)
22 | sum = max(0, sum)
23 | }
24 | return maxSum
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Swift/minimum-cost-to-move-chips-to-the-same-position.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/
3 | *
4 | *
5 | */
6 | // Date: Thu Nov 5 10:00:52 PST 2020
7 | class Solution {
8 | func minCostToMoveChips(_ position: [Int]) -> Int {
9 | var odds = 0
10 | var even = 0
11 | for p in position {
12 | if p % 2 == 0 { even += 1}
13 | else {odds += 1 }
14 | }
15 | return min(odds, even)
16 | }
17 | }/**
18 | * https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/
19 | *
20 | *
21 | */
22 | // Date: Thu Nov 5 10:01:09 PST 2020
23 | class Solution {
24 | func minCostToMoveChips(_ position: [Int]) -> Int {
25 | let count = position.filter { $0 % 2 == 0}.count
26 | return min(position.count - count, count)
27 | }
28 | }
--------------------------------------------------------------------------------
/Swift/maximum-erasure-value.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-erasure-value/
3 | *
4 | *
5 | */
6 | // Date: Fri May 28 22:36:38 PDT 2021
7 | class Solution {
8 | func maximumUniqueSubarray(_ nums: [Int]) -> Int {
9 | var map: [Int : Int] = [:]
10 | var sum = 0
11 | var result = 0
12 | var left = 0
13 | for right in stride(from: 0, to: nums.count, by: 1) {
14 | let n = nums[right]
15 | sum += n
16 | if let lastIndex = map[n] {
17 | while left <= lastIndex {
18 | sum -= nums[left]
19 | left += 1
20 | }
21 | }
22 | map[n] = right
23 | result = max(result, sum)
24 | // print("\(sum) - \(result)")
25 | }
26 | // print(map)
27 | return result
28 | }
29 | }
--------------------------------------------------------------------------------
/Swift/reshape-the-matrix.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/reshape-the-matrix/
3 | *
4 | *
5 | */
6 | // Date: Mon Jul 5 22:06:10 PDT 2021
7 | class Solution {
8 | func matrixReshape(_ mat: [[Int]], _ r: Int, _ c: Int) -> [[Int]] {
9 | let n = mat.count
10 | guard let m = mat.first?.count, n * m == r * c else { return mat }
11 | var result = Array(repeating: Array(repeating: 0, count: c), count: r)
12 | var xx = 0
13 | var yy = 0
14 | for x in stride(from: 0, to: mat.count, by: 1) {
15 | for y in stride(from: 0, to: mat.first?.count ?? 0, by: 1) {
16 | result[xx][yy] = mat[x][y]
17 | yy += 1
18 | if yy == c {
19 | xx += 1
20 | yy = 0
21 | }
22 | }
23 | }
24 | return result
25 | }
26 | }
--------------------------------------------------------------------------------
/Swift/goat-latin.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/goat-latin/
3 | *
4 | *
5 | */
6 | // Date: Wed Aug 19 17:18:51 PDT 2020
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(n), n is the number of single words in S.
10 | /// - Space: O(length of S)
11 | ///
12 | func toGoatLatin(_ S: String) -> String {
13 | var list = S.split(separator: " ")
14 | var trailing = ""
15 | for index in 0 ..< list.count {
16 | trailing += "a"
17 | var origin = list[index]
18 | if let first = origin.first, "aeiou".contains(first) == false, "AEIOU".contains(first) == false {
19 | origin += String(origin.removeFirst())
20 | }
21 | origin += "ma" + trailing
22 | list[index] = origin
23 | }
24 | return list.joined(separator: " ")
25 | }
26 | }
--------------------------------------------------------------------------------
/Swift/element-appearing-more-than-25-in-sorted-array.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/
3 | *
4 | *
5 | */
6 | // Date: Thu Aug 13 14:18:04 PDT 2020
7 | class Solution {
8 | func findSpecialInteger(_ arr: [Int]) -> Int {
9 | var last: Int? = nil
10 | var count = 0
11 | for n in arr {
12 | if let num = last {
13 | if num == n {
14 | count += 1
15 | } else {
16 | last = n
17 | count = 1
18 | }
19 | } else {
20 | last = n
21 | count = 1
22 | }
23 | // print("\(last) : \(count)")
24 | if count * 4 > arr.count {
25 | return last!
26 | }
27 | }
28 | return -1
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Swift/number-of-recent-calls.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/number-of-recent-calls/
3 | *
4 | *
5 | */
6 | // Date: Thu Oct 1 10:08:10 PDT 2020
7 | // Implementation with Sliding Window.
8 | class RecentCounter {
9 | var calls: [Int]
10 |
11 | init() {
12 | self.calls = []
13 | }
14 |
15 | /// - Complexity:
16 | /// - Time: O(3000)
17 | /// - Space: O(3000)
18 | func ping(_ t: Int) -> Int {
19 | while let first = self.calls.first {
20 | if t - first <= 3000 {
21 | break
22 | }
23 | self.calls.removeFirst()
24 | }
25 | self.calls.append(t)
26 | return self.calls.count
27 | }
28 | }
29 |
30 | /**
31 | * Your RecentCounter object will be instantiated and called as such:
32 | * let obj = RecentCounter()
33 | * let ret_1: Int = obj.ping(t)
34 | */
--------------------------------------------------------------------------------
/Java/sum-root-to-leaf-numbers.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/sum-root-to-leaf-numbers/
3 | *
4 | * Definition for a binary tree node.
5 | * public class TreeNode {
6 | * int val;
7 | * TreeNode left;
8 | * TreeNode right;
9 | * TreeNode(int x) { val = x; }
10 | * }
11 | */
12 | public class Solution {
13 | private int sum;
14 | public int sumNumbers(TreeNode root) {
15 | sum = 0;
16 | sumTrav(root, 0);
17 | return sum;
18 | }
19 |
20 | private void sumTrav(TreeNode root, int s) {
21 | if(root == null) {
22 | return;
23 | }
24 | if(root.left == null && root.right == null) {
25 | sum += s * 10 + root.val;
26 | return;
27 | }
28 | sumTrav(root.left, s * 10 + root.val);
29 | sumTrav(root.right, s * 10 + root.val);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Swift/beautiful-arrangement.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/beautiful-arrangement/
3 | *
4 | *
5 | */
6 | // Date: Sun Jan 3 17:23:07 PST 2021
7 | class Solution {
8 | func countArrangement(_ n: Int) -> Int {
9 | var result = 0
10 | func dfs(_ candidate: inout Set, at index: Int) {
11 | if candidate.isEmpty {
12 | result += 1
13 | return
14 | }
15 | let list = Array(candidate)
16 | for cand in list {
17 | if cand % index == 0 || index % cand == 0 {
18 | candidate.remove(cand)
19 | dfs(&candidate, at: index + 1)
20 | candidate.insert(cand)
21 | }
22 | }
23 | }
24 | var candidates = Set(1 ... n)
25 | dfs(&candidates, at: 1)
26 | return result
27 | }
28 | }
--------------------------------------------------------------------------------
/Swift/maximum-sum-circular-subarray.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-sum-circular-subarray/
3 | *
4 | *
5 | */
6 | // Date: Mon May 18 20:43:30 PDT 2020
7 | ///
8 | /// Ref Link: https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/178422/One-Pass
9 | ///
10 | class Solution {
11 | func maxSubarraySumCircular(_ A: [Int]) -> Int {
12 | var total = 0
13 | var currentMax = 0
14 | var currentMin = 0
15 | var sumMax = A[0]
16 | var sumMin = A[0]
17 |
18 | for a in A {
19 | total += a
20 | currentMax = max(a, currentMax + a)
21 | sumMax = max(sumMax, currentMax)
22 | currentMin = min(a, currentMin + a)
23 | sumMin = min(sumMin, currentMin)
24 | }
25 |
26 | return sumMax > 0 ? max(sumMax, total - sumMin) : sumMax
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Swift/minimum-cost-for-tickets.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/minimum-cost-for-tickets/
3 | *
4 | *
5 | */
6 | // Date: Fri Aug 28 16:06:32 PDT 2020
7 | /// - Complexity:
8 | /// - Time: O(time of converting days into a set + 365)
9 | /// - Space: O(366), store the cost of days from 0 to 365.
10 | ///
11 | class Solution {
12 | func mincostTickets(_ days: [Int], _ costs: [Int]) -> Int {
13 | let last = days[days.count - 1]
14 | var cost = Array(repeating: 0, count: last)
15 | let days = Set(days)
16 | for day in 1 ... last {
17 | if days.contains(day) {
18 | cost[day] = min(cost[day - 1] + costs[0], min(cost[max(0, day - 7)] + costs[1], cost[max(0, day - 30)] + costs[2]))
19 | } else {
20 | cost[day] = cost[day - 1]
21 | }
22 | }
23 | return cost[365]
24 | }
25 | }
--------------------------------------------------------------------------------
/Java/implement-queue-using-stacks.java:
--------------------------------------------------------------------------------
1 | class MyQueue {
2 | // Push element x to the back of queue.
3 | private Stack mainStack = new Stack();
4 | private Stack assistant = new Stack();
5 |
6 | public void push(int x) {
7 | while(!assistant.empty()) mainStack.push(assistant.pop());
8 | mainStack.push(x);
9 | }
10 |
11 | // Removes the element from in front of queue.
12 | public void pop() {
13 | while(!mainStack.empty()) assistant.push(mainStack.pop());
14 | assistant.pop();
15 | }
16 |
17 | // Get the front element.
18 | public int peek() {
19 | while(!mainStack.empty()) assistant.push(mainStack.pop());
20 | return assistant.peek();
21 | }
22 |
23 | // Return whether the queue is empty.
24 | public boolean empty() {
25 | return mainStack.empty() && assistant.empty();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Swift/set-matrix-zeroes.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/set-matrix-zeroes/
3 | *
4 | *
5 | */
6 | // Date: Fri Aug 13 09:08:58 PDT 2021
7 | class Solution {
8 | func setZeroes(_ matrix: inout [[Int]]) {
9 | let n = matrix.count
10 | guard let m = matrix.first?.count else { return }
11 | var row = Set()
12 | var col = Set()
13 | for x in 0 ..< n {
14 | for y in 0 ..< m {
15 | if matrix[x][y] == 0 {
16 | row.insert(x)
17 | col.insert(y)
18 | }
19 | }
20 | }
21 | for x in row {
22 | for y in 0 ..< m {
23 | matrix[x][y] = 0
24 | }
25 | }
26 | for y in col {
27 | for x in 0 ..< n {
28 | matrix[x][y] = 0
29 | }
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/Swift/two-city-scheduling.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/two-city-scheduling/
3 | *
4 | *
5 | */
6 | // Date: Wed Jun 3 10:14:05 PDT 2020
7 | class Solution {
8 | /// Sort the city traveling cost by its cost difference.
9 | /// Then, we add the cost of first n people going to city A, and the rest of people going to city B.
10 | /// - Complexity:
11 | /// - Time: O(nlogn), n is the number of people in the array.
12 | /// - Space: O(n), since we copy and sort the original array.
13 | ///
14 | func twoCitySchedCost(_ costs: [[Int]]) -> Int {
15 | let costs = costs.sorted { ($0[0] - $0[1]) < ($1[0] - $1[1]) }
16 | var minCost = 0
17 | for index in 0 ..< costs.count / 2 {
18 | minCost += costs[index][0]
19 | minCost += costs[costs.count - 1 - index][1]
20 | }
21 | return minCost
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Swift/wiggle-subsequence.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/wiggle-subsequence/
3 | *
4 | *
5 | */
6 | // Date: Thu Mar 18 15:30:35 PDT 2021
7 | class Solution {
8 | func wiggleMaxLength(_ nums: [Int]) -> Int {
9 | var up = Array(repeating: 1, count: nums.count)
10 | var down = Array(repeating: 1, count: nums.count)
11 | var result = 1
12 | for index in stride(from: 1, to: nums.count, by: 1) {
13 | for last in stride(from: 0, to: index, by: 1) {
14 | if nums[index] > nums[last] {
15 | up[index] = max(up[index], 1 + down[last])
16 | } else if nums[index] < nums[last] {
17 | down[index] = max(down[index], 1 + up[last])
18 | }
19 | }
20 | result = max(result, max(down[index], up[index]))
21 | }
22 | return result
23 | }
24 | }
--------------------------------------------------------------------------------
/Swift/convert-binary-number-in-a-linked-list-to-integer.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
3 | *
4 | *
5 | */
6 | // Date: Sun Nov 1 08:47:17 PST 2020
7 | /**
8 | * Definition for singly-linked list.
9 | * public class ListNode {
10 | * public var val: Int
11 | * public var next: ListNode?
12 | * public init() { self.val = 0; self.next = nil; }
13 | * public init(_ val: Int) { self.val = val; self.next = nil; }
14 | * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
15 | * }
16 | */
17 | class Solution {
18 | func getDecimalValue(_ head: ListNode?) -> Int {
19 | var node = head
20 | var result = 0
21 | while let cnode = node {
22 | result = (result << 1) + cnode.val
23 | node = cnode.next
24 | }
25 | return result
26 | }
27 | }
--------------------------------------------------------------------------------
/Swift/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/
3 | *
4 | *
5 | */
6 | // Date: Thu Jun 3 15:45:45 PDT 2021
7 | class Solution {
8 | func maxArea(_ h: Int, _ w: Int, _ horizontalCuts: [Int], _ verticalCuts: [Int]) -> Int {
9 | let hc = [0] + horizontalCuts.sorted() + [h]
10 | let vc = [0] + verticalCuts.sorted() + [w]
11 | var hDist = [Int]()
12 | var vDist = [Int]()
13 | for index in stride(from: 1, to: hc.count, by: 1) {
14 | hDist.append(hc[index] - hc[index - 1])
15 | }
16 | for index in stride(from: 1, to: vc.count, by: 1) {
17 | vDist.append(vc[index] - vc[index - 1])
18 | }
19 | return ((hDist.max()! % 1000000007) * (vDist.max()! % 1000000007)) % 1000000007
20 | }
21 | }
--------------------------------------------------------------------------------
/Swift/rotate-image.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/rotate-image/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func rotate(_ matrix: inout [[Int]]) {
8 | for offset in 0 ..< matrix.count / 2 {
9 | rotate(&matrix, offset)
10 | }
11 | }
12 |
13 | func rotate(_ matrix: inout [[Int]], _ offset: Int) {
14 | let size = matrix.count - offset * 2
15 | for index in 0 ..< (size - 1) {
16 | let tmp = matrix[offset][index + offset]
17 | matrix[offset][index + offset] = matrix[offset + size - index - 1][offset]
18 | matrix[offset + size - index - 1][offset] = matrix[offset + size - 1][offset + size - index - 1]
19 | matrix[offset + size - 1][offset + size - index - 1] = matrix[offset + index][offset + size - 1]
20 | matrix[offset + index][offset + size - 1] = tmp
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Java/restore-ip-addresses.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | private List list;
3 | public List restoreIpAddresses(String s) {
4 | list = new ArrayList();
5 | backtrack(s, 0, 4, "");
6 | return list;
7 | }
8 |
9 | private void backtrack(String s, int k, int n, String ret) {
10 | if(k == s.length() && n == 0) {
11 | list.add(ret.substring(1));
12 | return;
13 | } else if (k == s.length()) return;
14 | else if(n == 0) return;
15 |
16 | for(int len=1; len<=3 && k+len<=s.length(); len++) {
17 | String ss = s.substring(k, k+len);
18 | int num = Integer.parseInt(ss);
19 | if((""+num).length() != len) continue;
20 | if(num >=0 && num<=255) {
21 | backtrack(s, k+len, n-1, ret + "." + num);
22 | }
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Java/Combinations.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/combinations/
3 | *
4 | * Backtracking Problem, try out all the possible solutions and appropriate prunning
5 | */
6 | public class Solution {
7 | public List> combine(int n, int k) {
8 | list = new ArrayList>();
9 | combine(n, k, 1, new ArrayList());
10 | return list;
11 | }
12 |
13 | private List> list;
14 |
15 | private void combine(int n, int k, int start, ArrayList ret){
16 | if(ret.size() == k) {
17 | list.add(new ArrayList(ret));
18 | return;
19 | }
20 | if(ret.size() + n-start+1 < k) return;
21 | for(int i=start; i<=n; i++) {
22 | ret.add(i);
23 | combine(n, k, i+1, ret);
24 | ret.remove(ret.size()-1);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Java/pascal-triangle.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/pascals-triangle/
3 | */
4 | public class Solution {
5 | public List> generate(int n) {
6 | List> list = new ArrayList>();
7 | if(n == 0) return list;
8 | List tmp = new ArrayList();
9 | int[][] cand = new int[2][n];
10 | cand[0][0] = 1;
11 | tmp.add(1);
12 | list.add(new ArrayList(tmp));
13 | for(int i=1; i 0) cand[x][j] += cand[(x+1) % 2][j-1];
19 | tmp.add(cand[x][j]);
20 | }
21 | list.add(new ArrayList(tmp));
22 | }
23 | return list;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Java/word-pattern.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/word-pattern/
3 | */
4 | import java.util.*;
5 |
6 | public class Solution {
7 | public boolean wordPattern(String pattern, String str) {
8 | String[] ss = str.split(" ");
9 | HashMap map = new HashMap();
10 |
11 | if(ss.length != pattern.length()) return false;
12 |
13 | for(int i=0; i Bool {
9 | var queue = [start]
10 | var visited: Set = [start]
11 | while queue.isEmpty == false {
12 | let index = queue.removeFirst()
13 | if arr[index] == 0 { return true }
14 | let left = index - arr[index]
15 | let right = index + arr[index]
16 | if left >= 0, visited.contains(left) == false {
17 | visited.insert(left)
18 | queue.append(left)
19 | }
20 | if right < arr.count, visited.contains(right) == false {
21 | visited.insert(right)
22 | queue.append(right)
23 | }
24 | }
25 | return false
26 | }
27 | }
--------------------------------------------------------------------------------
/Java/longest-consecutive-sequence.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem: https://leetcode.com/problems/longest-consecutive-sequence/
3 | **/
4 | public class Solution {
5 | public int longestConsecutive(int[] nums) {
6 | HashSet set = new HashSet();
7 | for(int n : nums) {
8 | set.add(n);
9 | }
10 |
11 | int max = 0;
12 | for(int n : nums) {
13 | int count = 1;
14 | int left = n - 1;
15 | int right = n + 1;
16 | while(set.contains(left)) {
17 | count++;
18 | set.remove(left);
19 | left--;
20 | }
21 | while(set.contains(right)) {
22 | count++;
23 | set.remove(right);
24 | right++;
25 | }
26 | max = Math.max(max, count);
27 | }
28 | return max;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Swift/decode-string.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/decode-string/
3 | *
4 | *
5 | */
6 | // Date: Thu Nov 19 09:33:04 PST 2020
7 | class Solution {
8 | func decodeString(_ s: String) -> String {
9 | var num = 0
10 | var text = ""
11 | var stack1 = [Int]()
12 | var stack2 = [String]()
13 | for c in s {
14 | if "[" == String(c) {
15 | stack1.append(num)
16 | stack2.append(text)
17 | num = 0
18 | text = ""
19 | } else if "]" == String(c) {
20 | text = stack2.removeLast() + Array(repeating: text, count: stack1.removeLast()).joined()
21 | } else if "0123456789".contains(c) {
22 | num = num * 10 + Int(String(c))!
23 | } else {
24 | text += String(c)
25 | }
26 | }
27 | return text
28 | }
29 | }
--------------------------------------------------------------------------------
/Swift/determine-if-two-strings-are-close.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/determine-if-two-strings-are-close/
3 | *
4 | *
5 | */
6 | // Date: Fri Jan 22 09:07:14 PST 2021
7 | class Solution {
8 | func closeStrings(_ word1: String, _ word2: String) -> Bool {
9 | var count1 = Array(repeating: 0, count: 26)
10 | var count2 = Array(repeating: 0, count: 26)
11 | for c in word1 {
12 | count1[Int(c.asciiValue!) - 97] += 1
13 | }
14 | for c in word2 {
15 | count2[Int(c.asciiValue!) - 97] += 1
16 | }
17 | for index in 0 ..< 26 {
18 | if count1[index] > 0 && count2[index] == 0 { return false }
19 | if count2[index] > 0 && count1[index] == 0 { return false }
20 | }
21 | count1.sort()
22 | count2.sort()
23 | // print("\(count1) - \(count2)")
24 | return count1 == count2
25 | }
26 | }
--------------------------------------------------------------------------------
/Swift/four-divisors.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/four-divisors/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func sumFourDivisors(_ nums: [Int]) -> Int {
8 | var sum = 0
9 | for num in nums {
10 | if num < 5 { continue }
11 | var div = 0
12 | for d in stride(from: 2, through: Int(sqrt(Double(num))), by: 1) {
13 | // print("Div: \(d)")
14 | if num % d == 0 {
15 | if div != 0 {
16 | div = 0
17 | break
18 | } else {
19 | div = d
20 | }
21 | }
22 | }
23 | if div != 0, num != (div * div) {
24 | // print("\(num) - \(div)")
25 | sum += num + 1 + div + num / div
26 | }
27 | }
28 | return sum
29 | }
30 | }
--------------------------------------------------------------------------------
/Swift/partition-equal-subset-sum.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/partition-equal-subset-sum/
3 | *
4 | *
5 | */
6 | // Date: Fri Nov 27 16:18:27 PST 2020
7 | class Solution {
8 | func canPartition(_ nums: [Int]) -> Bool {
9 | let sum = nums.reduce(0) { $0 + $1 }
10 | if sum % 2 != 0 { return false }
11 | let half = sum / 2
12 | var mark = Array(repeating: Array(repeating: false, count: half + 1), count: 2)
13 | mark[0][0] = true
14 | for index in 1 ... nums.count {
15 | let n = nums[index - 1]
16 | for sum in 0 ... half {
17 | mark[index % 2][sum] = mark[1 - index % 2][sum]
18 | if sum >= n {
19 | mark[index % 2][sum] = mark[index % 2][sum] || mark[1 - index % 2][sum - n]
20 | }
21 | }
22 | }
23 | return mark[nums.count % 2][half]
24 | }
25 | }
--------------------------------------------------------------------------------
/Java/linked-list-cycle.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/linked-list-cycle/
3 | *
4 | * Definition for singly-linked list.
5 | * class ListNode {
6 | * int val;
7 | * ListNode next;
8 | * ListNode(int x) {
9 | * val = x;
10 | * next = null;
11 | * }
12 | * }
13 | */
14 | public class Solution {
15 | public boolean hasCycle(ListNode head) {
16 | ListNode node1 = head;
17 | ListNode node2 = null;
18 | if(head != null && head.next != null) {
19 | node2 = head.next;
20 | } else {
21 | return false;
22 | }
23 | while(node1 != null) {
24 | if(node1 == node2) return true;
25 | node1 = node1.next;
26 | if(node2.next != null && node2.next.next != null) node2 = node2.next.next;
27 | else return false;
28 | }
29 | return false;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Java/search-a-2d-matrix.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * Problem: https://leetcode.com/problems/search-a-2d-matrix/
4 | *
5 | * Binary Search since this 2D matrix could be seen as an ordered one dimension array.
6 | */
7 |
8 | public class Solution {
9 | public boolean searchMatrix(int[][] matrix, int target) {
10 | if(matrix==null || matrix.length==0 || matrix[0].length==0)
11 | return false;
12 | int m = matrix.length;
13 | int n = matrix[0].length;
14 | int left = 0;
15 | int right = m * n - 1;
16 |
17 | while(left <= right) {
18 | int mid = (left + right) / 2;
19 | int x = mid / n;
20 | int y = mid % n;
21 |
22 | if(target == matrix[x][y]) return true;
23 | if(target > matrix[x][y]) left = mid + 1;
24 | else right = mid - 1;
25 | }
26 | return false;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Python/two-sum.py:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/two-sum/
3 | *
4 | *
5 | */
6 |
7 | // Date Sun Mar 23 16:10:39 PDT 2025
8 | class Solution:
9 | def twoSum(self, nums: List[int], target: int) -> List[int]:
10 | for start in range(len(nums)):
11 | for end in range(start + 1, len(nums)):
12 | if nums[start] + nums[end] == target:
13 | return [start, end]
14 | return []
15 | /**
16 | * https://leetcode.com/problems/two-sum/
17 | *
18 | *
19 | */
20 | // Date: Thu Mar 27 16:50:15 PDT 2025
21 | class Solution:
22 | def twoSum(self, nums: List[int], target: int) -> List[int]:
23 | hashmap = {}
24 | for index in range(len(nums)):
25 | left = target - nums[index]
26 | if left in hashmap:
27 | return [hashmap[left], index]
28 | hashmap[nums[index]] = index
29 | return []
30 |
31 |
--------------------------------------------------------------------------------
/Swift/array-nesting.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/array-nesting/
3 | *
4 | *
5 | */
6 | // Date: Wed Sep 1 10:38:30 PDT 2021
7 | class Solution {
8 | /// - Complexity:
9 | /// - Time: O(n), n = nums.count
10 | /// - Space: O(n), n = nums.count
11 | func arrayNesting(_ nums: [Int]) -> Int {
12 | var visited = Set()
13 | let n = nums.count
14 | var result = 0
15 | for startIndex in 0 ..< n {
16 | var start = nums[startIndex]
17 | if visited.contains(start) { continue }
18 | visited.insert(start)
19 | var count = 1
20 | while visited.contains(nums[start]) == false {
21 | visited.insert(nums[start])
22 | count += 1
23 | start = nums[start]
24 | }
25 | result = max(result, count)
26 | }
27 | return result
28 | }
29 | }
--------------------------------------------------------------------------------
/Swift/binary-trees-with-factors.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/binary-trees-with-factors/
3 | *
4 | *
5 | */
6 | // Date: Thu Mar 18 21:09:13 PDT 2021
7 | class Solution {
8 | func numFactoredBinaryTrees(_ arr: [Int]) -> Int {
9 | let arr = arr.sorted()
10 | let mod = 1_000_000_007
11 | var map: [Int : Int] = [:]
12 | for x in arr {
13 | map[x] = 1
14 | }
15 | var result = 0
16 | for i in stride(from: 0, to: arr.count, by: 1) {
17 | for j in stride(from: 0, to: i, by: 1) {
18 | if arr[i] % arr[j] == 0, let x = map[arr[j]], let y = map[arr[i] / arr[j]] {
19 | map[arr[i]] = (map[arr[i]]! + x * y) % mod
20 | }
21 | }
22 | // print("\(arr[i]) - \(map[arr[i]])")
23 | result = (result + map[arr[i]]!) % mod
24 | }
25 | return result
26 | }
27 | }
--------------------------------------------------------------------------------
/Swift/unique-paths-ii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/unique-paths-ii/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int {
8 | let n = obstacleGrid.count
9 | guard let m = obstacleGrid.first?.count else { return 0 }
10 | var mark = Array(repeating: Array(repeating: 0, count: m), count: n)
11 | // It's important to check if the start position is valid or not.
12 | mark[0][0] = 1 - obstacleGrid[0][0]
13 | for x in 0 ..< n {
14 | for y in 0 ..< m {
15 | if obstacleGrid[x][y] == 1 { continue }
16 | if x > 0 {
17 | mark[x][y] += mark[x - 1][y]
18 | }
19 | if y > 0 {
20 | mark[x][y] += mark[x][y - 1]
21 | }
22 | }
23 | }
24 | return mark[n - 1][m - 1]
25 | }
26 | }
--------------------------------------------------------------------------------
/Swift/minimum-moves-to-equal-array-elements-ii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/
3 | *
4 | *
5 | */
6 | class Solution {
7 | func minMoves2(_ nums: [Int]) -> Int {
8 | let n = nums.count
9 | if n == 0 { return 0 }
10 | let list = nums.sorted()
11 | let med = list[n/2]
12 | var total = 0
13 | for n in list {
14 | total += abs(n - med)
15 | }
16 | return total
17 | }
18 | }
19 |
20 | /**
21 | * https://leetcode.com/problems/minimum-moves-to-equal-array-elements-i/
22 | *
23 | *
24 | */
25 | // Date: Wed May 19 08:51:03 PDT 2021
26 | class Solution {
27 | func minMoves2(_ nums: [Int]) -> Int {
28 | let nums = nums.sorted()
29 | let n = nums.count
30 | let med = nums[n / 2]
31 | let costL = nums.reduce(0) { $0 + abs($1 - med) }
32 | return costL
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Swift/remove-k-digits.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/remove-k-digits/
3 | *
4 | *
5 | */
6 | // Date: Wed May 13 09:29:38 PDT 2020
7 | class Solution {
8 | func removeKdigits(_ num: String, _ k: Int) -> String {
9 | if k == num.count { return "0" }
10 | var stack = [Character]()
11 | var k = k
12 | for c in num {
13 | while k > 0, let last = stack.last, last > c {
14 | stack.removeLast()
15 | k -= 1
16 | }
17 | stack.append(c)
18 | }
19 |
20 | // Case: 1122, k = 2
21 | while k > 0 {
22 | stack.removeLast()
23 | k -= 1
24 | }
25 |
26 | // Case: 10000, k = 1
27 | while let first = stack.first, "0" == String(first) {
28 | stack.removeFirst()
29 | }
30 | return stack.isEmpty ? "0" : String(stack)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Swift/single-number-ii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/single-number-ii/
3 | *
4 | *
5 | */
6 |
7 | class Solution {
8 | func singleNumber(_ nums: [Int]) -> Int {
9 | return self.singleNumber(nums, with: 3)
10 | }
11 |
12 | fileprivate func singleNumber(_ nums: [Int], with repeatNumber: Int) -> Int {
13 | var ret = 0
14 | for bit in 0 ..< 64 {
15 | var count = 0
16 | for n in nums {
17 | if ((n >> bit) & 1) == 1 { count += 1 }
18 | }
19 | count %= repeatNumber
20 | ret |= (count << bit)
21 | }
22 | return ret
23 | }
24 |
25 | func singleNumber(_ nums: [Int]) -> Int {
26 | var count: [Int : Int] = [:]
27 | for n in nums {
28 | count[n] = (count[n, default: 0] + 1)
29 | }
30 | return count.filter{$0.value == 1}.keys.first ?? 0
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Swift/valid-square.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/valid-square/
3 | *
4 | *
5 | */
6 | // Date: Wed Nov 11 09:45:43 PST 2020
7 | class Solution {
8 |
9 | private func dist(_ p1: [Int], _ p2: [Int]) -> Int {
10 | return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1])
11 | }
12 |
13 | func validSquare(_ p1: [Int], _ p2: [Int], _ p3: [Int], _ p4: [Int]) -> Bool {
14 | let p = [p1, p2, p3, p4].sorted {
15 | if $0[0] == $1[0] { return $0[1] < $1[1] }
16 | return $0[0] < $1[0]
17 | }
18 | let d1 = dist(p[0], p[1])
19 | let d2 = dist(p[3], p[1])
20 | let d3 = dist(p[2], p[3])
21 | let d4 = dist(p[0], p[2])
22 |
23 | let d5 = dist(p[0], p[3])
24 | let d6 = dist(p[1], p[2])
25 |
26 | return d1 > 0 && d1 == d2 && d2 == d3 && d3 == d4 && d4 == d1 && d5 == d6
27 | }
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/Swift/copy-list-with-random-pointer.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/copy-list-with-random-pointer/
3 | *
4 | *
5 | */
6 | // Date: Wed Mar 10 11:03:06 PST 2021
7 | /**
8 | * Definition for a Node.
9 | * public class Node {
10 | * public var val: Int
11 | * public var next: Node?
12 | * public var random: Node?
13 | * public init(_ val: Int) {
14 | * self.val = val
15 | * self.next = nil
16 | * self.random = nil
17 | * }
18 | * }
19 | */
20 |
21 | class Solution {
22 | var visited: [Node : Node] = [:]
23 | func copyRandomList(_ head: Node?) -> Node? {
24 | guard let head = head else { return nil }
25 | if let node = visited[head] { return node }
26 | let root = Node(head.val)
27 | visited[head] = root
28 | root.next = copyRandomList(head.next)
29 | root.random = copyRandomList(head.random)
30 | return root
31 | }
32 | }
--------------------------------------------------------------------------------
/Swift/word-pattern.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/word-pattern/
3 | *
4 | *
5 | */
6 | // Date: Mon Sep 7 08:31:44 PDT 2020
7 |
8 | class Solution {
9 | /// - Complexity:
10 | /// - Time: O(n + m), use O(n) to split, then O(m) to validate.
11 | /// - Space: O(n + m), for two dictionaries.
12 | func wordPattern(_ pattern: String, _ str: String) -> Bool {
13 | let list = str.split(separator: " ")
14 | if pattern.count != list.count { return false }
15 | var dict1: [Character : String] = [:]
16 | var dict2: [String : Character] = [:]
17 | for (index, c) in pattern.enumerated() {
18 | let v = String(list[index])
19 | if let value = dict1[c], value != v { return false }
20 | if let value = dict2[v], value != c { return false }
21 | dict1[c] = v
22 | dict2[v] = c
23 | }
24 | return true
25 | }
26 | }
--------------------------------------------------------------------------------
/Swift/4sum-ii.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/4sum-ii/
3 | *
4 | *
5 | */
6 | // Date: Thu Dec 17 10:28:28 PST 2020
7 | class Solution {
8 | func fourSumCount(_ A: [Int], _ B: [Int], _ C: [Int], _ D: [Int]) -> Int {
9 | let dict1 = self.combine(A, B)
10 | let dict2 = self.combine(C, D)
11 | var result = 0
12 | for (sum, count1) in dict1 {
13 | if let count2 = dict2[-sum] {
14 | result += count1 * count2
15 | }
16 | }
17 | return result
18 | }
19 |
20 | /// - Complexity:
21 | /// - Time: O(n^2)
22 | /// - Space: O(n^2)
23 | private func combine(_ A: [Int], _ B: [Int]) -> [Int : Int] {
24 | var result: [Int : Int] = [:]
25 | for a in A {
26 | for b in B {
27 | result[a + b] = 1 + result[a + b, default: 0]
28 | }
29 | }
30 | return result
31 | }
32 | }
--------------------------------------------------------------------------------
/Swift/verifying-an-alien-dictionary.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/verifying-an-alien-dictionary/
3 | *
4 | *
5 | */
6 | // Date: Fri Apr 9 14:30:32 PDT 2021
7 | class Solution {
8 | func isAlienSorted(_ words: [String], _ order: String) -> Bool {
9 | var mappedOrder = [Character : Int]()
10 | order.enumerated().forEach { mappedOrder[$1] = $0 }
11 | let sorted = words.sorted { (a, b) -> Bool in
12 | var index = 0
13 | let a = Array(a)
14 | let b = Array(b)
15 | while true {
16 | if index >= a.count { return true }
17 | if index >= b.count { return false }
18 | if a[index] != b[index] {
19 | return mappedOrder[a[index], default: 0] < mappedOrder[b[index], default: 0]
20 | }
21 | index += 1
22 | }
23 | }
24 | return sorted == words
25 | }
26 | }
--------------------------------------------------------------------------------
/Swift/3sum-closest.swift:
--------------------------------------------------------------------------------
1 | class Solution {
2 | func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
3 | let nums = nums.sorted()
4 |
5 | var minSum = 0
6 | var minDiff = Int.max
7 |
8 | for start in 0 ..< nums.count {
9 | let sum = target - nums[start]
10 |
11 | var left = start + 1
12 | var right = nums.count - 1
13 | while left < right {
14 | let tmpSum = nums[left] + nums[right]
15 | if minDiff > abs(sum - tmpSum) {
16 | minDiff = abs(sum - tmpSum)
17 | minSum = nums[start] + nums[left] + nums[right]
18 | }
19 | if tmpSum > sum {
20 | right -= 1
21 | } else {
22 | left += 1
23 | }
24 | }
25 | }
26 | return minSum
27 |
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Swift/maximum-units-on-a-truck.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/maximum-units-on-a-truck/
3 | *
4 | *
5 | */
6 | // Date: Mon Jun 14 11:02:41 PDT 2021
7 | class Solution {
8 | /// Sort + Greedy
9 | /// 1. Sort reversely to find the boxType with larger unit count.
10 | /// 2. Count the number of units could be put in the truck.
11 | /// - Complexity:
12 | /// - Time: (nlogn), where `n = boxTypes.count`
13 | /// - Space: O(n), where `n = boxTypes.count`
14 | func maximumUnits(_ boxTypes: [[Int]], _ truckSize: Int) -> Int {
15 | let sorted = boxTypes.sorted { $0[1] > $1[1] }
16 | var result = 0
17 | var left = truckSize
18 | var index = 0
19 | while index < sorted.count, left > 0 {
20 | result += min(sorted[index][0], left) * sorted[index][1]
21 | left -= sorted[index][0]
22 | index += 1
23 | }
24 | return result
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Java/binary-tree-preorder-traversal.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Problem Link: https://leetcode.com/problems/binary-tree-preorder-traversal/
3 | *
4 | * Iteratively traverse all the tree nodes.
5 | *
6 | * Definition for a binary tree node.
7 | * public class TreeNode {
8 | * int val;
9 | * TreeNode left;
10 | * TreeNode right;
11 | * TreeNode(int x) { val = x; }
12 | * }
13 | */
14 | public class Solution {
15 | public List preorderTraversal(TreeNode root) {
16 | Stack stack = new Stack();
17 | List list = new ArrayList();
18 | if(root == null) return list;
19 | stack.push(root);
20 | while(!stack.empty()) {
21 | TreeNode node = stack.pop();
22 | list.add(node.val);
23 | if(node.right != null) stack.push(node.right);
24 | if(node.left != null) stack.push(node.left);
25 | }
26 | return list;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Swift/minimum-operations-to-reduce-x-to-zero.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/
3 | *
4 | *
5 | */
6 | // Date: Thu Jan 14 11:27:10 PST 2021
7 | class Solution {
8 | func minOperations(_ nums: [Int], _ x: Int) -> Int {
9 | var leftSum = [0 : 0]
10 | var sum = 0
11 | for index in 0 ..< nums.count {
12 | sum += nums[index]
13 | if leftSum[sum] == nil {
14 | leftSum[sum] = index + 1
15 | }
16 | }
17 | sum = 0
18 | var minStep = leftSum[x, default: Int.max]
19 | for index in stride(from: nums.count - 1, through: 0, by: -1) {
20 | sum += nums[index]
21 | if let left = leftSum[x - sum], index >= left {
22 | minStep = min(minStep, left + nums.count - index)
23 | }
24 | }
25 |
26 |
27 | return minStep == Int.max ? -1 : minStep
28 | }
29 | }
--------------------------------------------------------------------------------
/Swift/delete-operation-for-two-strings.swift:
--------------------------------------------------------------------------------
1 | /**
2 | * https://leetcode.com/problems/delete-operation-for-two-strings/
3 | *
4 | *
5 | */
6 | // Date: Fri May 7 11:20:57 PDT 2021
7 | class Solution {
8 | func minDistance(_ word1: String, _ word2: String) -> Int {
9 | let word1 = Array(word1)
10 | let word2 = Array(word2)
11 | let n = word1.count
12 | let m = word2.count
13 | var dp = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
14 |
15 | for x in 0 ... n {
16 | for y in 0 ... m {
17 | if x == 0 || y == 0 {
18 | continue
19 | }
20 | dp[x][y] = max(dp[x][y], max(dp[x - 1][y], dp[x][y - 1]))
21 | if word1[x - 1] == word2[y - 1] {
22 | dp[x][y] = max(dp[x][y], 1 + dp[x - 1][y - 1])
23 | }
24 | }
25 | }
26 | return n + m - dp[n][m] * 2
27 | }
28 | }
--------------------------------------------------------------------------------