├── .gitattributes ├── Python ├── nim-game.py ├── reverse-string.py ├── to-lower-case.py ├── min-cost-climbing-stairs.py ├── number-of-1-bits.py ├── add-binary.py ├── contains-duplicate.py ├── reverse-words-in-a-string.py ├── reverse-words-in-a-string-iii.py ├── detect-capital.py ├── distribute-candies.py ├── hamming-distance.py ├── add-digits.py ├── array-partition-i.py ├── number-complement.py ├── single-number.py ├── climbing-stairs.py ├── jewels-and-stones.py ├── sort-array-by-parity.py ├── fibonacci-number.py ├── length-of-last-word.py ├── minimum-moves-to-equal-array-elements.py ├── rotate-string.py ├── house-robber.py ├── valid-anagram.py ├── peak-index-in-a-mountain-array.py ├── group-anagrams.py ├── intersection-of-two-arrays.py ├── sum-of-two-integers.py ├── single-number-ii.py ├── majority-element.py ├── minimum-moves-to-equal-array-elements-ii.py ├── excel-sheet-column-number.py ├── flip-game.py ├── missing-number.py ├── ugly-number.py ├── n-repeated-element-in-size-2n-array.py ├── palindrome-number.py ├── longest-uncommon-subsequence-i.py ├── find-anagram-mappings.py ├── powx-n.py ├── two-sum.py ├── find-pivot-index.py ├── line-reflection.py ├── paint-fence.py ├── implement-strstr.py ├── transpose-matrix.py ├── smallest-range-i.py ├── best-time-to-buy-and-sell-stock.py ├── fair-candy-swap.py ├── sqrtx.py ├── binary-gap.py ├── pascals-triangle-ii.py ├── toeplitz-matrix.py ├── prime-number-of-set-bits-in-binary-representation.py ├── remove-element.py ├── find-the-difference.py ├── plus-one.py ├── subsets.py ├── keyboard-row.py ├── contains-duplicate-ii.py ├── repeated-string-match.py ├── remove-duplicates-from-sorted-array.py ├── robot-return-to-origin.py ├── binary-number-with-alternating-bits.py ├── reverse-integer.py ├── coin-change.py ├── max-consecutive-ones.py ├── ransom-note.py ├── best-time-to-buy-and-sell-stock-ii.py ├── minimum-increment-to-make-array-unique.py ├── paint-house.py ├── permutations.py ├── maximum-subarray.py ├── self-dividing-numbers.py ├── smallest-range-ii.py ├── valid-word-square.py ├── 1-bit-and-2-bit-characters.py ├── fizz-buzz.py ├── house-robber-ii.py ├── two-sum-ii-input-array-is-sorted.py ├── best-time-to-buy-and-sell-stock-iii.py ├── reverse-only-letters.py ├── container-with-most-water.py ├── delete-node-in-a-linked-list.py ├── k-closest-points-to-origin.py ├── pascals-triangle.py ├── delete-columns-to-make-sorted.py ├── intersection-of-two-arrays-ii.py ├── subsets-ii.py ├── middle-of-the-linked-list.py ├── palindrome-permutation.py ├── kth-largest-element-in-an-array.py ├── paint-house-ii.py ├── reverse-linked-list.py ├── search-insert-position.py ├── uncommon-words-from-two-sentences.py ├── baseball-game.py ├── maximum-depth-of-n-ary-tree.py ├── backspace-string-compare.py ├── find-common-characters.py ├── permutations-ii.py ├── reverse-vowels-of-a-string.py ├── count-primes.py ├── first-bad-version.py ├── isomorphic-strings.py ├── rotate-array.py ├── longest-absolute-file-path.py ├── move-zeroes.py ├── valid-parenthesis.py ├── validate-stack-sequences.py ├── flipping-an-image.py ├── invert-binary-tree.py ├── next-closest-time.py ├── valid-palindrome.py ├── goat-latin.py ├── monotonic-array.py ├── next-greater-element-i.py ├── unique-morse-code-words.py ├── longest-substring-without-repeating-characters.py ├── partition-array-into-disjoint-intervals.py ├── sliding-window-median.py ├── squares-of-a-sorted-array.py ├── valid-mountain-array.py ├── trapping-rain-water.py ├── lemonade-change.py ├── number-of-recent-calls.py ├── projection-area-of-3D-shapes.py ├── zigzag-conversion.py ├── first-unique-character-in-a-string.py ├── remove-duplicates-from-sorted-list.py ├── find-all-numbers-disappeared-in-an-array.py ├── same-tree.py ├── search-in-a-binary-search-tree.py ├── linked-list-cycle.py ├── maximum-product-of-three-numbers.py ├── number-of-lines-to-write-string.py ├── range-sum-query-immutable.py ├── check-if-word-is-valid-after-substitutions.py ├── n-ary-tree-postorder-traversal.py ├── n-ary-tree-preorder-traversal.py ├── shortest-distance-to-a-character.py ├── univalued-binary-tree.py ├── merge-two-binary-trees.py ├── divide-two-integers.py ├── closest-binary-search-tree-value.py ├── encode-and-decode-strings.py ├── guess-number-higher-or-lower.py ├── house-robber-iii.py ├── roman-to-integer.py ├── integer-to-roman.py ├── merge-two-sorted-lists.py ├── sliding-window-maximum.py ├── sorted-array-by-parity-ii.py ├── strobogrammatic-number.py ├── unique-email-addresses.py ├── inorder-successor-in-bst.py ├── island-perimeter.py ├── symmetric-tree.py ├── reverse-words-in-a-string-ii.py ├── two-sum-input-is-a-bst.py ├── median-of-two-sorted-arrays.py ├── minimum-path-sum.py ├── path-sum.py ├── validate-binary-search-tree.py ├── minimum-depth-of-binary-tree.py ├── most-common-word.py ├── combination-sum-iii.py ├── sum-of-even-numbers-after-queries.py ├── trim-a-binary-search-tree.py ├── unique-paths.py ├── minimum-cost-to-hire-k-workers.py ├── remove-linked-list-elements.py ├── dungeon-game.py ├── letter-combinations-of-a-phone-number.py ├── missing-ranges.py ├── palindrome-linked-list.py ├── second-minimum-node-in-a-binary-tree.py ├── unique-paths-ii.py ├── word-break.py ├── 3sum-smaller.py ├── k-empty-slots.py ├── minimum-number-of-refueling-stops.py ├── subdomain-visit-count.py ├── bulls-and-cows.py ├── maximum-depth-of-binary-tree.py ├── count-and-say.py ├── diameter-of-binary-tree.py ├── find-k-closest-elements.py ├── number-of-boomerangs.py ├── read-n-characters-given-read4.py ├── kth-largest-element-in-a-stream.py ├── n-ary-tree-level-order-traversal.py ├── bag-of-tokens.py ├── longest-palindromic-substring.py ├── merge-k-sorted-lists.py ├── merge-sorted-array.py ├── contains-duplicate-iii.py ├── my-calendar-ii.py ├── shortest-completing-word.py ├── minimum-time-difference.py ├── linked-list-cycle-ii.py ├── verifying-an-alien-dictionary.py ├── couples-holding-hands.py ├── letter-case-permutation.py ├── binary-watch.py ├── find-and-replace-in-string.py ├── x-of-a-kind-in-a-deck-of-cards.py ├── lonely-pixel-i.py ├── maximum-product-of-word-lengths.py ├── remove-nth-node-from-end-of-list.py ├── split-array-into-consecutive-subsequences.py ├── longest-common-prefix.py ├── string-to-integer-atoi.py ├── word-break-ii.py ├── binary-tree-longest-consecutive-sequence.py ├── moving-average-from-data-stream.py ├── most-stones-removed-with-same-row-or-column.py ├── next-permutation.py ├── sentence-similarity.py ├── count-complete-tree-nodes.py ├── shortest-word-distance.py ├── generate-parentheses.py ├── subtree-of-another-tree.py ├── find-first-and-last-position-of-element-in-sorted-array.py ├── insert-into-a-cyclic-sorted-list.py ├── binary-tree-maximum-path-sum.py ├── license-key-formatting.py ├── minimum-falling-path-sum.py ├── convert-sorted-array-to-binary-search-tree.py ├── sort-colors.py ├── degree-of-an-array.py ├── increasing-order-search-tree.py ├── longest-substring-with-at-most-two-distinct-characters.py ├── binary-tree-level-order-traversal-ii.py ├── add-strings.py ├── kth-smallest-element-in-a-bst.py ├── largest-triangle-area.py ├── longest-univalue-path.py ├── number-of-islands.py ├── k-similar-strings.py ├── path-sum-ii.py ├── logger-rate-limiter.py ├── 3sum-closest.py ├── combination-sum.py ├── flood-fill.py ├── max-area-of-island.py ├── min-stack.py ├── find-median-from-data-stream.py ├── combination-sum-ii.py ├── employee-importance.py ├── n-queens-ii.py ├── path-sum-iii.py ├── count-univalue-subtrees.py ├── 3sum.py ├── balanced-binary-tree.py ├── length-of-longest-fibonacci-subsequence.py ├── merge-intervals.py ├── strobogrammatic-number-ii.py ├── binary-search-tree-iterator.py ├── set-matrix-zeroes.py ├── string-compression.py ├── find-all-anagrams-in-a-string.py ├── snakes-and-ladders.py ├── heaters.py ├── unique-word-abbreviation.py ├── range-sum-query-mutable.py ├── surface-area-of-3d-shapes.py ├── add-two-numbers.py ├── max-consecutive-ones-iii.py ├── copy-list-with-random-pointer.py ├── design-hit-counter.py └── number-of-distinct-islands.py ├── .gitignore └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /Python/nim-game.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/nim-game/ 2 | 3 | 4 | class Solution: 5 | def canWinNim(self, n): 6 | """ 7 | :type n: int 8 | :rtype: bool 9 | """ 10 | return n % 4 != 0 11 | -------------------------------------------------------------------------------- /Python/reverse-string.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-string/ 2 | 3 | 4 | class Solution: 5 | def reverseString(self, s): 6 | """ 7 | :type s: str 8 | :rtype: str 9 | """ 10 | return s[::-1] 11 | -------------------------------------------------------------------------------- /Python/to-lower-case.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/to-lower-case/submissions/ 2 | 3 | 4 | class Solution: 5 | def toLowerCase(self, str): 6 | """ 7 | :type str: str 8 | :rtype: str 9 | """ 10 | return str.lower() 11 | -------------------------------------------------------------------------------- /Python/min-cost-climbing-stairs.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/min-cost-climbing-stairs/ 2 | 3 | 4 | class Solution: 5 | def minCostClimbingStairs(self, cost): 6 | a, b = 0, 0 7 | for c in cost: a, b = b, min(a + c, b + c) 8 | return min(a, b) 9 | -------------------------------------------------------------------------------- /Python/number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-1-bits/ 2 | 3 | 4 | class Solution(object): 5 | def hammingWeight(self, n): 6 | """ 7 | :type n: int 8 | :rtype: int 9 | """ 10 | return bin(n).count('1') 11 | -------------------------------------------------------------------------------- /Python/add-binary.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/add-binary 2 | 3 | 4 | class Solution: 5 | def addBinary(self, a, b): 6 | """ 7 | :type a: str 8 | :type b: str 9 | :rtype: str 10 | """ 11 | return '{0:b}'.format(int(a, 2) + int(b, 2)) 12 | -------------------------------------------------------------------------------- /Python/contains-duplicate.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/contains-duplicate/ 2 | 3 | 4 | class Solution: 5 | def containsDuplicate(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: bool 9 | """ 10 | return len(set(nums)) != len(nums) 11 | -------------------------------------------------------------------------------- /Python/reverse-words-in-a-string.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-words-in-a-string/ 2 | 3 | 4 | class Solution(object): 5 | def reverseWords(self, s): 6 | """ 7 | :type s: str 8 | :rtype: str 9 | """ 10 | return ' '.join(reversed(s.split())) 11 | -------------------------------------------------------------------------------- /Python/reverse-words-in-a-string-iii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-words-in-a-string-iii/ 2 | 3 | 4 | class Solution: 5 | def reverseWords(self, s): 6 | """ 7 | :type s: str 8 | :rtype: str 9 | """ 10 | return ' '.join(x[::-1] for x in s.split(' ')) 11 | -------------------------------------------------------------------------------- /Python/detect-capital.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/detect-capital/ 2 | 3 | 4 | class Solution(object): 5 | def detectCapitalUse(self, word): 6 | """ 7 | :type word: str 8 | :rtype: bool 9 | """ 10 | return len(word) <= 1 or word.isupper() or word[1:].islower() 11 | -------------------------------------------------------------------------------- /Python/distribute-candies.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/distribute-candies/ 2 | 3 | 4 | class Solution(object): 5 | def distributeCandies(self, candies): 6 | """ 7 | :type candies: List[int] 8 | :rtype: int 9 | """ 10 | return min(len(set(candies)), len(candies) // 2) 11 | -------------------------------------------------------------------------------- /Python/hamming-distance.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/hamming-distance/ 2 | 3 | 4 | class Solution: 5 | def hammingDistance(self, x, y): 6 | """ 7 | :type x: int 8 | :type y: int 9 | :rtype: int 10 | """ 11 | return sum(int(i) for i in '{0:b}'.format(x ^ y)) 12 | -------------------------------------------------------------------------------- /Python/add-digits.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/add-digits/ 2 | 3 | 4 | class Solution(object): 5 | def addDigits(self, num): 6 | """ 7 | :type num: int 8 | :rtype: int 9 | """ 10 | if num == 0: return 0 11 | if num % 9 == 0: return 9 12 | return num % 9 13 | -------------------------------------------------------------------------------- /Python/array-partition-i.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/array-partition-i/ 2 | 3 | 4 | class Solution(object): 5 | def arrayPairSum(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | return sum(x for i, x in enumerate(sorted(nums)) if i & 1 == 0) 11 | -------------------------------------------------------------------------------- /Python/number-complement.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-complement/ 2 | 3 | 4 | class Solution(object): 5 | def findComplement(self, num): 6 | """ 7 | :type num: int 8 | :rtype: int 9 | """ 10 | return int(''.join(['0' if x == '1' else '1' for x in bin(num)[2:]])) 11 | -------------------------------------------------------------------------------- /Python/single-number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/single-number 2 | 3 | 4 | class Solution: 5 | def singleNumber(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | x = 0 11 | for num in nums: 12 | x ^= num 13 | return x 14 | -------------------------------------------------------------------------------- /Python/climbing-stairs.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/climbing-stairs 2 | 3 | 4 | class Solution: 5 | def climbStairs(self, n): 6 | """ 7 | :type n: int 8 | :rtype: int 9 | """ 10 | a, b = 0, 1 11 | for _ in range(n): 12 | a, b = b, a + b 13 | return b 14 | -------------------------------------------------------------------------------- /Python/jewels-and-stones.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/jewels-and-stones/ 2 | 3 | 4 | class Solution: 5 | def numJewelsInStones(self, J, S): 6 | """ 7 | :type J: str 8 | :type S: str 9 | :rtype: int 10 | """ 11 | J = set(J) 12 | return sum(s in J for s in S) 13 | -------------------------------------------------------------------------------- /Python/sort-array-by-parity.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sort-array-by-parity/ 2 | 3 | 4 | class Solution: 5 | def sortArrayByParity(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: List[int] 9 | """ 10 | return [a for a in A if a % 2 == 0] + [a for a in A if a % 2 == 1] 11 | -------------------------------------------------------------------------------- /Python/fibonacci-number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/fibonacci-number/ 2 | 3 | 4 | class Solution(object): 5 | def fib(self, N): 6 | """ 7 | :type N: int 8 | :rtype: int 9 | """ 10 | a, b = 0, 1 11 | for _ in range(N): 12 | a, b = b, a + b 13 | return a 14 | -------------------------------------------------------------------------------- /Python/length-of-last-word.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/length-of-last-word 2 | 3 | 4 | class Solution: 5 | def lengthOfLastWord(self, s): 6 | """ 7 | :type s: str 8 | :rtype: int 9 | """ 10 | if not s.strip(): 11 | return 0 12 | 13 | return len(s.split()[-1]) 14 | -------------------------------------------------------------------------------- /Python/minimum-moves-to-equal-array-elements.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-moves-to-equal-array-elements/ 2 | 3 | 4 | class Solution(object): 5 | def minMoves(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | return sum(nums) - min(nums) * len(nums) 11 | -------------------------------------------------------------------------------- /Python/rotate-string.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/rotate-string/ 2 | 3 | 4 | class Solution(object): 5 | def rotateString(self, A, B): 6 | """ 7 | :type A: str 8 | :type B: str 9 | :rtype: bool 10 | """ 11 | if len(A) != len(B): return False 12 | return B in A + A 13 | -------------------------------------------------------------------------------- /Python/house-robber.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/house-robber/ 2 | 3 | 4 | class Solution: 5 | def rob(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | a, b = 0, 0 11 | for num in nums: 12 | a, b = b, max(a + num, b) 13 | return b 14 | -------------------------------------------------------------------------------- /Python/valid-anagram.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-anagram/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution(object): 8 | def isAnagram(self, s, t): 9 | """ 10 | :type s: str 11 | :type t: str 12 | :rtype: bool 13 | """ 14 | return Counter(s) == Counter(t) 15 | -------------------------------------------------------------------------------- /Python/peak-index-in-a-mountain-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/peak-index-in-a-mountain-array/ 2 | 3 | 4 | class Solution: 5 | def peakIndexInMountainArray(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: int 9 | """ 10 | for i in range(len(A) - 1): 11 | if A[i] > A[i + 1]: return i 12 | -------------------------------------------------------------------------------- /Python/group-anagrams.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/group-anagrams 2 | 3 | 4 | class Solution: 5 | def groupAnagrams(self, strs): 6 | m = {} 7 | for str in strs: 8 | s = ''.join(sorted(str)) 9 | if s not in m: 10 | m[s] = [] 11 | m[s].append(str) 12 | 13 | return [i for i in m.values()] 14 | -------------------------------------------------------------------------------- /Python/intersection-of-two-arrays.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/intersection-of-two-arrays/ 2 | 3 | 4 | class Solution(object): 5 | def intersection(self, nums1, nums2): 6 | """ 7 | :type nums1: List[int] 8 | :type nums2: List[int] 9 | :rtype: List[int] 10 | """ 11 | return list(set(nums1).intersection(set(nums2))) 12 | -------------------------------------------------------------------------------- /Python/sum-of-two-integers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getSum(self, a, b): 3 | """ 4 | :type a: int 5 | :type b: int 6 | :rtype: int 7 | """ 8 | MAX, MASK = 0x7FFFFFFF, 0xFFFFFFFF 9 | while b != 0: 10 | a, b = (a ^ b) & MASK, ((a & b) << 1) & MASK 11 | return a if a <= MAX else ~(a ^ MASK) 12 | -------------------------------------------------------------------------------- /Python/single-number-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/single-number-ii 2 | 3 | 4 | class Solution: 5 | def singleNumber(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | a, b = 0, 0 11 | for num in nums: 12 | a = (a ^ num) & ~b 13 | b = (b ^ num) & ~a 14 | return a 15 | -------------------------------------------------------------------------------- /Python/majority-element.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/majority-element/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution(object): 8 | def majorityElement(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: int 12 | """ 13 | c = Counter(nums) 14 | return max([x for x in c], key=lambda x: c[x]) 15 | -------------------------------------------------------------------------------- /Python/minimum-moves-to-equal-array-elements-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ 2 | 3 | 4 | class Solution(object): 5 | def minMoves2(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | nums.sort() 11 | return sum(abs(nums[len(nums) // 2] - n) for n in nums) 12 | 13 | -------------------------------------------------------------------------------- /Python/excel-sheet-column-number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/excel-sheet-column-number/ 2 | 3 | 4 | class Solution(object): 5 | def titleToNumber(self, s): 6 | """ 7 | :type s: str 8 | :rtype: int 9 | """ 10 | n = 0 11 | for c in s: 12 | n *= 26 13 | n += 1 + ord(c) - ord('A') 14 | 15 | return n 16 | -------------------------------------------------------------------------------- /Python/flip-game.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/flip-game/submissions/ 2 | 3 | 4 | class Solution: 5 | def generatePossibleNextMoves(self, s): 6 | """ 7 | :type s: str 8 | :rtype: List[str] 9 | """ 10 | out = [] 11 | for i in range(0, len(s) - 1): 12 | if s[i:i+2] == '++': out.append(s[:i] + '--' + s[i+2:]) 13 | return out 14 | -------------------------------------------------------------------------------- /Python/missing-number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/missing-number/ 2 | 3 | 4 | class Solution: 5 | def missingNumber(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | x = 0 11 | for i in range(0, len(nums) - 1): 12 | x ^= i 13 | 14 | for n in nums: 15 | x ^= n 16 | 17 | return x 18 | -------------------------------------------------------------------------------- /Python/ugly-number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/ugly-number/ 2 | 3 | 4 | class Solution: 5 | def isUgly(self, num): 6 | """ 7 | :type num: int 8 | :rtype: bool 9 | """ 10 | if num < 1: return False 11 | while num % 2 == 0: num //= 2 12 | while num % 3 == 0: num //= 3 13 | while num % 5 == 0: num //= 5 14 | return num == 1 15 | -------------------------------------------------------------------------------- /Python/n-repeated-element-in-size-2n-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution(object): 8 | def repeatedNTimes(self, A): 9 | """ 10 | :type A: List[int] 11 | :rtype: int 12 | """ 13 | c = Counter(A) 14 | return [x for x in c if c[x] == len(A) // 2][0] 15 | -------------------------------------------------------------------------------- /Python/palindrome-number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/palindrome-number 2 | 3 | 4 | class Solution: 5 | def isPalindrome(self, x): 6 | """ 7 | :type x: int 8 | :rtype: bool 9 | """ 10 | x = str(x) 11 | n = len(x) 12 | for i in range(n // 2): 13 | if x[i] != x[n - i - 1]: 14 | return False 15 | return True 16 | -------------------------------------------------------------------------------- /Python/longest-uncommon-subsequence-i.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-uncommon-subsequence-i/ 2 | 3 | 4 | class Solution: 5 | def findLUSlength(self, a, b): 6 | """ 7 | :type a: str 8 | :type b: str 9 | :rtype: int 10 | """ 11 | if len(a) > len(b): return len(a) 12 | if len(a) < len(b): return len(b) 13 | return len(a) if a != b else -1 14 | -------------------------------------------------------------------------------- /Python/find-anagram-mappings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-anagram-mappings/ 2 | 3 | 4 | class Solution: 5 | def anagramMappings(self, A, B): 6 | """ 7 | :type A: List[int] 8 | :type B: List[int] 9 | :rtype: List[int] 10 | """ 11 | m = {} 12 | for i, b in enumerate(B): 13 | if b not in m: m[b] = i 14 | 15 | return [m[a] for a in A] 16 | -------------------------------------------------------------------------------- /Python/powx-n.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def myPow(self, x, n): 4 | """ 5 | :type x: float 6 | :type n: int 7 | :rtype: float 8 | """ 9 | if n < 0: 10 | n = -n 11 | x = 1 / x 12 | 13 | r = 1 14 | while n: 15 | if n % 2 == 1: 16 | r *= x 17 | n //= 2 18 | x *= x 19 | return r 20 | -------------------------------------------------------------------------------- /Python/two-sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/two-sum 2 | 3 | 4 | class Solution: 5 | def twoSum(self, nums, target): 6 | """ 7 | :type nums: List[int] 8 | :type target: int 9 | :rtype: List[int] 10 | """ 11 | m = {} 12 | for i, n in enumerate(nums): 13 | if (target - n) in m: 14 | return [m[target - n], i] 15 | m[n] = i 16 | -------------------------------------------------------------------------------- /Python/find-pivot-index.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-pivot-index/ 2 | 3 | 4 | class Solution(object): 5 | def pivotIndex(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | l, r = 0, sum(nums) 11 | 12 | for i, n in enumerate(nums): 13 | r -= n 14 | if l == r: return i 15 | l += n 16 | 17 | return -1 18 | -------------------------------------------------------------------------------- /Python/line-reflection.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/line-reflection/ 2 | 3 | 4 | class Solution(object): 5 | def isReflected(self, points): 6 | """ 7 | :type points: List[List[int]] 8 | :rtype: bool 9 | """ 10 | if not points: return True 11 | X = min(points)[0] + max(points)[0] 12 | return len({(x, y) for x, y in points}.difference((X - x, y) for x, y in points)) == 0 13 | -------------------------------------------------------------------------------- /Python/paint-fence.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/paint-fence/ 2 | 3 | 4 | class Solution(object): 5 | def numWays(self, n, k): 6 | """ 7 | :type n: int 8 | :type k: int 9 | :rtype: int 10 | """ 11 | if n == 0: return 0 12 | same, diff = 0, k 13 | for _ in range(1, n): 14 | same, diff = diff, (same + diff) * (k - 1) 15 | return same + diff 16 | -------------------------------------------------------------------------------- /Python/implement-strstr.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/implement-strstr 2 | 3 | 4 | class Solution: 5 | def strStr(self, haystack, needle): 6 | """ 7 | :type haystack: str 8 | :type needle: str 9 | :rtype: int 10 | """ 11 | for i in range(len(haystack) - len(needle) + 1): 12 | if haystack[i:i+len(needle)] == needle: 13 | return i 14 | return -1 15 | -------------------------------------------------------------------------------- /Python/transpose-matrix.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/transpose-matrix/ 2 | 3 | 4 | class Solution: 5 | def transpose(self, A): 6 | """ 7 | :type A: List[List[int]] 8 | :rtype: List[List[int]] 9 | """ 10 | if not A or not A[0]: return [] 11 | T = [] 12 | 13 | for col in range(len(A[0])): 14 | T.append([A[r][col] for r in range(len(A))]) 15 | return T 16 | -------------------------------------------------------------------------------- /Python/smallest-range-i.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/smallest-range-i 2 | 3 | 4 | class Solution: 5 | def smallestRangeI(self, A, K): 6 | """ 7 | :type A: List[int] 8 | :type K: int 9 | :rtype: int 10 | """ 11 | smallest = min(A) 12 | largest = max(A) 13 | 14 | if largest - smallest < K * 2: 15 | return 0 16 | 17 | return largest - smallest - K * 2 18 | -------------------------------------------------------------------------------- /Python/best-time-to-buy-and-sell-stock.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock 2 | 3 | 4 | class Solution: 5 | def maxProfit(self, prices): 6 | """ 7 | :type prices: List[int] 8 | :rtype: int 9 | """ 10 | profit, buy = 0, float('inf') 11 | for price in prices: 12 | buy = min(buy, price) 13 | profit = max(profit, price - buy) 14 | return profit 15 | -------------------------------------------------------------------------------- /Python/fair-candy-swap.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/fair-candy-swap/ 2 | 3 | 4 | class Solution: 5 | def fairCandySwap(self, A, B): 6 | """ 7 | :type A: List[int] 8 | :type B: List[int] 9 | :rtype: List[int] 10 | """ 11 | sa, sb = sum(A), sum(B) 12 | setb = set(B) 13 | for x in A: 14 | if x + (sb - sa) // 2 in setb: 15 | return x, x + (sb - sa) // 2 16 | -------------------------------------------------------------------------------- /Python/sqrtx.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sqrtx 2 | 3 | 4 | class Solution: 5 | def mySqrt(self, x): 6 | """ 7 | :type x: int 8 | :rtype: int 9 | """ 10 | l, r = 0, x 11 | 12 | while l <= r: 13 | m = (l + r) // 2 14 | s = m * m 15 | 16 | if s <= x: 17 | l = m + 1 18 | else: 19 | r = m - 1 20 | return l - 1 21 | -------------------------------------------------------------------------------- /Python/binary-gap.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-gap/ 2 | 3 | 4 | class Solution(object): 5 | def binaryGap(self, N): 6 | """ 7 | :type N: int 8 | :rtype: int 9 | """ 10 | biggest_gap = 0 11 | j = -1 12 | for i in range(N): 13 | if N & (1 << i): 14 | if j != -1: biggest_gap = max(biggest_gap, i - j) 15 | j = i 16 | return biggest_gap 17 | -------------------------------------------------------------------------------- /Python/pascals-triangle-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/pascals-triangle-ii 2 | 3 | 4 | class Solution: 5 | def getRow(self, rowIndex): 6 | """ 7 | :type rowIndex: int 8 | :rtype: List[int] 9 | """ 10 | out = [1] 11 | 12 | for i in range(0, rowIndex): 13 | out = ([1] + 14 | [out[x] + out[x + 1] for x in range(i)] + 15 | [1]) 16 | return out 17 | -------------------------------------------------------------------------------- /Python/toeplitz-matrix.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/toeplitz-matrix/ 2 | 3 | 4 | class Solution(object): 5 | def isToeplitzMatrix(self, matrix): 6 | """ 7 | :type matrix: List[List[int]] 8 | :rtype: bool 9 | """ 10 | for row in range(1, len(matrix)): 11 | for col in range(1, len(matrix[0])): 12 | if matrix[row][col] != matrix[row - 1][col - 1]: return False 13 | return True 14 | -------------------------------------------------------------------------------- /Python/prime-number-of-set-bits-in-binary-representation.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/ 2 | 3 | 4 | class Solution: 5 | def countPrimeSetBits(self, L, R): 6 | """ 7 | :type L: int 8 | :type R: int 9 | :rtype: int 10 | """ 11 | primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31} 12 | return sum(bin(x).count('1') in primes for x in range(L, R + 1)) 13 | 14 | -------------------------------------------------------------------------------- /Python/remove-element.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-element 2 | 3 | 4 | class Solution: 5 | def removeElement(self, nums, val): 6 | """ 7 | :type nums: List[int] 8 | :type val: int 9 | :rtype: int 10 | """ 11 | i = 0 12 | while i < len(nums): 13 | if nums[i] == val: 14 | nums.pop(i) 15 | else: 16 | i += 1 17 | return len(nums) 18 | -------------------------------------------------------------------------------- /Python/find-the-difference.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-the-difference/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution(object): 8 | def findTheDifference(self, s, t): 9 | """ 10 | :type s: str 11 | :type t: str 12 | :rtype: str 13 | """ 14 | sc = Counter(s) 15 | tc = Counter(t) 16 | 17 | for c in tc: 18 | if tc[c] > sc[c]: 19 | return c 20 | -------------------------------------------------------------------------------- /Python/plus-one.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/plus-one 2 | 3 | 4 | class Solution: 5 | def plusOne(self, digits): 6 | """ 7 | :type digits: List[int] 8 | :rtype: List[int] 9 | """ 10 | for i in range(len(digits) - 1, -1, -1): 11 | digits[i] = (digits[i] + 1) % 10 12 | if digits[i] != 0: 13 | break 14 | else: 15 | digits.insert(0, 1) 16 | return digits 17 | -------------------------------------------------------------------------------- /Python/subsets.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/subsets/ 2 | 3 | 4 | class Solution(object): 5 | def subsets(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: List[List[int]] 9 | """ 10 | out = [[]] 11 | 12 | for i in range(len(nums)): 13 | new_out = [] 14 | for o in out: 15 | new_out.append(o + [nums[i]]) 16 | out.extend(new_out) 17 | return out 18 | -------------------------------------------------------------------------------- /Python/keyboard-row.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/keyboard-row/ 2 | 3 | 4 | KEYS = { 5 | **{k:1 for k in 'QWERTYUIOP'}, 6 | **{k:2 for k in 'ASDFGHJKL'}, 7 | **{k:3 for k in 'ZXCVBNM'} 8 | } 9 | 10 | 11 | class Solution(object): 12 | def findWords(self, words): 13 | """ 14 | :type words: List[str] 15 | :rtype: List[str] 16 | """ 17 | return [word for word in words if len({KEYS[k] for k in word.upper()}) == 1] 18 | -------------------------------------------------------------------------------- /Python/contains-duplicate-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/contains-duplicate-ii/ 2 | 3 | 4 | class Solution: 5 | def containsNearbyDuplicate(self, nums, k): 6 | """ 7 | :type nums: List[int] 8 | :type k: int 9 | :rtype: bool 10 | """ 11 | prev = {} 12 | for i in range(len(nums)): 13 | if nums[i] not in prev or i - prev[nums[i]] > k: prev[nums[i]] = i 14 | else: return True 15 | return False 16 | -------------------------------------------------------------------------------- /Python/repeated-string-match.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/repeated-string-match/ 2 | 3 | 4 | class Solution(object): 5 | def repeatedStringMatch(self, A, B): 6 | """ 7 | :type A: str 8 | :type B: str 9 | :rtype: int 10 | """ 11 | t, c = '', 0 12 | while len(t) < len(B): 13 | t += A 14 | c += 1 15 | if B in t: return c 16 | 17 | if B in t + A: return c + 1 18 | return - 1 19 | -------------------------------------------------------------------------------- /Python/remove-duplicates-from-sorted-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-duplicates-from-sorted-array 2 | 3 | 4 | class Solution: 5 | def removeDuplicates(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | i = 0 11 | while i < len(nums) - 1: 12 | if nums[i] == nums[i + 1]: 13 | nums.pop(i) 14 | else: 15 | i += 1 16 | 17 | return len(nums) 18 | -------------------------------------------------------------------------------- /Python/robot-return-to-origin.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/robot-return-to-origin/ 2 | 3 | 4 | class Solution: 5 | def judgeCircle(self, moves): 6 | """ 7 | :type moves: str 8 | :rtype: bool 9 | """ 10 | x, y = 0, 0 11 | for move in moves: 12 | if move == 'U': y += 1 13 | elif move == 'D': y -= 1 14 | elif move == 'R': x += 1 15 | elif move == 'L': x -= 1 16 | return x == y == 0 17 | -------------------------------------------------------------------------------- /Python/binary-number-with-alternating-bits.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-number-with-alternating-bits/ 2 | 3 | 4 | class Solution: 5 | def hasAlternatingBits(self, n): 6 | """ 7 | :type n: int 8 | :rtype: bool 9 | """ 10 | prev_bit = -1 11 | 12 | while n > 0: 13 | cur_bit = n & 1 14 | if cur_bit == prev_bit: return False 15 | prev_bit = cur_bit 16 | n >>= 1 17 | 18 | return True 19 | -------------------------------------------------------------------------------- /Python/reverse-integer.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/zigzag-conversion 2 | 3 | 4 | class Solution: 5 | def reverse(self, x): 6 | """ 7 | :type x: int 8 | :rtype: int 9 | """ 10 | x = str(x) 11 | neg = 1 12 | if x[0] == '-': 13 | neg = -1 14 | x = x[1:] 15 | x = ''.join(reversed(x)) 16 | x = int(x) * neg 17 | if not (-2**31 <= x <= 2 ** 31 - 1): 18 | return 0 19 | return x 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # Distribution / packaging 7 | .Python 8 | build/ 9 | develop-eggs/ 10 | dist/ 11 | downloads/ 12 | eggs/ 13 | .eggs/ 14 | lib/ 15 | lib64/ 16 | parts/ 17 | sdist/ 18 | var/ 19 | wheels/ 20 | *.egg-info/ 21 | .installed.cfg 22 | *.egg 23 | MANIFEST 24 | 25 | # pyenv 26 | .python-version 27 | 28 | # Environments 29 | .env 30 | .venv 31 | env/ 32 | venv/ 33 | ENV/ 34 | env.bak/ 35 | venv.bak/ 36 | .idea 37 | -------------------------------------------------------------------------------- /Python/coin-change.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/coin-change/ 2 | 3 | 4 | class Solution(object): 5 | def coinChange(self, coins, amount): 6 | """ 7 | :type coins: List[int] 8 | :type amount: int 9 | :rtype: int 10 | """ 11 | dp = [0] + [float('inf')] * amount 12 | for coin in coins: 13 | for i in range(coin, amount + 1): 14 | dp[i] = min(dp[i], dp[i - coin] + 1) 15 | 16 | return dp[-1] if dp[-1] != float('inf') else -1 17 | -------------------------------------------------------------------------------- /Python/max-consecutive-ones.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/max-consecutive-ones/ 2 | 3 | 4 | class Solution: 5 | def findMaxConsecutiveOnes(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | max_ones = cur_ones = 0 11 | 12 | for n in nums: 13 | if n == 1: cur_ones += 1 14 | else: 15 | max_ones = max(max_ones, cur_ones) 16 | cur_ones = 0 17 | 18 | return max(max_ones, cur_ones) 19 | -------------------------------------------------------------------------------- /Python/ransom-note.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/ransom-note/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution(object): 8 | def canConstruct(self, ransomNote, magazine): 9 | """ 10 | :type ransomNote: str 11 | :type magazine: str 12 | :rtype: bool 13 | """ 14 | available = Counter(magazine) 15 | 16 | for c in ransomNote: 17 | if available[c] <= 0: return False 18 | available[c] -= 1 19 | return True 20 | -------------------------------------------------------------------------------- /Python/best-time-to-buy-and-sell-stock-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii 2 | 3 | 4 | class Solution: 5 | def maxProfit(self, prices): 6 | """ 7 | :type prices: List[int] 8 | :rtype: int 9 | """ 10 | profit, buy = 0, float('inf') 11 | for price in prices: 12 | if price < buy: 13 | buy = price 14 | else: 15 | profit += price - buy 16 | buy = price 17 | return profit 18 | -------------------------------------------------------------------------------- /Python/minimum-increment-to-make-array-unique.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-increment-to-make-array-unique/ 2 | 3 | 4 | class Solution(object): 5 | def minIncrementForUnique(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: int 9 | """ 10 | A.sort() 11 | next_unique = increments = 0 12 | 13 | for a in A: 14 | increments += max(next_unique - a, 0) 15 | next_unique = max(next_unique + 1, a + 1) 16 | 17 | return increments 18 | -------------------------------------------------------------------------------- /Python/paint-house.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/paint-house/ 2 | 3 | 4 | class Solution: 5 | def minCost(self, costs): 6 | """ 7 | :type costs: List[List[int]] 8 | :rtype: int 9 | """ 10 | for i in range(1, len(costs)): 11 | costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]) 12 | costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]) 13 | costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]) 14 | 15 | return min(costs[-1]) if costs else 0 16 | -------------------------------------------------------------------------------- /Python/permutations.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/permutations/ 2 | 3 | 4 | class Solution(object): 5 | def permute(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: List[List[int]] 9 | """ 10 | out = [[]] 11 | 12 | for i in range(len(nums)): 13 | new_out = [] 14 | for j in range(i + 1): 15 | for o in out: 16 | new_out.append(o[:j] + [nums[i]] + o[j:]) 17 | out = new_out 18 | return out 19 | -------------------------------------------------------------------------------- /Python/maximum-subarray.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-subarray 2 | 3 | 4 | class Solution: 5 | def maxSubArray(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | best_sum = nums[0] 11 | current_sum = 0 12 | 13 | for num in nums: 14 | current_sum += num 15 | 16 | best_sum = max(best_sum, current_sum) 17 | 18 | if current_sum < 0: 19 | current_sum = 0 20 | 21 | return best_sum 22 | -------------------------------------------------------------------------------- /Python/self-dividing-numbers.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/self-dividing-numbers/ 2 | 3 | 4 | class Solution: 5 | def selfDividingNumbers(self, left, right): 6 | """ 7 | :type left: int 8 | :type right: int 9 | :rtype: List[int] 10 | """ 11 | sdn = [] 12 | for i in range(left, right + 1): 13 | for d in map(int, str(i)): 14 | if d == 0: break 15 | if i % d != 0: break 16 | else: sdn.append(i) 17 | return sdn 18 | -------------------------------------------------------------------------------- /Python/smallest-range-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/smallest-range-ii 2 | 3 | 4 | class Solution: 5 | def smallestRangeII(self, A, K): 6 | """ 7 | :type A: List[int] 8 | :type K: int 9 | :rtype: int 10 | """ 11 | A.sort() 12 | diff = A[-1] - A[0] 13 | for i in range(len(A) - 1): 14 | largest = max(A[-1], A[i] + 2 * K) 15 | smallest = min(A[i + 1], A[0] + 2 * K) 16 | diff = min(diff, largest - smallest) 17 | return diff 18 | -------------------------------------------------------------------------------- /Python/valid-word-square.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-word-square/ 2 | 3 | 4 | class Solution(object): 5 | def validWordSquare(self, words): 6 | """ 7 | :type words: List[str] 8 | :rtype: bool 9 | """ 10 | for i in range(len(words)): 11 | for j in range(len(words[i])): 12 | if j >= len(words): return False 13 | if i >= len(words[j]): return False 14 | if words[i][j] != words[j][i]: return False 15 | return True 16 | -------------------------------------------------------------------------------- /Python/1-bit-and-2-bit-characters.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/1-bit-and-2-bit-characters/ 2 | 3 | 4 | class Solution(object): 5 | def isOneBitCharacter(self, bits): 6 | """ 7 | :type bits: List[int] 8 | :rtype: bool 9 | """ 10 | ret = False 11 | i = 0 12 | while i < len(bits): 13 | if bits[i] == 1: 14 | ret = False 15 | i += 2 16 | else: 17 | ret = True 18 | i += 1 19 | return ret 20 | -------------------------------------------------------------------------------- /Python/fizz-buzz.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/fizz-buzz/ 2 | 3 | 4 | class Solution(object): 5 | def fizzBuzz(self, n): 6 | """ 7 | :type n: int 8 | :rtype: List[str] 9 | """ 10 | def f(x): 11 | if x % 3 == x % 5 == 0: 12 | return 'FizzBuzz' 13 | elif x % 3 == 0: 14 | return 'Fizz' 15 | elif x % 5 == 0: 16 | return 'Buzz' 17 | return str(x) 18 | 19 | return list(map(f, range(1, n + 1))) 20 | -------------------------------------------------------------------------------- /Python/house-robber-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/house-robber-ii/ 2 | 3 | 4 | class Solution: 5 | def rob(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | def rob_set(nums): 11 | a, b = 0, 0 12 | for num in nums: 13 | a, b = b, max(a + num, b) 14 | return b 15 | 16 | if len(nums) == 0: return 0 17 | if len(nums) == 1: return nums[0] 18 | return max(rob_set(nums[:-1]), rob_set(nums[1:])) 19 | -------------------------------------------------------------------------------- /Python/two-sum-ii-input-array-is-sorted.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 2 | 3 | 4 | class Solution(object): 5 | def twoSum(self, numbers, target): 6 | """ 7 | :type numbers: List[int] 8 | :type target: int 9 | :rtype: List[int] 10 | """ 11 | l, r = 0, len(numbers) - 1 12 | while l < r: 13 | if numbers[l] + numbers[r] < target: l += 1 14 | elif numbers[l] + numbers[r] > target: r -= 1 15 | else: return l + 1, r + 1 16 | -------------------------------------------------------------------------------- /Python/best-time-to-buy-and-sell-stock-iii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii 2 | 3 | 4 | class Solution: 5 | def maxProfit(self, prices): 6 | """ 7 | :type prices: List[int] 8 | :rtype: int 9 | """ 10 | b1, b2, s1, s2 = -float('inf'), -float('inf'), 0, 0 11 | for price in prices: 12 | s2 = max(s2, b2 + price) 13 | b2 = max(b2, s1 - price) 14 | s1 = max(s1, b1 + price) 15 | b1 = max(b1, -price) 16 | return s2 17 | -------------------------------------------------------------------------------- /Python/reverse-only-letters.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-only-letters/ 2 | 3 | 4 | class Solution: 5 | def reverseOnlyLetters(self, S): 6 | """ 7 | :type S: str 8 | :rtype: str 9 | """ 10 | l, r = 0, len(S) - 1 11 | S = list(S) 12 | while l < r: 13 | while l < r and not S[l].isalpha(): l += 1 14 | while r > l and not S[r].isalpha(): r -= 1 15 | S[l], S[r] = S[r], S[l] 16 | l += 1 17 | r -= 1 18 | return ''.join(S) 19 | -------------------------------------------------------------------------------- /Python/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/container-with-most-water/ 2 | 3 | 4 | class Solution(object): 5 | def maxArea(self, height): 6 | """ 7 | :type height: List[int] 8 | :rtype: int 9 | """ 10 | water, i, j = 0, 0, len(height) - 1 11 | while i < j: 12 | h = min(height[i], height[j]) 13 | water = max(water, h * (j - i)) 14 | while i < j and height[i] <= h: i += 1 15 | while i < j and height[j] <= h: j -= 1 16 | return water 17 | -------------------------------------------------------------------------------- /Python/delete-node-in-a-linked-list.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/delete-node-in-a-linked-list/ 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution(object): 11 | def deleteNode(self, node): 12 | """ 13 | :type node: ListNode 14 | :rtype: void Do not return anything, modify node in-place instead. 15 | """ 16 | node.val = node.next.val 17 | node.next = node.next.next 18 | -------------------------------------------------------------------------------- /Python/k-closest-points-to-origin.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/k-closest-points-to-origin/ 2 | 3 | 4 | from heapq import * 5 | 6 | 7 | class Solution(object): 8 | def kClosest(self, points, K): 9 | """ 10 | :type points: List[List[int]] 11 | :type K: int 12 | :rtype: List[List[int]] 13 | """ 14 | heap = [] 15 | 16 | for p in points: 17 | heappush(heap, (-(p[0]**2 + p[1]**2), p)) 18 | if len(heap) > K: heappop(heap) 19 | 20 | return [p[1] for p in heap] 21 | 22 | -------------------------------------------------------------------------------- /Python/pascals-triangle.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/pascals-triangle 2 | 3 | 4 | class Solution: 5 | def generate(self, numRows): 6 | """ 7 | :type numRows: int 8 | :rtype: List[List[int]] 9 | """ 10 | if numRows == 0: return [] 11 | if numRows == 1: return [[1]] 12 | 13 | out = [[1]] 14 | 15 | for i in range(0, numRows - 1): 16 | out.append([1] + 17 | [out[-1][x] + out[-1][x + 1] for x in range(i)] + 18 | [1]) 19 | return out 20 | -------------------------------------------------------------------------------- /Python/delete-columns-to-make-sorted.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/delete-columns-to-make-sorted/ 2 | 3 | 4 | class Solution(object): 5 | def minDeletionSize(self, A): 6 | """ 7 | :type A: List[str] 8 | :rtype: int 9 | """ 10 | count = 0 11 | for i in range(len(A[0])): 12 | sc = 0 13 | for s in A: 14 | c = ord(s[i]) 15 | if c >= sc: sc = c 16 | else: 17 | count += 1 18 | break 19 | 20 | return count 21 | -------------------------------------------------------------------------------- /Python/intersection-of-two-arrays-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/intersection-of-two-arrays-ii/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution: 8 | def intersect(self, nums1, nums2): 9 | """ 10 | :type nums1: List[int] 11 | :type nums2: List[int] 12 | :rtype: List[int] 13 | """ 14 | f1 = Counter(nums1) 15 | out = [] 16 | 17 | for num in nums2: 18 | if f1[num] > 0: 19 | out.append(num) 20 | f1[num] -= 1 21 | 22 | return out 23 | -------------------------------------------------------------------------------- /Python/subsets-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/subsets-ii/ 2 | 3 | 4 | class Solution(object): 5 | def subsetsWithDup(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: List[List[int]] 9 | """ 10 | out = [[]] 11 | nums.sort() 12 | 13 | l = 1 14 | for i in range(len(nums)): 15 | if nums[i] != nums[i - 1]: 16 | l = len(out) 17 | 18 | for j in range(len(out) - l, len(out)): 19 | out.append(out[j] + [nums[i]]) 20 | 21 | return out 22 | -------------------------------------------------------------------------------- /Python/middle-of-the-linked-list.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/middle-of-the-linked-list/ 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution: 11 | def middleNode(self, head): 12 | """ 13 | :type head: ListNode 14 | :rtype: ListNode 15 | """ 16 | p1, p2 = head, head 17 | 18 | while p2 and p2.next: 19 | p1 = p1.next 20 | p2 = p2.next.next 21 | 22 | return p1 23 | -------------------------------------------------------------------------------- /Python/palindrome-permutation.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/palindrome-permutation/ 2 | 3 | 4 | class Solution: 5 | def canPermutePalindrome(self, s): 6 | """ 7 | :type s: str 8 | :rtype: bool 9 | """ 10 | n = len(s) 11 | odds = 0 12 | freq = {} 13 | 14 | for c in s: 15 | if c not in freq: 16 | freq[c] = 0 17 | freq[c] += 1 18 | if freq[c] % 2 == 1: odds += 1 19 | else: odds -= 1 20 | 21 | return n % 2 == odds == 0 or n % 2 == odds == 1 22 | -------------------------------------------------------------------------------- /Python/kth-largest-element-in-an-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/kth-largest-element-in-an-array/ 2 | 3 | 4 | from heapq import * 5 | 6 | 7 | class Solution(object): 8 | def findKthLargest(self, nums, k): 9 | """ 10 | :type nums: List[int] 11 | :type k: int 12 | :rtype: int 13 | """ 14 | heap = [] 15 | for num in nums: 16 | if len(heap) < k: heappush(heap, num) 17 | else: 18 | num = max(num, heappop(heap)) 19 | heappush(heap, num) 20 | return heap[0] 21 | -------------------------------------------------------------------------------- /Python/paint-house-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/paint-house-ii/ 2 | 3 | 4 | class Solution: 5 | def minCostII(self, costs): 6 | """ 7 | :type costs: List[List[int]] 8 | :rtype: int 9 | """ 10 | for i in range(1, len(costs)): 11 | m1 = min(costs[i - 1]) 12 | k = costs[i-1].index(m1) 13 | m2 = min(costs[i - 1][:k] + costs[i - 1][k + 1:]) 14 | for j in range(len(costs[i])): 15 | costs[i][j] += m2 if j == k else m1 16 | 17 | return min(costs[-1]) if costs else 0 18 | -------------------------------------------------------------------------------- /Python/reverse-linked-list.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-linked-list/ 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution: 11 | def reverseList(self, head): 12 | """ 13 | :type head: ListNode 14 | :rtype: ListNode 15 | """ 16 | prev, cur = None, head 17 | while cur: 18 | t = cur.next 19 | cur.next = prev 20 | prev, cur = cur, t 21 | return prev 22 | -------------------------------------------------------------------------------- /Python/search-insert-position.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/search-insert-position 2 | 3 | 4 | class Solution: 5 | def searchInsert(self, nums, target): 6 | """ 7 | :type nums: List[int] 8 | :type target: int 9 | :rtype: int 10 | """ 11 | l, r = 0, len(nums) - 1 12 | while l <= r: 13 | m = (l + r) // 2 14 | if nums[m] == target: 15 | return m 16 | if nums[m] < target: 17 | l = m + 1 18 | else: 19 | r = m - 1 20 | return l 21 | -------------------------------------------------------------------------------- /Python/uncommon-words-from-two-sentences.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/uncommon-words-from-two-sentences/ 2 | 3 | 4 | class Solution(object): 5 | def uncommonFromSentences(self, A, B): 6 | """ 7 | :type A: str 8 | :type B: str 9 | :rtype: List[str] 10 | """ 11 | f = {} 12 | for a in A.split(): 13 | if a not in f: f[a] = 0 14 | f[a] += 1 15 | 16 | for b in B.split(): 17 | if b not in f: f[b] = 0 18 | f[b] += 1 19 | 20 | return list(k for k, v in f.items() if v == 1) 21 | -------------------------------------------------------------------------------- /Python/baseball-game.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/baseball-game/ 2 | 3 | 4 | class Solution: 5 | def calPoints(self, ops): 6 | """ 7 | :type ops: List[str] 8 | :rtype: int 9 | """ 10 | stack = [] 11 | for op in ops: 12 | if op == 'C': 13 | stack.pop() 14 | elif op == '+': 15 | stack.append(stack[-1] + stack[-2]) 16 | elif op == 'D': 17 | stack.append(stack[-1] * 2) 18 | else: 19 | stack.append(int(op)) 20 | return sum(stack) 21 | -------------------------------------------------------------------------------- /Python/maximum-depth-of-n-ary-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ 2 | 3 | 4 | """ 5 | # Definition for a Node. 6 | class Node(object): 7 | def __init__(self, val, children): 8 | self.val = val 9 | self.children = children 10 | """ 11 | 12 | 13 | class Solution(object): 14 | def maxDepth(self, root): 15 | """ 16 | :type root: Node 17 | :rtype: int 18 | """ 19 | if not root: return 0 20 | if not root.children: return 1 21 | return max(self.maxDepth(child) for child in root.children) + 1 22 | -------------------------------------------------------------------------------- /Python/backspace-string-compare.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/backspace-string-compare/ 2 | 3 | 4 | class Solution: 5 | def backspaceCompare(self, S, T): 6 | """ 7 | :type S: str 8 | :type T: str 9 | :rtype: bool 10 | """ 11 | s = [] 12 | for c in S: 13 | if c == '#': 14 | if s: s.pop() 15 | else: s.append(c) 16 | 17 | t = [] 18 | for c in T: 19 | if c == '#': 20 | if t: t.pop() 21 | else: t.append(c) 22 | 23 | return ''.join(s) == ''.join(t) 24 | -------------------------------------------------------------------------------- /Python/find-common-characters.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-common-characters/ 2 | 3 | 4 | from collections import Counter 5 | from string import ascii_lowercase 6 | 7 | 8 | class Solution(object): 9 | def commonChars(self, A): 10 | """ 11 | :type A: List[str] 12 | :rtype: List[str] 13 | """ 14 | counters = [Counter(a) for a in A] 15 | 16 | ret = [] 17 | for c in ascii_lowercase: 18 | m = min(count[c] for count in counters) 19 | for i in range(m): 20 | ret.append(c) 21 | 22 | return ret 23 | -------------------------------------------------------------------------------- /Python/permutations-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/permutations-ii/ 2 | 3 | 4 | class Solution(object): 5 | def permuteUnique(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: List[List[int]] 9 | """ 10 | out = [[]] 11 | 12 | for i in range(len(nums)): 13 | new_out = [] 14 | for o in out: 15 | for j in range(i + 1): 16 | new_out.append(o[:j] + [nums[i]] + o[j:]) 17 | if j < len(o) and o[j] == nums[i]: break 18 | out = new_out 19 | return out 20 | -------------------------------------------------------------------------------- /Python/reverse-vowels-of-a-string.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-vowels-of-a-string/ 2 | 3 | 4 | class Solution(object): 5 | def reverseVowels(self, s): 6 | """ 7 | :type s: str 8 | :rtype: str 9 | """ 10 | l, r = 0, len(s) - 1 11 | s = list(s) 12 | vowels = set('aeiouAEIOU') 13 | while l < r: 14 | while l < r and s[l] not in vowels: l += 1 15 | while l < r and s[r] not in vowels: r -= 1 16 | s[l], s[r] = s[r], s[l] 17 | l += 1 18 | r -= 1 19 | return ''.join(s) 20 | -------------------------------------------------------------------------------- /Python/count-primes.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/count-primes/ 2 | 3 | 4 | class Solution: 5 | def countPrimes(self, n): 6 | """ 7 | :type n: int 8 | :rtype: int 9 | """ 10 | if n < 3: return 0 11 | primes = [True] * n 12 | primes[0] = primes[1] = False 13 | m = int(pow(n, 0.5)) + 1 14 | for i in range(2, m): 15 | if not primes[i]: continue 16 | for j in range(2, (n - 1) // i + 1): 17 | primes[i * j] = False 18 | return sum(primes) 19 | 20 | 21 | print(Solution().countPrimes(999983)) 22 | -------------------------------------------------------------------------------- /Python/first-bad-version.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/first-bad-version 2 | 3 | 4 | # The isBadVersion API is already defined for you. 5 | # @param version, an integer 6 | # @return a bool 7 | # def isBadVersion(version): 8 | 9 | class Solution: 10 | def firstBadVersion(self, n): 11 | """ 12 | :type n: int 13 | :rtype: int 14 | """ 15 | l, r = 1, n 16 | while l <= r: 17 | m = (l + r) // 2 18 | if isBadVersion(m): 19 | r = m - 1 20 | else: 21 | l = m + 1 22 | return l 23 | 24 | 25 | -------------------------------------------------------------------------------- /Python/isomorphic-strings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/isomorphic-strings/ 2 | 3 | 4 | class Solution: 5 | def isIsomorphic(self, s, t): 6 | """ 7 | :type s: str 8 | :type t: str 9 | :rtype: bool 10 | """ 11 | mapping = {} 12 | mapped_chars = set() 13 | for i in range(len(s)): 14 | if s[i] not in mapping: 15 | if t[i] in mapped_chars: return False 16 | mapping[s[i]] = t[i] 17 | mapped_chars.add(t[i]) 18 | elif mapping[s[i]] != t[i]: return False 19 | return True 20 | -------------------------------------------------------------------------------- /Python/rotate-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/rotate-array/ 2 | 3 | 4 | class Solution: 5 | def rotate(self, nums, k): 6 | """ 7 | :type nums: List[int] 8 | :type k: int 9 | :rtype: void Do not return anything, modify nums in-place instead. 10 | """ 11 | def reverse(s, e): 12 | while s < e: 13 | nums[s], nums[e] = nums[e], nums[s] 14 | s += 1 15 | e -= 1 16 | 17 | k %= len(nums) 18 | reverse(0, len(nums) - 1) 19 | reverse(0, k - 1) 20 | reverse(k, len(nums) - 1) 21 | -------------------------------------------------------------------------------- /Python/longest-absolute-file-path.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-absolute-file-path/ 2 | 3 | 4 | class Solution: 5 | def lengthLongestPath(self, input): 6 | """ 7 | :type input: str 8 | :rtype: int 9 | """ 10 | maxlen = 0 11 | pathlen = {0: 0} 12 | for line in input.splitlines(): 13 | name = line.lstrip('\t') 14 | depth = len(line) - len(name) 15 | if '.' in name: maxlen = max(maxlen, pathlen[depth] + len(name)) 16 | else: pathlen[depth + 1] = pathlen[depth] + len(name) + 1 17 | return maxlen 18 | -------------------------------------------------------------------------------- /Python/move-zeroes.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/move-zeroes/ 2 | 3 | 4 | class Solution: 5 | def moveZeroes(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: void Do not return anything, modify nums in-place instead. 9 | """ 10 | l, r = 0, 0 11 | 12 | while True: 13 | while r < len(nums) and nums[r] != 0: r += 1 14 | while l < len(nums) and (nums[l] == 0 or l < r): l += 1 15 | if l == len(nums) or r == len(nums): break 16 | nums[l], nums[r] = nums[r], nums[l] 17 | l += 1 18 | r += 1 19 | -------------------------------------------------------------------------------- /Python/valid-parenthesis.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-parentheses 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | class Solution: 8 | def isValid(self, s): 9 | """ 10 | :type s: str 11 | :rtype: bool 12 | """ 13 | stack = deque() 14 | 15 | for c in s: 16 | if c == '(': stack.append(')') 17 | elif c == '[': stack.append(']') 18 | elif c == '{': stack.append('}') 19 | else: 20 | if not stack or stack.pop() != c: 21 | return False 22 | 23 | return not stack 24 | -------------------------------------------------------------------------------- /Python/validate-stack-sequences.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/validate-stack-sequences/ 2 | 3 | 4 | class Solution(object): 5 | def validateStackSequences(self, pushed, popped): 6 | """ 7 | :type pushed: List[int] 8 | :type popped: List[int] 9 | :rtype: bool 10 | """ 11 | stack = [] 12 | pop_index = 0 13 | 14 | for x in pushed: 15 | stack.append(x) 16 | 17 | while stack and stack[-1] == popped[pop_index]: 18 | pop_index += 1 19 | stack.pop() 20 | 21 | return pop_index == len(popped) 22 | -------------------------------------------------------------------------------- /Python/flipping-an-image.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/flipping-an-image/ 2 | 3 | 4 | class Solution: 5 | def flipAndInvertImage(self, A): 6 | """ 7 | :type A: List[List[int]] 8 | :rtype: List[List[int]] 9 | """ 10 | for row in range(len(A)): 11 | l, r = 0, len(A[0]) - 1 12 | while l < r: 13 | A[row][l], A[row][r] = A[row][r], A[row][l] 14 | l += 1 15 | r -= 1 16 | 17 | for row in range(len(A)): 18 | for col in range(len(A[0])): 19 | A[row][col] ^= 1 20 | 21 | return A 22 | -------------------------------------------------------------------------------- /Python/invert-binary-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/invert-binary-tree/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def invertTree(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: TreeNode 16 | """ 17 | if not root: return root 18 | root.left, root.right = root.right, root.left 19 | self.invertTree(root.left) 20 | self.invertTree(root.right) 21 | return root 22 | -------------------------------------------------------------------------------- /Python/next-closest-time.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/next-closest-time/ 2 | 3 | 4 | class Solution(object): 5 | def nextClosestTime(self, time): 6 | """ 7 | :type time: str 8 | :rtype: str 9 | """ 10 | h, m = time.split(':') 11 | digits = h + m 12 | while True: 13 | if int(m) == 59: h, m = str(int(h) + 1), '00' 14 | else: m = str(int(m) + 1) 15 | if int(h) > 23: h = '00' 16 | if len(h) == 1: h = '0' + h 17 | if len(m) == 1: m = '0' + m 18 | if all(x in digits for x in h + m): return h + ':' + m 19 | -------------------------------------------------------------------------------- /Python/valid-palindrome.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-palindrome 2 | 3 | 4 | class Solution: 5 | def isPalindrome(self, s): 6 | """ 7 | :type s: str 8 | :rtype: bool 9 | """ 10 | l = 0 11 | r = len(s) - 1 12 | 13 | while l < r: 14 | while l < r and not s[l].isalnum(): 15 | l += 1 16 | 17 | while r > l and not s[r].isalnum(): 18 | r -= 1 19 | 20 | if s[l].lower() != s[r].lower(): 21 | return False 22 | 23 | l += 1 24 | r -= 1 25 | 26 | return True 27 | -------------------------------------------------------------------------------- /Python/goat-latin.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/goat-latin 2 | 3 | 4 | class Solution: 5 | def toGoatLatin(self, S): 6 | """ 7 | :type S: str 8 | :rtype: str 9 | """ 10 | out = [] 11 | for i, word in enumerate(S.split()): 12 | w = [] 13 | if word[0].lower() in 'aeiou': 14 | w.append(word) 15 | else: 16 | w.append(word[1:]) 17 | w.append(word[0]) 18 | w.append('ma') 19 | w.extend(['a'] * (i + 1)) 20 | out.append(''.join(w)) 21 | 22 | return ' '.join(out) 23 | -------------------------------------------------------------------------------- /Python/monotonic-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/monotonic-array/ 2 | 3 | 4 | class Solution: 5 | def isMonotonic(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: bool 9 | """ 10 | if len(A) <= 1: return True 11 | inc = 0 12 | prev = A[0] 13 | 14 | for a in A: 15 | if a < prev: 16 | if inc == 0: inc = 1 17 | elif inc == -1: return False 18 | elif a > prev: 19 | if inc == 0: inc = -1 20 | elif inc == 1: return False 21 | 22 | prev = a 23 | 24 | return True 25 | -------------------------------------------------------------------------------- /Python/next-greater-element-i.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/next-greater-element-i/ 2 | 3 | 4 | class Solution: 5 | def nextGreaterElement(self, nums1, nums2): 6 | """ 7 | :type nums1: List[int] 8 | :type nums2: List[int] 9 | :rtype: List[int] 10 | """ 11 | out = [] 12 | for num in nums1: 13 | i = nums2.index(num) 14 | for j in range(i + 1, len(nums2)): 15 | if nums2[j] > num: 16 | out.append(nums2[j]) 17 | break 18 | else: 19 | out.append(-1) 20 | return out 21 | 22 | -------------------------------------------------------------------------------- /Python/unique-morse-code-words.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/unique-morse-code-words/ 2 | 3 | 4 | mapping = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 5 | 6 | 7 | class Solution: 8 | def uniqueMorseRepresentations(self, words): 9 | """ 10 | :type words: List[str] 11 | :rtype: int 12 | """ 13 | transformations = set() 14 | for word in words: 15 | transformations.add(''.join([mapping[ord(c) - ord('a')] for c in word])) 16 | return len(transformations) 17 | -------------------------------------------------------------------------------- /Python/longest-substring-without-repeating-characters.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-substring-without-repeating-characters 2 | 3 | 4 | class Solution: 5 | def lengthOfLongestSubstring(self, s): 6 | if not s: 7 | return 0 8 | 9 | chars = {s[0]} 10 | longest_length = 1 11 | l, r = 0, 0 12 | 13 | while r < len(s) - 1: 14 | while s[r + 1] in chars: 15 | chars.remove(s[l]) 16 | l += 1 17 | r += 1 18 | chars.add(s[r]) 19 | longest_length = max(longest_length, r - l + 1) 20 | return longest_length 21 | -------------------------------------------------------------------------------- /Python/partition-array-into-disjoint-intervals.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/partition-array-into-disjoint-intervals 2 | 3 | 4 | class Solution: 5 | def partitionDisjoint(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: int 9 | """ 10 | largest_in_partition = A[0] 11 | largest_seen = A[0] 12 | pp = 0 13 | 14 | for i in range(1, len(A)): 15 | if A[i] < largest_in_partition: 16 | pp = i 17 | largest_in_partition = largest_seen 18 | else: 19 | largest_seen = max(largest_seen, A[i]) 20 | return pp + 1 21 | -------------------------------------------------------------------------------- /Python/sliding-window-median.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sliding-window-median/ 2 | 3 | 4 | from bisect import * 5 | 6 | 7 | class Solution(object): 8 | def medianSlidingWindow(self, nums, k): 9 | """ 10 | :type nums: List[int] 11 | :type k: int 12 | :rtype: List[float] 13 | """ 14 | medians = [] 15 | window = [] 16 | for i in range(len(nums)): 17 | if i >= k: window.pop(bisect(window, nums[i - k]) - 1) 18 | insort(window, nums[i]) 19 | if i >= k - 1: medians.append((window[k // 2] + window[(k - 1) // 2]) / 2) 20 | 21 | return medians 22 | -------------------------------------------------------------------------------- /Python/squares-of-a-sorted-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/squares-of-a-sorted-array/ 2 | 3 | 4 | class Solution(object): 5 | def sortedSquares(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: List[int] 9 | """ 10 | out = [0] * len(A) 11 | l, r = 0, len(A) - 1 12 | i = len(A) - 1 13 | while l <= r: 14 | if abs(A[l]) > abs(A[r]): 15 | out[i] = A[l]**2 16 | l += 1 17 | i -= 1 18 | else: 19 | out[i] = A[r]**2 20 | r -= 1 21 | i -= 1 22 | 23 | return out 24 | -------------------------------------------------------------------------------- /Python/valid-mountain-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-mountain-array/ 2 | 3 | class Solution(object): 4 | def validMountainArray(self, A): 5 | """ 6 | :type A: List[int] 7 | :rtype: bool 8 | """ 9 | if len(A) <= 2: return False 10 | if A[0] > A[1]: return False 11 | 12 | increasing = True 13 | for i in range(1, len(A)): 14 | if A[i] > A[i - 1]: 15 | if not increasing: return False 16 | elif A[i] < A[i - 1]: 17 | increasing = False 18 | else: 19 | return False 20 | 21 | return not increasing 22 | -------------------------------------------------------------------------------- /Python/trapping-rain-water.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/trapping-rain-water/ 2 | 3 | 4 | class Solution: 5 | def trap(self, height): 6 | """ 7 | :type height: List[int] 8 | :rtype: int 9 | """ 10 | right = [0] * len(height) 11 | for i in range(len(height) - 2, -1, -1): 12 | right[i] = max(right[i + 1], height[i + 1]) 13 | 14 | water_trapped = current_height = 0 15 | for i in range(len(height)): 16 | if height[i] >= current_height: current_height = min(height[i], right[i]) 17 | else: water_trapped += current_height - height[i] 18 | 19 | return water_trapped 20 | -------------------------------------------------------------------------------- /Python/lemonade-change.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/lemonade-change/ 2 | 3 | 4 | class Solution(object): 5 | def lemonadeChange(self, bills): 6 | """ 7 | :type bills: List[int] 8 | :rtype: bool 9 | """ 10 | fives = tens = 0 11 | for bill in bills: 12 | if bill == 5: 13 | fives += 1 14 | elif bill == 10: 15 | if fives == 0: return False 16 | fives -= 1 17 | tens += 1 18 | else: 19 | if fives == 0 or tens == 0: return False 20 | fives -= 1 21 | tens -= 1 22 | return True 23 | -------------------------------------------------------------------------------- /Python/number-of-recent-calls.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-recent-calls/ 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | class RecentCounter(object): 8 | 9 | def __init__(self): 10 | self.counter = deque() 11 | 12 | def ping(self, t): 13 | """ 14 | :type t: int 15 | :rtype: int 16 | """ 17 | self.counter.append(t) 18 | while self.counter and self.counter[0] < t - 3000: 19 | self.counter.popleft() 20 | 21 | return len(self.counter) 22 | 23 | # Your RecentCounter object will be instantiated and called as such: 24 | # obj = RecentCounter() 25 | # param_1 = obj.ping(t) 26 | -------------------------------------------------------------------------------- /Python/projection-area-of-3D-shapes.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/projection-area-of-3d-shapes/ 2 | 3 | 4 | class Solution(object): 5 | def projectionArea(self, grid): 6 | """ 7 | :type grid: List[List[int]] 8 | :rtype: int 9 | """ 10 | n = len(grid) 11 | x, y, z = 0, 0, 0 12 | 13 | for r in range(n): 14 | max_y, max_z = 0, 0 15 | for c in range(n): 16 | if grid[r][c] > 0: x += 1 17 | max_y = max(max_y, grid[r][c]) 18 | max_z = max(max_z, grid[c][r]) 19 | y += max_y 20 | z += max_z 21 | 22 | return x + y + z 23 | -------------------------------------------------------------------------------- /Python/zigzag-conversion.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/zigzag-conversion/ 2 | 3 | 4 | class Solution(object): 5 | def convert(self, s, numRows): 6 | """ 7 | :type s: str 8 | :type numRows: int 9 | :rtype: str 10 | """ 11 | 12 | if numRows == 1 or numRows >= len(s): 13 | return s 14 | 15 | L = [''] * numRows 16 | index, step = 0, 1 17 | 18 | for x in s: 19 | L[index] += x 20 | if index == 0: 21 | step = 1 22 | elif index == numRows - 1: 23 | step = -1 24 | index += step 25 | 26 | return ''.join(L) 27 | -------------------------------------------------------------------------------- /Python/first-unique-character-in-a-string.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/first-unique-character-in-a-string/ 2 | 3 | 4 | class Solution(object): 5 | def firstUniqChar(self, s): 6 | """ 7 | :type s: str 8 | :rtype: int 9 | """ 10 | chars = [float('inf')] * 26 11 | 12 | for i, c in enumerate(s): 13 | p = ord(c) - ord('a') 14 | if chars[p] == float('inf'): chars[p] = i 15 | else: chars[p] = -1 16 | 17 | m = float('inf') 18 | for i in chars: 19 | if i not in (-1, float('inf')): 20 | m = min(m, i) 21 | 22 | return m if m != float('inf') else -1 23 | -------------------------------------------------------------------------------- /Python/remove-duplicates-from-sorted-list.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-duplicates-from-sorted-list 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | 11 | class Solution: 12 | def deleteDuplicates(self, head): 13 | """ 14 | :type head: ListNode 15 | :rtype: ListNode 16 | """ 17 | node = head 18 | while node and node.next: 19 | if node.val == node.next.val: 20 | node.next = node.next.next 21 | else: 22 | node = node.next 23 | return head 24 | -------------------------------------------------------------------------------- /Python/find-all-numbers-disappeared-in-an-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ 2 | 3 | 4 | class Solution(object): 5 | def findDisappearedNumbers(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: List[int] 9 | """ 10 | out = [] 11 | target = 1 12 | for n in sorted(nums): 13 | if n > target: 14 | out.extend(range(target, n)) 15 | target = n + 1 16 | else: 17 | target = n + 1 18 | 19 | if target <= len(nums): 20 | out.extend(range(target, len(nums) + 1)) 21 | 22 | return out 23 | -------------------------------------------------------------------------------- /Python/same-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/same-tree 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def isSameTree(self, p, q): 13 | """ 14 | :type p: TreeNode 15 | :type q: TreeNode 16 | :rtype: bool 17 | """ 18 | if (p and not q) or (not p and q): 19 | return False 20 | 21 | if p and q: 22 | return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 23 | 24 | return True 25 | -------------------------------------------------------------------------------- /Python/search-in-a-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/search-in-a-binary-search-tree/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def searchBST(self, root, val): 13 | """ 14 | :type root: TreeNode 15 | :type val: int 16 | :rtype: TreeNode 17 | """ 18 | if root is None: return None 19 | if root.val == val: return root 20 | if root.val < val: return self.searchBST(root.right, val) 21 | return self.searchBST(root.left, val) 22 | -------------------------------------------------------------------------------- /Python/linked-list-cycle.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/linked-list-cycle 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution(object): 11 | def hasCycle(self, head): 12 | """ 13 | :type head: ListNode 14 | :rtype: bool 15 | """ 16 | try: 17 | slow = head 18 | fast = head.next 19 | 20 | while slow != fast: 21 | slow = slow.next 22 | fast = fast.next.next 23 | return True 24 | except AttributeError: 25 | return False 26 | -------------------------------------------------------------------------------- /Python/maximum-product-of-three-numbers.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-product-of-three-numbers/ 2 | 3 | 4 | class Solution: 5 | def maximumProduct(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | min1 = min2 = float('inf') 11 | max1 = max2 = max3 = -float('inf') 12 | 13 | for n in nums: 14 | if n <= min1: min1, min2 = n, min1 15 | elif n <= min2: min2 = n 16 | if n >= max1: max1, max2, max3 = n, max1, max2 17 | elif n >= max2: max2, max3 = n, max2 18 | elif n >= max3: max3 = n 19 | 20 | return max(min1 * min2 * max1, max1 * max2 * max3) 21 | -------------------------------------------------------------------------------- /Python/number-of-lines-to-write-string.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-lines-to-write-string/ 2 | 3 | 4 | class Solution(object): 5 | def numberOfLines(self, widths, S): 6 | """ 7 | :type widths: List[int] 8 | :type S: str 9 | :rtype: List[int] 10 | """ 11 | if not S: return 0, 0 12 | lines, cur_line_width = 1, 0 13 | 14 | for c in S: 15 | width = widths[ord(c) - ord('a')] 16 | if cur_line_width + width > 100: 17 | lines += 1 18 | cur_line_width = width 19 | else: 20 | cur_line_width += width 21 | 22 | return lines, cur_line_width 23 | -------------------------------------------------------------------------------- /Python/range-sum-query-immutable.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/range-sum-query-immutable/ 2 | 3 | 4 | class NumArray: 5 | def __init__(self, nums): 6 | """ 7 | :type nums: List[int] 8 | """ 9 | self.rsq = [0] * (len(nums) + 1) 10 | for i in range(1, len(nums) + 1): 11 | self.rsq[i] = self.rsq[i - 1] + nums[i - 1] 12 | 13 | def sumRange(self, i, j): 14 | """ 15 | :type i: int 16 | :type j: int 17 | :rtype: int 18 | """ 19 | return self.rsq[j + 1] - self.rsq[i] 20 | 21 | # Your NumArray object will be instantiated and called as such: 22 | # obj = NumArray(nums) 23 | # param_1 = obj.sumRange(i,j) 24 | -------------------------------------------------------------------------------- /Python/check-if-word-is-valid-after-substitutions.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/ 2 | 3 | 4 | class Solution(object): 5 | def isValid(self, S): 6 | """ 7 | :type S: str 8 | :rtype: bool 9 | """ 10 | na = nb = 0 11 | 12 | for c in S: 13 | if c == 'a': 14 | na += 1 15 | elif c == 'b': 16 | if na == 0: 17 | return False 18 | nb += 1 19 | na -= 1 20 | else: 21 | if nb == 0: 22 | return False 23 | nb -= 1 24 | 25 | return na == nb == 0 26 | 27 | -------------------------------------------------------------------------------- /Python/n-ary-tree-postorder-traversal.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/n-ary-tree-postorder-traversal/ 2 | 3 | 4 | """ 5 | # Definition for a Node. 6 | class Node(object): 7 | def __init__(self, val, children): 8 | self.val = val 9 | self.children = children 10 | """ 11 | 12 | 13 | class Solution(object): 14 | def postorder(self, root): 15 | """ 16 | :type root: Node 17 | :rtype: List[int] 18 | """ 19 | def traverse(root): 20 | if not root: return 21 | for child in root.children: 22 | traverse(child) 23 | ret.append(root.val) 24 | 25 | ret = [] 26 | traverse(root) 27 | return ret 28 | -------------------------------------------------------------------------------- /Python/n-ary-tree-preorder-traversal.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/n-ary-tree-preorder-traversal/ 2 | 3 | 4 | """ 5 | # Definition for a Node. 6 | class Node(object): 7 | def __init__(self, val, children): 8 | self.val = val 9 | self.children = children 10 | """ 11 | 12 | 13 | class Solution(object): 14 | def preorder(self, root): 15 | """ 16 | :type root: Node 17 | :rtype: List[int] 18 | """ 19 | def traverse(root): 20 | if not root: return 21 | ret.append(root.val) 22 | for child in root.children: 23 | traverse(child) 24 | 25 | ret = [] 26 | traverse(root) 27 | return ret 28 | -------------------------------------------------------------------------------- /Python/shortest-distance-to-a-character.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/shortest-distance-to-a-character/ 2 | 3 | 4 | class Solution(object): 5 | def shortestToChar(self, S, C): 6 | """ 7 | :type S: str 8 | :type C: str 9 | :rtype: List[int] 10 | """ 11 | out = [float('inf')] * len(S) 12 | dist = float('inf') 13 | 14 | for i in range(len(S)): 15 | if S[i] == C: dist = 0 16 | else: dist += 1 17 | out[i] = min(out[i], dist) 18 | 19 | for i in range(len(S) - 1, -1, -1): 20 | if S[i] == C: dist = 0 21 | else: dist += 1 22 | out[i] = min(out[i], dist) 23 | 24 | return out 25 | -------------------------------------------------------------------------------- /Python/univalued-binary-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/univalued-binary-tree/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution(object): 12 | def isUnivalTree(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: bool 16 | """ 17 | def search(root, v): 18 | if root is None: return True 19 | if root.val != v: return False 20 | return search(root.left, v) and search(root.right, v) 21 | 22 | if not root: return True 23 | return search(root, root.val) 24 | -------------------------------------------------------------------------------- /Python/merge-two-binary-trees.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/merge-two-binary-trees/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def mergeTrees(self, t1, t2): 13 | """ 14 | :type t1: TreeNode 15 | :type t2: TreeNode 16 | :rtype: TreeNode 17 | """ 18 | if t1 is None: return t2 19 | if t2 is None: return t1 20 | node = TreeNode(t1.val + t2.val) 21 | node.left = self.mergeTrees(t1.left, t2.left) 22 | node.right = self.mergeTrees(t1.right, t2.right) 23 | return node 24 | -------------------------------------------------------------------------------- /Python/divide-two-integers.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/divide-two-integers 2 | 3 | 4 | class Solution: 5 | def divide(self, dividend, divisor): 6 | """ 7 | :type dividend: int 8 | :type divisor: int 9 | :rtype: int 10 | """ 11 | neg = (dividend < 0) ^ (divisor < 0) 12 | dividend, divisor = abs(dividend), abs(divisor) 13 | res = 0 14 | 15 | while dividend >= divisor: 16 | t, c = divisor, 1 17 | while t <= dividend: 18 | t <<= 1 19 | c <<= 1 20 | res += c >> 1 21 | dividend -= t >> 1 22 | 23 | if neg: 24 | return -res 25 | 26 | return min(2**31 - 1, res) 27 | -------------------------------------------------------------------------------- /Python/closest-binary-search-tree-value.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/closest-binary-search-tree-value/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | 12 | class Solution: 13 | def closestValue(self, root, target): 14 | """ 15 | :type root: TreeNode 16 | :type target: float 17 | :rtype: int 18 | """ 19 | child = root.left if target < root.val else root.right 20 | if not child: return root.val 21 | child_val = self.closestValue(child, target) 22 | return min((root.val, child_val), key=lambda x: abs(target - x)) 23 | -------------------------------------------------------------------------------- /Python/encode-and-decode-strings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/encode-and-decode-strings/ 2 | 3 | 4 | class Codec: 5 | 6 | def encode(self, strs): 7 | """Encodes a list of strings to a single string. 8 | 9 | :type strs: List[str] 10 | :rtype: str 11 | """ 12 | return ''.join(s.replace('|', '||') + ' | ' for s in strs) 13 | 14 | def decode(self, s): 15 | """Decodes a single string to a list of strings. 16 | 17 | :type s: str 18 | :rtype: List[str] 19 | """ 20 | return [x.replace('||', '|') for x in s.split(' | ')[:-1]] 21 | 22 | # Your Codec object will be instantiated and called as such: 23 | # codec = Codec() 24 | # codec.decode(codec.encode(strs)) 25 | -------------------------------------------------------------------------------- /Python/guess-number-higher-or-lower.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/guess-number-higher-or-lowe 2 | 3 | 4 | # The guess API is already defined for you. 5 | # @param num, your guess 6 | # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 7 | # def guess(num): 8 | 9 | class Solution(object): 10 | def guessNumber(self, n): 11 | """ 12 | :type n: int 13 | :rtype: int 14 | """ 15 | l, r = 1, n 16 | while l <= r: 17 | m = (l + r) // 2 18 | g = guess(m) 19 | if g == 0: 20 | return m 21 | if g == -1: 22 | r = m - 1 23 | else: 24 | l = m + 1 25 | return l 26 | -------------------------------------------------------------------------------- /Python/house-robber-iii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/house-robber-iii/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def rob(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | def recurse(root): 18 | plv = lv = prv = rv = 0 19 | if root.left: plv, lv = recurse(root.left) 20 | if root.right: prv, rv = recurse(root.right) 21 | return lv + rv, max(root.val + plv + prv, lv + rv) 22 | 23 | return max(recurse(root)) if root else 0 24 | 25 | 26 | -------------------------------------------------------------------------------- /Python/roman-to-integer.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/roman-to-integer 2 | 3 | 4 | m = { 5 | 'I': 1, 6 | 'V': 5, 7 | 'X': 10, 8 | 'L': 50, 9 | 'C': 100, 10 | 'D': 500, 11 | 'M': 1000 12 | } 13 | 14 | 15 | class Solution: 16 | def romanToInt(self, s): 17 | """ 18 | :type s: str 19 | :rtype: int 20 | """ 21 | num = 0 22 | highest = 1 23 | for i in range(len(s) - 1, -1, -1): 24 | c = s[i] 25 | if m[c] == highest: 26 | num += m[c] 27 | elif m[c] > highest: 28 | highest = m[c] 29 | num += highest 30 | else: 31 | num -= m[c] 32 | return num 33 | -------------------------------------------------------------------------------- /Python/integer-to-roman.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/integer-to-roman 2 | 3 | m = [ 4 | [1, 'I'], 5 | [4, 'IV'], 6 | [5, 'V'], 7 | [9, 'IX'], 8 | [10, 'X'], 9 | [40, 'XL'], 10 | [50, 'L'], 11 | [90, 'XC'], 12 | [100, 'C'], 13 | [400, 'CD'], 14 | [500, 'D'], 15 | [900, 'CM'], 16 | [1000, 'M'] 17 | ] 18 | 19 | 20 | class Solution: 21 | def intToRoman(self, num): 22 | """ 23 | :type num: int 24 | :rtype: str 25 | """ 26 | out = [] 27 | i = len(m) - 1 28 | while num: 29 | while m[i][0] > num: 30 | i -= 1 31 | out.append(m[i][1]) 32 | num -= m[i][0] 33 | 34 | return ''.join(out) 35 | -------------------------------------------------------------------------------- /Python/merge-two-sorted-lists.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/merge-two-sorted-lists 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution: 11 | def mergeTwoLists(self, l1, l2): 12 | """ 13 | :type l1: ListNode 14 | :type l2: ListNode 15 | :rtype: ListNode 16 | """ 17 | if not l1: 18 | return l2 19 | 20 | if not l2: 21 | return l1 22 | 23 | if l1.val < l2.val: 24 | l1.next = self.mergeTwoLists(l1.next, l2) 25 | return l1 26 | 27 | l2.next = self.mergeTwoLists(l1, l2.next) 28 | return l2 29 | -------------------------------------------------------------------------------- /Python/sliding-window-maximum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sliding-window-maximum 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | class Solution(object): 8 | def maxSlidingWindow(self, nums, k): 9 | """ 10 | :type nums: List[int] 11 | :type k: int 12 | :rtype: List[int] 13 | """ 14 | out = [] 15 | window = deque() 16 | 17 | for i, n in enumerate(nums): 18 | while window and nums[window[-1]] < n: 19 | window.pop() 20 | 21 | window.append(i) 22 | if window[0] == i - k: 23 | window.popleft() 24 | 25 | if i >= k - 1: 26 | out.append(nums[window[0]]) 27 | 28 | return out 29 | -------------------------------------------------------------------------------- /Python/sorted-array-by-parity-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sort-array-by-parity-ii/ 2 | 3 | 4 | class Solution(object): 5 | def sortArrayByParityII(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: List[int] 9 | """ 10 | even, odd = 0, 1 11 | 12 | while True: 13 | while even < len(A) and not A[even] & 1: 14 | even += 2 15 | 16 | while odd < len(A) and A[odd] & 1: 17 | odd += 2 18 | 19 | if even >= len(A) or odd >= len(A): break 20 | A[odd], A[even] = A[even], A[odd] 21 | odd += 2 22 | even += 2 23 | 24 | return A 25 | 26 | 27 | print(Solution().sortArrayByParityII([4,2,5,7])) 28 | -------------------------------------------------------------------------------- /Python/strobogrammatic-number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/strobogrammatic-number/ 2 | 3 | 4 | class Solution: 5 | def isStrobogrammatic(self, num): 6 | """ 7 | :type num: str 8 | :rtype: bool 9 | """ 10 | l, r = 0, len(num) - 1 11 | while l < r: 12 | if num[l] == num[r] == '0': pass 13 | elif num[l] == num[r] == '8': pass 14 | elif num[l] == num[r] == '1': pass 15 | elif num[l] == '6' and num[r] == '9': pass 16 | elif num[l] == '9' and num[r] == '6': pass 17 | else: return False 18 | l += 1 19 | r -= 1 20 | 21 | if len(num) % 2 == 1: return num[len(num) // 2] in ('0', '8', '1') 22 | return True 23 | -------------------------------------------------------------------------------- /Python/unique-email-addresses.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/unique-email-addresses/ 2 | 3 | 4 | class Solution: 5 | def numUniqueEmails(self, emails): 6 | """ 7 | :type emails: List[str] 8 | :rtype: int 9 | """ 10 | def create_unique_email(email): 11 | local, domain = email.split('@') 12 | built_local = [] 13 | for c in local: 14 | if c == '.': continue 15 | if c == '+': break 16 | built_local.append(c) 17 | return ''.join(built_local) + domain 18 | 19 | unique_emails = set() 20 | for email in emails: 21 | unique_emails.add(create_unique_email(email)) 22 | 23 | return len(unique_emails) 24 | -------------------------------------------------------------------------------- /Python/inorder-successor-in-bst.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/inorder-successor-in-bst/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | 12 | class Solution(object): 13 | def inorderSuccessor(self, root, p): 14 | """ 15 | :type root: TreeNode 16 | :type p: TreeNode 17 | :rtype: TreeNode 18 | """ 19 | ancestor = None 20 | while root and root.val: 21 | if p.val < root.val: 22 | ancestor = root 23 | root = root.left 24 | else: 25 | root = root.right 26 | return ancestor 27 | -------------------------------------------------------------------------------- /Python/island-perimeter.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/island-perimeter/ 2 | 3 | 4 | class Solution: 5 | def islandPerimeter(self, grid): 6 | """ 7 | :type grid: List[List[int]] 8 | :rtype: int 9 | """ 10 | perimeter = 0 11 | for row in range(len(grid)): 12 | for col in range(len(grid[0])): 13 | if grid[row][col] == 1: 14 | if row == 0 or grid[row - 1][col] == 0: perimeter += 1 15 | if row == len(grid) - 1 or grid[row + 1][col] == 0: perimeter += 1 16 | if col == 0 or grid[row][col - 1] == 0: perimeter += 1 17 | if col == len(grid[0]) - 1 or grid[row][col + 1] == 0: perimeter += 1 18 | return perimeter 19 | -------------------------------------------------------------------------------- /Python/symmetric-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/symmetric-tree 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def isSymmetric(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: bool 16 | """ 17 | return not root or self.is_same(root.left, root.right) 18 | 19 | def is_same(self, a, b): 20 | if (a and not b) or (not a and b): 21 | return False 22 | 23 | if a and b: 24 | return a.val == b.val and self.is_same(a.left, b.right) and self.is_same(a.right, b.left) 25 | 26 | return True 27 | -------------------------------------------------------------------------------- /Python/reverse-words-in-a-string-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-words-in-a-string-ii/ 2 | 3 | 4 | class Solution: 5 | def reverseWords(self, str): 6 | """ 7 | :type str: List[str] 8 | :rtype: void Do not return anything, modify str in-place instead. 9 | """ 10 | def reverse(l, r): 11 | while l < r: 12 | str[l], str[r] = str[r], str[l] 13 | l += 1 14 | r -= 1 15 | 16 | reverse(0, len(str) - 1) 17 | 18 | l, r = 0, 0 19 | while r < len(str): 20 | while r < len(str) and str[r] != ' ': 21 | r += 1 22 | reverse(l, r - 1) 23 | r += 1 24 | l = r 25 | 26 | reverse(l, r) 27 | -------------------------------------------------------------------------------- /Python/two-sum-input-is-a-bst.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution(object): 12 | def findTarget(self, root, k): 13 | """ 14 | :type root: TreeNode 15 | :type k: int 16 | :rtype: bool 17 | """ 18 | def search(root, memo): 19 | if root is None: return False 20 | if k - root.val in memo: return True 21 | memo.add(root.val) 22 | return search(root.left, memo) or search(root.right, memo) 23 | 24 | return search(root, set()) 25 | -------------------------------------------------------------------------------- /Python/median-of-two-sorted-arrays.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/median-of-two-sorted-arrays 2 | 3 | 4 | class Solution(object): 5 | def findMedianSortedArrays(self, A, B): 6 | l = len(A) + len(B) 7 | if l % 2 == 1: return self.kth(A, B, l // 2) 8 | return (self.kth(A, B, l // 2) + self.kth(A, B, l // 2 - 1)) / 2. 9 | 10 | def kth(self, a, b, k): 11 | if not a: return b[k] 12 | if not b: return a[k] 13 | 14 | ia, ib = len(a) // 2, len(b) // 2 15 | 16 | if ia + ib < k: 17 | if a[ia] > b[ib]: return self.kth(a, b[ib + 1:], k - ib - 1) 18 | return self.kth(a[ia + 1:], b, k - ia - 1) 19 | 20 | if a[ia] > b[ib]: return self.kth(a[:ia], b, k) 21 | return self.kth(a, b[:ib], k) 22 | -------------------------------------------------------------------------------- /Python/minimum-path-sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-path-sum/description/ 2 | 3 | 4 | class Solution(object): 5 | def minPathSum(self, grid): 6 | """ 7 | :type grid: List[List[int]] 8 | :rtype: int 9 | """ 10 | m, n = len(grid), len(grid[0]) 11 | dp = [[0] * n for _ in range(m)] 12 | for row in range(m): 13 | for col in range(n): 14 | if row == 0 and col == 0: dp[row][col] = grid[row][col] 15 | elif row == 0: dp[row][col] = grid[row][col] + dp[row][col - 1] 16 | elif col == 0: dp[row][col] = grid[row][col] + dp[row - 1][col] 17 | else: dp[row][col] = min(dp[row - 1][col], dp[row][col - 1]) + grid[row][col] 18 | return dp[-1][-1] 19 | -------------------------------------------------------------------------------- /Python/path-sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/path-sum 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def hasPathSum(self, root, sum): 13 | """ 14 | :type root: TreeNode 15 | :type sum: int 16 | :rtype: bool 17 | """ 18 | if not root: 19 | return False 20 | 21 | if not root.left and not root.right: 22 | return sum - root.val == 0 23 | 24 | return (root.left is not None and self.hasPathSum(root.left, sum - root.val)) or \ 25 | (root.right is not None and self.hasPathSum(root.right, sum - root.val)) 26 | -------------------------------------------------------------------------------- /Python/validate-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/validate-binary-search-tree/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def isValidBST(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: bool 16 | """ 17 | def validate_branch(root, min, max): 18 | if root is None: return True 19 | if not (min < root.val < max): return False 20 | return validate_branch(root.right, root.val, max) and validate_branch(root.left, min, root.val) 21 | 22 | return validate_branch(root, -float('inf'), float('inf')) 23 | -------------------------------------------------------------------------------- /Python/minimum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-depth-of-binary-tree 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def minDepth(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | if not root: 18 | return 0 19 | 20 | if root.left and not root.right: 21 | return self.minDepth(root.left) + 1 22 | 23 | if not root.left and root.right: 24 | return self.minDepth(root.right) + 1 25 | 26 | return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 27 | -------------------------------------------------------------------------------- /Python/most-common-word.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/most-common-word/ 2 | 3 | 4 | class Solution: 5 | def mostCommonWord(self, paragraph, banned): 6 | """ 7 | :type paragraph: str 8 | :type banned: List[str] 9 | :rtype: str 10 | """ 11 | freq = {} 12 | mfw = None 13 | mfc = 0 14 | for word in ''.join(w if w.isalpha() else ' ' for w in paragraph.lower()).split(' '): 15 | if not word or word in banned: continue 16 | if word not in freq: freq[word] = 0 17 | freq[word] += 1 18 | if freq[word] > mfc: 19 | mfc = freq[word] 20 | mfw = word 21 | return mfw 22 | 23 | 24 | print(Solution().mostCommonWord("Bob. hIt, baLl", ["bob", "hit"])) 25 | -------------------------------------------------------------------------------- /Python/combination-sum-iii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/combination-sum-iii/ 2 | 3 | 4 | class Solution(object): 5 | def combination_helper(self, k, n, index, comb, ans): 6 | if k < 0: return 7 | if n == 0: 8 | if k == 0: ans.append(comb[:]) 9 | return 10 | 11 | if index > 9: return 12 | 13 | for i in range(index, 10): 14 | comb.append(i) 15 | self.combination_helper(k - 1, n - i, i + 1, comb, ans) 16 | comb.pop() 17 | 18 | def combinationSum3(self, k, n): 19 | """ 20 | :type candidates: List[int] 21 | :type target: int 22 | :rtype: List[List[int]] 23 | """ 24 | ans = [] 25 | self.combination_helper(k, n, 1, [], ans) 26 | return ans 27 | -------------------------------------------------------------------------------- /Python/sum-of-even-numbers-after-queries.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sum-of-even-numbers-after-queries/ 2 | 3 | 4 | class Solution(object): 5 | def sumEvenAfterQueries(self, A, queries): 6 | """ 7 | :type A: List[int] 8 | :type queries: List[List[int]] 9 | :rtype: List[int] 10 | """ 11 | even_sum = sum(x for x in A if x % 2 == 0) 12 | out = [] 13 | 14 | for v, i in queries: 15 | if (A[i] % 2) == 0: 16 | if A[i] + v % 2 == 0: 17 | even_sum += v 18 | else: 19 | even_sum -= A[i] 20 | elif (A[i] + v % 2) == 0: 21 | even_sum += A[i] + v 22 | A[i] += v 23 | out.append(even_sum) 24 | return out 25 | -------------------------------------------------------------------------------- /Python/trim-a-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/trim-a-binary-search-tree/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def trimBST(self, root, L, R): 13 | """ 14 | :type root: TreeNode 15 | :type L: int 16 | :type R: int 17 | :rtype: TreeNode 18 | """ 19 | if not root: return None 20 | if root.val < L: return self.trimBST(root.right, L, R) 21 | elif root.val > R: return self.trimBST(root.left, L, R) 22 | root.left = self.trimBST(root.left, L, R) 23 | root.right = self.trimBST(root.right, L, R) 24 | return root 25 | -------------------------------------------------------------------------------- /Python/unique-paths.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/unique-paths/ 2 | 3 | 4 | class Solution(object): 5 | def uniquePaths(self, m, n): 6 | """ 7 | :type m: int 8 | :type n: int 9 | :rtype: int 10 | """ 11 | def search(x, y): 12 | if (x, y) in memo: return memo[x, y] 13 | if x >= m: return 0 14 | if y >= n: return 0 15 | 16 | paths = 0 17 | if x > 0: paths += search(x - 1, y) 18 | if y > 0: paths += search(x, y - 1) 19 | memo[(x, y)] = paths 20 | search(x + 1, y) 21 | search(x, y + 1) 22 | return paths 23 | 24 | memo = {(0, 0): 1} 25 | search(0, 1) 26 | search(1, 0) 27 | return memo[(m - 1, n - 1)] 28 | -------------------------------------------------------------------------------- /Python/minimum-cost-to-hire-k-workers.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-cost-to-hire-k-workers/ 2 | 3 | 4 | from heapq import * 5 | 6 | 7 | class Solution: 8 | def mincostToHireWorkers(self, quality, wage, K): 9 | """ 10 | :type quality: List[int] 11 | :type wage: List[int] 12 | :type K: int 13 | :rtype: float 14 | """ 15 | workers = sorted((w / q, q, w) for q, w in zip(quality, wage)) 16 | heap = [] 17 | ans, sum_quality = float('inf'), 0 18 | 19 | for r, q, w in workers: 20 | heappush(heap, -q) 21 | sum_quality += q 22 | 23 | if len(heap) > K: sum_quality += heappop(heap) 24 | if len(heap) == K: ans = min(ans, r * sum_quality) 25 | 26 | return float(ans) 27 | -------------------------------------------------------------------------------- /Python/remove-linked-list-elements.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-linked-list-elements/ 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution: 11 | def removeElements(self, head, val): 12 | """ 13 | :type head: ListNode 14 | :type val: int 15 | :rtype: ListNode 16 | """ 17 | while head and head.val == val: 18 | head = head.next 19 | 20 | if not head: return None 21 | 22 | node = head 23 | while node.next: 24 | if node.next.val == val: 25 | node.next = node.next.next 26 | else: 27 | node = node.next 28 | 29 | return head 30 | -------------------------------------------------------------------------------- /Python/dungeon-game.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/dungeon-game/ 2 | 3 | 4 | class Solution(object): 5 | def calculateMinimumHP(self, dungeon): 6 | """ 7 | :type dungeon: List[List[int]] 8 | :rtype: int 9 | """ 10 | m, n = len(dungeon), len(dungeon[0]) 11 | dungeon[m - 1][n - 1] = -min(0, dungeon[m - 1][n - 1]) 12 | 13 | for row in range(m - 1, -1, -1): 14 | for col in range(n - 1, -1, -1): 15 | if row == m - 1 and col == n - 1: continue 16 | down = dungeon[row + 1][col] if row < m - 1 else float('inf') 17 | right = dungeon[row][col + 1] if col < n - 1 else float('inf') 18 | dungeon[row][col] = max(0, min(down, right) - dungeon[row][col]) 19 | return dungeon[0][0] + 1 20 | 21 | -------------------------------------------------------------------------------- /Python/letter-combinations-of-a-phone-number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/letter-combinations-of-a-phone-number 2 | 3 | 4 | m = { 5 | '2': 'abc', 6 | '3': 'def', 7 | '4': 'ghi', 8 | '5': 'jkl', 9 | '6': 'mno', 10 | '7': 'pqrs', 11 | '8': 'tuv', 12 | '9': 'wxyz' 13 | } 14 | 15 | 16 | class Solution: 17 | def letterCombinations(self, digits): 18 | """ 19 | :type digits: str 20 | :rtype: List[str] 21 | """ 22 | s = [] 23 | for d in digits: 24 | if not s: 25 | s = [c for c in m[d]] 26 | else: 27 | sn = [] 28 | for c in m[d]: 29 | sc = [x + c for x in s] 30 | sn.extend(sc) 31 | s = sn 32 | return s 33 | -------------------------------------------------------------------------------- /Python/missing-ranges.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/missing-ranges/ 2 | 3 | 4 | class Solution: 5 | def findMissingRanges(self, nums, lower, upper): 6 | """ 7 | :type nums: List[int] 8 | :type lower: int 9 | :type upper: int 10 | :rtype: List[str] 11 | """ 12 | if not nums: 13 | if lower == upper: return [str(lower)] 14 | else: return ['%s->%s' % (lower, upper)] 15 | 16 | out = [] 17 | prev = lower - 1 18 | for num in nums + [upper + 1]: 19 | if num == prev: continue 20 | if num != prev + 1: 21 | if num == prev + 2: out.append(str(prev + 1)) 22 | else: out.append('%s->%s' % (prev + 1, num - 1)) 23 | prev = num 24 | 25 | return out 26 | -------------------------------------------------------------------------------- /Python/palindrome-linked-list.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/palindrome-linked-list/ 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution: 11 | def isPalindrome(self, head): 12 | """ 13 | :type head: ListNode 14 | :rtype: bool 15 | """ 16 | rev = None 17 | slow, fast = head, head 18 | 19 | while fast and fast.next: 20 | fast = fast.next.next 21 | rev, rev.next, slow = slow, rev, slow.next 22 | 23 | if fast: 24 | slow = slow.next 25 | 26 | while rev and rev.val == slow.val: 27 | slow = slow.next 28 | rev = rev.next 29 | 30 | return not rev 31 | -------------------------------------------------------------------------------- /Python/second-minimum-node-in-a-binary-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def findSecondMinimumValue(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | def search(node): 18 | nonlocal res 19 | if not node: return 20 | if root.val < node.val < res: res = node.val 21 | search(node.left) 22 | search(node.right) 23 | 24 | res = float('inf') 25 | search(root) 26 | return res if res != float('inf') else -1 27 | -------------------------------------------------------------------------------- /Python/unique-paths-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/unique-paths-ii/ 2 | 3 | 4 | class Solution(object): 5 | def uniquePathsWithObstacles(self, obstacleGrid): 6 | """ 7 | :type obstacleGrid: List[List[int]] 8 | :rtype: int 9 | """ 10 | if obstacleGrid[0][0] != 1: obstacleGrid[0][0] = -1 11 | for row in range(len(obstacleGrid)): 12 | for col in range(len(obstacleGrid[0])): 13 | if obstacleGrid[row][col] == 1: continue 14 | paths = 0 15 | if row > 0: paths += min(0, obstacleGrid[row - 1][col]) 16 | if col > 0: paths += min(0, obstacleGrid[row][col - 1]) 17 | obstacleGrid[row][col] += paths 18 | 19 | return -obstacleGrid[-1][-1] if obstacleGrid[-1][-1] != 1 else 0 20 | -------------------------------------------------------------------------------- /Python/word-break.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/word-break/ 2 | 3 | 4 | class Solution(object): 5 | def wordBreak(self, s, wordDict): 6 | """ 7 | :type s: str 8 | :type wordDict: List[str] 9 | :rtype: bool 10 | """ 11 | def search(index): 12 | if index == len(s): return True 13 | if index in memo: return False 14 | 15 | for word in wordDict: 16 | if len(word) > len(s) - index: continue 17 | 18 | for i in range(len(word)): 19 | if s[index + i] != word[i]: break 20 | else: 21 | if search(index + len(word)): return True 22 | memo.add(index) 23 | return False 24 | 25 | memo = set() 26 | return search(0) 27 | -------------------------------------------------------------------------------- /Python/3sum-smaller.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/3sum-smaller/ 2 | 3 | 4 | class Solution: 5 | def threeSumSmaller(self, nums, target): 6 | """ 7 | :type nums: List[int] 8 | :type target: int 9 | :rtype: int 10 | """ 11 | def twoSumSmaller(index, target): 12 | triplets = 0 13 | l, r = index, len(nums) - 1 14 | while l < r: 15 | if nums[l] + nums[r] < target: 16 | triplets += r - l 17 | l += 1 18 | else: 19 | r -= 1 20 | return triplets 21 | 22 | nums.sort() 23 | triplets = 0 24 | for i in range(len(nums) - 2): 25 | triplets += twoSumSmaller(i + 1, target - nums[i]) 26 | return triplets 27 | -------------------------------------------------------------------------------- /Python/k-empty-slots.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/k-empty-slots/ 2 | 3 | 4 | class Solution(object): 5 | def kEmptySlots(self, flowers, k): 6 | """ 7 | :type flowers: List[int] 8 | :type k: int 9 | :rtype: int 10 | """ 11 | days = [0] * len(flowers) 12 | for i in range(len(flowers)): 13 | days[flowers[i] - 1] = i + 1 14 | 15 | i, l, r = 0, 0, k + 1 16 | res = float('inf') 17 | while r < len(days): 18 | di, dl, dr = days[i], days[l], days[r] 19 | if days[i] < days[l] or days[i] <= days[r]: 20 | if i == r: res = min(res, max(days[l], days[r])) 21 | l = i 22 | r = i + k + 1 23 | i += 1 24 | 25 | return res if res != float('inf') else -1 26 | -------------------------------------------------------------------------------- /Python/minimum-number-of-refueling-stops.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-number-of-refueling-stops/ 2 | 3 | 4 | from heapq import * 5 | 6 | 7 | class Solution(object): 8 | def minRefuelStops(self, target, startFuel, stations): 9 | """ 10 | :type target: int 11 | :type startFuel: int 12 | :type stations: List[List[int]] 13 | :rtype: int 14 | """ 15 | heap = [] 16 | res, i = 0, 0 17 | current_fuel = startFuel 18 | while current_fuel < target: 19 | while i < len(stations) and stations[i][0] <= current_fuel: 20 | heappush(heap, -stations[i][1]) 21 | i += 1 22 | if not heap: return -1 23 | current_fuel += -heappop(heap) 24 | res += 1 25 | return res 26 | -------------------------------------------------------------------------------- /Python/subdomain-visit-count.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/subdomain-visit-count/ 2 | 3 | 4 | class Solution: 5 | def subdomainVisits(self, cpdomains): 6 | """ 7 | :type cpdomains: List[str] 8 | :rtype: List[str] 9 | """ 10 | counts = {} 11 | for x in cpdomains: 12 | count, cpdomain = x.split() 13 | if cpdomain not in counts: counts[cpdomain] = 0 14 | counts[cpdomain] += int(count) 15 | 16 | for i in range(len(cpdomain)): 17 | if cpdomain[i] == '.': 18 | subdomain = cpdomain[i + 1:] 19 | if subdomain not in counts: counts[subdomain] = 0 20 | counts[subdomain] += int(count) 21 | 22 | return ['%s %s' % (v, k) for k, v in counts.items()] 23 | -------------------------------------------------------------------------------- /Python/bulls-and-cows.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/bulls-and-cows/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution: 8 | def getHint(self, secret, guess): 9 | """ 10 | :type secret: str 11 | :type guess: str 12 | :rtype: str 13 | """ 14 | bulls, cows = 0, 0 15 | counter = Counter(list(secret)) 16 | 17 | for i in range(len(guess)): 18 | if guess[i] == secret[i]: 19 | counter[guess[i]] -= 1 20 | bulls += 1 21 | 22 | for i in range(len(guess)): 23 | if guess[i] == secret[i]: continue 24 | if guess[i] in counter and counter[guess[i]] > 0: 25 | cows += 1 26 | counter[guess[i]] -= 1 27 | 28 | return '%sA%sB' % (bulls, cows) 29 | -------------------------------------------------------------------------------- /Python/maximum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-depth-of-binary-tree 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def maxDepth(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | if not root: 18 | return 0 19 | 20 | return max(self.max_depth_branch(root.left, 1), self.max_depth_branch(root.right, 1)) 21 | 22 | def max_depth_branch(self, root, depth): 23 | if not root: 24 | return depth 25 | 26 | return max(self.max_depth_branch(root.left, depth + 1), self.max_depth_branch(root.right, depth + 1)) 27 | -------------------------------------------------------------------------------- /Python/count-and-say.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/count-and-say/description/ 2 | 3 | 4 | class Solution: 5 | def countAndSay(self, n): 6 | """ 7 | :type n: int 8 | :rtype: str 9 | """ 10 | s = ['1'] 11 | for i in range(n - 1): 12 | s = self.countAndSayHelper(s) 13 | return ''.join(s) 14 | 15 | def countAndSayHelper(self, s): 16 | p = None 17 | c = 0 18 | o = [] 19 | for i in range(len(s)): 20 | if p is None or s[i] == p: 21 | c += 1 22 | else: 23 | o.append(str(c)) 24 | o.append(p) 25 | c = 1 26 | p = s[i] 27 | 28 | if p is not None: 29 | o.append(str(c)) 30 | o.append(p) 31 | return o 32 | -------------------------------------------------------------------------------- /Python/diameter-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/diameter-of-binary-tree/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def diameterOfBinaryTree(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | def find_diameter(root): 18 | if not root: return 0 19 | 20 | l = find_diameter(root.left) 21 | r = find_diameter(root.right) 22 | 23 | nonlocal diameter 24 | diameter = max(diameter, l + r) 25 | return max(l, r) + 1 26 | 27 | diameter = 0 28 | find_diameter(root) 29 | return diameter 30 | -------------------------------------------------------------------------------- /Python/find-k-closest-elements.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-k-closest-elements/ 2 | 3 | 4 | from bisect import bisect_left 5 | 6 | 7 | class Solution(object): 8 | def findClosestElements(self, arr, k, x): 9 | """ 10 | :type arr: List[int] 11 | :type k: int 12 | :type x: int 13 | :rtype: List[int] 14 | """ 15 | l = bisect_left(arr, x) 16 | if l > 0 and abs(arr[l - 1] - x) < abs(arr[l] - x): l -= 1 17 | r = l 18 | 19 | while r - l + 1 < k: 20 | if r + 1 >= len(arr): l -= 1 21 | elif l - 1 < 0: r += 1 22 | elif abs(x - arr[l - 1]) <= abs(arr[r + 1] - x): l -= 1 23 | else: r += 1 24 | 25 | return arr[l: r + 1] 26 | 27 | 28 | print(Solution().findClosestElements([0,0,1,2,3,3,4,7,7,8], 3, 5)) 29 | -------------------------------------------------------------------------------- /Python/number-of-boomerangs.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-boomerangs/ 2 | 3 | 4 | class Solution(object): 5 | def numberOfBoomerangs(self, points): 6 | """ 7 | :type points: List[List[int]] 8 | :rtype: int 9 | """ 10 | def calc_sq_dist(p1, p2): 11 | return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 12 | 13 | boomerangs = 0 14 | for i in range(len(points)): 15 | sq_dist_map = {} 16 | for j in range(len(points)): 17 | if i == j: continue 18 | sq_dist = calc_sq_dist(points[i], points[j]) 19 | if sq_dist not in sq_dist_map: sq_dist_map[sq_dist] = 0 20 | boomerangs += sq_dist_map[sq_dist] * 2 21 | sq_dist_map[sq_dist] += 1 22 | 23 | return boomerangs 24 | -------------------------------------------------------------------------------- /Python/read-n-characters-given-read4.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/read-n-characters-given-read4/ 2 | 3 | 4 | # The read4 API is already defined for you. 5 | # @param buf, a list of characters 6 | # @return an integer 7 | # def read4(buf): 8 | 9 | class Solution(object): 10 | def read(self, buf, n): 11 | """ 12 | :type buf: Destination buffer (List[str]) 13 | :type n: Maximum number of characters to read (int) 14 | :rtype: The number of characters read (int) 15 | """ 16 | chars_read = 0 17 | while chars_read < n: 18 | buf4 = [''] * 4 19 | cr = read4(buf4) 20 | if cr == 0: break 21 | cr = min(cr, n - chars_read) 22 | buf[chars_read:] = buf4[:cr] 23 | chars_read += cr 24 | 25 | return chars_read 26 | -------------------------------------------------------------------------------- /Python/kth-largest-element-in-a-stream.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/kth-largest-element-in-a-stream/ 2 | 3 | 4 | from heapq import * 5 | 6 | 7 | class KthLargest(object): 8 | 9 | def __init__(self, k, nums): 10 | """ 11 | :type k: int 12 | :type nums: List[int] 13 | """ 14 | self.k = k 15 | self.heap = nums 16 | heapify(self.heap) 17 | while len(self.heap) > self.k: heappop(self.heap) 18 | 19 | def add(self, val): 20 | """ 21 | :type val: int 22 | :rtype: int 23 | """ 24 | heappush(self.heap, val) 25 | if len(self.heap) > self.k: heappop(self.heap) 26 | return self.heap[0] 27 | 28 | # Your KthLargest object will be instantiated and called as such: 29 | # obj = KthLargest(k, nums) 30 | # param_1 = obj.add(val) 31 | -------------------------------------------------------------------------------- /Python/n-ary-tree-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/n-ary-tree-level-order-traversal/ 2 | 3 | 4 | """ 5 | # Definition for a Node. 6 | class Node(object): 7 | def __init__(self, val, children): 8 | self.val = val 9 | self.children = children 10 | """ 11 | 12 | 13 | class Solution(object): 14 | def levelOrder(self, root): 15 | """ 16 | :type root: Node 17 | :rtype: List[List[int]] 18 | """ 19 | def traverse(root, level): 20 | if not root: return 21 | while len(ret) <= level: 22 | ret.append([]) 23 | 24 | ret[level].append(root.val) 25 | for child in root.children: 26 | traverse(child, level + 1) 27 | 28 | ret = [] 29 | traverse(root, 0) 30 | return ret 31 | -------------------------------------------------------------------------------- /Python/bag-of-tokens.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/bag-of-tokens/ 2 | 3 | 4 | class Solution(object): 5 | def bagOfTokensScore(self, tokens, P): 6 | """ 7 | :type tokens: List[int] 8 | :type P: int 9 | :rtype: int 10 | """ 11 | tokens.sort() 12 | max_points, current_points = 0, 0 13 | l, r = 0, len(tokens) - 1 14 | 15 | while l <= r: 16 | if tokens[l] <= P: 17 | current_points += 1 18 | P -= tokens[l] 19 | l += 1 20 | elif current_points == 0: 21 | break 22 | else: 23 | current_points -= 1 24 | P += tokens[r] 25 | r -= 1 26 | 27 | max_points = max(max_points, current_points) 28 | 29 | return max_points 30 | -------------------------------------------------------------------------------- /Python/longest-palindromic-substring.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-palindromic-substring 2 | 3 | 4 | class Solution: 5 | def longestPalindrome(self, s): 6 | if not s or len(s) == 1: return s 7 | min_start, max_len = 0, 1 8 | 9 | i = 0 10 | while i < len(s): 11 | if len(s) - i <= max_len / 2: break 12 | j, k = i, i 13 | while k < len(s) - 1 and s[k + 1] == s[k]: 14 | k += 1 15 | 16 | i = k + 1 17 | 18 | while k < len(s) - 1 and j > 0 and s[k + 1] == s[j - 1]: 19 | k += 1 20 | j -= 1 21 | 22 | new_len = k - j + 1 23 | if new_len > max_len: 24 | min_start = j 25 | max_len = new_len 26 | 27 | return s[min_start:min_start+max_len] 28 | -------------------------------------------------------------------------------- /Python/merge-k-sorted-lists.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/merge-k-sorted-lists/ 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | from heapq import * 11 | 12 | 13 | class Solution: 14 | def mergeKLists(self, lists): 15 | """ 16 | :type lists: List[ListNode] 17 | :rtype: ListNode 18 | """ 19 | head, tail = None, None 20 | heap = [(node.val, node) for node in lists if node] 21 | heapify(heap) 22 | 23 | while heap: 24 | _, node = heappop(heap) 25 | if node.next: heappush(heap, (node.next.val, node.next)) 26 | if head is None: head = tail = node 27 | else: tail.next = tail = node 28 | 29 | return head 30 | -------------------------------------------------------------------------------- /Python/merge-sorted-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/merge-sorted-array 2 | 3 | 4 | class Solution: 5 | def merge(self, nums1, m, nums2, n): 6 | """ 7 | :type nums1: List[int] 8 | :type m: int 9 | :type nums2: List[int] 10 | :type n: int 11 | :rtype: void Do not return anything, modify nums1 in-place instead. 12 | """ 13 | p1 = m - 1 14 | p2 = n - 1 15 | k = m + n - 1 16 | 17 | while p1 >= 0 and p2 >= 0: 18 | if nums1[p1] < nums2[p2]: 19 | nums1[k] = nums2[p2] 20 | p2 -= 1 21 | else: 22 | nums1[k] = nums1[p1] 23 | p1 -= 1 24 | k -= 1 25 | 26 | while p2 >= 0: 27 | nums1[k] = nums2[p2] 28 | p2 -= 1 29 | k -= 1 30 | -------------------------------------------------------------------------------- /Python/contains-duplicate-iii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/contains-duplicate-iii/ 2 | 3 | 4 | class Solution: 5 | def containsNearbyAlmostDuplicate(self, nums, k, t): 6 | """ 7 | :type nums: List[int] 8 | :type k: int 9 | :type t: int 10 | :rtype: bool 11 | """ 12 | if k <= 0 or t < 0: return False 13 | prev = {} 14 | bucket_width = t + 1 15 | for i in range(len(nums)): 16 | m = nums[i] // bucket_width 17 | if m in prev: return True 18 | if m - 1 in prev and abs(nums[i] - prev[m - 1]) < bucket_width: return True 19 | if m + 1 in prev and abs(nums[i] - prev[m + 1]) < bucket_width: return True 20 | prev[m] = nums[i] 21 | if i >= k: del prev[nums[i - k] // bucket_width] 22 | return False 23 | -------------------------------------------------------------------------------- /Python/my-calendar-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/my-calendar-ii/ 2 | 3 | 4 | class MyCalendarTwo(object): 5 | 6 | def __init__(self): 7 | self.bookings = [] 8 | self.overlaps = [] 9 | 10 | def book(self, start, end): 11 | """ 12 | :type start: int 13 | :type end: int 14 | :rtype: bool 15 | """ 16 | for os, oe in self.overlaps: 17 | if os < end and start < oe: return False 18 | 19 | for bs, be in self.bookings: 20 | if bs < end and start < be: 21 | self.overlaps.append((max(bs, start), min(be, end))) 22 | 23 | self.bookings.append((start, end)) 24 | return True 25 | 26 | 27 | # Your MyCalendarTwo object will be instantiated and called as such: 28 | # obj = MyCalendarTwo() 29 | # param_1 = obj.book(start,end) 30 | -------------------------------------------------------------------------------- /Python/shortest-completing-word.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/shortest-completing-word/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution(object): 8 | def shortestCompletingWord(self, licensePlate, words): 9 | """ 10 | :type licensePlate: str 11 | :type words: List[str] 12 | :rtype: str 13 | """ 14 | lp = Counter([c for c in licensePlate.lower() if c.isalpha()]) 15 | smallest_word = None 16 | 17 | for word in words: 18 | if smallest_word is None or len(smallest_word) > len(word): 19 | wc = Counter(word.lower()) 20 | for c in lp: 21 | if wc[c] < lp[c]: 22 | break 23 | else: 24 | smallest_word = word 25 | 26 | return smallest_word 27 | -------------------------------------------------------------------------------- /Python/minimum-time-difference.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-time-difference/ 2 | 3 | 4 | class Solution: 5 | def findMinDifference(self, timePoints): 6 | """ 7 | :type timePoints: List[str] 8 | :rtype: int 9 | """ 10 | def convert_to_minutes(x): 11 | h, m = map(int, x.split(':')) 12 | return h * 60 + m 13 | 14 | times = [convert_to_minutes(timePoints[i]) for i in range(len(timePoints))] 15 | times.sort() 16 | 17 | min_difference = float('inf') 18 | for i in range(1, len(times)): 19 | min_difference = min(min_difference, times[i] - times[i - 1]) 20 | 21 | midnight = 24 * 60 22 | return min(min_difference, midnight - times[-1] + times[0]) 23 | 24 | 25 | 26 | print(Solution().findMinDifference(["12:57","05:02","16:01"])) 27 | -------------------------------------------------------------------------------- /Python/linked-list-cycle-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/linked-list-cycle-ii 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution(object): 11 | def detectCycle(self, head): 12 | """ 13 | :type head: ListNode 14 | :rtype: ListNode 15 | """ 16 | try: 17 | slow = head.next 18 | fast = head.next.next 19 | 20 | while slow != fast: 21 | slow = slow.next 22 | fast = fast.next.next 23 | 24 | slow = head 25 | while slow != fast: 26 | slow = slow.next 27 | fast = fast.next 28 | return slow 29 | except AttributeError: 30 | return None 31 | -------------------------------------------------------------------------------- /Python/verifying-an-alien-dictionary.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/verifying-an-alien-dictionary/ 2 | 3 | 4 | class Solution: 5 | def isAlienSorted(self, words, order): 6 | """ 7 | :type words: List[str] 8 | :type order: str 9 | :rtype: bool 10 | """ 11 | if len(words) < 2: return True 12 | order_index = {o: i for i, o in enumerate(order)} 13 | 14 | for i in range(0, len(words) - 1): 15 | prev_word, cur_word = words[i], words[i + 1] 16 | 17 | for j in range(min(len(prev_word), len(cur_word))): 18 | po, co = order_index[prev_word[j]], order_index[cur_word[j]] 19 | if po > co: return False 20 | if po < co: break 21 | else: 22 | if len(prev_word) > len(cur_word): return False 23 | 24 | return True 25 | -------------------------------------------------------------------------------- /Python/couples-holding-hands.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/couples-holding-hands/ 2 | 3 | 4 | class Solution: 5 | def minSwapsCouples(self, row): 6 | """ 7 | :type row: List[int] 8 | :rtype: int 9 | """ 10 | def find_partner(index, partner): 11 | for j in range(index, len(row)): 12 | if row[j] == partner: return j 13 | 14 | swaps = 0 15 | for i in range(1, len(row), 2): 16 | if row[i] % 2 == 0 and row[i - 1] == row[i] + 1: continue 17 | if row[i] % 2 == 1 and row[i - 1] == row[i] - 1: continue 18 | if row[i] == row[i - 1]: continue 19 | pv = row[i - 1] + 1 if row[i - 1] % 2 == 0 else row[i - 1] - 1 20 | p = find_partner(i, pv) 21 | row[i], row[p] = row[p], row[i] 22 | swaps += 1 23 | return swaps 24 | -------------------------------------------------------------------------------- /Python/letter-case-permutation.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/letter-case-permutation/ 2 | 3 | 4 | class Solution(object): 5 | def letterCasePermutation(self, S): 6 | """ 7 | :type S: str 8 | :rtype: List[str] 9 | """ 10 | def helper(S, i): 11 | if i == len(S) - 1: 12 | if S[i].isalpha(): 13 | yield S[i].lower() 14 | yield S[i].upper() 15 | else: 16 | yield S[i] 17 | else: 18 | for x in helper(S, i + 1): 19 | if S[i].isalpha(): 20 | yield S[i].lower() + x 21 | yield S[i].upper() + x 22 | else: 23 | yield S[i] + x 24 | 25 | if not S: return [""] 26 | return list(helper(S, 0)) 27 | -------------------------------------------------------------------------------- /Python/binary-watch.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-watch/ 2 | 3 | 4 | class Solution: 5 | def readBinaryWatch(self, num): 6 | """ 7 | :type num: int 8 | :rtype: List[str] 9 | """ 10 | def count_bits(x): 11 | bits = 0 12 | while x > 0: 13 | if x & 1: bits += 1 14 | x >>= 1 15 | return bits 16 | 17 | possible_times = [] 18 | hours = 0 19 | while hours < 12: 20 | hb = count_bits(hours) 21 | minutes = 0 22 | while minutes < 60: 23 | mb = count_bits(minutes) 24 | if hb + mb == num: 25 | possible_times.append('%s:%s' % (str(hours), str(minutes).rjust(2, '0'))) 26 | minutes += 1 27 | hours += 1 28 | return possible_times 29 | -------------------------------------------------------------------------------- /Python/find-and-replace-in-string.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-and-replace-in-string/ 2 | 3 | 4 | class Solution: 5 | def findReplaceString(self, S, indexes, sources, targets): 6 | """ 7 | :type S: str 8 | :type indexes: List[int] 9 | :type sources: List[str] 10 | :type targets: List[str] 11 | :rtype: str 12 | """ 13 | def source_match(index, source): 14 | if index + len(source) > len(S): return False 15 | return S[index:index + len(source)] == source 16 | 17 | out = list(S) 18 | for index, source, target in zip(indexes, sources, targets): 19 | if source_match(index, source): 20 | out[index] = target 21 | for i in range(index + 1, index + len(source)): 22 | out[i] = '' 23 | 24 | return ''.join(out) 25 | -------------------------------------------------------------------------------- /Python/x-of-a-kind-in-a-deck-of-cards.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards 2 | 3 | class Solution: 4 | def hasGroupsSizeX(self, deck): 5 | """ 6 | :type deck: List[int] 7 | :rtype: bool 8 | """ 9 | smallest_group_size = float('inf') 10 | m = {} 11 | 12 | for card in deck: 13 | if card not in m: 14 | m[card] = 0 15 | m[card] += 1 16 | 17 | for card in m: 18 | smallest_group_size = min(smallest_group_size, m[card]) 19 | 20 | if smallest_group_size < 2: 21 | return False 22 | 23 | for i in range(2, smallest_group_size + 1): 24 | for card in m: 25 | if m[card] % i != 0: 26 | break 27 | else: 28 | return True 29 | 30 | return False 31 | -------------------------------------------------------------------------------- /Python/lonely-pixel-i.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/lonely-pixel-i/ 2 | 3 | 4 | class Solution(object): 5 | def findLonelyPixel(self, picture): 6 | """ 7 | :type picture: List[List[str]] 8 | :rtype: int 9 | """ 10 | r = [0] * len(picture) 11 | c = [0] * len(picture[0]) 12 | 13 | for row in range(len(picture)): 14 | for col in range(len(picture[0])): 15 | if picture[row][col] == 'B': 16 | r[row] += 1 17 | c[col] += 1 18 | 19 | lp = 0 20 | for row in range(len(picture)): 21 | for col in range(len(picture[0])): 22 | if picture[row][col] == 'B' and r[row] == c[col] == 1: 23 | lp += 1 24 | 25 | return lp 26 | 27 | print(Solution().findLonelyPixel([["W","W","B"],["W","B","W"],["B","W","W"]])) 28 | -------------------------------------------------------------------------------- /Python/maximum-product-of-word-lengths.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-product-of-word-lengths/ 2 | 3 | 4 | class Solution(object): 5 | def maxProduct(self, words): 6 | """ 7 | :type words: List[str] 8 | :rtype: int 9 | """ 10 | masks = {} 11 | for word in words: 12 | mask = 0 13 | for c in word: 14 | mask |= 1 << (ord(c) - ord('a')) 15 | if mask not in masks: masks[mask] = len(word) 16 | else: masks[mask] = max(masks[mask], len(word)) 17 | 18 | max_product = 0 19 | for m1 in masks: 20 | for m2 in masks: 21 | if m1 & m2: continue 22 | max_product = max(max_product, masks[m1] * masks[m2]) 23 | return max_product 24 | 25 | 26 | print(Solution().maxProduct(["abcw","baz","foo","bar","xtfn","abcdef"])) 27 | -------------------------------------------------------------------------------- /Python/remove-nth-node-from-end-of-list.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-nth-node-from-end-of-list 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | 11 | class Solution: 12 | def removeNthFromEnd(self, head, n): 13 | """ 14 | :type head: ListNode 15 | :type n: int 16 | :rtype: ListNode 17 | """ 18 | node1 = head 19 | node2 = head 20 | for _ in range(n): 21 | node2 = node2.next 22 | 23 | node_prev = None 24 | while node2: 25 | node_prev = node1 26 | node1 = node1.next 27 | node2 = node2.next 28 | 29 | if node_prev is None: 30 | return head.next 31 | 32 | node_prev.next = node1.next 33 | return head 34 | -------------------------------------------------------------------------------- /Python/split-array-into-consecutive-subsequences.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/split-array-into-consecutive-subsequences/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution(object): 8 | def isPossible(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: bool 12 | """ 13 | remaining = Counter(nums) 14 | end = Counter() 15 | 16 | for num in nums: 17 | if remaining[num] == 0: continue 18 | remaining[num] -= 1 19 | if end[num - 1] > 0: 20 | end[num - 1] -= 1 21 | end[num] += 1 22 | elif remaining[num + 1] > 0 and remaining[num + 2] > 0: 23 | remaining[num + 1] -= 1 24 | remaining[num + 2] -= 1 25 | end[num + 2] += 1 26 | else: return False 27 | return True 28 | -------------------------------------------------------------------------------- /Python/longest-common-prefix.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-common-prefix/description/ 2 | 3 | 4 | class Solution: 5 | def longestCommonPrefix(self, strs): 6 | """ 7 | :type strs: List[str] 8 | :rtype: str 9 | """ 10 | prefix = [] 11 | i = 0 12 | while True: 13 | char = None 14 | matched = True 15 | for str in strs: 16 | if i >= len(str): 17 | matched = False 18 | break 19 | if char is None: 20 | char = str[i] 21 | continue 22 | 23 | if str[i] != char: 24 | matched = False 25 | break 26 | 27 | if char is None or not matched: 28 | return ''.join(prefix) 29 | prefix.append(char) 30 | i += 1 31 | -------------------------------------------------------------------------------- /Python/string-to-integer-atoi.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/string-to-integer-atoi 2 | 3 | 4 | INT_MAX = 2**31 - 1 5 | INT_MIN = -2**31 6 | 7 | 8 | class Solution: 9 | def myAtoi(self, str): 10 | """ 11 | :type str: str 12 | :rtype: int 13 | """ 14 | str = str.strip() 15 | neg = 1 16 | num = 0 17 | for i in range(len(str)): 18 | c = str[i] 19 | if i == 0 and c == '-': 20 | neg = -1 21 | elif i == 0 and c == '+': 22 | continue 23 | elif c.isdigit(): 24 | num = num * 10 + int(c) 25 | 26 | if neg == - 1and -num < INT_MIN: 27 | return INT_MIN 28 | if neg == 1 and num > INT_MAX: 29 | return INT_MAX 30 | else: 31 | break 32 | return num * neg 33 | -------------------------------------------------------------------------------- /Python/word-break-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/word-break-ii/ 2 | 3 | 4 | class Solution(object): 5 | def wordBreak(self, s, wordDict): 6 | """ 7 | :type s: str 8 | :type wordDict: List[str] 9 | :rtype: List[str] 10 | """ 11 | def search(index): 12 | if index == len(s): return [[]] 13 | if index in memo: return memo[index] 14 | 15 | sentences_made = [] 16 | for word in wordDict: 17 | if len(word) > len(s) - index: continue 18 | if s[index:index + len(word)] == word: 19 | sm = search(index + len(word)) 20 | for r in sm: sentences_made.append([word] + r) 21 | 22 | memo[index] = sentences_made 23 | return sentences_made 24 | 25 | memo = {} 26 | return list(map(lambda x: ' '.join(x), search(0))) 27 | -------------------------------------------------------------------------------- /Python/binary-tree-longest-consecutive-sequence.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def longestConsecutive(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | def search(root, prev, conseq): 18 | nonlocal lcs 19 | lcs = max(lcs, conseq) 20 | if not root: return 21 | else: 22 | if prev + 1 != root.val: conseq = 0 23 | search(root.left, root.val, conseq + 1) 24 | search(root.right, root.val, conseq + 1) 25 | 26 | lcs = 0 27 | search(root, -float('inf'), 0) 28 | return lcs 29 | -------------------------------------------------------------------------------- /Python/moving-average-from-data-stream.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/moving-average-from-data-stream/ 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | class MovingAverage: 8 | 9 | def __init__(self, size): 10 | """ 11 | Initialize your data structure here. 12 | :type size: int 13 | """ 14 | self.size = size 15 | self.elements = deque() 16 | self.sum = 0 17 | 18 | def next(self, val): 19 | """ 20 | :type val: int 21 | :rtype: float 22 | """ 23 | self.elements.append(val) 24 | self.sum += val 25 | 26 | if len(self.elements) > self.size: 27 | self.sum -= self.elements.popleft() 28 | 29 | return self.sum / len(self.elements) 30 | 31 | 32 | # Your MovingAverage object will be instantiated and called as such: 33 | # obj = MovingAverage(size) 34 | # param_1 = obj.next(val) 35 | -------------------------------------------------------------------------------- /Python/most-stones-removed-with-same-row-or-column.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/ 2 | 3 | 4 | class Solution(object): 5 | def colorStones(self, stones, stone, colors, color): 6 | colors[stone] = color 7 | for i in range(len(stones)): 8 | if colors[i] != -1: continue 9 | if stones[i][0] == stones[stone][0] or stones[i][1] == stones[stone][1]: 10 | self.colorStones(stones, i, colors, color) 11 | 12 | def removeStones(self, stones): 13 | """ 14 | :type stones: List[List[int]] 15 | :rtype: int 16 | """ 17 | colors = [-1] * len(stones) 18 | color = 0 19 | 20 | for i in range(len(stones)): 21 | if colors[i] == -1: 22 | self.colorStones(stones, i, colors, color) 23 | color += 1 24 | 25 | return len(stones) - color 26 | -------------------------------------------------------------------------------- /Python/next-permutation.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/next-permutation/ 2 | 3 | 4 | class Solution(object): 5 | def swap(self, nums, i): 6 | for j in range(len(nums) - 1, i, -1): 7 | if nums[j] > nums[i]: 8 | nums[i], nums[j] = nums[j], nums[i] 9 | break 10 | 11 | def reverse(self, nums, i): 12 | j = len(nums) - 1 13 | while i < j: 14 | nums[i], nums[j] = nums[j], nums[i] 15 | i += 1 16 | j -= 1 17 | 18 | def nextPermutation(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: void Do not return anything, modify nums in-place instead. 22 | """ 23 | if len(nums) <= 1: return; 24 | 25 | for i in range(len(nums) - 1, -1, -1): 26 | if nums[i] > nums[i - 1]: break 27 | 28 | if i > 0: self.swap(nums, i - 1) 29 | self.reverse(nums, i) 30 | -------------------------------------------------------------------------------- /Python/sentence-similarity.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sentence-similarity/ 2 | 3 | 4 | class Solution: 5 | def areSentencesSimilar(self, words1, words2, pairs): 6 | """ 7 | :type words1: List[str] 8 | :type words2: List[str] 9 | :type pairs: List[List[str]] 10 | :rtype: bool 11 | """ 12 | if len(words1) != len(words2): return False 13 | similar_words = {} 14 | for a, b in pairs: 15 | if a not in similar_words: similar_words[a] = set() 16 | if b not in similar_words: similar_words[b] = set() 17 | similar_words[a].add(b) 18 | similar_words[b].add(a) 19 | 20 | for i in range(len(words1)): 21 | a, b = words1[i], words2[i] 22 | if a == b: continue 23 | if a in similar_words and b in similar_words[a]: continue 24 | return False 25 | return True 26 | -------------------------------------------------------------------------------- /Python/count-complete-tree-nodes.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/count-complete-tree-nodes/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def countNodes(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | def get_height(root): 18 | if not root: return -1 19 | return get_height(root.left) + 1 20 | 21 | nodes, height = 0, get_height(root) 22 | while root: 23 | if get_height(root.right) == height - 1: 24 | nodes += 1 << height 25 | root = root.right 26 | else: 27 | nodes += 1 << height - 1 28 | root = root.left 29 | height -= 1 30 | return nodes 31 | -------------------------------------------------------------------------------- /Python/shortest-word-distance.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/shortest-word-distance/ 2 | 3 | 4 | class Solution: 5 | def shortestDistance(self, words, word1, word2): 6 | """ 7 | :type words: List[str] 8 | :type word1: str 9 | :type word2: str 10 | :rtype: int 11 | """ 12 | cur_word, cur_pos, shortest_dist = None, -1, float('inf') 13 | 14 | for i, word in enumerate(words): 15 | if word in (word1, word2): 16 | if cur_word is None: 17 | cur_word = word 18 | cur_pos = i 19 | else: 20 | if cur_word != word: 21 | shortest_dist = min(shortest_dist, i - cur_pos) 22 | cur_word = word 23 | cur_pos = i 24 | else: 25 | cur_pos = i 26 | 27 | return shortest_dist 28 | -------------------------------------------------------------------------------- /Python/generate-parentheses.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/generate-parentheses 2 | 3 | 4 | class Solution: 5 | def generateParenthesis(self, n): 6 | """ 7 | :type n: int 8 | :rtype: List[str] 9 | """ 10 | memo = {} 11 | return self.generateParenthesis_helper(n * 2, 0, memo) 12 | 13 | def generateParenthesis_helper(self, n, l, memo): 14 | if (n, l) in memo: 15 | return memo[(n, l)] 16 | 17 | if n == 0: 18 | return [''] 19 | 20 | out = [] 21 | 22 | if l > 0: 23 | for p in self.generateParenthesis_helper(n - 1, l - 1, memo): 24 | out.append(')' + p) 25 | 26 | if n > l: 27 | for p in self.generateParenthesis_helper(n - 1, l + 1, memo): 28 | out.append('(' + p) 29 | 30 | memo[(n, l)] = out 31 | return out 32 | 33 | print(Solution().generateParenthesis(3)) 34 | -------------------------------------------------------------------------------- /Python/subtree-of-another-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/subtree-of-another-tree/ 2 | 3 | 4 | class Solution: 5 | def isSubtree(self, s, t): 6 | """ 7 | :type s: TreeNode 8 | :type t: TreeNode 9 | :rtype: bool 10 | """ 11 | def compare_subtree(sroot, troot): 12 | if sroot is None: return troot is None 13 | if troot is None: return sroot is None 14 | if sroot.val != troot.val: return False 15 | return compare_subtree(sroot.left, troot.left) and \ 16 | compare_subtree(sroot.right, troot.right) 17 | 18 | def search(s, t): 19 | if s.val == t.val and compare_subtree(s, t): return True 20 | if s.left and search(s.left, t): return True 21 | if s.right and search(s.right, t): return True 22 | return False 23 | 24 | if not t: return not s 25 | return search(s, t) 26 | -------------------------------------------------------------------------------- /Python/find-first-and-last-position-of-element-in-sorted-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array 2 | 3 | 4 | class Solution(object): 5 | def searchRange(self, nums, target): 6 | """ 7 | :type nums: List[int] 8 | :type target: int 9 | :rtype: List[int] 10 | """ 11 | l, r = 0, len(nums) - 1 12 | 13 | while l <= r: 14 | m = (l + r) // 2 15 | if nums[m] == target: 16 | l = m - 1 17 | while l >= 0 and nums[l] == target: 18 | l -= 1 19 | 20 | r = m + 1 21 | while r < len(nums) and nums[r] == target: 22 | r += 1 23 | 24 | return [l + 1, r - 1] 25 | 26 | elif nums[m] < target: 27 | l = m + 1 28 | else: 29 | r = m - 1 30 | 31 | return [-1, -1] 32 | -------------------------------------------------------------------------------- /Python/insert-into-a-cyclic-sorted-list.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/insert-into-a-cyclic-sorted-list/ 2 | 3 | 4 | # Definition for a Node. 5 | # class Node(object): 6 | # def __init__(self, val, next): 7 | # self.val = val 8 | # self.next = next 9 | 10 | 11 | class Solution(object): 12 | def insert(self, head, insertVal): 13 | """ 14 | :type head: Node 15 | :type insertVal: int 16 | :rtype: Node 17 | """ 18 | node = Node(insertVal, head) 19 | if not head: return node 20 | 21 | cur, prev = head.next, head 22 | 23 | while True: 24 | if prev.val <= node.val <= cur.val: break 25 | if prev.val > cur.val and (node.val < cur.val or node.val > prev.val): break 26 | if cur == head: break 27 | cur, prev = cur.next, prev.next 28 | 29 | prev.next = node 30 | node.next = cur 31 | return head 32 | -------------------------------------------------------------------------------- /Python/binary-tree-maximum-path-sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-tree-maximum-path-sum/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def maxPathSum(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | def search(root): 18 | nonlocal max_path 19 | if not root: return 0 20 | max_path = max(max_path, root.val) 21 | 22 | left = search(root.left) 23 | right = search(root.right) 24 | max_path = max(max_path, left + root.val, right + root.val, left + right + root.val) 25 | return max(root.val, left + root.val, right + root.val) 26 | 27 | max_path = -float('inf') 28 | search(root) 29 | return max_path 30 | -------------------------------------------------------------------------------- /Python/license-key-formatting.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/license-key-formatting/ 2 | 3 | 4 | class Solution: 5 | def licenseKeyFormatting(self, S, K): 6 | """ 7 | :type S: str 8 | :type K: int 9 | :rtype: str 10 | """ 11 | S = ''.join(s.upper() for s in S if s.isalnum()) 12 | first_group = len(S) % K 13 | out = [] 14 | 15 | is_first_group = first_group > 0 16 | 17 | i = 0 18 | for s in S: 19 | if is_first_group and i == first_group: 20 | is_first_group = False 21 | out.append('-') 22 | i = 0 23 | 24 | if is_first_group: 25 | out.append(s) 26 | else: 27 | out.append(s) 28 | if i == K - 1: out.append('-') 29 | 30 | i = (i + 1) % K 31 | 32 | if out and out[-1] == '-': out.pop() 33 | return ''.join(out) 34 | -------------------------------------------------------------------------------- /Python/minimum-falling-path-sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-falling-path-sum/ 2 | 3 | 4 | class Solution(object): 5 | def minFallingPathSum(self, A): 6 | """ 7 | :type A: List[List[int]] 8 | :rtype: int 9 | """ 10 | def children(row, col): 11 | if row < rows - 1: 12 | yield row + 1, col 13 | if col > 0: yield row + 1, col - 1 14 | if col < cols - 1: yield row + 1, col + 1 15 | 16 | def search(row, col): 17 | if (row, col) in mem: return mem[row, col] 18 | mem[row, col] = A[row][col] 19 | childs = list(search(r, c) for r, c in children(row, col)) 20 | if childs: mem[row, col] += min(childs) 21 | return mem[row, col] 22 | 23 | if not A: return 0 24 | rows, cols = len(A), len(A[0]) 25 | mem = {} 26 | return min(search(0, c) for c in range(cols)) 27 | -------------------------------------------------------------------------------- /Python/convert-sorted-array-to-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree 2 | 3 | 4 | # Definition for a binary tree node. 5 | class TreeNode: 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | class Solution: 12 | def sortedArrayToBST(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: TreeNode 16 | """ 17 | if not nums: 18 | return None 19 | 20 | return self.sub_tree(nums, 0, len(nums) - 1) 21 | 22 | def sub_tree(self, nums, l, r): 23 | if l == r: 24 | return TreeNode(nums[l]) 25 | if l > r: 26 | return TreeNode('null') 27 | 28 | m = (l + r) // 2 29 | node = TreeNode(nums[m]) 30 | node.left = self.sub_tree(nums, l, m - 1) 31 | node.right = self.sub_tree(nums, m + 1, r) 32 | return node 33 | -------------------------------------------------------------------------------- /Python/sort-colors.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sort-colors/ 2 | 3 | 4 | class Solution: 5 | def sortColors(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: void Do not return anything, modify nums in-place instead. 9 | """ 10 | if len(nums) < 2: return 11 | l, r = 0, len(nums) - 1 12 | 13 | while l < r: 14 | while l < r and nums[l] in (0, 1): l += 1 15 | while r > l and nums[r] == 2: r -= 1 16 | 17 | if l < r: 18 | nums[l], nums[r] = nums[r], nums[l] 19 | l += 1 20 | r -= 1 21 | 22 | l = 0 23 | if nums[r] == 2: r -= 1 24 | while l < r: 25 | while l < r and nums[l] == 0: l += 1 26 | while r > l and nums[r] == 1: r -= 1 27 | 28 | if l < r: 29 | nums[l], nums[r] = nums[r], nums[l] 30 | l += 1 31 | r -= 1 32 | -------------------------------------------------------------------------------- /Python/degree-of-an-array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/degree-of-an-array/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution(object): 8 | def findShortestSubArray(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: int 12 | """ 13 | freq = Counter(nums) 14 | degree = max(freq.values()) 15 | if degree <= 1: return degree 16 | 17 | degree_elements = {k: [-1, -1] for k in freq if freq[k] == degree} 18 | 19 | for i, n in enumerate(nums): 20 | if n in degree_elements: 21 | if degree_elements[n][0] == -1: 22 | degree_elements[n][0] = i 23 | else: 24 | degree_elements[n][1] = i 25 | 26 | min_length = float('inf') 27 | for de in degree_elements: 28 | min_length = min(min_length, degree_elements[de][1] - degree_elements[de][0] + 1) 29 | return min_length 30 | -------------------------------------------------------------------------------- /Python/increasing-order-search-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/increasing-order-search-tree/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution(object): 12 | def increasingBST(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: TreeNode 16 | """ 17 | def search(root): 18 | nonlocal new_root, cur_root 19 | 20 | if root is None: return 21 | search(root.left) 22 | if new_root is None: 23 | new_root = cur_root = TreeNode(root.val) 24 | else: 25 | cur_root.right = TreeNode(root.val) 26 | cur_root = cur_root.right 27 | search(root.right) 28 | 29 | new_root = cur_root = None 30 | search(root) 31 | return new_root 32 | -------------------------------------------------------------------------------- /Python/longest-substring-with-at-most-two-distinct-characters.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ 2 | 3 | 4 | class Solution: 5 | def lengthOfLongestSubstringTwoDistinct(self, s): 6 | """ 7 | :type s: str 8 | :rtype: int 9 | """ 10 | l, r = 0, 0 11 | substring_chars = set() 12 | freq = {} 13 | longest_substring = 0 14 | while r < len(s): 15 | if s[r] not in freq: freq[s[r]] = 0 16 | freq[s[r]] += 1 17 | substring_chars.add(s[r]) 18 | 19 | while len(substring_chars) > 2: 20 | freq[s[l]] -= 1 21 | if freq[s[l]] == 0: substring_chars.remove(s[l]) 22 | l += 1 23 | 24 | r += 1 25 | longest_substring = max(longest_substring, r - l) 26 | 27 | longest_substring = max(longest_substring, r - l) 28 | return longest_substring 29 | -------------------------------------------------------------------------------- /Python/binary-tree-level-order-traversal-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-tree-level-order-traversal-ii 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | from collections import deque 12 | 13 | 14 | class Solution: 15 | def levelOrderBottom(self, root): 16 | """ 17 | :type root: TreeNode 18 | :rtype: List[List[int]] 19 | """ 20 | out = [] 21 | queue = deque([(root, 1)]) 22 | 23 | while queue: 24 | node, depth = queue.pop() 25 | 26 | if node: 27 | if len(out) < depth: 28 | out.append([]) 29 | out[depth - 1].append(node.val) 30 | queue.appendleft((node.left, depth + 1)) 31 | queue.appendleft((node.right, depth + 1)) 32 | return list(reversed(out)) 33 | -------------------------------------------------------------------------------- /Python/add-strings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/add-strings/ 2 | 3 | 4 | class Solution: 5 | def addStrings(self, num1, num2): 6 | """ 7 | :type num1: str 8 | :type num2: str 9 | :rtype: str 10 | """ 11 | s = [] 12 | c = 0 13 | i1, i2 = len(num1) - 1, len(num2) - 1 14 | 15 | while i1 >= 0 and i2 >= 0: 16 | n, c = c + int(num1[i1]) + int(num2[i2]), 0 17 | if n > 9: n, c = n % 10, 1 18 | s.append(n) 19 | i1, i2 = i1 - 1, i2 - 1 20 | 21 | while i1 >= 0: 22 | n, c = c + int(num1[i1]), 0 23 | if n > 9: n, c = n % 10, 1 24 | s.append(n) 25 | i1 -= 1 26 | 27 | while i2 >= 0: 28 | n, c = c + int(num2[i2]), 0 29 | if n > 9: n, c = n % 10, 1 30 | s.append(n) 31 | i2 -= 1 32 | 33 | if c > 0: s.append(1) 34 | return ''.join(map(str, reversed(s))) 35 | -------------------------------------------------------------------------------- /Python/kth-smallest-element-in-a-bst.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/kth-smallest-element-in-a-bst/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution(object): 12 | def kthSmallest(self, root, k): 13 | """ 14 | :type root: TreeNode 15 | :type k: int 16 | :rtype: int 17 | """ 18 | def search(root): 19 | nonlocal current_pos 20 | if not root: return float('inf') 21 | left = search(root.left) 22 | if left != float('inf'): return left 23 | current_pos += 1 24 | if current_pos == k: return root.val 25 | right = search(root.right) 26 | if right != float('inf'): return right 27 | return float('inf') 28 | 29 | current_pos = 0 30 | return search(root) 31 | -------------------------------------------------------------------------------- /Python/largest-triangle-area.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/largest-triangle-area/ 2 | 3 | 4 | class Solution(object): 5 | def largestTriangleArea(self, points): 6 | """ 7 | :type points: List[List[int]] 8 | :rtype: float 9 | """ 10 | max_area = 0 11 | for i in range(len(points)): 12 | for j in range(i, len(points)): 13 | for k in range(j, len(points)): 14 | max_area = max(max_area, 0.5 * abs(points[i][0] * points[j][1] + 15 | points[j][0] * points[k][1] + 16 | points[k][0] * points[i][1] - 17 | points[i][1] * points[j][0] - 18 | points[j][1] * points[k][0] - 19 | points[k][1] * points[i][0])) 20 | return max_area 21 | -------------------------------------------------------------------------------- /Python/longest-univalue-path.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-univalue-path/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | 12 | class Solution(object): 13 | def longestUnivaluePath(self, root): 14 | """ 15 | :type root: TreeNode 16 | :rtype: int 17 | """ 18 | def search(root): 19 | l, r = 0, 0 20 | if root.left: l = search(root.left) 21 | if root.right: r = search(root.right) 22 | 23 | if root.left and root.left.val != root.val: l = 0 24 | if root.right and root.right.val != root.val: r = 0 25 | nonlocal longest_path 26 | longest_path = max(longest_path, l + r) 27 | return max(l, r) + 1 28 | 29 | longest_path = 0 30 | if root: search(root) 31 | return longest_path 32 | -------------------------------------------------------------------------------- /Python/number-of-islands.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-islands/ 2 | 3 | 4 | class Solution(object): 5 | def numIslands(self, grid): 6 | """ 7 | :type grid: List[List[str]] 8 | :rtype: int 9 | """ 10 | def search(row, col): 11 | grid[row][col] = '0' 12 | 13 | for nr, nc in neighbors(row, col): 14 | if grid[nr][nc] == '1': 15 | search(nr, nc) 16 | 17 | def neighbors(row, col): 18 | if row > 0: yield row - 1, col 19 | if row < len(grid) - 1: yield row + 1, col 20 | if col > 0: yield row, col - 1 21 | if col < len(grid[0]) - 1: yield row, col + 1 22 | 23 | num_islands = 0 24 | for row in range(len(grid)): 25 | for col in range(len(grid[0])): 26 | if grid[row][col] == '1': 27 | num_islands += 1 28 | search(row, col) 29 | return num_islands 30 | -------------------------------------------------------------------------------- /Python/k-similar-strings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/k-similar-strings/ 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | class Solution(object): 8 | def kSimilarity(self, A, B): 9 | """ 10 | :type A: str 11 | :type B: str 12 | :rtype: int 13 | """ 14 | def neighbors(S): 15 | for i, c in enumerate(S): 16 | if c != B[i]: break 17 | 18 | T = list(S) 19 | for j in range(i + 1, len(S)): 20 | if S[j] == B[i]: 21 | T[i], T[j] = T[j], T[i] 22 | yield ''.join(T) 23 | T[i], T[j] = T[j], T[i] 24 | 25 | queue = deque([A]) 26 | seen = {A: 0} 27 | while queue: 28 | S = queue.popleft() 29 | if S == B: return seen[S] 30 | for T in neighbors(S): 31 | if T not in seen: 32 | seen[T] = seen[S] + 1 33 | queue.append(T) 34 | -------------------------------------------------------------------------------- /Python/path-sum-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/path-sum-ii 2 | 3 | 4 | # Definition for a binary tree node. 5 | class TreeNode: 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | class Solution: 12 | def pathSum(self, root, sum): 13 | """ 14 | :type root: TreeNode 15 | :type sum: int 16 | :rtype: List[List[int]] 17 | """ 18 | if not root: 19 | return [] 20 | 21 | if not root.left and not root.right: 22 | if sum == root.val: 23 | return [[root.val]] 24 | return [] 25 | 26 | ret = [] 27 | if root.left: 28 | for path in self.pathSum(root.left, sum - root.val): 29 | ret.append([root.val] + path) 30 | 31 | if root.right: 32 | for path in self.pathSum(root.right, sum - root.val): 33 | ret.append([root.val] + path) 34 | 35 | return ret 36 | -------------------------------------------------------------------------------- /Python/logger-rate-limiter.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/logger-rate-limiter/ 2 | 3 | 4 | class Logger: 5 | 6 | def __init__(self): 7 | """ 8 | Initialize your data structure here. 9 | """ 10 | self.history = {} 11 | 12 | def shouldPrintMessage(self, timestamp, message): 13 | """ 14 | Returns true if the message should be printed in the given timestamp, otherwise returns false. 15 | If this method returns false, the message will not be printed. 16 | The timestamp is in seconds granularity. 17 | :type timestamp: int 18 | :type message: str 19 | :rtype: bool 20 | """ 21 | if message not in self.history or timestamp - self.history[message] >= 10: 22 | self.history[message] = timestamp 23 | return True 24 | return False 25 | 26 | # Your Logger object will be instantiated and called as such: 27 | # obj = Logger() 28 | # param_1 = obj.shouldPrintMessage(timestamp,message) 29 | -------------------------------------------------------------------------------- /Python/3sum-closest.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/3sum-closest 2 | 3 | 4 | class Solution: 5 | def threeSumClosest(self, nums, target): 6 | """ 7 | :type nums: List[int] 8 | :type target: int 9 | :rtype: int 10 | """ 11 | nums.sort() 12 | best = float('inf') 13 | 14 | for i in range(len(nums) - 2): 15 | v = self.twoSumClosest(nums, target, nums[i], i + 1) 16 | if abs(v - target) < abs(best - target): 17 | best = v 18 | return best 19 | 20 | def twoSumClosest(self, nums, target, other_num, start_index): 21 | i, j = start_index, len(nums) - 1 22 | best = float('inf') 23 | 24 | while i < j: 25 | v = nums[i] + nums[j] + other_num 26 | if abs(v - target) < abs(best - target): 27 | best = v 28 | 29 | if v < target: 30 | i += 1 31 | else: 32 | j -= 1 33 | 34 | return best 35 | -------------------------------------------------------------------------------- /Python/combination-sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/combination-sum/ 2 | 3 | 4 | class Solution(object): 5 | def combination_helper(self, candidates, target, index, comb, ans): 6 | if target == 0: 7 | ans.append(comb[:]) 8 | return 9 | 10 | if index >= len(candidates): 11 | return 12 | 13 | self.combination_helper(candidates, target, index + 1, comb, ans) 14 | if candidates[index] <= target: 15 | comb.append(candidates[index]) 16 | self.combination_helper(candidates, target - candidates[index], index, comb, ans) 17 | comb.pop() 18 | 19 | def combinationSum(self, candidates, target): 20 | """ 21 | :type candidates: List[int] 22 | :type target: int 23 | :rtype: List[List[int]] 24 | """ 25 | candidates = list(sorted(candidates, reverse=True)) 26 | ans = [] 27 | self.combination_helper(candidates, target, 0, [], ans) 28 | return ans 29 | -------------------------------------------------------------------------------- /Python/flood-fill.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/flood-fill/ 2 | 3 | 4 | class Solution: 5 | def floodFill(self, image, sr, sc, newColor): 6 | """ 7 | :type image: List[List[int]] 8 | :type sr: int 9 | :type sc: int 10 | :type newColor: int 11 | :rtype: List[List[int]] 12 | """ 13 | def fill(row, col, color): 14 | image[row][col] = newColor 15 | 16 | for nr, nc in neighbors(row, col): 17 | if image[nr][nc] == color: 18 | fill(nr, nc, color) 19 | 20 | def neighbors(row, col): 21 | if row > 0: yield row - 1, col 22 | if row < len(image) - 1: yield row + 1, col 23 | if col > 0: yield row, col - 1 24 | if col < len(image[0]) - 1: yield row, col + 1 25 | 26 | if image[sr][sc] == newColor: return image 27 | fill(sr, sc, image[sr][sc]) 28 | return image 29 | 30 | 31 | print(Solution().floodFill([[0,0,0],[0,1,1]],1,1,1)) 32 | -------------------------------------------------------------------------------- /Python/max-area-of-island.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/max-area-of-island/ 2 | 3 | 4 | class Solution: 5 | def maxAreaOfIsland(self, grid): 6 | """ 7 | :type grid: List[List[int]] 8 | :rtype: int 9 | """ 10 | def search(row, col): 11 | grid[row][col] = 0 12 | area = 1 13 | for nr, nc in neighbors(row, col): 14 | if grid[nr][nc] == 1: 15 | area += search(nr, nc) 16 | return area 17 | 18 | def neighbors(row, col): 19 | if row > 0: yield row - 1, col 20 | if row < len(grid) - 1: yield row + 1, col 21 | if col > 0: yield row, col - 1 22 | if col < len(grid[0]) - 1: yield row, col + 1 23 | 24 | max_area = 0 25 | for row in range(len(grid)): 26 | for col in range(len(grid[0])): 27 | if grid[row][col] == 1: 28 | max_area = max(max_area, search(row, col)) 29 | return max_area 30 | -------------------------------------------------------------------------------- /Python/min-stack.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/min-stack/ 2 | 3 | 4 | class MinStack: 5 | 6 | def __init__(self): 7 | """ 8 | initialize your data structure here. 9 | """ 10 | self.stack = [] 11 | 12 | def push(self, x): 13 | """ 14 | :type x: int 15 | :rtype: void 16 | """ 17 | m = x if not self.stack else min(self.stack[-1][0], x) 18 | self.stack.append((m, x)) 19 | 20 | def pop(self): 21 | """ 22 | :rtype: void 23 | """ 24 | return self.stack.pop()[1] 25 | 26 | def top(self): 27 | """ 28 | :rtype: int 29 | """ 30 | return self.stack[-1][1] 31 | 32 | def getMin(self): 33 | """ 34 | :rtype: int 35 | """ 36 | return self.stack[-1][0] 37 | 38 | # Your MinStack object will be instantiated and called as such: 39 | # obj = MinStack() 40 | # obj.push(x) 41 | # obj.pop() 42 | # param_3 = obj.top() 43 | # param_4 = obj.getMin() 44 | -------------------------------------------------------------------------------- /Python/find-median-from-data-stream.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-median-from-data-stream/ 2 | 3 | 4 | from heapq import * 5 | 6 | 7 | class MedianFinder(object): 8 | 9 | def __init__(self): 10 | """ 11 | initialize your data structure here. 12 | """ 13 | self.heap_left = [] 14 | self.heap_right = [] 15 | 16 | def addNum(self, num): 17 | """ 18 | :type num: int 19 | :rtype: void 20 | """ 21 | heappush(self.heap_left, -num) 22 | heappush(self.heap_right, -heappop(self.heap_left)) 23 | 24 | if len(self.heap_left) < len(self.heap_right): 25 | heappush(self.heap_left, -heappop(self.heap_right)) 26 | 27 | def findMedian(self): 28 | """ 29 | :rtype: float 30 | """ 31 | if not self.heap_left and not self.heap_right: return 0 32 | if len(self.heap_left) > len(self.heap_right): return -self.heap_left[0] 33 | return (-self.heap_left[0] + self.heap_right[0]) / 2 34 | 35 | -------------------------------------------------------------------------------- /Python/combination-sum-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/combination-sum-ii/ 2 | 3 | 4 | class Solution(object): 5 | def combination_helper(self, candidates, target, index, comb, ans): 6 | if target == 0: 7 | ans.append(comb[:]) 8 | return 9 | 10 | if index >= len(candidates) or target < 0: 11 | return 12 | 13 | for i in range(index, len(candidates)): 14 | if i > index and candidates[i] == candidates[i - 1]: 15 | continue 16 | 17 | comb.append(candidates[i]) 18 | self.combination_helper(candidates, target - candidates[i], i + 1, comb, ans) 19 | comb.pop() 20 | 21 | def combinationSum2(self, candidates, target): 22 | """ 23 | :type candidates: List[int] 24 | :type target: int 25 | :rtype: List[List[int]] 26 | """ 27 | candidates = list(sorted(candidates, reverse=True)) 28 | ans = [] 29 | self.combination_helper(candidates, target, 0, [], ans) 30 | return ans 31 | -------------------------------------------------------------------------------- /Python/employee-importance.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/employee-importance/ 2 | 3 | 4 | """ 5 | # Employee info 6 | class Employee(object): 7 | def __init__(self, id, importance, subordinates): 8 | # It's the unique id of each node. 9 | # unique id of this employee 10 | self.id = id 11 | # the importance value of this employee 12 | self.importance = importance 13 | # the id of direct subordinates 14 | self.subordinates = subordinates 15 | """ 16 | 17 | 18 | class Solution(object): 19 | def getImportance(self, employees, id): 20 | """ 21 | :type employees: Employee 22 | :type id: int 23 | :rtype: int 24 | """ 25 | def calc_importance(employee): 26 | importance = employee.importance 27 | for sid in employee.subordinates: 28 | importance += calc_importance(employees[sid]) 29 | return importance 30 | 31 | employees = {e.id: e for e in employees} 32 | return calc_importance(employees[id]) 33 | -------------------------------------------------------------------------------- /Python/n-queens-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/n-queens-ii/ 2 | 3 | 4 | class Solution(object): 5 | def valid_pieces(self, n, pieces, current_piece): 6 | for i in range(n): 7 | if i == current_piece or pieces[i] == -1: continue 8 | if pieces[i] == pieces[current_piece]: return False 9 | if abs(i - current_piece) == abs(pieces[i] - pieces[current_piece]): return False 10 | 11 | return True 12 | 13 | def nqueens_helper(self, n, pieces, current_piece): 14 | if current_piece == n: 15 | return 1 16 | 17 | sols = 0 18 | for i in range(n): 19 | pieces[current_piece] = i 20 | if self.valid_pieces(n, pieces, current_piece): 21 | sols += self.nqueens_helper(n, pieces, current_piece + 1) 22 | pieces[current_piece] = -1 23 | return sols 24 | 25 | def totalNQueens(self, n): 26 | """ 27 | :type n: int 28 | :rtype: int 29 | """ 30 | return self.nqueens_helper(n, [-1] * n, 0) 31 | -------------------------------------------------------------------------------- /Python/path-sum-iii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/path-sum-iii/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution(object): 12 | def pathSum(self, root, sum): 13 | """ 14 | :type root: TreeNode 15 | :type sum: int 16 | :rtype: int 17 | """ 18 | def search(root, sums): 19 | if not root: return 20 | 21 | sums.append(0) 22 | for i in range(len(sums)): 23 | sums[i] += root.val 24 | if sums[i] == sum: 25 | nonlocal total_sums 26 | total_sums += 1 27 | 28 | search(root.left, sums) 29 | search(root.right, sums) 30 | 31 | for i in range(len(sums)): 32 | sums[i] -= root.val 33 | sums.pop() 34 | 35 | total_sums = 0 36 | search(root, []) 37 | return total_sums 38 | -------------------------------------------------------------------------------- /Python/count-univalue-subtrees.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/count-univalue-subtrees/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def countUnivalSubtrees(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | def search(root): 18 | lu, lv = True, root.val 19 | ru, rv = True, root.val 20 | if root.left: lu, lv = search(root.left) 21 | if root.right: ru, rv = search(root.right) 22 | if not lu: return False, root.val 23 | if not ru: return False, root.val 24 | if not (lv == rv == root.val): return False, root.val 25 | 26 | nonlocal univalue_subtrees 27 | univalue_subtrees += 1 28 | return True, root.val 29 | 30 | univalue_subtrees = 0 31 | if root: search(root) 32 | return univalue_subtrees 33 | -------------------------------------------------------------------------------- /Python/3sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/3sum 2 | 3 | 4 | class Solution: 5 | def threeSum(self, nums): 6 | if len(nums) < 3: 7 | return [] 8 | 9 | out = set() 10 | nums = sorted(nums) 11 | i = 0 12 | while i < len(nums) - 2: 13 | while i < len(nums) - 2 and nums[i] == nums[i + 1] and nums[i + 1] == nums[i + 2]: 14 | if nums[i] == 0 and nums[i + 1] == 0 and nums[i + 2] == 0: 15 | out.add((0, 0, 0)) 16 | i += 1 17 | out.update(self.twoSum(nums, i + 1, nums[i])) 18 | i += 1 19 | return [list(i) for i in out] 20 | 21 | def twoSum(self, nums, ind, v): 22 | out = set() 23 | l, r = ind, len(nums) - 1 24 | 25 | while l < r: 26 | if v + nums[l] + nums[r] == 0: 27 | out.add((v, nums[l], nums[r])) 28 | l += 1 29 | r -= 1 30 | elif v + nums[l] + nums[r] < 0: 31 | l += 1 32 | else: 33 | r -= 1 34 | 35 | return out 36 | -------------------------------------------------------------------------------- /Python/balanced-binary-tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/balanced-binary-tree 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Solution: 12 | def isBalanced(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: bool 16 | """ 17 | return self.is_balanced_helper(root)[0] 18 | 19 | def is_balanced_helper(self, root): 20 | if not root: 21 | return True, 0 22 | 23 | left_balanced, left_depth = self.is_balanced_helper(root.left) 24 | 25 | if not left_balanced: 26 | return False, left_depth + 1 27 | 28 | right_balanced, right_depth = self.is_balanced_helper(root.right) 29 | 30 | if not right_balanced: 31 | return False, right_depth + 1 32 | 33 | if abs(left_depth - right_depth) > 1: 34 | return False, max(left_depth, right_depth) + 1 35 | 36 | return True, max(left_depth, right_depth) + 1 37 | -------------------------------------------------------------------------------- /Python/length-of-longest-fibonacci-subsequence.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/ 2 | 3 | 4 | class Solution(object): 5 | def lenLongestFibSubseq(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: int 9 | """ 10 | def search_fibonacci(a, b): 11 | if (a + b) in subsequences: 12 | return subsequences[a, b] 13 | 14 | if a + b in numset: 15 | subsequences[a, b] = search_fibonacci(b, a + b) + 1 16 | return subsequences[a, b] 17 | 18 | return 0 19 | 20 | subsequences = {} 21 | numset = set(A) 22 | 23 | largest_subsequence = 0 24 | for i in range(len(A)): 25 | for j in range(i + 1, len(A)): 26 | if (A[i], A[j]) in subsequences: continue 27 | if (A[i] + A[j]) in numset: 28 | largest_subsequence = max(largest_subsequence, search_fibonacci(A[i], A[j]) + 2) 29 | 30 | return largest_subsequence 31 | 32 | 33 | print(Solution().lenLongestFibSubseq([1,2,3,4,5,6,7,8])) 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Jared Gillespie 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Python/merge-intervals.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/merge-intervals/ 2 | 3 | 4 | # Definition for an interval. 5 | # class Interval: 6 | # def __init__(self, s=0, e=0): 7 | # self.start = s 8 | # self.end = e 9 | 10 | class Solution: 11 | def merge(self, intervals): 12 | """ 13 | :type intervals: List[Interval] 14 | :rtype: List[Interval] 15 | """ 16 | if not intervals: return intervals 17 | 18 | intervals.sort(key=lambda x: (x.start, x.end)) 19 | merged_intervals = [] 20 | prev_interval = None 21 | 22 | for interval in intervals: 23 | if prev_interval is None: 24 | prev_interval = interval 25 | elif prev_interval.start <= interval.end and interval.start <= prev_interval.end: 26 | prev_interval = Interval(min(prev_interval.start, interval.start), max(prev_interval.end, interval.end)) 27 | else: 28 | merged_intervals.append(prev_interval) 29 | prev_interval = interval 30 | 31 | merged_intervals.append(prev_interval) 32 | return merged_intervals 33 | -------------------------------------------------------------------------------- /Python/strobogrammatic-number-ii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/strobogrammatic-number-ii/ 2 | 3 | 4 | class Solution: 5 | def findStrobogrammatic(self, n): 6 | """ 7 | :type n: int 8 | :rtype: List[str] 9 | """ 10 | def search(index): 11 | if n % 2 == 0 and index == n // 2: 12 | numbers.append(''.join(number)) 13 | elif n % 2 == 1 and index == n // 2: 14 | for i in range(len(nums_middle)): 15 | number[index] = str(nums_middle[i]) 16 | numbers.append(''.join(number)) 17 | else: 18 | for i in range(len(nums_left)): 19 | if index == 0 and nums_left[i] == '0': continue 20 | number[index] = str(nums_left[i]) 21 | number[n - index - 1] = str(nums_right[i]) 22 | search(index + 1) 23 | 24 | nums_middle = ['0', '1', '8'] 25 | nums_left = ['0', '1', '8', '6', '9'] 26 | nums_right = ['0', '1', '8', '9', '6'] 27 | numbers = [] 28 | number = ['0'] * n 29 | search(0) 30 | return numbers 31 | -------------------------------------------------------------------------------- /Python/binary-search-tree-iterator.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-search-tree-iterator/ 2 | 3 | 4 | # Definition for a binary tree node 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | # 11 | # def __repr__(self): 12 | # return str(self.val) 13 | 14 | 15 | class BSTIterator(object): 16 | def __init__(self, root): 17 | """ 18 | :type root: TreeNode 19 | """ 20 | self.path = [] 21 | while root: 22 | self.path.append(root) 23 | root = root.left 24 | 25 | def hasNext(self): 26 | """ 27 | :rtype: bool 28 | """ 29 | return len(self.path) > 0 30 | 31 | def next(self): 32 | """ 33 | :rtype: int 34 | """ 35 | ret = self.path.pop() 36 | node = ret.right 37 | while node: 38 | self.path.append(node) 39 | node = node.left 40 | 41 | return ret.val 42 | 43 | # Your BSTIterator will be called like this: 44 | # i, v = BSTIterator(root), [] 45 | # while i.hasNext(): v.append(i.next()) 46 | -------------------------------------------------------------------------------- /Python/set-matrix-zeroes.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/set-matrix-zeroe 2 | 3 | 4 | class Solution: 5 | def setZeroes(self, matrix): 6 | n = len(matrix) 7 | if n == 0: 8 | return matrix 9 | 10 | m = len(matrix[0]) 11 | if m == 0: 12 | return matrix 13 | 14 | upper_left_is_zero = matrix[0][0] == 0 15 | row_zero_is_zero = any(True for i in range(m) if matrix[0][i] == 0) 16 | col_zero_is_zero = any(True for i in range(n) if matrix[i][0] == 0) 17 | 18 | for i in range(1, n): 19 | for j in range(1, m): 20 | if matrix[i][j] == 0: 21 | matrix[i][0] = 0 22 | matrix[0][j] = 0 23 | 24 | for i in range(1, n): 25 | for j in range(1, m): 26 | if matrix[i][0] == 0 or matrix[0][j] == 0: 27 | matrix[i][j] = 0 28 | 29 | if row_zero_is_zero or upper_left_is_zero: 30 | for i in range(m): 31 | matrix[0][i] = 0 32 | 33 | if col_zero_is_zero or upper_left_is_zero: 34 | for i in range(n): 35 | matrix[i][0] = 0 36 | 37 | -------------------------------------------------------------------------------- /Python/string-compression.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/string-compression/ 2 | 3 | 4 | class Solution: 5 | def compress(self, chars): 6 | """ 7 | :type chars: List[str] 8 | :rtype: int 9 | """ 10 | size = 0 11 | prev_char = '' 12 | pos = 0 13 | num_chars = 1 14 | for i, c in enumerate(chars): 15 | if prev_char == '': 16 | prev_char = c 17 | elif prev_char == c: 18 | num_chars += 1 19 | else: 20 | s = str(num_chars) 21 | size += len(s) 22 | chars[pos] = prev_char 23 | if num_chars > 1: 24 | size += 1 25 | chars[pos + 1:pos + 1 + len(s)] = s 26 | 27 | num_chars = 1 28 | prev_char = c 29 | pos = size 30 | 31 | if prev_char != '': 32 | chars[pos] = prev_char 33 | s = str(num_chars) 34 | size += len(s) 35 | if num_chars > 1: 36 | size += 1 37 | chars[pos + 1: pos + 1 + len(s)] = s 38 | 39 | return size 40 | -------------------------------------------------------------------------------- /Python/find-all-anagrams-in-a-string.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-all-anagrams-in-a-string/ 2 | 3 | 4 | from collections import Counter 5 | 6 | 7 | class Solution: 8 | def findAnagrams(self, s, p): 9 | """ 10 | :type s: str 11 | :type p: str 12 | :rtype: List[int] 13 | """ 14 | freq = Counter(p) 15 | remaining_to_match = set(p) 16 | matching_chars = set(p) 17 | anagram_pos = [] 18 | 19 | l, r = 0, 0 20 | 21 | while r < len(s): 22 | c = s[r] 23 | freq[c] -= 1 24 | if remaining_to_match and c in remaining_to_match and freq[c] == 0: 25 | remaining_to_match.remove(c) 26 | 27 | while not remaining_to_match and l < r and (s[l] not in matching_chars or freq[s[l]] < 0): 28 | freq[s[l]] += 1 29 | l += 1 30 | 31 | if not remaining_to_match and r - l + 1== len(p): 32 | anagram_pos.append(l) 33 | 34 | r += 1 35 | 36 | if not remaining_to_match and len(remaining_to_match) == len(p): 37 | anagram_pos.append(l) 38 | 39 | return anagram_pos 40 | -------------------------------------------------------------------------------- /Python/snakes-and-ladders.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/snakes-and-ladders 2 | 3 | from collections import deque 4 | 5 | 6 | class Solution: 7 | def snakesAndLadders(self, board): 8 | """ 9 | :type board: List[List[int]] 10 | :rtype: int 11 | """ 12 | N = len(board) 13 | N2 = N*N 14 | 15 | queue = deque([1]) 16 | visited = {1: 0} 17 | 18 | while queue: 19 | pos = queue.popleft() 20 | if pos == N2: 21 | return visited[pos] 22 | 23 | for other in range(pos + 1, min(pos + 6, N2) + 1): 24 | r, c = self.get_board_position(N, other) 25 | 26 | if board[r][c] != -1: 27 | other = board[r][c] 28 | 29 | if other not in visited: 30 | visited[other] = visited[pos] + 1 31 | queue.append(other) 32 | 33 | return -1 34 | 35 | def get_board_position(self, N, p): 36 | row = N - 1 - (p - 1) // N 37 | if row % 2 == N % 2: 38 | col = N - 1 - (p - 1) % N 39 | else: 40 | col = (p - 1) % N 41 | return row, col 42 | -------------------------------------------------------------------------------- /Python/heaters.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/heaters/ 2 | 3 | 4 | class Solution: 5 | def findRadius(self, houses, heaters): 6 | """ 7 | :type houses: List[int] 8 | :type heaters: List[int] 9 | :rtype: int 10 | """ 11 | left = [0] * len(houses) 12 | right = [0] * len(houses) 13 | 14 | houses.sort() 15 | heaters.sort() 16 | closest_heater = -float('inf') 17 | j = 0 18 | for i in range(len(houses)): 19 | while j < len(heaters) and heaters[j] <= houses[i]: 20 | closest_heater = heaters[j] 21 | j += 1 22 | left[i] = closest_heater 23 | 24 | closest_heater = float('inf') 25 | j = len(heaters) - 1 26 | for i in range(len(houses) - 1, -1, -1): 27 | while j > -1 and heaters[j] >= houses[i]: 28 | closest_heater = heaters[j] 29 | j -= 1 30 | right[i] = closest_heater 31 | 32 | warm_radius = 0 33 | for i in range(len(houses)): 34 | warm_radius = max(warm_radius, min(houses[i] - left[i], right[i] - houses[i])) 35 | 36 | return warm_radius 37 | -------------------------------------------------------------------------------- /Python/unique-word-abbreviation.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/unique-word-abbreviation/ 2 | 3 | 4 | class ValidWordAbbr: 5 | 6 | def __init__(self, dictionary): 7 | """ 8 | :type dictionary: List[str] 9 | """ 10 | self.abbrevs = {} 11 | for word in dictionary: 12 | if len(word) == 0: continue 13 | abbrev = word[0] + str(len(word) - 2) + word[-1] 14 | if abbrev not in self.abbrevs: self.abbrevs[abbrev] = set() 15 | self.abbrevs[abbrev].add(word) 16 | 17 | def isUnique(self, word): 18 | """ 19 | :type word: str 20 | :rtype: bool 21 | """ 22 | if word == '': return True 23 | abbrev = word[0] + str(len(word) - 2) + word[-1] 24 | if abbrev not in self.abbrevs: return True 25 | if len(self.abbrevs[abbrev]) > 1: return False 26 | if word not in self.abbrevs[abbrev]: return False 27 | return True 28 | 29 | 30 | vwa = ValidWordAbbr(['hello']) 31 | print(vwa.isUnique('hello')) 32 | 33 | # Your ValidWordAbbr object will be instantiated and called as such: 34 | # obj = ValidWordAbbr(dictionary) 35 | # param_1 = obj.isUnique(word) 36 | -------------------------------------------------------------------------------- /Python/range-sum-query-mutable.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/range-sum-query-mutable/ 2 | 3 | 4 | class NumArray: 5 | 6 | def __init__(self, nums): 7 | """ 8 | :type nums: List[int] 9 | """ 10 | self.arr = [0] * len(nums) 11 | self.BIT = [0] * (len(nums) + 1) 12 | for i, n in enumerate(nums): self.update(i, n) 13 | 14 | def update(self, i, val): 15 | """ 16 | :type i: int 17 | :type val: int 18 | :rtype: void 19 | """ 20 | diff, self.arr[i] = val - self.arr[i], val 21 | i += 1 22 | while i < len(self.BIT): 23 | self.BIT[i] += diff 24 | i += i & -i 25 | 26 | def sum(self, k): 27 | res = 0 28 | while k: 29 | res += self.BIT[k] 30 | k -= k & -k 31 | return res 32 | 33 | def sumRange(self, i, j): 34 | """ 35 | :type i: int 36 | :type j: int 37 | :rtype: int 38 | """ 39 | return self.sum(j + 1) - self.sum(i) 40 | 41 | # Your NumArray object will be instantiated and called as such: 42 | # obj = NumArray(nums) 43 | # obj.update(i,val) 44 | # param_2 = obj.sumRange(i,j) 45 | -------------------------------------------------------------------------------- /Python/surface-area-of-3d-shapes.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/surface-area-of-3d-shapes/ 2 | 3 | 4 | class Solution: 5 | def surfaceArea(self, grid): 6 | """ 7 | :type grid: List[List[int]] 8 | :rtype: int 9 | """ 10 | surface_area = 0 11 | for row in range(len(grid)): 12 | for col in range(len(grid[0])): 13 | if grid[row][col] == 0: continue 14 | surface_area += 2 15 | if row == 0: surface_area += grid[row][col] 16 | elif grid[row][col] > grid[row - 1][col]: surface_area += grid[row][col] - grid[row - 1][col] 17 | if row == len(grid) - 1: surface_area += grid[row][col] 18 | elif grid[row][col] > grid[row + 1][col]: surface_area += grid[row][col] - grid[row + 1][col] 19 | if col == 0: surface_area += grid[row][col] 20 | elif grid[row][col] > grid[row][col - 1]: surface_area += grid[row][col] - grid[row][col - 1] 21 | if col == len(grid[row]) - 1: surface_area += grid[row][col] 22 | elif grid[row][col] > grid[row][col + 1]: surface_area += grid[row][col] - grid[row][col + 1] 23 | 24 | return surface_area 25 | -------------------------------------------------------------------------------- /Python/add-two-numbers.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/add-two-numbers 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution: 11 | def addTwoNumbers(self, l1, l2): 12 | """ 13 | :type l1: ListNode 14 | :type l2: ListNode 15 | :rtype: ListNode 16 | """ 17 | n1 = self.get_num(l1) 18 | n2 = self.get_num(l2) 19 | return self.create_num(n1 + n2) 20 | 21 | def get_num(self, node): 22 | n = 0 23 | p = 1 24 | while node: 25 | n += node.val * p 26 | p *= 10 27 | node = node.next 28 | return n 29 | 30 | def create_num(self, num): 31 | if num == 0: 32 | return ListNode(0) 33 | 34 | head = None 35 | current = None 36 | while num > 0: 37 | num, r = divmod(num, 10) 38 | node = ListNode(r) 39 | if head is None: 40 | head = node 41 | current = node 42 | else: 43 | current.next = node 44 | current = node 45 | return head 46 | -------------------------------------------------------------------------------- /Python/max-consecutive-ones-iii.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/contest/problems/max-consecutive-ones-iii/ 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | class Solution(object): 8 | def longestOnes(self, A, K): 9 | """ 10 | :type A: List[int] 11 | :type K: int 12 | :rtype: int 13 | """ 14 | C = [0] * len(A) 15 | for i in range(len(A) - 1): 16 | if A[i] == 1: 17 | C[i + 1] = C[i] + A[i] 18 | 19 | longest = 0 20 | curlength = 0 21 | k = 0 22 | placed = deque() 23 | for i in range(len(A)): 24 | if A[i] == 0: 25 | if K == 0: 26 | curlength = 0 27 | elif k < K: 28 | curlength += 1 29 | k += 1 30 | placed.append(i) 31 | longest = max(curlength, longest) 32 | else: 33 | curlength -= C[placed.popleft()] 34 | placed.append(i) 35 | longest = max(curlength, longest) 36 | else: 37 | curlength += 1 38 | longest = max(curlength, longest) 39 | 40 | return longest 41 | -------------------------------------------------------------------------------- /Python/copy-list-with-random-pointer.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/copy-list-with-random-pointer/ 2 | 3 | 4 | # Definition for singly-linked list with a random pointer. 5 | # class RandomListNode(object): 6 | # def __init__(self, x): 7 | # self.label = x 8 | # self.next = None 9 | # self.random = None 10 | 11 | class Solution(object): 12 | def copyRandomList(self, head): 13 | """ 14 | :type head: RandomListNode 15 | :rtype: RandomListNode 16 | """ 17 | def get_cloned_node(node): 18 | if not node: return None 19 | if node in visited: return visited[node] 20 | else: 21 | visited[node] = RandomListNode(node.label) 22 | return visited[node] 23 | 24 | if not head: return None 25 | visited = {} 26 | 27 | new_head = new_node = get_cloned_node(head) 28 | new_head.random = get_cloned_node(head.random) 29 | node = head 30 | 31 | while node: 32 | new_node.next = get_cloned_node(node.next) 33 | new_node.random = get_cloned_node(node.random) 34 | new_node = new_node.next 35 | node = node.next 36 | 37 | return new_head 38 | -------------------------------------------------------------------------------- /Python/design-hit-counter.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/design-hit-counter/ 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | class HitCounter: 8 | 9 | def __init__(self): 10 | """ 11 | Initialize your data structure here. 12 | """ 13 | self.hits = deque() 14 | 15 | def hit(self, timestamp): 16 | """ 17 | Record a hit. 18 | @param timestamp - The current timestamp (in seconds granularity). 19 | :type timestamp: int 20 | :rtype: void 21 | """ 22 | while self.hits and timestamp - self.hits[0] >= 300: 23 | self.hits.popleft() 24 | self.hits.append(timestamp) 25 | 26 | def getHits(self, timestamp): 27 | """ 28 | Return the number of hits in the past 5 minutes. 29 | @param timestamp - The current timestamp (in seconds granularity). 30 | :type timestamp: int 31 | :rtype: int 32 | """ 33 | while self.hits and timestamp - self.hits[0] >= 300: 34 | self.hits.popleft() 35 | return len(self.hits) 36 | 37 | # Your HitCounter object will be instantiated and called as such: 38 | # obj = HitCounter() 39 | # obj.hit(timestamp) 40 | # param_2 = obj.getHits(timestamp) 41 | -------------------------------------------------------------------------------- /Python/number-of-distinct-islands.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-distinct-islands/ 2 | 3 | 4 | class Solution(object): 5 | def numDistinctIslands(self, grid): 6 | """ 7 | :type grid: List[List[int]] 8 | :rtype: int 9 | """ 10 | def neighbors(row, col): 11 | if row > 0: yield row - 1, col 12 | if row < rows - 1: yield row + 1, col 13 | if col > 0: yield row, col - 1 14 | if col < cols - 1: yield row, col + 1 15 | 16 | def search(start_row, start_col, row, col, island): 17 | grid[row][col] = 0 18 | island.append(str(row * cols + col - (start_row * cols + start_col))) 19 | 20 | for nr, nc in neighbors(row, col): 21 | if grid[nr][nc] == 1: 22 | search(start_row, start_col, nr, nc, island) 23 | 24 | islands = set() 25 | rows, cols = len(grid), len(grid[0]) 26 | for row in range(rows): 27 | for col in range(cols): 28 | if grid[row][col] == 1: 29 | island = [] 30 | search(row, col, row, col, island) 31 | islands.add('|'.join(island)) 32 | 33 | return len(islands) 34 | --------------------------------------------------------------------------------