├── .gitignore ├── README.md ├── leetcode ├── Array │ ├── 3sum.py │ ├── array-Partition-I.py │ ├── available-captures-for-rook.py │ ├── candy-crush.py │ ├── container-with-most-water.py │ ├── contains-duplicate-ii.py │ ├── degree-of-an-array.py │ ├── fibonacci-number.py │ ├── find-all-duplicates-in-an-array.py │ ├── find-n-unique-integers-sum-up-to-zero.py │ ├── find-numbers-with-even-number-of-digits.py │ ├── flipping-an-image.py │ ├── game-of-life.py │ ├── high-five.py │ ├── image-smoother.py │ ├── is-subsequence.py │ ├── jump-game-ii.py │ ├── jump-game.py │ ├── largest-number-at-least-twice-of-others.py │ ├── longest-continuous-increasing-subsequence.py │ ├── longest-line-of-consecutive-one-in-matrix.py │ ├── majority-element.py │ ├── max-consecutive-ones.py │ ├── median-of-two-sorted-arrays.py │ ├── merge-intervals.py │ ├── merge-sorted-array.py │ ├── missing-number.py │ ├── missing-ranges.py │ ├── move-zeroes.py │ ├── pascals-triangle-ii.py │ ├── pascals-triangle.py │ ├── plus-one.py │ ├── product-of-array-except-self.py │ ├── queens-that-can-attack-the-king.py │ ├── range-addition.py │ ├── remove-element.py │ ├── replace-elements-with-greatest-element-on-right-side.py │ ├── reshape-the-matrix.py │ ├── reveal-cards-in-increasing-order.py │ ├── rotate-array.py │ ├── search-in-rotated-array.py │ ├── shuffle-an-array.py │ ├── sort-array-by-parity.py │ ├── subarray-sum-equals-k-NEW.py │ ├── subarray-sum-equals-k.py │ ├── sum-of-digits-in-the-minimum-number.py │ ├── sum-of-even-numbers-after-queries.py │ ├── teemo-attacking.py │ ├── toeplitz-matrix.py │ ├── transpose-matrix.py │ ├── two-sum-ii-input-array-is-sorted.py │ ├── two-sum.py │ ├── valid-mountain-array.py │ ├── valid-triangle-number.py │ └── wiggle-sort.py ├── Backtracking │ ├── beautiful-arrangement.py │ ├── binary-watch.py │ ├── elimination-game.py │ ├── flip-game-ii.py │ ├── letter-tile-possibilities.py │ └── palindrome-partitioning.py ├── Binary Search │ ├── capacity-to-ship-packages-within-d-days.py │ ├── find-first-and-last-position-of-element-in-sorted-array.py │ ├── find-smallest-letter-greater-than-target.py │ ├── peak-index-in-mountain-array.py │ └── search-a-2d-matrix.py ├── Bit-Manipulation │ ├── base-7.py │ ├── binary-number-with-alternating-bits.py │ ├── binary_complement.py │ ├── binary_points_of_difference.py │ ├── convert-a-number-to-hexadecimal.py │ ├── hamming-distance.py │ ├── maximum-product-of-word-lengths.py │ ├── number-of-1-bits.py │ ├── prime-number-of-set-bits-in-binary-representation.py │ ├── reverse-bits.py │ ├── single-number-ii.py │ ├── single-number-iii.py │ └── sum_of_binary_points_of_difference.py ├── Brainteaser │ ├── fizz-buzz.py │ └── nim-game.py ├── Breadth-first-Search │ └── shortest-distance-from-all-buildings.py ├── Database │ ├── activity-participants.sql │ ├── all-people-report-to-the-given-manager.sql │ ├── list-the-products-ordered-in-a-period.sql │ ├── movie-rating.sql │ ├── students-with-invalid-departments.sql │ └── trips-and-users.sql ├── Depth-first-Search │ ├── 24-game.py │ ├── clone-graph.py │ ├── keys-and-rooms.py │ ├── nested-list-weight-sum.py │ ├── sentence-similarity-ii.py │ ├── surrounded-regions.py │ └── validate-binary-search-tree.py ├── Design │ ├── all-oone-data-structure.py │ ├── design-circular-queue.py │ ├── design-tinyurl.py │ ├── insert-delete-getrandom-o1.py │ ├── lru-cache.py │ ├── min-stack.py │ └── moving-average-from-data-stream.py ├── Divide-And-Conquer │ └── merge-k-sorted-lists.py ├── Dynamic-Programming │ ├── best-time-to-buy-and-sell-stock-ii.py │ ├── best-time-to-buy-and-sell-stock.py │ ├── climbing-stairs.py │ ├── coin-change.py │ ├── count-numbers-with-unique-digits.py │ ├── countBits.py │ ├── house-robber-ii.py │ ├── house-robber-iii.py │ ├── house-robber.py │ ├── longest-palindromic-subsequence.py │ ├── longest-valid-parentheses.py │ ├── maximal-square.py │ ├── maximum-subarray.py │ ├── minimum-path-sum.py │ ├── number-of-corner-rectangles.py │ ├── sentence-screen-fitting.py │ ├── shortest-way.py │ ├── triangle.py │ ├── unique-paths-ii.py │ └── unique-paths.py ├── Greedy │ ├── boats-to-save-people.py │ ├── campus-bikes.py │ ├── lemonade-change.py │ ├── partition-labels.py │ ├── queue-reconstruction-by-height.py │ └── score-after-flipping-matrix.py ├── Hash-Table │ ├── SOLlengthOfLongestSubstring.py │ ├── bulls-and-cows.py │ ├── distribute-candies.py │ ├── find-anagram-mappings.py │ ├── find-common-characters.py │ ├── find-smallest-common-element-in-all-rows.py │ ├── find-the-difference.py │ ├── group-anagrams.py │ ├── happy-number.py │ ├── implement-magic-dictionary.py │ ├── intersection-of-three-sorted-arrays.py │ ├── island-perimeter.py │ ├── jewels-and-stones.py │ ├── keyboard-row.py │ ├── logger-rate-limiter.py │ ├── longest-harmonious-subsequence.py │ ├── longest-palindrome.py │ ├── longest-substring-without-repeating-characters.py │ ├── max-points-on-a-line.py │ ├── minimum-area-rectangle.py │ ├── minimum-index-sum-of-two-lists.py │ ├── most-frequent-subtree-sum.py │ ├── n-repeated-element-in-size-2n-array.py │ ├── palindrome-permutation.py │ ├── repeated-dna-sequences.py │ ├── sentence-similarity.py │ ├── single-number.py │ ├── sort-characters-by-frequency.py │ ├── top-k-frequent-elements.py │ ├── top-k-frequent-words.py │ ├── uncommon-words-from-two-sentences.py │ ├── unique-number-of-occurrences.py │ ├── unique-word-abbreviation.py │ ├── valid-sudoku.py │ └── verifying-an-alien-dictionary.py ├── Heap │ └── sliding-window-maximum.py ├── Linked-List │ ├── add-two-numbers-ii.py │ ├── add-two-numbers.py │ ├── delete-node-in-a-linked-list.py │ ├── design-linked-list.py │ ├── intersection-of-two-linked-lists.py │ ├── merge-two-sorted-lists.py │ ├── palindrome-linked-list.py │ ├── reorder-list.py │ ├── reverse-linked-list.py │ └── swap-nodes-in-pairs.py ├── Math │ ├── airplane-seat-assignment-probability.py │ ├── armstrong-number.py │ ├── binary-gap.py │ ├── complex_number_multiplication.py │ ├── count-primes.py │ ├── count-substrings-with-only-one-distinct-letter.py │ ├── excel-sheet-column-number.py │ ├── integer-to-english-words.py │ ├── integer-to-roman.py │ ├── largest-palindrome-product.py │ ├── minimum-moves-to-equal-array-elements-ii.py │ ├── multiply-strings.py │ ├── optimal-division.py │ ├── palindrome-number.py │ ├── perfect-number.py │ ├── prime-palindrome.py │ ├── projection-area-of-3d-shapes.py │ ├── range-addition-ii.py │ ├── reverse-integer.py │ ├── roman-to-integer.py │ ├── self-dividing-number.py │ ├── similar-rgb-color.py │ ├── solve-the-equation.cpp │ ├── sqrtx.py │ ├── sum-of-square-numbers.py │ ├── super-pow.py │ ├── valid-number.py │ ├── valid-perfect-square.py │ ├── valid-square.py │ └── water-and-jug-problem.py ├── Ordered-Map │ └── my-calendar-ii.py ├── Queue │ └── number-of-recent-calls.py ├── README.md ├── Sort │ ├── all-elements-in-two-binary-search-trees.py │ ├── matrix-cells-in-distance-order.py │ └── meeting-rooms.py ├── Stack │ ├── baseball-game.py │ ├── binary-search-tree-iterator.py │ ├── daily-temperatures.py │ ├── flatten-nested-list-iterator.py │ ├── next-greater-element-i.py │ ├── next-greater-element-ii.py │ ├── print-immutable-linked-list-in-reverse.py │ ├── remove-outermost-parentheses.py │ ├── simplify-path.py │ ├── tag-validator.py │ ├── ternary-expression-parser.py │ └── valid-parantheses.py ├── String │ ├── add-bold-tag-in-string.py │ ├── compare-version-numbers.py │ ├── complement-of-base-10-integer.py │ ├── confusing-number.py │ ├── custom-sort-string.py │ ├── defanging-an-ip-address.py │ ├── delete-columns-to-make-sorted.py │ ├── encode-and-decode-strings.py │ ├── find-and-replace-in-string.py │ ├── find-and-replace-pattern.py │ ├── first-unique-character-in-a-string.py │ ├── flip-game.py │ ├── goat-latin.py │ ├── integer-to-english-words.py │ ├── interleaving-string.py │ ├── judge-route-circle.py │ ├── letter-combinations-of-a-phone-number.py │ ├── longest-common-prefix.py │ ├── longest-uncommon-subsequence-i.py │ ├── output-contest-matches.py │ ├── remove-vowels-from-a-string.py │ ├── reorder-data-in-log-files.py │ ├── reverse-string.py │ ├── reverse-vowels.py │ ├── single-row-keyboard.py │ ├── split-a-string-in-balanced-strings.py │ ├── string-compression.py │ ├── string-to-integer-atoi.py │ ├── tag-validator.py │ ├── text-justification.py │ ├── to-lower-case.py │ ├── unique-morse-code-words.py │ ├── valid-palindrome-ii.py │ ├── validate-ip-address.py │ └── zigzag-conversion.py ├── Tree │ ├── average-of-levels-in-binary-tree.py │ ├── balanced-binary-tree.py │ ├── binary-search-tree-to-greater-sum-tree.py │ ├── binary-tree-coloring-game.py │ ├── binary-tree-inorder-traversal.py │ ├── binary-tree-level-order-traversal-ii.py │ ├── binary-tree-level-order-traversal.py │ ├── binary-tree-longest-consecutive-sequence.py │ ├── binary-tree-paths.py │ ├── binary-tree-postorder-traversal.py │ ├── binary-tree-preorder-traversal.py │ ├── binary-tree-pruning.py │ ├── binary-tree-zigzag-level-order-traversal.py │ ├── closest-binary-search-tree-value.py │ ├── count-complete-tree-nodes.py │ ├── deepest-leaves-sum.py │ ├── find-bottom-left-tree-value.py │ ├── find-largest-value-in-each-tree-row.py │ ├── find-leaves-of-binary-tree.py │ ├── increasing-order-search-tree.py │ ├── invert-binary-tree.py │ ├── kill-process.py │ ├── kth-smallest-element-in-a-bst.py │ ├── leaf-similar-trees.py │ ├── lowest-common-ancestor-of-a-binary-tree.py │ ├── maximum-binary-tree.py │ ├── maximum-depth-of-binary-tree.py │ ├── maximum-level-sum-of-a-binary-tree.py │ ├── merge-two-binary-trees.py │ ├── minimum-depth-of-binary-tree.py │ ├── n-ary-tree-level-order-traversal.py │ ├── n-ary-tree-postorder-traversal.py │ ├── n-ary-tree-preorder-traversal.py │ ├── second-minimum-node-in-a-binary-tree.py │ ├── smallest-subtree-with-all-the-deepest-nodes.py │ ├── trim-a-binary-search-tree.py │ └── univalued-binary-tree.py ├── Trie │ └── map-sum-pairs.py ├── Two-Pointers │ ├── backspace-string-compare.py │ ├── linked-list-cycle.py │ ├── middle-of-the-linked-list.py │ ├── permutation-in-string.py │ ├── remove-nth-node-from-end-of-list.py │ ├── reverse-vowels-of-a-string.py │ └── valid-palindrome.py ├── Union-Find │ └── longest-consecutive-sequence.py ├── Unsorted │ ├── battleships-in-a-board.py │ ├── diagonal-traverse.py │ ├── license-key-formatting.py │ ├── max-increase-to-keep-city-skyline.py │ ├── number-of-lines-to-write-string.py │ ├── permutationSequence.py │ ├── random.py │ ├── relative-ranks.py │ ├── reverse-only-letters.py │ ├── reverse_words_not_string.py │ ├── smallest-range-i.py │ ├── unique-email-addresses.py │ └── unique-morse-code-words.py └── Virtual-Contest │ └── 71 │ ├── 1.py │ ├── 1.txt │ ├── 2.py │ ├── 3.py │ ├── 4.py │ └── readme.txt └── projectEuler ├── p042_words.txt ├── problem1.ipynb ├── problem10.py ├── problem12.py ├── problem13.py ├── problem14.py ├── problem15.py ├── problem16.py ├── problem17.py ├── problem18.py ├── problem19.py ├── problem2.ipynb ├── problem20.py ├── problem21.py ├── problem22.py ├── problem23.py ├── problem25.py ├── problem26.py ├── problem27.py ├── problem28.py ├── problem29.py ├── problem30.py ├── problem31.py ├── problem32.py ├── problem33.py ├── problem34.py ├── problem35.py ├── problem36.py ├── problem37.py ├── problem39.py ├── problem4.py ├── problem40.py ├── problem41.py ├── problem42.py ├── problem43.py ├── problem44.py ├── problem45.py ├── problem46.py ├── problem47.py ├── problem5.py ├── problem6.py ├── problem7.py ├── problem8.py └── problem9.py /.gitignore: -------------------------------------------------------------------------------- 1 | template 2 | .DS_Store 3 | article.md 4 | .ipynb_checkpoints 5 | Contest 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Programming practice 2 | These are some of the solutions to the algorithms practice that I do on the side 3 | -------------------------------------------------------------------------------- /leetcode/Array/3sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSum(self, nums: List[int]) -> List[List[int]]: 3 | # https://leetcode.com/problems/3sum/ 4 | nums.sort() 5 | res = [] 6 | for i in range(len(nums) - 2): 7 | j = i + 1 8 | # small optimization 9 | if nums[i] + nums[j] + nums[j + 1] > 0: 10 | return res 11 | k = len(nums) - 1 12 | if i > 0 and nums[i] == nums[i - 1]: 13 | continue 14 | while j < k: 15 | if j > i + 1 and nums[j] == nums[j - 1]: 16 | j += 1 17 | continue 18 | total = nums[i] + nums[j] + nums[k] 19 | if total > 0: 20 | k -= 1 21 | else: 22 | if total == 0: 23 | res.append([nums[i], nums[j], nums[k]]) 24 | j += 1 25 | return res -------------------------------------------------------------------------------- /leetcode/Array/array-Partition-I.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def arrayPairSum(self, nums): 3 | """ 4 | https://leetcode.com/problems/array-partition-i/description/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | nums = sorted(nums) 9 | sum = 0 10 | for i in range(0,len(nums),2): 11 | sum += nums[i] 12 | return sum 13 | -------------------------------------------------------------------------------- /leetcode/Array/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | # https://leetcode.com/problems/container-with-most-water/description/ 4 | max_area = area = 0 5 | left, right = 0, len(height) - 1 6 | while left < right: 7 | l, r = height[left], height[right] 8 | if l < r: 9 | area = (right - left) * l 10 | while height[left] <= l: 11 | left += 1 12 | else: 13 | area = (right - left) * r 14 | while height[right] <= r and right: 15 | right -= 1 16 | if area > max_area: 17 | max_area = area 18 | return max_area 19 | -------------------------------------------------------------------------------- /leetcode/Array/contains-duplicate-ii.py: -------------------------------------------------------------------------------- 1 | def containsNearbyDuplicate(nums, k): 2 | """ 3 | https://leetcode.com/problems/contains-duplicate-ii/#/description 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: bool 7 | """ 8 | dic = {} 9 | for i, v in enumerate(nums): 10 | if v in dic and i - dic[v] <= k: 11 | return True 12 | dic[v] = i 13 | return False 14 | -------------------------------------------------------------------------------- /leetcode/Array/degree-of-an-array.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution(object): 3 | def findShortestSubArray(self, nums): 4 | """ 5 | https://leetcode.com/problems/degree-of-an-array/description/ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | map = defaultdict(list) 10 | for i in range(len(nums)): 11 | map[nums[i]].append(i) 12 | return min((-len(list), list[-1] - list[0] + 1) for list in map.values())[1] 13 | 14 | -------------------------------------------------------------------------------- /leetcode/Array/fibonacci-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, N: int) -> int: 3 | # https://leetcode.com/problems/fibonacci-number/ 4 | a = 0 5 | b = 1 6 | for _ in range(N): 7 | a,b = b,a + b 8 | 9 | return a 10 | def gg_fib(self, N: int) -> int: 11 | return [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040][N] 12 | -------------------------------------------------------------------------------- /leetcode/Array/find-all-duplicates-in-an-array.py: -------------------------------------------------------------------------------- 1 | def findDuplicates(nums): 2 | """ 3 | https://leetcode.com/problems/find-all-duplicates-in-an-array/#/description 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | def duplicate(x,pos,a=nums): 8 | if x in a[:pos]: 9 | return x 10 | return list(set(map(duplicate,nums,range(len(nums)))))[1:] 11 | 12 | print(findDuplicates([4,3,2,7,8,2,3,1])) 13 | -------------------------------------------------------------------------------- /leetcode/Array/find-n-unique-integers-sum-up-to-zero.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumZero(self, n: int) -> List[int]: 3 | # https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/ 4 | L, rem = n // 2, n % 2 5 | if rem != 0: ans = [0] 6 | else: ans = [] 7 | for i in range(1,L+1): 8 | ans.append(-i) 9 | ans.append(i) 10 | return ans -------------------------------------------------------------------------------- /leetcode/Array/find-numbers-with-even-number-of-digits.py: -------------------------------------------------------------------------------- 1 | from math import log10 2 | class Solution: 3 | def findNumbers(self, nums: List[int]) -> int: 4 | # https://leetcode.com/problems/find-numbers-with-even-number-of-digits/ 5 | ans = 0 6 | for num in nums: 7 | l = log10(num) 8 | if pow(10, l) == num and int(l) % 2 == 1: 9 | ans += 1 10 | elif int(l + 1) % 2 == 0: 11 | ans += 1 12 | # print(l) 13 | return ans -------------------------------------------------------------------------------- /leetcode/Array/flipping-an-image.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def flipAndInvertImage(self, A): 3 | """ 4 | https://leetcode.com/problems/flipping-an-image/description/ 5 | :type A: List[List[int]] 6 | :rtype: List[List[int]] 7 | """ 8 | def invert(i): 9 | return 0 if i == 1 else 1 10 | def flip(l): 11 | return list(map(invert, l))[::-1] 12 | return map(flip, A) 13 | 14 | -------------------------------------------------------------------------------- /leetcode/Array/high-five.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def highFive(self, items: List[List[int]]) -> List[List[int]]: 3 | # https://leetcode.com/problems/high-five/ 4 | di = {} 5 | for i, score in items: 6 | di[i] = di.get(i, []) + [score] 7 | ans = [] 8 | for i, scores in di.items(): 9 | top5 = list(sorted(scores, reverse=True))[:5] 10 | # print(i, top5, scores) 11 | ans.append([i, sum(top5)//5]) 12 | return sorted(ans, key=lambda x: x[0]) -------------------------------------------------------------------------------- /leetcode/Array/image-smoother.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def imageSmoother(self, M): 3 | """ 4 | https://leetcode.com/problems/image-smoother/description/ 5 | :type M: List[List[int]] 6 | :rtype: List[List[int]] 7 | """ 8 | R, C = len(M), len(M[0]) 9 | ans = [[0] * C for _ in M] 10 | 11 | for r in range(R): 12 | for c in range(C): 13 | count = 0 14 | for nr in (r-1, r, r+1): 15 | for nc in (c-1, c, c+1): 16 | if 0 <= nr < R and 0 <= nc < C: 17 | ans[r][c] += M[nr][nc] 18 | count += 1 19 | ans[r][c] /= count 20 | 21 | return ans 22 | -------------------------------------------------------------------------------- /leetcode/Array/is-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isSubsequence(self, s, t): 3 | """ 4 | https://leetcode.com/problems/is-subsequence/ 5 | :type s: str 6 | :type t: str 7 | :rtype: bool 8 | """ 9 | index = 0 10 | for c in s: 11 | index = t.find(c,index) 12 | if index == -1: 13 | return False 14 | index += 1 15 | return True 16 | -------------------------------------------------------------------------------- /leetcode/Array/jump-game-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def jump(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | # https://leetcode.com/problems/jump-game-ii/ 8 | n, end, start, step = len(nums), 0, 0, 0 9 | while end < n-1: 10 | step += 1 11 | maxend = end + 1 12 | for i in range(start, end+1): 13 | if i + nums[i] >= n-1: 14 | return step 15 | maxend=max(maxend, i+nums[i]) 16 | start, end = end + 1, maxend 17 | return step 18 | def dp_jump(self, nums): 19 | # Time Limit Exceeded 20 | """ 21 | :type nums: List[int] 22 | :rtype: int 23 | """ 24 | dp = [i for i in range(len(nums))] 25 | for i in range(len(nums)): 26 | for j in range(min(len(nums),i+1+nums[i])-1, i, -1): 27 | print((i,j), dp) 28 | if dp[i] + 1 > dp[j]: 29 | break 30 | dp[j] = min(dp[i] + 1, dp[j]) 31 | return dp[-1] 32 | -------------------------------------------------------------------------------- /leetcode/Array/jump-game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canJump(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | # started from the back 8 | if len(nums) < 2: 9 | return True 10 | 11 | min_successful_index = len(nums) - 1 12 | for i in range(len(nums) - 2, -1, -1): 13 | if nums[i] + i >= min_successful_index: 14 | min_successful_index = i 15 | 16 | return min_successful_index == 0 17 | 18 | def dp_canJump(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: bool 22 | """ 23 | if nums[0] == 0: 24 | if len(nums) != 1: 25 | return False 26 | else: 27 | return True 28 | 29 | dp = [-1]*len(nums) 30 | dp[0] = nums[0] 31 | for i in range(1, len(nums)): 32 | dp[i] = max(dp[i-1]-1, nums[i]) 33 | if dp[i] == 0: 34 | break 35 | print(dp) 36 | return dp[-1] != -1 37 | -------------------------------------------------------------------------------- /leetcode/Array/largest-number-at-least-twice-of-others.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def dominantIndex(self, nums): 3 | """ 4 | https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | ma, idx = max(nums), -1 9 | for i in range(len(nums)): 10 | if nums[i] == ma: 11 | idx = i 12 | elif 2 * nums[i] > ma: 13 | return -1 14 | return idx 15 | 16 | -------------------------------------------------------------------------------- /leetcode/Array/longest-continuous-increasing-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLengthOfLCIS(self, a): 3 | """ 4 | https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | le = len(a) 9 | if le <= 1: 10 | return le 11 | i, j = 0, 1 12 | maSe = 1 13 | while j < le: 14 | if a[j] > a[j-1]: 15 | j += 1 16 | else: 17 | maSe = max(maSe, j - i) 18 | i = j 19 | j += 1 20 | return max(maSe, j-i) 21 | -------------------------------------------------------------------------------- /leetcode/Array/majority-element.py: -------------------------------------------------------------------------------- 1 | import operator 2 | def majorityElement(nums): 3 | """ 4 | https://leetcode.com/problems/majority-element/#/description 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | num_dict = {k: nums.count(k) for k in set(nums)} 9 | count=0 10 | key_save=0 11 | for key in num_dict: 12 | if num_dict[key] > count: 13 | count=num_dict[key] 14 | key_save=key 15 | return key_save 16 | -------------------------------------------------------------------------------- /leetcode/Array/max-consecutive-ones.py: -------------------------------------------------------------------------------- 1 | def findMaxConsecutiveOnes(nums): 2 | """ 3 | https://leetcode.com/problems/max-consecutive-ones/#/description 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | maxLength=0 8 | j=-1 9 | zeroPlaces=[-1,len(nums)] 10 | for i in range(len(nums)+1): 11 | if i==len(nums) or nums[i] == 0: 12 | print(i,j,maxLength) 13 | maxLength=max(maxLength,i-j-1) 14 | j=i 15 | return maxLength 16 | -------------------------------------------------------------------------------- /leetcode/Array/median-of-two-sorted-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 3 | nums1.extend(nums2) 4 | nums1.sort() 5 | l = len(nums1) 6 | if l%2==1: 7 | return nums1[l//2] 8 | return (nums1[l//2]+nums1[l//2-1])/2 -------------------------------------------------------------------------------- /leetcode/Array/merge-intervals.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def merge(self, intervals): 3 | """ 4 | https://leetcode.com/problems/merge-intervals/description/ 5 | :type intervals: List[Interval] 6 | :rtype: List[Interval] 7 | """ 8 | if not intervals: 9 | return [] 10 | intervals.sort(key=lambda x: x[0]) 11 | merged = [intervals[0]] 12 | for i in range(1, len(intervals)): 13 | if merged[-1][1] >= intervals[i][0]: 14 | merged[-1][1] = max(intervals[i][1], merged[-1][1]) 15 | else: 16 | merged.append(intervals[i]) 17 | return merged 18 | -------------------------------------------------------------------------------- /leetcode/Array/merge-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, nums1, m, nums2, n): 3 | """ 4 | https://leetcode.com/problems/merge-sorted-array/description/ 5 | :type nums1: List[int] 6 | :type m: int 7 | :type nums2: List[int] 8 | :type n: int 9 | :rtype: void Do not return anything, modify nums1 in-place instead. 10 | """ 11 | while n > 0: 12 | if m <= 0 or nums2[n-1] >= nums1[m-1]: 13 | nums1[m+n-1] = nums2[n-1] 14 | n -= 1 15 | else: 16 | nums1[m+n-1] = nums1[m-1] 17 | m -= 1 18 | -------------------------------------------------------------------------------- /leetcode/Array/missing-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def missingNumber(self, nums): 3 | """ 4 | https://leetcode.com/problems/missing-number/description/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | su, le = 0, 0 9 | for i in nums: 10 | su += i 11 | le += 1 12 | return int((le*(le+1))/2 - su) 13 | 14 | -------------------------------------------------------------------------------- /leetcode/Array/move-zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def moveZeroes(self, nums): 3 | """ 4 | https://leetcode.com/problems/move-zeroes/description/ 5 | :type nums: List[int] 6 | :rtype: void Do not return anything, modify nums in-place instead. 7 | """ 8 | le = len(nums) 9 | cnt = 0 10 | i = 0 11 | while i < le: 12 | if nums[i] == 0: 13 | nums.pop(i) 14 | cnt += 1 15 | le -= 1 16 | else: 17 | i += 1 18 | nums.extend([0]*cnt) 19 | -------------------------------------------------------------------------------- /leetcode/Array/plus-one.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, digits): 3 | """ 4 | :type digits: List[int] 5 | :rtype: List[int] 6 | """ 7 | if digits[-1] != 9: 8 | digits[-1] += 1 9 | else: 10 | digits[-1] = 0 11 | carry = 1 12 | for i in range(len(digits)-2,-1,-1): 13 | # print(digits) 14 | su = digits[i]+carry 15 | carry = su//10 16 | su = su%10 17 | digits[i] = su 18 | if carry == 0: 19 | break 20 | # print(digits) 21 | if carry != 0: 22 | digits = [carry] + digits[:] 23 | # print(digits) 24 | return digits 25 | -------------------------------------------------------------------------------- /leetcode/Array/product-of-array-except-self.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def productExceptSelf(self, nums): 3 | """ 4 | https://leetcode.com/problems/product-of-array-except-self/description/ 5 | :type nums: List[int] 6 | :rtype: List[int] 7 | """ 8 | result = [1] * len(nums) 9 | leftsum = 1 10 | rightsum = 1 11 | for i in range(len(nums)): 12 | result[i] *= leftsum 13 | result[len(nums)-i-1] *= rightsum 14 | leftsum *= nums[i] 15 | rightsum *= nums[len(nums)-i-1] 16 | return result 17 | -------------------------------------------------------------------------------- /leetcode/Array/range-addition.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getModifiedArray(self, length, updates): 3 | """ 4 | https://leetcode.com/problems/range-addition/description/ 5 | :type length: int 6 | :type updates: List[List[int]] 7 | :rtype: List[int] 8 | """ 9 | ans = [0] * (length+1) 10 | for start, end, inc in updates: 11 | ans[start] += inc 12 | ans[end+1] -= inc 13 | for i in range(1,len(ans)): 14 | ans[i] += ans[i-1] 15 | ans.pop() 16 | return ans 17 | -------------------------------------------------------------------------------- /leetcode/Array/remove-element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeElement(self, nums, val): 3 | """ 4 | https://leetcode.com/problems/remove-element/description/ 5 | :type nums: List[int] 6 | :type val: int 7 | :rtype: int 8 | """ 9 | cnt = nums.count(val) 10 | for i in range(cnt): 11 | nums.remove(val) 12 | return len(nums) 13 | -------------------------------------------------------------------------------- /leetcode/Array/replace-elements-with-greatest-element-on-right-side.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def replaceElements(self, arr: List[int]) -> List[int]: 3 | # https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/ 4 | dp = [-1]*(len(arr)+1) 5 | dp[len(arr) - 1] = arr[-1] 6 | for i in range(len(arr) - 2, -1, -1): 7 | dp[i] = max(dp[i+1], arr[i]) 8 | return dp[1:] -------------------------------------------------------------------------------- /leetcode/Array/reshape-the-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def matrixReshape(self, nums, r, c): 3 | """ 4 | https://leetcode.com/problems/reshape-the-matrix/description/ 5 | :type nums: List[List[int]] 6 | :type r: int 7 | :type c: int 8 | :rtype: List[List[int]] 9 | """ 10 | new_matrix=[] 11 | list_of_numbers=[] 12 | count=0 13 | if r*c==len(nums)*len(nums[0]): 14 | for i in range(len(nums)): 15 | for j in range(len(nums[i])): 16 | list_of_numbers.append(nums[i][j]) 17 | for i in range(r): 18 | row=[] 19 | for j in range(c): 20 | row.append(list_of_numbers[count]) 21 | count+=1 22 | new_matrix.append(row) 23 | return (new_matrix) 24 | else: 25 | return (nums) 26 | -------------------------------------------------------------------------------- /leetcode/Array/reveal-cards-in-increasing-order.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: 3 | # https://leetcode.com/problems/reveal-cards-in-increasing-order/ 4 | N = len(deck) 5 | index = collections.deque(range(N)) 6 | ans = [None] * N 7 | 8 | for card in sorted(deck): 9 | ans[index.popleft()] = card 10 | if index: 11 | index.append(index.popleft()) 12 | 13 | return ans -------------------------------------------------------------------------------- /leetcode/Array/rotate-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rotate(self, nums, k): 3 | """ 4 | https://leetcode.com/problems/rotate-array/description/ 5 | :type nums: List[int] 6 | :type k: int 7 | :rtype: void Do not return anything, modify nums in-place instead. 8 | """ 9 | le = len(nums) 10 | nums[:] = nums[le-k:]+nums[:le-k] 11 | -------------------------------------------------------------------------------- /leetcode/Array/search-in-rotated-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def search(self, nums, target): 3 | """ 4 | https://leetcode.com/problems/search-in-rotated-sorted-array/description/ 5 | :type nums: List[int] 6 | :type target: int 7 | :rtype: int 8 | """ 9 | try: 10 | return nums.index(target) 11 | except ValueError: 12 | return -1 13 | -------------------------------------------------------------------------------- /leetcode/Array/shuffle-an-array.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import random 3 | class Solution(object): 4 | """ 5 | https://leetcode.com/problems/shuffle-an-array/#/description 6 | """ 7 | def __init__(self, nums): 8 | """ 9 | :type nums: List[int] 10 | """ 11 | self.nums=nums 12 | 13 | 14 | 15 | def reset(self): 16 | """ 17 | Resets the array to its original configuration and return it. 18 | :rtype: List[int] 19 | """ 20 | return self.nums 21 | 22 | def shuffle(self): 23 | """ 24 | Returns a random shuffling of the array. 25 | :rtype: List[int] 26 | """ 27 | def anagram(nums): 28 | return list(itertools.permutations(list(nums))) 29 | returnList=anagram(self.nums) 30 | return list(returnList[random.randint(0,len(returnList)-1)]) 31 | 32 | 33 | 34 | # Your Solution object will be instantiated and called as such: 35 | obj = Solution([1,2,3,4]) 36 | param_1 = obj.reset() 37 | param_2 = obj.shuffle() 38 | -------------------------------------------------------------------------------- /leetcode/Array/sort-array-by-parity.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortArrayByParity(self, A): 3 | """ 4 | https://leetcode.com/problems/sort-array-by-parity/description/ 5 | :type A: List[int] 6 | :rtype: List[int] 7 | """ 8 | even, odd = [], [] 9 | for i in A: 10 | if i%2 == 0: 11 | even.append(i) 12 | else: 13 | odd.append(i) 14 | return even + odd 15 | -------------------------------------------------------------------------------- /leetcode/Array/subarray-sum-equals-k-NEW.py: -------------------------------------------------------------------------------- 1 | def subarray_sum(nums,k): 2 | sums = {0:1} # prefix sum array 3 | res = s = 0 4 | for n in nums: 5 | s += n # increment current sum 6 | res += sums.get(s - k, 0) # check if there is a prefix subarray we can take out to reach k 7 | sums[s] = sums.get(s, 0) + 1 # add current sum to sum count 8 | return res 9 | nums=[1] 10 | print(subarray_sum(nums,6)) 11 | 12 | -------------------------------------------------------------------------------- /leetcode/Array/subarray-sum-equals-k.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def subarray_sum(nums,k): 3 | """ 4 | https://leetcode.com/problems/subarray-sum-equals-k/description/ 5 | :type nums: List[int] 6 | :type k: int 7 | :rtype: int 8 | """ 9 | count=0 10 | for i in range(len(nums)): 11 | j=i 12 | save=0 13 | while save != k and j < len(nums): 14 | save=save+nums[j] 15 | j += 1 16 | if save == k and k!=0: 17 | count += 1 18 | return count 19 | -------------------------------------------------------------------------------- /leetcode/Array/sum-of-digits-in-the-minimum-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumOfDigits(self, A: List[int]) -> int: 3 | # https://leetcode.com/problems/sum-of-digits-in-the-minimum-number/ 4 | mi = min(A) 5 | su = sum(map(int, list(str(mi)))) 6 | return (su + 1) % 2 -------------------------------------------------------------------------------- /leetcode/Array/sum-of-even-numbers-after-queries.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]: 3 | su0 = sum([a for a in A if a % 2 == 0]) 4 | ans = [] 5 | 6 | for query in queries: 7 | val = query[0] 8 | index = query[1] 9 | prev = A[index] 10 | A[index] += val 11 | 12 | if A[index] % 2 == 0: 13 | if prev % 2 ==0: 14 | su0 += val 15 | else: 16 | su0 += A[index] 17 | else: 18 | if prev % 2 == 0: 19 | su0 -= prev 20 | 21 | ans.append(su0) 22 | 23 | return ans 24 | -------------------------------------------------------------------------------- /leetcode/Array/teemo-attacking.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findPoisonedDuration(self, timeSeries, duration): 3 | """ 4 | https://leetcode.com/problems/teemo-attacking/description/ 5 | :type timeSeries: List[int] 6 | :type duration: int 7 | :rtype: int 8 | """ 9 | intervals = [] 10 | for i in timeSeries: 11 | intervals.append([i,i+duration]) 12 | out = [] 13 | for i in sorted(intervals, key=lambda i: i[0]): 14 | if out and i[0] <= out[-1][1]: 15 | out[-1][1] = max(out[-1][1], i[1]) 16 | else: 17 | out += i, 18 | cnt = 0 19 | for i in out: 20 | cnt += i[1] - i[0] 21 | return cnt 22 | -------------------------------------------------------------------------------- /leetcode/Array/toeplitz-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isToeplitzMatrix(self, matrix): 3 | """ 4 | https://leetcode.com/problems/toeplitz-matrix/description/ 5 | :type matrix: List[List[int]] 6 | :rtype: bool 7 | """ 8 | rows = len(matrix) 9 | cols = len(matrix[0]) 10 | 11 | for i in range(rows-1): 12 | for j in range(cols-1): 13 | if (matrix[i][j] != matrix[i+1][j+1]): 14 | return False 15 | 16 | return True 17 | -------------------------------------------------------------------------------- /leetcode/Array/transpose-matrix.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | class Solution: 3 | def transpose(self, A): 4 | """ 5 | :type A: List[List[int]] 6 | :rtype: List[List[int]] 7 | """ 8 | return np.array(A).transpose().tolist() 9 | -------------------------------------------------------------------------------- /leetcode/Array/two-sum-ii-input-array-is-sorted.py: -------------------------------------------------------------------------------- 1 | def twoSumII(numbers,target): 2 | num_dict={} 3 | for i in range(len(numbers)): 4 | if numbers[i] in num_dict.keys(): 5 | if target == 2 * numbers[i]: 6 | if num_dict[target-numbers[i]]>0: 7 | return [numbers.index(target-numbers[i]),i] 8 | else: 9 | num_dict[target-numbers[i]] += 1 10 | else: 11 | return [numbers.index(target-numbers[i]),i] 12 | else: 13 | num_dict[target-numbers[i]]=1 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /leetcode/Array/two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSum(self, nums, target): 3 | """ 4 | # https://leetcode.com/problems/two-sum/ 5 | :type nums: List[int] 6 | :type target: int 7 | :rtype: List[int] 8 | """ 9 | h = {} 10 | for i, num in enumerate(nums): 11 | n = target - num 12 | if n not in h: 13 | h[num] = i 14 | else: 15 | return [h[n], i] -------------------------------------------------------------------------------- /leetcode/Array/valid-mountain-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validMountainArray(self, A: List[int]) -> bool: 3 | # https://leetcode.com/problems/valid-mountain-array/ 4 | if len(A) < 3: 5 | return False 6 | flag = True 7 | for i in range(1, len(A)): 8 | if A[i] == A[i-1]: 9 | return False 10 | if flag: 11 | if not (A[i] > A[i-1]): 12 | if i == 1: 13 | return False 14 | flag = False 15 | else: 16 | if not (A[i] < A[i-1]): 17 | return False 18 | return True and not flag 19 | -------------------------------------------------------------------------------- /leetcode/Array/valid-triangle-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def triangleNumber(self, nums): 3 | """ 4 | https://leetcode.com/problems/valid-triangle-number/description/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | nums, count, n = sorted(nums, reverse=1), 0, len(nums) 9 | for i in range(n): 10 | j, k = i + 1, n - 1 11 | while j < k: 12 | if nums[j] + nums[k] > nums[i]: 13 | count += k - j 14 | j += 1 15 | else: 16 | k -= 1 17 | return count 18 | 19 | -------------------------------------------------------------------------------- /leetcode/Array/wiggle-sort.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wiggleSort(self, nums): 3 | """ 4 | https://leetcode.com/problems/wiggle-sort/description/ 5 | :type nums: List[int] 6 | :rtype: void Do not return anything, modify nums in-place instead. 7 | """ 8 | nums.sort() 9 | for i in range(1,len(nums)-1,2): 10 | nums[i], nums[i+1] = nums[i+1], nums[i] 11 | 12 | -------------------------------------------------------------------------------- /leetcode/Backtracking/beautiful-arrangement.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | def countArrangement(N): 3 | """ 4 | https://leetcode.com/problems/beautiful-arrangement/description/ 5 | :type N: int 6 | :rtype: int 7 | """ 8 | def isArrangement(x): 9 | for i in range(len(x),2): 10 | if (x[i]%(i+1) != 0 and (i+1)%x[i]!=0): 11 | return False 12 | for i in range(1,len(x),2): 13 | if (x[i]%(i+1) != 0 and (i+1)%x[i]!=0): 14 | return False 15 | return True 16 | k = 0 17 | for i in permutations(list(range(1,N+1,1))): 18 | if isArrangement(i): 19 | k = k + 1 20 | return k 21 | 22 | 23 | for i in range(2,16): 24 | print(countArrangement(i)) 25 | -------------------------------------------------------------------------------- /leetcode/Backtracking/binary-watch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def readBinaryWatch(self, num): 3 | """ 4 | https://leetcode.com/problems/binary-watch/description/ 5 | :type num: int 6 | :rtype: List[str] 7 | """ 8 | return ['%d:%02d' % (h, m) 9 | for h in range(12) for m in range(60) 10 | if (bin(h) + bin(m)).count('1') == num] 11 | 12 | -------------------------------------------------------------------------------- /leetcode/Backtracking/elimination-game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lastRemaining(self, n): 3 | """ 4 | https://leetcode.com/problems/elimination-game/#/description 5 | :type n: int 6 | :rtype: int 7 | """ 8 | if n == 3 or n == 2: 9 | return 2 10 | elif n == 1: 11 | return 1 12 | else: 13 | base = 4 * self.lastRemaining(n/4) 14 | if n%4 == 0 or n%4 == 1: 15 | return base - 2 16 | else: 17 | return base 18 | -------------------------------------------------------------------------------- /leetcode/Backtracking/flip-game-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canWin(self, s): 3 | """ 4 | https://leetcode.com/problems/flip-game-ii/description/ 5 | :type s: str 6 | :rtype: bool 7 | """ 8 | for i in range(len(s)-1): 9 | if s[i]+s[i+1] == '++' and not self.canWin(s[:i]+'--'+s[i+2:]): 10 | return True 11 | return False 12 | -------------------------------------------------------------------------------- /leetcode/Backtracking/letter-tile-possibilities.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numTilePossibilities(self, tiles: str) -> int: 3 | # https://leetcode.com/problems/letter-tile-possibilities/ 4 | ans = 0 5 | for i in range(1,len(tiles)+1): 6 | ans += len(set(itertools.permutations(tiles,i))) 7 | return ans -------------------------------------------------------------------------------- /leetcode/Backtracking/palindrome-partitioning.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def partition(self, s: str) -> List[List[str]]: 3 | res = [] 4 | self.dfs(s, [], res) 5 | return res 6 | 7 | def dfs(self, s: str, path: List[str], res: List[str]) -> None: 8 | if not s: 9 | res.append(path) 10 | return 11 | for i in range(1, len(s)+1): 12 | if self.isPal(s[:i]): 13 | self.dfs(s[i:], path+[s[:i]], res) 14 | 15 | def isPal(self, s: str) -> bool 16 | return s == s[::-1] 17 | -------------------------------------------------------------------------------- /leetcode/Binary Search/capacity-to-ship-packages-within-d-days.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shipWithinDays(self, weights: List[int], D: int) -> int: 3 | # https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/ 4 | def guess(capacity): 5 | rounds, curr = 1, 0 6 | for w in weights: 7 | curr += w 8 | if curr > capacity: 9 | curr = w 10 | rounds += 1 11 | if rounds > D: 12 | return False 13 | return True 14 | 15 | low = max(math.ceil(sum(weights)/D), max(weights)) 16 | high = math.ceil(len(weights)/D) * max(weights) 17 | 18 | while low <= high: 19 | mid = (low + high) // 2 20 | if guess(mid): 21 | high = mid - 1 22 | else: 23 | low = mid + 1 24 | 25 | return low -------------------------------------------------------------------------------- /leetcode/Binary Search/find-smallest-letter-greater-than-target.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def nextGreatestLetter(self, letters, target): 3 | """ 4 | https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/ 5 | :type letters: List[str] 6 | :type target: str 7 | :rtype: str 8 | """ 9 | index = bisect.bisect(letters, target) 10 | return letters[index % len(letters)] 11 | -------------------------------------------------------------------------------- /leetcode/Binary Search/peak-index-in-mountain-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def peakIndexInMountainArray(self, A): 3 | """ 4 | https://leetcode.com/problems/peak-index-in-a-mountain-array/description/ 5 | :type A: List[int] 6 | :rtype: int 7 | """ 8 | low, high = 0, len(A)-1 9 | peak = 0 10 | 11 | while low <= high: 12 | mid = low + (high-low)//2 13 | if A[mid-1] < A[mid] > A[mid+1]: 14 | peak = mid 15 | return peak 16 | elif A[mid-1] < A[mid]: 17 | low = mid+1 18 | else: 19 | high = mid-1 20 | -------------------------------------------------------------------------------- /leetcode/Binary Search/search-a-2d-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: 3 | # https://leetcode.com/problems/search-a-2d-matrix/ 4 | targetRow = [] 5 | for row in matrix: 6 | if not row: return False 7 | if row[-1] >= target: 8 | targetRow = row 9 | break 10 | if not targetRow: return False 11 | left = 0 12 | right = len(targetRow) - 1 13 | while left <= right: 14 | mid = left + (right - left) // 2 15 | if targetRow[mid] == target: 16 | return True 17 | elif targetRow[mid] > target: 18 | right = mid - 1 19 | else: 20 | left = mid + 1 21 | return False -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/base-7.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convertToBase7(self, num): 3 | """ 4 | https://leetcode.com/problems/base-7/ 5 | :type num: int 6 | :rtype: str 7 | """ 8 | base7 = "0123456" 9 | if num == 0: 10 | return "0" 11 | rl = "" 12 | flag = "" 13 | if num < 0: 14 | flag = "-" 15 | num = num * -1 16 | while num > 0: 17 | rl += base7[num%7] 18 | num //= 7 19 | return flag + rl[::-1] 20 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/binary-number-with-alternating-bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hasAlternatingBits(self, n): 3 | """ 4 | https://leetcode.com/problems/binary-number-with-alternating-bits/description/ 5 | :type n: int 6 | :rtype: bool 7 | """ 8 | xBin = "{0:b}".format(n) 9 | Value = xBin[0] 10 | for i in range(len(xBin)-1): 11 | if xBin[i] == xBin[i+1]: 12 | return False 13 | return True 14 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/binary_complement.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findComplement(self, num): 3 | """ 4 | https://leetcode.com/problems/number-complement/description/ 5 | :type num: int 6 | :rtype: int 7 | """ 8 | x_bin="{0:b}".format(num) 9 | y_bin="" 10 | for i in x_bin: 11 | if i=='0': 12 | y_bin += '1' 13 | else: 14 | y_bin += '0' 15 | return int(y_bin,2) 16 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/binary_points_of_difference.py: -------------------------------------------------------------------------------- 1 | def points_of_binary_difference(x,y): 2 | x_bin="{0:b}".format(x) 3 | y_bin="{0:b}".format(y) 4 | k=max(len(x_bin),len(y_bin)) 5 | x_bin='0'*(k-len(x_bin))+x_bin 6 | y_bin='0'*(k-len(y_bin))+y_bin 7 | count=0 8 | for i in range(k): 9 | if x_bin[i] != y_bin[i]: 10 | count += 1 11 | return count 12 | 13 | x=int(input()) 14 | y=int(input()) 15 | 16 | print(points_of_binary_difference(x,y)) 17 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/hamming-distance.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hammingDistance(self, x, y): 3 | """ 4 | https://leetcode.com/problems/hamming-distance/description/ 5 | :type x: int 6 | :type y: int 7 | :rtype: int 8 | """ 9 | x_bin="{0:b}".format(x) 10 | y_bin="{0:b}".format(y) 11 | k=max(len(x_bin),len(y_bin)) 12 | x_bin='0'*(k-len(x_bin))+x_bin 13 | y_bin='0'*(k-len(y_bin))+y_bin 14 | count=0 15 | for i in range(k): 16 | if x_bin[i] != y_bin[i]: 17 | count += 1 18 | return count 19 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/maximum-product-of-word-lengths.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProduct(self, words): 3 | """ 4 | https://leetcode.com/problems/maximum-product-of-word-lengths/description/ 5 | :type words: List[str] 6 | :rtype: int 7 | """ 8 | words.sort(key = len) 9 | words = words[::-1] 10 | se = [set(word) for word in words] 11 | ma = 0 12 | for i in range(len(words)): 13 | for j in range(len(words)): 14 | if len(se[j] - se[i]) == len(se[j]) and len(se[i] - se[j]) == len(se[i]) and i != j: 15 | # print(words[i],words[j]) 16 | ma = max(ma,len(words[j])*len(words[i])) 17 | if len(words[i]) * len(words[j]) < ma: 18 | break 19 | if len(words[i]) * len(words[0]) < ma: 20 | break 21 | return ma 22 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hammingWeight(self, n): 3 | """ 4 | https://leetcode.com/problems/number-of-1-bits/description/ 5 | :type n: int 6 | :rtype: int 7 | """ 8 | return bin(n).count('1') 9 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/reverse-bits.py: -------------------------------------------------------------------------------- 1 | def reverseBits(n): 2 | """ 3 | https://leetcode.com/problems/reverse-bits/#/description 4 | """ 5 | n_bin = "{0:b}".format(n) 6 | n_bin = str(n_bin) 7 | print(n_bin) 8 | n_bin = n_bin[::-1] + "0" * (32 - len(n_bin)) 9 | print(n_bin) 10 | return int(n_bin,2) 11 | 12 | print(reverseBits(1)) 13 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/single-number-ii.py: -------------------------------------------------------------------------------- 1 | def singleNumber(nums): 2 | """ 3 | https://leetcode.com/problems/single-number-ii/#/description 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if len(nums) == 1: 8 | return nums[0] 9 | else: 10 | nums.sort() 11 | nums_dict = {} 12 | for num in nums: 13 | nums_dict[num] = nums_dict.get(num,0) + 1 14 | for num in nums_dict: 15 | if nums_dict[num] == 1: 16 | return num 17 | 18 | print(singleNumber([0,1,1,1])) 19 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/single-number-iii.py: -------------------------------------------------------------------------------- 1 | def singleNumber(nums): 2 | """ 3 | https://leetcode.com/problems/single-number-iii/#/description 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if len(nums) == 1: 8 | return nums[0] 9 | else: 10 | nums.sort() 11 | nums_dict = {} 12 | for num in nums: 13 | nums_dict[num] = nums_dict.get(num,0) + 1 14 | return_list = [] 15 | for num in nums_dict: 16 | if nums_dict[num] == 1: 17 | return_list.append(num) 18 | return return_list 19 | 20 | print(singleNumber([1, 2, 1, 3, 2, 5])) 21 | -------------------------------------------------------------------------------- /leetcode/Bit-Manipulation/sum_of_binary_points_of_difference.py: -------------------------------------------------------------------------------- 1 | def totalHammingDistance(nums): 2 | """ 3 | https://leetcode.com/problems/total-hamming-distance/description/ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | def points_of_binary_difference(x,y): 8 | x_bin="{0:b}".format(x) 9 | y_bin="{0:b}".format(y) 10 | k=max(len(x_bin),len(y_bin)) 11 | x_bin='0'*(k-len(x_bin))+x_bin 12 | y_bin='0'*(k-len(y_bin))+y_bin 13 | count=0 14 | for i in range(k): 15 | if x_bin[i] != y_bin[i]: 16 | count += 1 17 | return count 18 | answer=0 19 | if len(nums) != 0: 20 | for i in range(0,len(nums)-1): 21 | for j in range(i,len(nums)): 22 | answer += points_of_binary_difference(nums[i],nums[j]) 23 | return answer 24 | 25 | print(totalHammingDistance([4,14,2])) 26 | -------------------------------------------------------------------------------- /leetcode/Brainteaser/fizz-buzz.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def fizzBuzz(self, n): 3 | """ 4 | https://leetcode.com/problems/fizz-buzz/description/ 5 | :type n: int 6 | :rtype: List[str] 7 | """ 8 | return_list=[] 9 | for i in range(1,n+1): 10 | if i%3==0 and i%5==0: 11 | return_list.append("FizzBuzz") 12 | elif i%3==0: 13 | return_list.append("Fizz") 14 | elif i%5==0: 15 | return_list.append("Buzz") 16 | else: 17 | return_list.append(str(i)) 18 | return return_list 19 | 20 | -------------------------------------------------------------------------------- /leetcode/Brainteaser/nim-game.py: -------------------------------------------------------------------------------- 1 | nim_dict={1:True,2:True,3:True,4:False} 2 | def canWinNim(n): 3 | """ 4 | https://leetcode.com/problems/nim-game/#/description 5 | :type n: int 6 | :rtype: bool 7 | """ 8 | global nim_dict 9 | if n in nim_dict: 10 | return nim_dict[n] 11 | if canWinNim(n-1) == False or canWinNim(n-2)==False or canWinNim(n-3)==False: 12 | nim_dict[n]=True 13 | return True 14 | nim_dict[n]=False 15 | return False 16 | 17 | print(nim_dict) 18 | print(canWinNim(8)) 19 | -------------------------------------------------------------------------------- /leetcode/Database/activity-participants.sql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | -- https://leetcode.com/problems/activity-participants/ 3 | with cte as 4 | ( 5 | select activity, count(id) as num 6 | from Friends 7 | group by activity 8 | ) 9 | select activity as ACTIVITY 10 | from cte 11 | where num not in (select max(num) from cte) 12 | and num not in (select min(num) from cte) -------------------------------------------------------------------------------- /leetcode/Database/all-people-report-to-the-given-manager.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/all-people-report-to-the-given-manager/submissions/s 2 | SELECT e.employee_id FROM employees e 3 | JOIN employees x ON e.manager_id = x.employee_id 4 | JOIN employees y ON x.manager_id = y.employee_id 5 | JOIN employees z ON y.manager_id = z.employee_id 6 | WHERE (x.manager_id = 1 OR y.manager_id = 1 OR z.manager_id = 1) AND e.employee_id != 1 -------------------------------------------------------------------------------- /leetcode/Database/list-the-products-ordered-in-a-period.sql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | -- https://leetcode.com/problems/list-the-products-ordered-in-a-period/submissions/ 3 | WITH product_counts AS ( 4 | SELECT product_id, SUM(unit) as unit 5 | from Orders 6 | WHERE order_date < '2020-03-01' AND order_date > '2020-01-31' 7 | GROUP BY product_id 8 | ) 9 | SELECT product_name, unit 10 | FROM Products 11 | INNER JOIN product_counts pc ON pc.product_id = Products.product_id 12 | WHERE unit >= 100 13 | 14 | -------------------------------------------------------------------------------- /leetcode/Database/movie-rating.sql: -------------------------------------------------------------------------------- 1 | -- Write your MySQL query statement below 2 | SELECT user_name as results FROM 3 | ( 4 | SELECT b.name as user_name,COUNT(*) as counts FROM Movie_rating as a 5 | JOIN Users as b 6 | ON a.user_id=b.user_id 7 | GROUP BY a.user_id 8 | ORDER BY counts DESC,user_name ASC LIMIT 1 9 | ) first_query -- query for the person who rates the greatest number of movies 10 | UNION 11 | SELECT movie_name as results FROM 12 | ( 13 | SELECT d.title as movie_name,AVG(c.rating) as grade FROM Movie_rating as c 14 | JOIN Movies as d 15 | ON c.movie_id=d.movie_id 16 | WHERE SUBSTR(c.created_at,1,7)="2020-02" 17 | GROUP BY c.movie_id 18 | ORDER BY grade DESC,movie_name ASC LIMIT 1 19 | ) second_query; -- query for the movie with the highest average rating in February -------------------------------------------------------------------------------- /leetcode/Database/students-with-invalid-departments.sql: -------------------------------------------------------------------------------- 1 | -- Write your MySQL query statement below 2 | SELECT id, name FROM Students 3 | WHERE department_id not in (SELECT id from Departments) -------------------------------------------------------------------------------- /leetcode/Database/trips-and-users.sql: -------------------------------------------------------------------------------- 1 | -- Write your MySQL query statement below 2 | SELECT 3 | t.Request_at AS Day 4 | ,ROUND(SUM(t.Status != "completed") / COUNT(*), 2) AS 'Cancellation Rate' 5 | FROM Trips t 6 | JOIN Users d ON t.Driver_Id = d.Users_Id 7 | JOIN Users c ON t.Client_Id = c.Users_Id 8 | WHERE d.Banned = "No" 9 | AND c.Banned = "No" 10 | AND t.Request_at BETWEEN "2013-10-01" AND "2013-10-03" 11 | GROUP BY t.Request_at 12 | ORDER BY t.Request_at; -------------------------------------------------------------------------------- /leetcode/Depth-first-Search/24-game.py: -------------------------------------------------------------------------------- 1 | from operator import truediv, mul, add, sub 2 | class Solution: 3 | def judgePoint24(self, nums: List[int]) -> bool: 4 | if not nums: return False 5 | if len(nums) == 1: return abs(nums[0] - 24) < 1e-6 6 | 7 | for i in range(len(nums)): 8 | for j in range(len(nums)): 9 | if i != j: 10 | B = [nums[k] for k in range(len(nums)) if i != k != j] 11 | for op in (truediv, mul, add, sub): 12 | if (op is add or op is mul) and j > i: continue 13 | if op is not truediv or nums[j]: 14 | B.append(op(nums[i], nums[j])) 15 | if self.judgePoint24(B): return True 16 | B.pop() 17 | return False 18 | 19 | def cheatingjudgePoint24(self, num: List[int]) -> bool: 20 | bad = '떢븻각걎냇갅갸꺚뵟숣욄뵴뵞뤼갈갌뤔떌옊메늄숭캸긶꺛옖갍뇐쩢곴듇걯궄옕왹눞솴걃끗긬땉궿가쌀낐걄숤뺴늘걘꽸숢걂갋갃쫐꼔솾쩡쇔솿끛뤜간븺쩬웨딴옠뤛갂뵪덠놤빐옋귒늂갰갖놥궾갆옌뼘묰거갎긷낤겼' 21 | return chr(int(''.join(map(str, sorted(nums)))) + 42921) not in bad -------------------------------------------------------------------------------- /leetcode/Depth-first-Search/clone-graph.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node(object): 4 | def __init__(self, val, neighbors): 5 | self.val = val 6 | self.neighbors = neighbors 7 | """ 8 | class Solution(object): 9 | di = {} 10 | def cloneGraph(self, node): 11 | # https://leetcode.com/problems/clone-graph/ 12 | """ 13 | :type node: Node 14 | :rtype: Node 15 | """ 16 | if not node: 17 | return node 18 | 19 | if node in self.di: 20 | return self.di[node] 21 | 22 | new_node = Node(node.val, []) 23 | self.di[node] = new_node 24 | 25 | if node.neighbors: 26 | new_node.neighbors = [self.cloneGraph(n) for n in node.neighbors] 27 | 28 | return new_node 29 | 30 | -------------------------------------------------------------------------------- /leetcode/Depth-first-Search/keys-and-rooms.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canVisitAllRooms(self, rooms): 3 | """ 4 | https://leetcode.com/problems/keys-and-rooms/description/ 5 | :type rooms: List[List[int]] 6 | :rtype: bool 7 | """ 8 | ans = [] 9 | level = rooms[0] 10 | le = len(rooms) 11 | unlocked = [False]*le 12 | unlocked[0] = True 13 | cn = 1 14 | while level: 15 | # print(level) 16 | temp = set() 17 | for i in level: 18 | if unlocked[i] == False: 19 | unlocked[i] = True 20 | cn += 1 21 | temp |= set(rooms[i]) 22 | rooms[i] = [] 23 | level = temp 24 | return cn == le 25 | -------------------------------------------------------------------------------- /leetcode/Depth-first-Search/validate-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidBST(self, root, lessThan = float('inf'), largerThan = float('-inf')): 3 | """ 4 | https://leetcode.com/problems/validate-binary-search-tree/description/ 5 | :type root: TreeNode 6 | :rtype: bool 7 | """ 8 | if not root: 9 | return True 10 | if root.val <= largerThan or root.val >= lessThan: 11 | return False 12 | return self.isValidBST(root.left, min(lessThan, root.val), largerThan) and self.isValidBST(root.right, lessThan, max(root.val, largerThan)) 13 | -------------------------------------------------------------------------------- /leetcode/Design/design-tinyurl.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | class Codec: 4 | """ 5 | https://leetcode.com/problems/design-tinyurl/ 6 | """ 7 | STRING = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 8 | map = {} 9 | 10 | def encode(self, longUrl): 11 | tag = self.gen_tag() 12 | self.map[tag] = longUrl 13 | return "http://tinyurl.com/" + tag 14 | 15 | def gen_tag(self): 16 | tag = self.gen_random_str() 17 | while tag in self.map.keys(): 18 | tag = self.gen_random_str() 19 | return tag 20 | 21 | def gen_random_str(self): 22 | result = "" 23 | for i in range(6): 24 | result += self.STRING[random.randint(0,61)] 25 | return result 26 | 27 | def decode(self, shortUrl): 28 | return self.map[shortUrl[-6:]] 29 | 30 | codec = Codec() 31 | print(codec.decode(codec.encode("https://leetcode.com/problems/design-tingdrtdyurl"))) 32 | -------------------------------------------------------------------------------- /leetcode/Design/min-stack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | """ 5 | initialize your data structure here. 6 | """ 7 | self.mi = 0 8 | self.li = [] 9 | 10 | def push(self, x): 11 | """ 12 | :type x: int 13 | :rtype: void 14 | """ 15 | self.li.append(x) 16 | 17 | def pop(self): 18 | """ 19 | :rtype: void 20 | """ 21 | self.li.pop() 22 | 23 | def top(self): 24 | """ 25 | :rtype: int 26 | """ 27 | return self.li[-1] 28 | 29 | def getMin(self): 30 | """ 31 | :rtype: int 32 | """ 33 | return min(self.li) 34 | 35 | 36 | 37 | # Your MinStack object will be instantiated and called as such: 38 | # obj = MinStack() 39 | # obj.push(x) 40 | # obj.pop() 41 | # param_3 = obj.top() 42 | # param_4 = obj.getMin() 43 | -------------------------------------------------------------------------------- /leetcode/Design/moving-average-from-data-stream.py: -------------------------------------------------------------------------------- 1 | class MovingAverage: 2 | """ 3 | https://leetcode.com/problems/moving-average-from-data-stream/description/ 4 | """ 5 | def __init__(self, size): 6 | """ 7 | Initialize your data structure here. 8 | :type size: int 9 | """ 10 | self.li = [] 11 | self.size = size 12 | 13 | def next(self, val): 14 | """ 15 | :type val: int 16 | :rtype: float 17 | """ 18 | self.li.append(val) 19 | return sum(self.li[-self.size:])/len(self.li[-self.size:]) 20 | 21 | 22 | # Your MovingAverage object will be instantiated and called as such: 23 | # obj = MovingAverage(size) 24 | # param_1 = obj.next(val) 25 | -------------------------------------------------------------------------------- /leetcode/Divide-And-Conquer/merge-k-sorted-lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def mergeKLists(self, lists: List[ListNode]) -> ListNode: 9 | # https://leetcode.com/problems/merge-k-sorted-lists/ 10 | merged=[] 11 | for li in lists: 12 | while li: 13 | merged.append(li) 14 | li=li.next 15 | merged.sort(key=lambda x:x.val) 16 | for i in range(len(merged)-1): 17 | merged[i].next=merged[i+1] 18 | if merged==[]: 19 | return None 20 | else: 21 | return merged[0] -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/best-time-to-buy-and-sell-stock-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices): 3 | """ 4 | :type prices: List[int] 5 | :rtype: int 6 | """ 7 | profit = 0 8 | for i in range(1,len(prices)): 9 | if prices[i] > prices[i-1]: 10 | profit += (prices[i] - prices[i-1]) 11 | return profit 12 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/best-time-to-buy-and-sell-stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices): 3 | """ 4 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 5 | :type prices: List[int] 6 | :rtype: int 7 | """ 8 | n = len(prices) 9 | if n <= 1: 10 | return 0 11 | profit = 0 12 | currMin = prices[0] 13 | 14 | for p in prices: 15 | if p> currMin: 16 | profit = max(p - currMin, profit) 17 | else: 18 | currMin = p 19 | 20 | return profit 21 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/climbing-stairs.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def climbStairs(self, n): 3 | """ 4 | https://leetcode.com/problems/climbing-stairs/description/ 5 | :type n: int 6 | :rtype: int 7 | """ 8 | n = n + 1 9 | root5 = pow(5, 0.5) 10 | result = 1/root5*( pow((1+root5)/2, n) - pow((1-root5)/2, n) ) 11 | return int(result) 12 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/coin-change.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def coinChange(self, coins, amount): 3 | """ 4 | https://leetcode.com/problems/coin-change/description/ 5 | :type coins: List[int] 6 | :type amount: int 7 | :rtype: int 8 | """ 9 | MAX = float('inf') 10 | dp = [0] + [MAX] * amount 11 | 12 | for i in range(1, amount + 1): 13 | dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1 14 | 15 | return [dp[amount], -1][dp[amount] == MAX] 16 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/count-numbers-with-unique-digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countNumbersWithUniqueDigits(self, n): 3 | """ 4 | https://leetcode.com/problems/count-numbers-with-unique-digits/description/ 5 | :type n: int 6 | :rtype: int 7 | """ 8 | choices = [9, 9, 8, 7, 6, 5, 4, 3, 2, 1] 9 | count = 1 10 | prod = 1 11 | 12 | for i in range(min(n,10)): 13 | prod *= choices[i] 14 | count += prod 15 | return count 16 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/countBits.py: -------------------------------------------------------------------------------- 1 | def countBits(num): 2 | """ 3 | https://leetcode.com/problems/counting-bits/#/description 4 | :type num: int 5 | :rtype: List[int] 6 | """ 7 | def points_of_binary_difference(x,y): 8 | count=0 9 | for i in range(len(x)): 10 | if x[i] != y[i]: 11 | count += 1 12 | return count 13 | return_list=[] 14 | for i in range(num+1): 15 | x="{0:b}".format(i) 16 | return_list.append(points_of_binary_difference(x,len(x) * '0')) 17 | return return_list 18 | 19 | print(countBits(5)) 20 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/house-robber-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rob(self, nums): 3 | """ 4 | https://leetcode.com/problems/house-robber-ii/description/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | lea = len(nums) 9 | if lea == 0: 10 | return 0 11 | if lea == 1: 12 | return nums[0] 13 | if lea == 2: 14 | return max(nums) 15 | if lea == 3: 16 | return max(nums[0], nums[1], nums[2]) 17 | if lea == 4: 18 | return max(nums[1] + nums[3], nums[0] + nums[2]) 19 | dpl = [0] * lea 20 | dpl[0], dpl[1], dpl[2], dpl[3] = nums[0], nums[1], nums[0] + nums[2], nums[3] + nums[0] 21 | dpr = [0] * lea 22 | dpr[0], dpr[1], dpr[2], dpr[3] = nums[0], nums[1], nums[2], nums[3] + nums[1] 23 | for i in range(4, lea-1): 24 | dpl[i] = nums[i] + max(dpl[i-2], dpl[i-3]) 25 | dpr[i] = nums[i] + max(dpr[i-2], dpr[i-3]) 26 | dpr[-1] = nums[-1] + max(dpr[-4], dpr[-3]) 27 | return max(dpl[-2], dpl[-3], dpr[-1], dpr[-2]) 28 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/house-robber-iii.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def rob(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | return max(self.helper(root)) 15 | 16 | def helper(self, root): 17 | if root == None: 18 | return [0,0] 19 | if root.left == None and root.right == None: 20 | return [0, root.val] 21 | left = self.helper(root.left) 22 | right = self.helper(root.right) 23 | return [max(left) + max(right), root.val + left[0] + right[0]] 24 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/house-robber.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rob(self, nums): 3 | """ 4 | https://leetcode.com/problems/house-robber/description/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | lea = len(nums) 9 | if lea == 0: 10 | return 0 11 | if lea == 1: 12 | return nums[0] 13 | if lea == 2: 14 | return max(nums) 15 | if lea == 3: 16 | return max(nums[0] + nums[2], nums[1]) 17 | dp = [0] * lea 18 | dp[0], dp[1], dp[2] = nums[0], nums[1], nums[0] + nums[2] 19 | for i in range(3, lea): 20 | dp[i] = nums[i] + max(dp[i-2], dp[i-3]) 21 | return max(dp[-1], dp[-2]) 22 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/longest-palindromic-subsequence.py: -------------------------------------------------------------------------------- 1 | def longestPalindromeSubseq(s): 2 | """ 3 | https://leetcode.com/problems/longest-palindromic-subsequence/#/description 4 | :type s: str 5 | :rtype: int 6 | """ 7 | count, max_odd = 0, 0 8 | char_dict = {} 9 | for char in s: 10 | char_dict[char] = char_dict.get(char, 0) + 1 11 | for char in char_dict: 12 | if char_dict[char] % 2 == 0: 13 | count += char_dict[char] 14 | else: 15 | max_odd = max(max_odd,char_dict[char]) 16 | 17 | return count + max_odd 18 | 19 | print(longestPalindromeSubseq("bbbab")) 20 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/longest-valid-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestValidParentheses(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | le = len(s) 8 | dp = [0]*le 9 | ma = 0 10 | for i in range(le): 11 | if s[i] == ')': 12 | if i > 1 and s[i - 1] == '(': 13 | if i > 2: 14 | dp[i] = dp[i - 2] + 2 15 | else: 16 | dp[i] = 2 17 | elif i - dp[i - 1] - 2 > 0 and s[i - 1] == ')': 18 | dp[i] = dp[i-1] + dp[i - dp[i - 1] - 2] + 2 19 | ma = max(ma, dp[i]) 20 | return ma -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/maximal-square.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximalSquare(self, M: List[List[str]]) -> int: 3 | # https://leetcode.com/problems/maximal-square/ 4 | if len(M) == 0: 5 | return 0 6 | R, C = len(M), len(M[0]) 7 | S = [[0 for k in range(C)] for l in range(R)] 8 | S[0] = [int(x) for x in M[0]] 9 | ma = max(S[0]) 10 | for i in range(1, R): 11 | S[i][0] = int(M[i][0]) 12 | ma = max(S[i][0], ma) 13 | for j in range(1, C): 14 | if (M[i][j] == "1"): 15 | S[i][j] = min(S[i][j-1], S[i-1][j], 16 | S[i-1][j-1]) + 1 17 | ma = max(S[i][j], ma) 18 | else: 19 | S[i][j] = 0 20 | return ma*ma -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/maximum-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxSubArray(self, nums): 3 | """ 4 | https://leetcode.com/problems/maximum-subarray/description/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | sums = [0 for i in range(len(nums))] 9 | sums[0] = nums[0] 10 | max = sums[0] 11 | for i in range(1, len(sums)): 12 | sums[i] = sums[i-1] + nums[i] if sums[i-1] > 0 else nums[i] 13 | max = sums[i] if sums[i] > max else max 14 | return max 15 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/minimum-path-sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minPathSum(self, grid): 3 | """ 4 | https://leetcode.com/problems/minimum-path-sum/description/ 5 | :type grid: List[List[int]] 6 | :rtype: int 7 | """ 8 | m = len(grid) 9 | if m > 0: 10 | n = len(grid[0]) 11 | else: 12 | return 0 13 | dp = [[0] * n for _ in range(m)] 14 | dp[0][0] = grid[0][0] 15 | for i in range(1, m): 16 | dp[i][0] = grid[i][0] + dp[i-1][0] 17 | for j in range(1, n): 18 | dp[0][j] = grid[0][j] + dp[0][j-1] 19 | for i in range(1, m): 20 | for j in range(1, n): 21 | dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]) 22 | return dp[m-1][n-1] 23 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/number-of-corner-rectangles.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countCornerRectangles(self, grid): 3 | """ 4 | https://leetcode.com/problems/number-of-corner-rectangles 5 | :type grid: List[List[int]] 6 | :rtype: int 7 | """ 8 | R, C = len(grid), len(grid[0]) 9 | if R == 1 or C == 1: 10 | return 0 11 | rs = {} 12 | for i in range(R): 13 | rs[i] = set() 14 | for j in range(C): 15 | if grid[i][j]: 16 | rs[i] |= {j} 17 | count = 0 18 | rsl, rows, le = {}, [], 0 19 | for i in rs: 20 | rsl[i] = len(rs[i]) 21 | rows.append(i) 22 | le += 1 23 | for i in range(le): 24 | for j in range(i+1, le): 25 | n = rsl[rows[i]] - len(rs[rows[i]] - rs[rows[j]]) 26 | count += (n * (n-1))/2 27 | return count 28 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/sentence-screen-fitting.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def TLE_wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int: 3 | le = len(sentence) 4 | dp = [0]*le 5 | for i in range(le): 6 | dp[i] = len(sentence[i]) 7 | # print(dp) 8 | r, c = rows, cols 9 | i = 0 10 | while r > 0: 11 | l = 0 12 | while c >= l: 13 | # print('C1', i,l,r,c) 14 | l += dp[i%le] 15 | if l < c: 16 | l += 1 17 | i += 1 18 | # print('C2', i,l,r,c) 19 | # print('R', i,l,r,c) 20 | i -= 1 21 | r -= 1 22 | return i//le -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/triangle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minimumTotal(self, triangle): 3 | """ 4 | https://leetcode.com/problems/triangle/description/ 5 | :type triangle: List[List[int]] 6 | :rtype: int 7 | """ 8 | lastRow = triangle[-1] 9 | 10 | for row in reversed(triangle[:-1]): 11 | tempRow = row[:] 12 | for i in range(0,len(row)): 13 | tempRow[i] += min(lastRow[i], lastRow[i+1]) 14 | lastRow = tempRow 15 | return lastRow[0] 16 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/unique-paths-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniquePathsWithObstacles(self, obstacleGrid): 3 | """ 4 | https://leetcode.com/problems/unique-paths-ii/description/ 5 | :type obstacleGrid: List[List[int]] 6 | :rtype: int 7 | """ 8 | m = len(obstacleGrid) 9 | n = len(obstacleGrid[0]) 10 | dp = [[1]*n for _ in range(m)] 11 | for i in range(m): 12 | if obstacleGrid[i][0] == 1: 13 | for ix in range(i,m): 14 | dp[ix][0] = 0 15 | break; 16 | for j in range(n): 17 | if obstacleGrid[0][j] == 1: 18 | for jx in range(j,n): 19 | dp[0][jx] = 0 20 | break; 21 | for i in range(1,m): 22 | for j in range(1,n): 23 | if obstacleGrid[i][j] == 1: 24 | dp[i][j] = 0 25 | else: 26 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 27 | return dp[m-1][n-1] 28 | -------------------------------------------------------------------------------- /leetcode/Dynamic-Programming/unique-paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m, n): 3 | """ 4 | https://leetcode.com/problems/unique-paths/description/ 5 | :type m: int 6 | :type n: int 7 | :rtype: int 8 | """ 9 | dp = [[1]*n for _ in range(m)] 10 | for i in range(m): 11 | dp[i][0] = 1 12 | for j in range(n): 13 | dp[0][j] = 1 14 | for i in range(1,m): 15 | for j in range(1,n): 16 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 17 | return dp[m-1][n-1] 18 | -------------------------------------------------------------------------------- /leetcode/Greedy/boats-to-save-people.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numRescueBoats(self, people, limit): 3 | """ 4 | https://leetcode.com/problems/boats-to-save-people/description/ 5 | :type people: List[int] 6 | :type limit: int 7 | :rtype: int 8 | """ 9 | people.sort() 10 | i, j = 0, len(people) - 1 11 | ans = 0 12 | while i <= j: 13 | ans += 1 14 | if people[i] + people[j] <= limit: 15 | i += 1 16 | j -= 1 17 | return ans 18 | 19 | -------------------------------------------------------------------------------- /leetcode/Greedy/lemonade-change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lemonadeChange(self, bills): 3 | """ 4 | https://leetcode.com/problems/lemonade-change/description/ 5 | :type bills: List[int] 6 | :rtype: bool 7 | """ 8 | five = 0 9 | ten = 0 10 | twenty = 0 11 | for bill in bills: 12 | if bill == 5: 13 | five += 1 14 | elif bill == 10: 15 | if five == 0: 16 | return False 17 | ten += 1 18 | five -= 1 19 | elif bill == 20: 20 | if five >= 1 and ten >= 1: 21 | twenty += 1 22 | five -= 1 23 | ten -= 1 24 | elif five >= 3: 25 | twenty += 1 26 | five -= 3 27 | else: 28 | return False 29 | return True 30 | -------------------------------------------------------------------------------- /leetcode/Greedy/queue-reconstruction-by-height.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reconstructQueue(self, people): 3 | """ 4 | https://leetcode.com/problems/queue-reconstruction-by-height/description/ 5 | :type people: List[List[int]] 6 | :rtype: List[List[int]] 7 | """ 8 | people.sort(key=lambda x: (-x[0], x[1])) 9 | ret = [] 10 | for i in range(len(people)): 11 | ret.insert(people[i][1], people[i]) 12 | return ret 13 | -------------------------------------------------------------------------------- /leetcode/Greedy/score-after-flipping-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def matrixScore(self, A): 3 | """ 4 | https://leetcode.com/problems/score-after-flipping-matrix/description/ 5 | :type A: List[List[int]] 6 | :rtype: int 7 | """ 8 | R, C = len(A), len(A[0]) 9 | ans = 0 10 | for c in range(C): 11 | col = 0 12 | for r in range(R): 13 | col += A[r][c] ^ A[r][0] 14 | ans += max(col, R - col) * (1 << (C - 1 - c)) 15 | return ans 16 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/SOLlengthOfLongestSubstring.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLongestSubstring(self, s): 3 | """ 4 | https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ 5 | :type s: str 6 | :rtype: int 7 | """ 8 | start = maxLength = 0 9 | usedChar = {} 10 | 11 | for i in range(len(s)): 12 | if s[i] in usedChar and start <= usedChar[s[i]]: 13 | start = usedChar[s[i]] + 1 14 | else: 15 | j=i-start+1 16 | maxLength = max(maxLength, i - start + 1) 17 | 18 | usedChar[s[i]] = i 19 | 20 | return maxLength 21 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/bulls-and-cows.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def getHint(self, secret: str, guess: str) -> str: 4 | # https://leetcode.com/problems/bulls-and-cows/ 5 | ses, seg = Counter(secret), Counter(guess) 6 | ik = ses & seg 7 | C = 0 8 | for k in ik: 9 | C += ik[k] 10 | B = 0 11 | for i in range(len(secret)): 12 | if secret[i] == guess[i]: 13 | B += 1 14 | C -= 1 15 | return f"{B}A{C}B" -------------------------------------------------------------------------------- /leetcode/Hash-Table/distribute-candies.py: -------------------------------------------------------------------------------- 1 | import operator 2 | def distributeCandies(candies): 3 | """ 4 | https://leetcode.com/problems/distribute-candies/#/description 5 | :type candies: List[int] 6 | :rtype: int 7 | """ 8 | candies.sort() 9 | total_unique=len(set(candies)) 10 | total_count=len(candies) 11 | if total_unique * 2 <= total_count: 12 | return total_unique 13 | else: 14 | return int(total_count/2) 15 | 16 | lel=(distributeCandies([0,1,2,3])) 17 | print(lel) 18 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/find-anagram-mappings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def anagramMappings(self, A, B): 3 | """ 4 | https://leetcode.com/problems/find-anagram-mappings/description/ 5 | :type A: List[int] 6 | :type B: List[int] 7 | :rtype: List[int] 8 | """ 9 | dc = {} 10 | for i in range(len(B)): 11 | dc[B[i]] = i 12 | li = [] 13 | for i in A: 14 | li.append(dc[i]) 15 | return li 16 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/find-smallest-common-element-in-all-rows.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def smallestCommonElement(self, mat: List[List[int]]) -> int: 3 | # https://leetcode.com/problems/find-smallest-common-element-in-all-rows/ 4 | mat = list(map(set, mat)) 5 | ans = mat[0] 6 | for row in mat: 7 | ans &= row 8 | # print(ans) 9 | return min(ans) if ans else -1 -------------------------------------------------------------------------------- /leetcode/Hash-Table/find-the-difference.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findTheDifference(self, s, t): 3 | """ 4 | https://leetcode.com/problems/find-the-difference/description/ 5 | :type s: str 6 | :type t: str 7 | :rtype: str 8 | """ 9 | def convert_to_dict(d): 10 | x = {} 11 | for char in d: 12 | x[char] = x.get(char,0) + 1 13 | return x 14 | 15 | def subtract_dict(d,k): 16 | l = {} 17 | if len(d) > len(k): 18 | t = k 19 | k = d 20 | d = t 21 | for char in k.keys(): 22 | l[char] = abs(k[char] - d.get(char,0)) 23 | for char in l: 24 | if l[char] != 0: 25 | return char 26 | y = convert_to_dict(s) 27 | z = convert_to_dict(t) 28 | return subtract_dict(y, z) 29 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/group-anagrams.py: -------------------------------------------------------------------------------- 1 | def groupAnagrams(strs): 2 | """ 3 | https://leetcode.com/problems/group-anagrams/#/solutions 4 | :type strs: List[str] 5 | :rtype: List[List[str]] 6 | """ 7 | d = {} 8 | for w in sorted(strs): 9 | key = tuple(sorted(w)) 10 | d[key] = d.get(key, []) + [w] 11 | return d.values() 12 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/happy-number.py: -------------------------------------------------------------------------------- 1 | def isHappy(n): 2 | """ 3 | https://leetcode.com/problems/happy-number 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | 8 | def sumOf(lst): 9 | sumOf=0 10 | for i in lst: 11 | sumOf += (i**2) 12 | print(sumOf,lst) 13 | return sumOf 14 | lst = [int(i) for i in str(n)] 15 | n=sumOf(lst) 16 | while n >= 10: 17 | lst = [int(i) for i in str(n)] 18 | n = sumOf(lst) 19 | if n==1 or n==7: 20 | return True 21 | return False 22 | 23 | print(isHappy(1111111)) 24 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/intersection-of-three-sorted-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: 3 | # https://leetcode.com/problems/intersection-of-three-sorted-arrays/ 4 | return list(sorted(set(arr1) & set(arr2) & set(arr3))) -------------------------------------------------------------------------------- /leetcode/Hash-Table/jewels-and-stones.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numJewelsInStones(self, J, S): 3 | """ 4 | https://leetcode.com/problems/jewels-and-stones/description/ 5 | :type J: str 6 | :type S: str 7 | :rtype: int 8 | """ 9 | J = set(J) 10 | cnt = 0 11 | for i in S: 12 | if i in J: 13 | cnt += 1 14 | return cnt 15 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/keyboard-row.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findWords(self, words): 3 | """ 4 | https://leetcode.com/problems/keyboard-row/description/ 5 | :type words: List[str] 6 | :rtype: List[str] 7 | """ 8 | row1=['Q','W','E','R','T','Y','U','I','O','P'] 9 | row2=['A','S','D','F','G','H','J','K','L'] 10 | row3=['Z','X','C','V','B','N','M'] 11 | row_words=[] 12 | for word in words: 13 | count1=0 14 | count2=0 15 | count3=0 16 | for letter in word: 17 | if letter.upper() in row1: 18 | count1 += 1 19 | elif letter.upper() in row2: 20 | count2 += 1 21 | elif letter.upper() in row3: 22 | count3 += 1 23 | if max(count1,count2,count3)==len(word): 24 | row_words.append(word) 25 | return row_words 26 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/longest-harmonious-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLHS(self, nums): 3 | """ 4 | https://leetcode.com/problems/longest-harmonious-subsequence/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | le = 0 9 | numDict = {} 10 | for x in nums: 11 | numDict[x] = numDict.get(x, 0) + 1 12 | for i in numDict: 13 | if i+1 in numDict: 14 | le=max(numDict[i] + numDict[i+1],le) 15 | return le 16 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/longest-palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestPalindrome(self, s): 3 | """ 4 | https://leetcode.com/problems/longest-palindrome/description/ 5 | :type s: str 6 | :rtype: int 7 | """ 8 | di={} 9 | for char in s: 10 | di[char] = di.get(char,0) + 1 11 | flag = True 12 | length = 0 13 | for char in di: 14 | if di[char]%2 == 0: 15 | length += di[char] 16 | elif flag and di[char]%2==1: 17 | length += di[char] 18 | flag = False 19 | else: 20 | length += di[char]-1 21 | return length 22 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/longest-substring-without-repeating-characters.py: -------------------------------------------------------------------------------- 1 | def lengthOfLongestSubstring(s): 2 | """ 3 | https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description 4 | :type s: str 5 | :rtype: int 6 | """ 7 | if len(s)==0: 8 | return "" 9 | else: 10 | def isrepeat(s): 11 | s=sorted(s) 12 | char_list=[] 13 | for char in s: 14 | if char in char_list: 15 | return False 16 | else: 17 | char_list.append(char) 18 | return True 19 | max_len=0 20 | saved_string=s[0] 21 | for i in range(len(s)+1): 22 | for j in range(len(s),-1,-1): 23 | print(s[i:j],isrepeat(s[i:j]),saved_string,max_len) 24 | if max_len<(j-i): 25 | if isrepeat(s[i:j]): 26 | max_len=j-i 27 | saved_string=s[i:j] 28 | else: 29 | break 30 | return saved_string 31 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/max-points-on-a-line.py: -------------------------------------------------------------------------------- 1 | def maxPoints(self, points): 2 | """ 3 | https://leetcode.com/problems/max-points-on-a-line/description/ 4 | :type points: List[Point] 5 | :rtype: int 6 | """ 7 | l = len(points) 8 | if l == 0: 9 | return 0 10 | if l == 1: 11 | return 1 12 | m = 0 13 | for i in range(l): 14 | dic = {'i': 1} 15 | same = 0 16 | for j in range(i+1, l): 17 | tx, ty = points[j].x, points[j].y 18 | if tx == points[i].x and ty == points[i].y: 19 | same += 1 20 | continue 21 | if points[i].x == tx: slope = 'i' 22 | else:slope = ((points[i].y-ty) * np.longdouble(1)) /(points[i].x-tx) 23 | if slope not in dic: dic[slope] = 1 24 | dic[slope] += 1 25 | m = max(m, max(dic.values()) + same) 26 | return m 27 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/minimum-index-sum-of-two-lists.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findRestaurant(self, list1, list2): 3 | """ 4 | https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/ 5 | :type list1: List[str] 6 | :type list2: List[str] 7 | :rtype: List[str] 8 | """ 9 | exist = {x: i for i, x in enumerate(list1)} 10 | tmp = float('inf') 11 | ans = [] 12 | 13 | for i, x in enumerate(list2): 14 | if x in exist: 15 | if i + exist[x] < tmp: 16 | tmp = i + exist[x] 17 | ans = [x] 18 | elif i + exist[x] == tmp: 19 | ans.append(x) 20 | 21 | return ans 22 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/most-frequent-subtree-sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def findFrequentTreeSum(self, root): 10 | """ 11 | https://leetcode.com/problems/most-frequent-subtree-sum/description/ 12 | :type root: TreeNode 13 | :rtype: List[int] 14 | """ 15 | di = {} 16 | def recurse(root): 17 | if root == None: return 0 18 | su = root.val + recurse(root.left) + recurse(root.right) 19 | if su not in di: 20 | di[su] = 0 21 | di[su] += 1 22 | return su 23 | recurse(root) 24 | re, ma = [], 0 25 | for i in di: 26 | if di[i] > ma: 27 | re = [i] 28 | ma = di[i] 29 | elif di[i] == ma: 30 | re.append(i) 31 | return re 32 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/n-repeated-element-in-size-2n-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedNTimes(self, A: List[int]) -> int: 3 | # https://leetcode.com/problems/n-repeated-element-in-size-2n-array 4 | di = {} 5 | for i in A: 6 | if i in di: 7 | return i 8 | else: 9 | di[i] = 1 10 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/palindrome-permutation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canPermutePalindrome(self, s): 3 | """ 4 | https://leetcode.com/problems/palindrome-permutation/description/ 5 | :type s: str 6 | :rtype: bool 7 | """ 8 | di = {} 9 | for char in s: 10 | di[char] = di.get(char, 0) + 1 11 | flag = True 12 | for i in di: 13 | if di[i]%2 == 1: 14 | if flag: 15 | flag = False 16 | else: 17 | return False 18 | return True 19 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/repeated-dna-sequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findRepeatedDnaSequences(self, s): 3 | """ 4 | https://leetcode.com/problems/repeated-dna-sequences/description/ 5 | :type s: str 6 | :rtype: List[str] 7 | """ 8 | di = {} 9 | for i in range(len(s)-9): 10 | if s[i:i+10] in di: 11 | di[s[i:i+10]] += 1 12 | else: 13 | di[s[i:i+10]] = 1 14 | ans = [] 15 | for i in di: 16 | if di[i] > 1: 17 | ans.append(i) 18 | return ans 19 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/sentence-similarity.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution: 3 | def areSentencesSimilar(self, words1: List[str], words2: List[str], pairs: List[List[str]]) -> bool: 4 | if len(words1) != len(words2): 5 | return False 6 | di = defaultdict(set) 7 | i = 0 8 | for word1, word2 in pairs: 9 | di[word1].add(i) 10 | di[word2].add(i) 11 | i += 1 12 | # print(di) 13 | for i in range(len(words1)): 14 | word1 = words1[i] 15 | word2 = words2[i] 16 | if len(di[word1] & di[word2]) == 0 and word1 != word2: 17 | return False 18 | return True -------------------------------------------------------------------------------- /leetcode/Hash-Table/single-number.py: -------------------------------------------------------------------------------- 1 | def singleNumber(nums): 2 | """ 3 | https://leetcode.com/problems/single-number/#/description 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | nums.sort() 8 | print(nums) 9 | print(set(nums)) 10 | for i,num in enumerate(sorted(set(nums))): 11 | try: 12 | print(i,num,(i*2)+1) 13 | if nums[(i*2)+1] != num: 14 | break 15 | except: 16 | True 17 | return num 18 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/sort-characters-by-frequency.py: -------------------------------------------------------------------------------- 1 | import operator 2 | class Solution(object): 3 | def frequencySort(self, s): 4 | """ 5 | https://leetcode.com/problems/sort-characters-by-frequency/description/ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | d = {} 10 | for i in s: 11 | d[i] = d.get(i,0) + 1 12 | k = "" 13 | for i in sorted(d, key=d.get, reverse=True): 14 | k += i * d[i] 15 | return k 16 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/top-k-frequent-elements.py: -------------------------------------------------------------------------------- 1 | import operator 2 | def topKFrequent(nums, k): 3 | """ 4 | https://leetcode.com/problems/top-k-frequent-elements/#/description 5 | :type nums: List[int] 6 | :type k: int 7 | :rtype: List[int] 8 | """ 9 | num_dict={} 10 | for i in sorted(set(nums)): 11 | num_dict[i]=nums.count(i) 12 | num_dict = dict(sorted(num_dict.items(), key=operator.itemgetter(1),reverse=True)) 13 | count=1 14 | return_list=[] 15 | for num in num_dict: 16 | if count <= k: 17 | count += 1 18 | else: 19 | break 20 | return_list.append(num) 21 | return return_list 22 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/top-k-frequent-words.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def topKFrequent(self, words, k): 3 | """ 4 | https://leetcode.com/problems/top-k-frequent-words/description/ 5 | :type words: List[str] 6 | :type k: int 7 | :rtype: List[str] 8 | """ 9 | frequencies = {} 10 | for word in words: 11 | if word in frequencies: 12 | frequencies[word] += 1 13 | else: 14 | frequencies[word] = 1 15 | uniqueWords = frequencies.keys() 16 | uniqueWords.sort() 17 | uniqueWords = sorted(uniqueWords, key = lambda x: frequencies[x], reverse = True) 18 | return uniqueWords[:k] 19 | 20 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/uncommon-words-from-two-sentences.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uncommonFromSentences(self, A, B): 3 | """ 4 | https://leetcode.com/problems/uncommon-words-from-two-sentences/description/ 5 | :type A: str 6 | :type B: str 7 | :rtype: List[str] 8 | """ 9 | 10 | count = {} 11 | for word in A.split(): 12 | count[word] = count.get(word, 0) + 1 13 | for word in B.split(): 14 | count[word] = count.get(word, 0) + 1 15 | return [word for word in count if count[word] == 1] 16 | -------------------------------------------------------------------------------- /leetcode/Hash-Table/unique-number-of-occurrences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniqueOccurrences(self, arr: List[int]) -> bool: 3 | # https://leetcode.com/problems/unique-number-of-occurrences/ 4 | di = {} 5 | for num in arr: 6 | di[num] = di.get(num, 0) + 1 7 | v = di.values() 8 | return len(set(v)) == len(v) -------------------------------------------------------------------------------- /leetcode/Heap/sliding-window-maximum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSlidingWindow(self, nums, k): 3 | """ 4 | https://leetcode.com/problems/sliding-window-maximum/description/ 5 | :type nums: List[int] 6 | :type k: int 7 | :rtype: List[int] 8 | """ 9 | li = [] 10 | for i in range(len(nums)-k+1): 11 | if i == i + k: 12 | continue 13 | li.append(max(nums[i:i+k])) 14 | return li 15 | -------------------------------------------------------------------------------- /leetcode/Linked-List/delete-node-in-a-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def deleteNode(self, node): 9 | """ 10 | https://leetcode.com/problems/delete-node-in-a-linked-list/description/ 11 | :type node: ListNode 12 | :rtype: void Do not return anything, modify node in-place instead. 13 | """ 14 | node.val = node.next.val 15 | node.next = node.next.next 16 | -------------------------------------------------------------------------------- /leetcode/Linked-List/intersection-of-two-linked-lists.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getIntersectionNode(self, headA, headB): 3 | """ 4 | https://leetcode.com/problems/intersection-of-two-linked-lists/description/ 5 | :type head1, head1: ListNode 6 | :rtype: ListNode 7 | """ 8 | di = collections.OrderedDict() 9 | while headA: 10 | di[headA] = 1 11 | headA = headA.next 12 | while headB: 13 | if headB in di: 14 | return headB 15 | else: 16 | di[headB] = 1 17 | headB = headB.next 18 | return None 19 | -------------------------------------------------------------------------------- /leetcode/Linked-List/palindrome-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def isPalindrome(self, head): 9 | """ 10 | https://leetcode.com/problems/palindrome-linked-list/description/ 11 | :type head: ListNode 12 | :rtype: bool 13 | """ 14 | st = [] 15 | while head != None: 16 | st.append(head.val) 17 | head = head.next 18 | # print(st) 19 | return st == st[::-1] 20 | -------------------------------------------------------------------------------- /leetcode/Linked-List/reorder-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def reorderList(self, head: ListNode) -> None: 9 | # https://leetcode.com/problems/reorder-list/ 10 | st = [] 11 | traverser = head 12 | while traverser: 13 | st.append(traverser) 14 | traverser = traverser.next 15 | # print([x.val for x in st]) 16 | traverser = head 17 | if len(st) > 0: 18 | last = st.pop() 19 | else: 20 | return 21 | le = len(st) 22 | counter = 0 23 | while counter < le: 24 | # print(traverser.val) 25 | first = traverser 26 | second = traverser.next 27 | first.next = last 28 | last.next = second 29 | last = st.pop() 30 | traverser = second 31 | counter += 2 32 | # print('HERE') 33 | # print(traverser.val) 34 | traverser.next = None 35 | -------------------------------------------------------------------------------- /leetcode/Linked-List/reverse-linked-list.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseList(self, head): 3 | """ 4 | https://leetcode.com/problems/reverse-linked-list/description/ 5 | :type head: ListNode 6 | :rtype: ListNode 7 | """ 8 | if head == None or head.next == None: 9 | return head 10 | li = [] 11 | while head: 12 | li.append(head.val) 13 | head = head.next 14 | li = li[::-1] 15 | head = ListNode(li[0]) 16 | sa = head 17 | for i in li[1:]: 18 | ne = ListNode(i) 19 | head.next = ne 20 | head = head.next 21 | return sa 22 | -------------------------------------------------------------------------------- /leetcode/Linked-List/swap-nodes-in-pairs.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def swapPairs(self, head: ListNode) -> ListNode: 9 | # https://leetcode.com/problems/swap-nodes-in-pairs/ 10 | pre, pre.next = self, head 11 | while pre.next and pre.next.next: 12 | a = pre.next 13 | b = a.next 14 | pre.next, b.next, a.next = b, a, b.next 15 | pre = a 16 | return self.next -------------------------------------------------------------------------------- /leetcode/Math/airplane-seat-assignment-probability.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nthPersonGetsNthSeat(self, n: int) -> float: 3 | # https://leetcode.com/problems/airplane-seat-assignment-probability 4 | return 1.0 if n == 1 else 0.5 -------------------------------------------------------------------------------- /leetcode/Math/armstrong-number.py: -------------------------------------------------------------------------------- 1 | from math import log10 2 | 3 | class Solution: 4 | def isArmstrong(self, N: int) -> bool: 5 | # https://leetcode.com/problems/armstrong-number/ 6 | st = str(N) 7 | k = len(st) 8 | su = 0 9 | for num in st: 10 | su += pow(int(num), k) 11 | if su > N: 12 | return False 13 | return su == N 14 | -------------------------------------------------------------------------------- /leetcode/Math/binary-gap.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def binaryGap(self, N): 3 | """ 4 | https://leetcode.com/problems/binary-gap/description/ 5 | :type N: int 6 | :rtype: int 7 | """ 8 | s = bin(N) 9 | prev, ma = -1, 0 10 | for i in range(2, len(s)): 11 | if s[i] == '1': 12 | if prev == -1: 13 | prev = i 14 | else: 15 | ma = max(ma, i-prev) 16 | prev = i 17 | # print(s[i], i, prev, ma) 18 | return ma 19 | 20 | -------------------------------------------------------------------------------- /leetcode/Math/complex_number_multiplication.py: -------------------------------------------------------------------------------- 1 | def complexNumberMultiply(a, b): 2 | a_comp=a.split('+') 3 | b_comp=b.split('+') 4 | a_comp[1]=a_comp[1][:len(a_comp[1])-1] 5 | b_comp[1]=b_comp[1][:len(b_comp[1])-1] 6 | ans="" 7 | ans=(str((int(a_comp[0])*int(b_comp[0]))-(int(a_comp[1])*int(b_comp[1]))))+"+"+(str((int(a_comp[0])*int(b_comp[1]))+(int(a_comp[1])*int(b_comp[0]))))+"i" 8 | return ans 9 | 10 | print(complexNumberMultiply("1+-1i", "1+-1i")) 11 | -------------------------------------------------------------------------------- /leetcode/Math/count-primes.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countPrimes(self, n): 3 | """ 4 | https://leetcode.com/problems/count-primes/description/ 5 | :type n: int 6 | :rtype: int 7 | """ 8 | isprime=[] 9 | for i in range(2,n): 10 | isprime[i]=1 11 | for i in range(2,n): 12 | if i * i > n: 13 | break 14 | if isprime[i] == 0: 15 | continue 16 | for j in range(i*i,n,i): 17 | isprime[j]=0 18 | count=0 19 | for i in range(n+1): 20 | if isprime[i]: 21 | count += 1 22 | return count 23 | -------------------------------------------------------------------------------- /leetcode/Math/count-substrings-with-only-one-distinct-letter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countLetters(self, S: str) -> int: 3 | # https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter/ 4 | ans = 0 5 | i, j = 0, 0 6 | while j < len(S): 7 | if S[j] == S[i]: 8 | j += 1 9 | else: 10 | # print((j-i+1)*(j-i)/2, i, j) 11 | ans += (j-i+1)*(j-i)/2 12 | i = j 13 | # print((j-i+1)*(j-i)/2, i, j) 14 | ans += (j-i+1)*(j-i)/2 15 | return int(ans) -------------------------------------------------------------------------------- /leetcode/Math/excel-sheet-column-number.py: -------------------------------------------------------------------------------- 1 | def titleToNumber(s): 2 | """ 3 | https://leetcode.com/problems/excel-sheet-column-number/#/description 4 | :type s: str 5 | :rtype: int 6 | """ 7 | count=0 8 | letter_dict={'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, 'Q': 17, 'R': 18, 'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26} 9 | for i in range(len(s)): 10 | count+=(letter_dict[s[len(s)-i-1]]*(26**i)) 11 | return count 12 | 13 | print(titleToNumber("AB")) 14 | -------------------------------------------------------------------------------- /leetcode/Math/integer-to-roman.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intToRoman(self, num: int) -> str: 3 | # https://leetcode.com/problems/integer-to-roman 4 | M = ["", "M", "MM", "MMM"] 5 | C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] 6 | X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] 7 | I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"] 8 | 9 | return M[num//1000] + C[(num%1000)//100] + X[(num%100)//10] + I[num%10] -------------------------------------------------------------------------------- /leetcode/Math/largest-palindrome-product.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPalindrome(self, n: int) -> int: 3 | # https://leetcode.com/problems/largest-palindrome-product/ 4 | return {1: 9, 2: 987, 3: 123, 4: 597, 5: 677, 6: 1218, 7: 877, 8: 475}[n] -------------------------------------------------------------------------------- /leetcode/Math/minimum-moves-to-equal-array-elements-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minMoves2(self, nums): 3 | """ 4 | https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | nums = sorted(nums) 9 | median = nums[len(nums) / 2] 10 | res = 0 11 | for n in nums: 12 | res += abs(n-median) 13 | return res 14 | -------------------------------------------------------------------------------- /leetcode/Math/multiply-strings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def multiply(self, num1, num2): 3 | """ 4 | https://leetcode.com/problems/multiply-strings/description/ 5 | :type num1: str 6 | :type num2: str 7 | :rtype: str 8 | """ 9 | su = 0 10 | i = 0 11 | le2 = len(num2) 12 | while i < le2: 13 | su1 = 0 14 | a = int(num2[i]) 15 | for j in num1: 16 | # print(a, j) 17 | su1 += int(j) * a 18 | su1 *= 10 19 | su += su1 20 | su *= 10 21 | i += 1 22 | return str(su/100) 23 | -------------------------------------------------------------------------------- /leetcode/Math/optimal-division.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def optimalDivision(self, nums): 3 | """ 4 | https://leetcode.com/problems/optimal-division/description/ 5 | :type nums: List[int] 6 | :rtype: str 7 | """ 8 | A = map(str, nums) 9 | if len(A) <= 2: return '/'.join(A) 10 | return A[0] + '/(' + '/'.join(A[1:]) + ')' 11 | -------------------------------------------------------------------------------- /leetcode/Math/palindrome-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | # https://leetcode.com/problems/palindrome-number/ 4 | y = str(x) 5 | return y == y[::-1] -------------------------------------------------------------------------------- /leetcode/Math/perfect-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def checkPerfectNumber(self, num): 3 | """ 4 | https://leetcode.com/problems/perfect-number/description/ 5 | :type num: int 6 | :rtype: bool 7 | """ 8 | if num <= 0: return False 9 | ans, sqrt = 0, int(num ** 0.5) 10 | ans = sum(i + num//i for i in range(1, sqrt+1) if not num % i) 11 | if num == sqrt ** 2: ans -= sqrt 12 | return ans - num == num 13 | -------------------------------------------------------------------------------- /leetcode/Math/projection-area-of-3d-shapes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def projectionArea(self, grid): 3 | """ 4 | https://leetcode.com/problems/projection-area-of-3d-shapes/description/ 5 | :type grid: List[List[int]] 6 | :rtype: int 7 | """ 8 | su = 0 9 | for i in grid: 10 | ma = -1 11 | for j in i: 12 | if ma < j: 13 | ma = j 14 | if j != 0: 15 | su += 1 16 | su += ma 17 | # print(su) 18 | for i in range(len(grid)): 19 | ma = -1 20 | for j in range(len(grid[i])): 21 | # print(grid[j][i]) 22 | if ma < grid[j][i]: 23 | ma = grid[j][i] 24 | # print(ma) 25 | su += ma 26 | # print(su) 27 | return su 28 | -------------------------------------------------------------------------------- /leetcode/Math/range-addition-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxCount(self, m, n, ops): 3 | """ 4 | https://leetcode.com/problems/range-addition-ii/description/ 5 | :type m: int 6 | :type n: int 7 | :type ops: List[List[int]] 8 | :rtype: int 9 | """ 10 | for op in ops: 11 | m = min(m,op[0]) 12 | n = min(n,op[1]) 13 | return m*n 14 | -------------------------------------------------------------------------------- /leetcode/Math/reverse-integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverse(self, x: str) -> int: 3 | # https://leetcode.com/problems/reverse-integer/ 4 | st = str(x) 5 | if st[0] == "-": 6 | k = -1 * int(st[::-1][:-1]) 7 | # print(k) 8 | if k < -2147483648: 9 | return 0 10 | else: 11 | return k 12 | k = int(st[::-1]) 13 | # print(k) 14 | if k > 2147483647: 15 | return 0 16 | else: 17 | return k 18 | -------------------------------------------------------------------------------- /leetcode/Math/roman-to-integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | # https://leetcode.com/problems/roman-to-integer 4 | if not s: 5 | return 0 6 | roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} 7 | su = 0 8 | for i in range(len(s)-1): 9 | if roman[s[i]] < roman[s[i+1]]: 10 | su -= roman[s[i]] 11 | else: 12 | su += roman[s[i]] 13 | return su + roman[s[-1]] -------------------------------------------------------------------------------- /leetcode/Math/self-dividing-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def selfDividingNumbers(self, left, right): 3 | """ 4 | https://leetcode.com/problems/self-dividing-numbers/description/ 5 | :type left: int 6 | :type right: int 7 | :rtype: List[int] 8 | """ 9 | l = [] 10 | def isSelfDividing(num): 11 | numAsList = list(str(num)) 12 | for i in numAsList: 13 | if i == '0' or int(num)%int(i) != 0: 14 | return False 15 | return True 16 | for i in range(left,right+1): 17 | if isSelfDividing(i): 18 | l.append(i) 19 | return l 20 | -------------------------------------------------------------------------------- /leetcode/Math/similar-rgb-color.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def similarRGB(self, color): 3 | """ 4 | https://leetcode.com/problems/similar-rgb-color/description/ 5 | :type color: str 6 | :rtype: str 7 | """ 8 | def close(s): 9 | a,b = divmod(int(s, 16), 17) 10 | if b > 8: a += 1 11 | a = hex(a)[-1] 12 | return a + a 13 | return '#' + close(color[1:3]) + close(color[3:5]) + close(color[5:]) 14 | -------------------------------------------------------------------------------- /leetcode/Math/sqrtx.py: -------------------------------------------------------------------------------- 1 | def mySqrt(x): 2 | """ 3 | https://leetcode.com/problems/sqrtx/description/ 4 | :type x: int 5 | :rtype: int 6 | """ 7 | 8 | def check(li, num): 9 | for i in li[-5:]: 10 | if i != int(num): 11 | return False 12 | return True 13 | li = [None, None, None, None, None, None] 14 | root = 1 15 | flag = True 16 | while True: 17 | root = 0.5 * (root + (x/root)) 18 | # print(root, check(li, root), li[-5:]) 19 | if check(li, root): 20 | return int(root) 21 | li.append(int(root)) 22 | print(mySqrt(2147395599)) 23 | -------------------------------------------------------------------------------- /leetcode/Math/sum-of-square-numbers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def judgeSquareSum(self, c): 3 | """ 4 | https://leetcode.com/problems/sum-of-square-numbers/description/ 5 | :type c: int 6 | :rtype: bool 7 | """ 8 | def is_square(N): 9 | return int(N**.5)**2 == N 10 | 11 | return any(is_square(c - a*a) 12 | for a in range(int(c**.5) + 1)) 13 | -------------------------------------------------------------------------------- /leetcode/Math/super-pow.py: -------------------------------------------------------------------------------- 1 | from math import fmod 2 | class Solution(object): 3 | def superPow(self, a, b): 4 | """ 5 | https://leetcode.com/problems/super-pow/description/ 6 | :type a: int 7 | :type b: List[int] 8 | :rtype: int 9 | """ 10 | if a % 1337 == 0: 11 | return 0 12 | else: 13 | a = a%1337 14 | count = 1 15 | length = len(b) 16 | for i in range(length): 17 | count *= (a**(b[i]*(10**(length-i-1)))%1337) 18 | return int(fmod(count,1337)) 19 | -------------------------------------------------------------------------------- /leetcode/Math/valid-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isNumber(self, s): 3 | """ 4 | https://leetcode.com/problems/valid-number/description/ 5 | :type s: str 6 | :rtype: bool 7 | """ 8 | try: 9 | float(s) 10 | return True 11 | except ValueError: 12 | return False 13 | -------------------------------------------------------------------------------- /leetcode/Math/valid-perfect-square.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPerfectSquare(self, x): 3 | """ 4 | https://leetcode.com/problems/valid-perfect-square/description/ 5 | :type num: int 6 | :rtype: bool 7 | """ 8 | def check(li, num): 9 | for i in li[-5:]: 10 | if i != int(num): 11 | return False 12 | return True 13 | li = [None, None, None, None, None, None] 14 | root = 1 15 | flag = True 16 | while True: 17 | root = 0.5 * (root + (x/root)) 18 | # print(root, check(li, root), li[-5:]) 19 | if check(li, root): 20 | return int(root) == root 21 | li.append(int(root)) 22 | -------------------------------------------------------------------------------- /leetcode/Math/water-and-jug-problem.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canMeasureWater(self, x, y, z): 3 | """ 4 | https://leetcode.com/problems/water-and-jug-problem/description/ 5 | :type x: int 6 | :type y: int 7 | :type z: int 8 | :rtype: bool 9 | """ 10 | from fractions import gcd 11 | return z == 0 or x + y >= z and z % gcd(x, y) == 0 12 | 13 | -------------------------------------------------------------------------------- /leetcode/Queue/number-of-recent-calls.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | class RecentCounter(object): 3 | # https://leetcode.com/problems/number-of-recent-calls/ 4 | def __init__(self): 5 | self.q = collections.deque() 6 | 7 | def ping(self, t): 8 | self.q.append(t) 9 | while len(self.q)>0 and self.q[0] int: 19 | counter = 0 20 | i = -1 21 | for i in range(len(self.arr)-1,-1,-1): 22 | if self.arr[i] < t - 3000: 23 | break 24 | counter += 1 25 | # print(counter, self.arr) 26 | self.arr = self.arr[-counter:] 27 | self.arr.append(t) 28 | return counter + 1 29 | 30 | 31 | # Your RecentCounter object will be instantiated and called as such: 32 | # obj = RecentCounter() 33 | # param_1 = obj.ping(t) 34 | -------------------------------------------------------------------------------- /leetcode/README.md: -------------------------------------------------------------------------------- 1 | # leetcode 2 | 3 | Most of these problems are solved, some are partial. 4 | All of them have links to the problem website in the docstring 5 | -------------------------------------------------------------------------------- /leetcode/Sort/all-elements-in-two-binary-search-trees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def inorder(self, root: TreeNode) -> List[int]: 10 | # https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ 11 | if root.left: 12 | self.inorder(root.left) 13 | self.ans.append(root.val) 14 | if root.right: 15 | self.inorder(root.right) 16 | def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: 17 | self.ans = [] 18 | if root1: 19 | self.inorder(root1) 20 | r1 = self.ans 21 | self.ans = [] 22 | if root2: 23 | self.inorder(root2) 24 | r2 = self.ans 25 | return sorted(r1 + r2) -------------------------------------------------------------------------------- /leetcode/Sort/matrix-cells-in-distance-order.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: 3 | # https://leetcode.com/problems/matrix-cells-in-distance-order/ 4 | return sorted([[i,j] for i in range(R) for j in range(C)], key=lambda x: abs(x[0] - r0) + abs(x[1] - c0)) 5 | -------------------------------------------------------------------------------- /leetcode/Sort/meeting-rooms.py: -------------------------------------------------------------------------------- 1 | # Definition for an interval. 2 | # class Interval(object): 3 | # def __init__(self, s=0, e=0): 4 | # self.start = s 5 | # self.end = e 6 | 7 | class Solution(object): 8 | def canAttendMeetings(self, intervals): 9 | """ 10 | https://leetcode.com/problems/meeting-rooms/description/ 11 | :type intervals: List[Interval] 12 | :rtype: bool 13 | """ 14 | intervals.sort(key=lambda x: x.start) 15 | 16 | for i in range(1, len(intervals)): 17 | if intervals[i].start < intervals[i-1].end: 18 | return False 19 | 20 | return True 21 | 22 | -------------------------------------------------------------------------------- /leetcode/Stack/baseball-game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def calPoints(self, ops): 3 | """ 4 | https://leetcode.com/problems/baseball-game/description/ 5 | :type ops: List[str] 6 | :rtype: int 7 | """ 8 | compiledList = [] 9 | for i in ops: 10 | if i == "C": 11 | del compiledList[-1] 12 | elif i == "+": 13 | compiledList.append(compiledList[-1]+compiledList[-2]) 14 | elif i == "D": 15 | compiledList.append(2 * compiledList[-1]) 16 | else: 17 | compiledList.append(int(i)) 18 | return sum(compiledList) 19 | -------------------------------------------------------------------------------- /leetcode/Stack/binary-search-tree-iterator.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class BSTIterator: 9 | # https://leetcode.com/problems/binary-search-tree-iterator/ 10 | def __init__(self, root: TreeNode): 11 | 12 | self.stack = [] 13 | self.leftmost_inorder(root) 14 | 15 | def leftmost_inorder(self, root): 16 | 17 | while root: 18 | self.stack.append(root) 19 | root = root.left 20 | 21 | def next(self) -> int: 22 | """ 23 | @return the next smallest number 24 | """ 25 | 26 | topmost_node = self.stack.pop() 27 | 28 | if topmost_node.right: 29 | self.leftmost_inorder(topmost_node.right) 30 | return topmost_node.val 31 | 32 | def hasNext(self) -> bool: 33 | """ 34 | @return whether we have a next smallest number 35 | """ 36 | return len(self.stack) > 0 -------------------------------------------------------------------------------- /leetcode/Stack/daily-temperatures.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, temperatures): 3 | """ 4 | https://leetcode.com/problems/daily-temperatures/description/ 5 | :type temperatures: List[int] 6 | :rtype: List[int] 7 | """ 8 | if not temperatures: return [] 9 | result, stack = [0] * len(temperatures), [] 10 | stack.append((temperatures[0], 0)) 11 | 12 | for i in range(1, len(temperatures)): 13 | while stack: 14 | prev = stack[-1] 15 | if prev[0] < temperatures[i]: 16 | result[prev[1]] = i - prev[1] 17 | stack.pop() 18 | else: 19 | break 20 | stack.append((temperatures[i], i)) 21 | return result 22 | -------------------------------------------------------------------------------- /leetcode/Stack/next-greater-element-i.py: -------------------------------------------------------------------------------- 1 | def nextGreaterElement(findNums, nums): 2 | """ 3 | https://leetcode.com/problems/next-greater-element-i/#/description 4 | :type findNums: List[int] 5 | :type nums: List[int] 6 | :rtype: List[int] 7 | """ 8 | returnList=[] 9 | for num in findNums: 10 | flag=True 11 | index=nums.index(num) 12 | for i in range(index,len(nums)): 13 | if nums[i] > num: 14 | returnList.append(nums[i]) 15 | flag=False 16 | break 17 | if flag: 18 | returnList.append(-1) 19 | return returnList 20 | 21 | print(nextGreaterElement([4,1,2],[1,3,4,2])) 22 | -------------------------------------------------------------------------------- /leetcode/Stack/next-greater-element-ii.py: -------------------------------------------------------------------------------- 1 | def nextGreaterElements(nums): 2 | """ 3 | https://leetcode.com/problems/next-greater-element-ii/#/description 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | def returnNumber(num,nums): 8 | i=nums.index(num)+1 9 | index=i-1 10 | while i <= len(nums) and i != index: 11 | if i == len(nums): 12 | i=0 13 | if nums[i] > num: 14 | return nums[i] 15 | i += 1 16 | return -1 17 | returnList=[] 18 | sorted_nums=sorted(nums) 19 | for num in nums: 20 | returnList.append(returnNumber(num,nums)) 21 | return returnList 22 | print(nextGreaterElements([5,4,3,2,1])) 23 | -------------------------------------------------------------------------------- /leetcode/Stack/print-immutable-linked-list-in-reverse.py: -------------------------------------------------------------------------------- 1 | # """ 2 | # This is the ImmutableListNode's API interface. 3 | # You should not implement it, or speculate about its implementation. 4 | # """ 5 | # class ImmutableListNode: 6 | # def printValue(self) -> None: # print the value of this node. 7 | # def getNext(self) -> 'ImmutableListNode': # return the next node. 8 | 9 | class Solution: 10 | def printLinkedListInReverse(self, head: 'ImmutableListNode') -> None: 11 | # https://leetcode.com/problems/print-immutable-linked-list-in-reverse/ 12 | st = [] 13 | node = head 14 | while node: 15 | st.append(node) 16 | node = node.getNext() 17 | while st: 18 | st.pop().printValue() 19 | -------------------------------------------------------------------------------- /leetcode/Stack/remove-outermost-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeOuterParentheses(self, S: str) -> str: 3 | # https://leetcode.com/problems/remove-outermost-parentheses/ 4 | st = [] 5 | a, b = '', '' 6 | for char in S: 7 | # print(char, a, b, st) 8 | if char == '(': 9 | a += char 10 | st.append(char) 11 | else: 12 | a += ')' 13 | st.pop() 14 | if st == []: 15 | b += a[1:-1] 16 | a = '' 17 | return b 18 | -------------------------------------------------------------------------------- /leetcode/Stack/simplify-path.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def simplifyPath(self, path: str) -> str: 3 | # https://leetcode.com/problems/simplify-path 4 | st = path.split('/') 5 | # print(st) 6 | st_new = [] 7 | for subpath in st: 8 | # print(subpath, subpath == '') 9 | if subpath == '' or subpath == '.': 10 | pass 11 | elif subpath == '..': 12 | if len(st_new) > 0: 13 | st_new.pop() 14 | else: 15 | st_new.append(subpath) 16 | # print(st_new) 17 | return '/'+'/'.join(st_new) 18 | 19 | -------------------------------------------------------------------------------- /leetcode/Stack/ternary-expression-parser.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def parseTernary(self, expression: str) -> str: 3 | # https://leetcode.com/problems/ternary-expression-parser/ 4 | while len(expression) != 1: 5 | print(expression) 6 | i = expression.rindex("?") # begin with the last '?'. 7 | tmp = expression[i+1] if expression[i-1] == 'T' else expression[i+3] 8 | expression = expression[:i-1] + tmp + expression[i+4:] 9 | return expression -------------------------------------------------------------------------------- /leetcode/Stack/valid-parantheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | # https://leetcode.com/problems/valid-parentheses/ 4 | stack = [] 5 | le = 0 6 | clos = {"}":"{", ")":"(", "]":"["} 7 | ope = ("{", "(", "[") 8 | for i in s: 9 | if i in ope: 10 | stack.append(i) 11 | le += 1 12 | elif le != 0 and stack[-1] != clos[i]: 13 | return False 14 | elif le != 0: 15 | stack.pop() 16 | le -=1 17 | else: 18 | return False 19 | return le == 0 -------------------------------------------------------------------------------- /leetcode/String/compare-version-numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def compareVersion(self, version1: str, version2: str) -> int: 3 | # https://leetcode.com/problems/compare-version-numbers/ 4 | version1 = version1.split('.') 5 | version2 = version2.split('.') 6 | le1, le2 = len(version1), len(version2) 7 | if le1 < le2: 8 | version1 += [0] * (le2 - le1) 9 | le1 = le2 10 | else: 11 | version2 += [0] * (le1 - le2) 12 | le2 = le1 13 | i,j = 0,0 14 | 15 | while i < le1 and j < le2: 16 | v1, v2 = int(version1[i]), int(version2[j]) 17 | # print(v1, v2) 18 | if v1 < v2: 19 | return -1 20 | elif v1 > v2: 21 | return 1 22 | i += 1 23 | j += 1 24 | return 0 25 | -------------------------------------------------------------------------------- /leetcode/String/complement-of-base-10-integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bitwiseComplement(self, N: int) -> int: 3 | # https://leetcode.com/problems/complement-of-base-10-integer/ 4 | bi = bin(N)[2:] 5 | bi = bi.replace('0','2') 6 | bi = bi.replace('1','0') 7 | bi = bi.replace('2','1') 8 | return int('0b'+bi, 2) 9 | -------------------------------------------------------------------------------- /leetcode/String/confusing-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def confusingNumber(self, N: int) -> bool: 3 | pairs = { 4 | # '2': '5', 5 | # '5': '2', 6 | '1': '1', 7 | '8': '8', 8 | '6': '9', 9 | '9': '6' 10 | } 11 | k = '' 12 | for i in str(N): 13 | if i in pairs: 14 | k = k + pairs[i] 15 | else: 16 | k = k + i 17 | return int(k) == N -------------------------------------------------------------------------------- /leetcode/String/custom-sort-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def customSortString(self, S, T): 3 | """ 4 | https://leetcode.com/problems/custom-sort-string/description/ 5 | :type S: str 6 | :type T: str 7 | :rtype: str 8 | """ 9 | 10 | di = {"q": float('inf'),"w": float('inf'),"e": float('inf'),"r": float('inf'),"t": float('inf'),"y": float('inf'),"u": float('inf'),"i": float('inf'),"o": float('inf'),"p": float('inf'),"a": float('inf'),"s": float('inf'),"d": float('inf'),"f": float('inf'),"g": float('inf'),"h": float('inf'),"j": float('inf'),"k": float('inf'),"l": float('inf'),"z": float('inf'),"x": float('inf'),"c": float('inf'),"v": float('inf'),"b": float('inf'),"n": float('inf'),"m": float('inf')} 11 | for i in range(len(S)): 12 | di[S[i]] = i 13 | return ''.join(sorted(T, key=lambda x: di[x])) 14 | -------------------------------------------------------------------------------- /leetcode/String/defanging-an-ip-address.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def defangIPaddr(self, address: str) -> str: 3 | # https://leetcode.com/problems/defanging-an-ip-address/ 4 | return address.replace('.','[.]') -------------------------------------------------------------------------------- /leetcode/String/delete-columns-to-make-sorted.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDeletionSize(self, A: List[str]) -> int: 3 | # https://leetcode.com/problems/delete-columns-to-make-sorted/ 4 | B = list(map(list,zip(*A))) 5 | answerCount = 0 6 | for i in range(len(B)): 7 | if B[i] != sorted(B[i]): 8 | answerCount+=1 9 | return answerCount 10 | def slowerString_minDeletionSize(self, A: List[str]) -> int: 11 | counter = 0 12 | for j in range(len(A[0])): 13 | prev = A[0][j] 14 | for i in range(1, len(A)): 15 | if A[i][j] < prev: 16 | counter += 1 17 | break 18 | prev = A[i][j] 19 | return counter 20 | -------------------------------------------------------------------------------- /leetcode/String/encode-and-decode-strings.py: -------------------------------------------------------------------------------- 1 | class Codec: 2 | # https://leetcode.com/problems/encode-and-decode-strings/ 3 | def encode(self, strs): 4 | """Encodes a list of strings to a single string. 5 | 6 | :type strs: List[str] 7 | :rtype: str 8 | """ 9 | if strs == []: 10 | return "-." 11 | return '+&*+'.join(strs) 12 | 13 | def decode(self, s): 14 | """Decodes a single string to a list of strings. 15 | 16 | :type s: str 17 | :rtype: List[str] 18 | """ 19 | if s == "-.": 20 | return [] 21 | return s.split('+&*+') 22 | 23 | 24 | # Your Codec object will be instantiated and called as such: 25 | # codec = Codec() 26 | # codec.decode(codec.encode(strs)) 27 | ["q?6?^7z5*","2_`Gw","+_D4-.3","-z5PU2="] 28 | ["q?6?^7z5*","2_`Gw+","_D4-.3","-z5PU2="] 29 | -------------------------------------------------------------------------------- /leetcode/String/find-and-replace-pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mapping(self, word1, word2): 3 | di = {} 4 | for i in range(len(word1)): 5 | if word1[i] in di and word2[i] != di[word1[i]]: 6 | return False 7 | else: 8 | di[word1[i]] = word2[i] 9 | word2, word1 = word1, word2 10 | di = {} 11 | for i in range(len(word1)): 12 | if word1[i] in di and word2[i] != di[word1[i]]: 13 | return False 14 | else: 15 | di[word1[i]] = word2[i] 16 | return True 17 | 18 | def findAndReplacePattern(self, words, pattern): 19 | """ 20 | https://leetcode.com/problems/find-and-replace-pattern/description/ 21 | :type words: List[str] 22 | :type pattern: str 23 | :rtype: List[str] 24 | """ 25 | a = [] 26 | for i in words: 27 | if self.mapping(i, pattern): 28 | a.append(i) 29 | return a 30 | -------------------------------------------------------------------------------- /leetcode/String/first-unique-character-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | https://leetcode.com/problems/first-unique-character-in-a-string/description/ 5 | :type s: str 6 | :rtype: int 7 | """ 8 | letters='abcdefghijklmnopqrstuvwxyz' 9 | index=[s.index(l) for l in letters if s.count(l) == 1] 10 | return min(index) if len(index) > 0 else -1 11 | -------------------------------------------------------------------------------- /leetcode/String/flip-game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generatePossibleNextMoves(self, s): 3 | """ 4 | https://leetcode.com/problems/flip-game/description/ 5 | :type s: str 6 | :rtype: List[str] 7 | """ 8 | result = [] 9 | for c in range(len(s)-1): 10 | res = "" 11 | if s[c] == s[c+1]: 12 | if s[c] == "+": 13 | res = s[:c]+"--"+s[c+2:] 14 | result.append(res) 15 | return result 16 | -------------------------------------------------------------------------------- /leetcode/String/goat-latin.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toGoatLatin(self, S): 3 | """ 4 | https://leetcode.com/problems/goat-latin/description/ 5 | :type S: str 6 | :rtype: str 7 | """ 8 | vowels = ['a','e','i','o','u','A','E','I','O','U'] 9 | words = S.split(" ") 10 | for i,v in enumerate(words): 11 | if v[0] in vowels: 12 | words[i] += "ma" + 'a'* (i + 1) 13 | else: 14 | temp = words[i][0] 15 | words[i] = words[i][1:] + temp + "ma" + 'a'* (i + 1) 16 | 17 | answer =' '.join(words) 18 | 19 | return answer 20 | -------------------------------------------------------------------------------- /leetcode/String/interleaving-string.py: -------------------------------------------------------------------------------- 1 | def isInterleave(s1, s2, s3): 2 | """ 3 | https://leetcode.com/problems/interleaving-string/description/ 4 | :type s1: str 5 | :type s2: str 6 | :type s3: str 7 | :rtype: bool 8 | """ 9 | k,i,j=0,0,0 10 | char=s3[k] 11 | if len(s3)!=len(s1)+len(s2): 12 | return False 13 | while k < len(s3): 14 | flag=True 15 | while i < len(s1) and k < len(s3) and s3[k] == s1[i]: 16 | char=s3[k] 17 | i += 1 18 | k += 1 19 | flag=False 20 | while j < len(s2) and k < len(s3) and s3[k] == s2[j]: 21 | char=s3[k] 22 | j += 1 23 | k += 1 24 | flag=False 25 | if flag: 26 | char=s3[k] 27 | k += 1 28 | else: 29 | break 30 | 31 | if i != len(s1) or j!= len(s2): 32 | return False 33 | return True 34 | -------------------------------------------------------------------------------- /leetcode/String/judge-route-circle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def judgeCircle(self, moves): 3 | """ 4 | https://leetcode.com/problems/judge-route-circle/description/ 5 | :type moves: str 6 | :rtype: bool 7 | """ 8 | ud , lr = 0, 0 9 | for char in moves: 10 | if char == "U": 11 | ud += 1 12 | elif char == "D": 13 | ud -= 1 14 | if char == "R": 15 | lr += 1 16 | elif char == "L": 17 | lr -= 1 18 | return ud == 0 and lr == 0 19 | -------------------------------------------------------------------------------- /leetcode/String/letter-combinations-of-a-phone-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | letters = [None, None, ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l'], ['m', 'n', 'o'], ['p', 'q', 'r', 's'], ['t', 'u', 'v'], ['w', 'x', 'y', 'z']] 3 | 4 | def letterCombinations(self, digits: str) -> List[str]: 5 | # https://leetcode.com/problems/letter-combinations-of-a-phone-number 6 | if not digits: return [] 7 | pre = Solution.letterCombinations(None, digits[:-1]) 8 | if pre == []: pre = [""] 9 | return [x + y for x in pre for y in Solution.letters[int(digits[-1])]] -------------------------------------------------------------------------------- /leetcode/String/longest-common-prefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def transpose(self, A: List[List[int]]) -> List[List[int]]: 3 | return list(zip(*A)) 4 | def longestCommonPrefix(self, strs: List[str]) -> str: 5 | # https://leetcode.com/problems/longest-common-prefix/description/ 6 | if strs == []: 7 | return "" 8 | l = [] 9 | for i in strs: 10 | l.append(list(i)) 11 | l = self.transpose(l) 12 | cnt = 0 13 | for i in map(lambda x: len(set(x)), l): 14 | if i == 1: 15 | cnt += 1 16 | else: 17 | break 18 | return strs[0][:cnt] -------------------------------------------------------------------------------- /leetcode/String/longest-uncommon-subsequence-i.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLUSlength(self, a, b): 3 | """ 4 | https://leetcode.com/problems/longest-uncommon-subsequence-i/description/ 5 | :type a: str 6 | :type b: str 7 | :rtype: int 8 | """ 9 | lea, leb = len(a), len(b) 10 | if lea != leb: 11 | return max(lea, leb) 12 | if a == b: 13 | return -1 14 | else: 15 | return lea 16 | -------------------------------------------------------------------------------- /leetcode/String/output-contest-matches.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findContestMatch(self, n): 3 | """ 4 | https://leetcode.com/problems/output-contest-matches/ 5 | :type n: int 6 | :rtype: str 7 | """ 8 | res = map(str, range(1, n+1)) 9 | while n > 1: 10 | res = ["(" + res[i] + "," + res[n-1-i] + ")" for i in range(n // 2)] 11 | n //= 2 12 | return res[0] 13 | -------------------------------------------------------------------------------- /leetcode/String/remove-vowels-from-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeVowels(self, S: str) -> str: 3 | # https://leetcode.com/problems/remove-vowels-from-a-string/ 4 | se = set(['a','e','i','o','u']) 5 | ans = '' 6 | for s in S: 7 | if s not in se: 8 | ans += s 9 | return ans -------------------------------------------------------------------------------- /leetcode/String/reorder-data-in-log-files.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def key(self, log): 3 | id, rest = log.split(" ", 1) 4 | return (0, rest, id) if rest[0].isalpha() else (1,) 5 | 6 | def reorderLogFiles(self, logs: List[str]) -> List[str]: 7 | # https://leetcode.com/problems/reorder-data-in-log-files/ 8 | return sorted(logs, key = self.key) -------------------------------------------------------------------------------- /leetcode/String/reverse-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseString(self, s): 3 | """ 4 | https://leetcode.com/problems/reverse-string/description/ 5 | :type s: str 6 | :rtype: str 7 | """ 8 | return s[::-1] 9 | -------------------------------------------------------------------------------- /leetcode/String/reverse-vowels.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseVowels(self, s): 3 | """ 4 | https://leetcode.com/problems/reverse-vowels-of-a-string/description/ 5 | :type s: str 6 | :rtype: str 7 | """ 8 | vowels="" 9 | not_vowels="" 10 | reversed_vowels="" 11 | for letter in s: 12 | if letter.upper() in "AEIOU": 13 | vowels += letter 14 | else: 15 | not_vowels += letter 16 | i=len(vowels)-1 17 | j=0 18 | for letter in s: 19 | if letter.upper() in "AEIOU": 20 | reversed_vowels += vowels[i] 21 | i -= 1 22 | else: 23 | reversed_vowels += not_vowels[j] 24 | j += 1 25 | return(reversed_vowels) 26 | -------------------------------------------------------------------------------- /leetcode/String/single-row-keyboard.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calculateTime(self, keyboard: str, word: str) -> int: 3 | # https://leetcode.com/problems/single-row-keyboard/ 4 | di = {} 5 | for i, char in enumerate(keyboard): 6 | di[char] = i 7 | ans = 0 8 | pos = 0 9 | for char in word: 10 | ans += abs(di[char] - pos) 11 | pos = di[char] 12 | return ans -------------------------------------------------------------------------------- /leetcode/String/split-a-string-in-balanced-strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def balancedStringSplit(self, s: str) -> int: 3 | # https://leetcode.com/problems/split-a-string-in-balanced-strings/ 4 | i = 0 5 | ans = 0 6 | for move in s: 7 | if move == 'L': 8 | i += 1 9 | if move == 'R': 10 | i -= 1 11 | if i == 0: 12 | ans += 1 13 | return ans -------------------------------------------------------------------------------- /leetcode/String/string-compression.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def compress(self, chars: List[str]) -> int: 3 | # https://leetcode.com/problems/string-compression/submissions/ 4 | i, j= 0, 0 5 | while i < len(chars): 6 | char = chars[i] 7 | chars[j] = char 8 | j += 1 9 | # capture the multiple numbers 10 | count = 1 11 | while i+1 < len(chars) and char == chars[i+1]: 12 | i += 1 13 | count += 1 14 | if count > 1: 15 | for num in str(count): 16 | chars[j] = num 17 | j += 1 18 | i += 1 19 | return j -------------------------------------------------------------------------------- /leetcode/String/to-lower-case.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toLowerCase(self, st): 3 | """ 4 | https://leetcode.com/problems/to-lower-case/description/ 5 | :type str: str 6 | :rtype: str 7 | """ 8 | return st.lower() 9 | -------------------------------------------------------------------------------- /leetcode/String/unique-morse-code-words.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniqueMorseRepresentations(self, words): 3 | """ 4 | https://leetcode.com/problems/unique-morse-code-words/description/ 5 | :type words: List[str] 6 | :rtype: int 7 | """ 8 | a = set() 9 | for word in words: 10 | k = "" 11 | mapping = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 12 | for i in s: 13 | k += mapping[ord(i) - 97] 14 | a.add(k) 15 | return len(a) 16 | -------------------------------------------------------------------------------- /leetcode/String/valid-palindrome-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validPalindrome(self, s): 3 | """ 4 | https://leetcode.com/problems/valid-palindrome-ii/description/ 5 | :type s: str 6 | :rtype: bool 7 | """ 8 | left, right = 0, len(s) - 1 9 | while left < right: 10 | if s[left] != s[right]: 11 | one, two = s[left:right], s[left + 1:right + 1] 12 | return one == one[::-1] or two == two[::-1] 13 | left, right = left + 1, right - 1 14 | return True 15 | 16 | 17 | -------------------------------------------------------------------------------- /leetcode/String/zigzag-conversion.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convert(self, s: str, numRows: int) -> str: 3 | # https://leetcode.com/problems/zigzag-conversion/ 4 | if numRows<=1: return s 5 | ans=[""]*numRows 6 | i=0 7 | for c in s: 8 | ans[i]+=c 9 | if i==numRows-1: 10 | d=-1 11 | if i==0: 12 | d=1 13 | i+=d 14 | return ''.join(ans) -------------------------------------------------------------------------------- /leetcode/Tree/average-of-levels-in-binary-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def averageOfLevels(self, root): 3 | """ 4 | https://leetcode.com/problems/average-of-levels-in-binary-tree/description/ 5 | :type root: TreeNode 6 | :rtype: List[float] 7 | """ 8 | if not root: 9 | return [] 10 | ans, level = [], [root] 11 | while level: 12 | ans.append([node.val for node in level]) 13 | temp = [] 14 | for node in level: 15 | temp.extend([node.left, node.right]) 16 | level = [leaf for leaf in temp if leaf] 17 | # print(ans, temp, level) 18 | k = [] 19 | for i in ans: 20 | k.append(sum(i)/len(i)) 21 | return k 22 | -------------------------------------------------------------------------------- /leetcode/Tree/balanced-binary-tree.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isBalanced(self, root): 3 | """ 4 | https://leetcode.com/problems/balanced-binary-tree/description/ 5 | :type root: TreeNode 6 | :rtype: bool 7 | """ 8 | def check(root): 9 | if root is None: 10 | return 0 11 | left = check(root.left) 12 | right = check(root.right) 13 | if left == -1 or right == -1 or abs(left - right) > 1: 14 | return -1 15 | return 1 + max(left, right) 16 | 17 | return check(root) != -1 18 | -------------------------------------------------------------------------------- /leetcode/Tree/binary-search-tree-to-greater-sum-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def bstToGst(self, root: TreeNode) -> TreeNode: 10 | # https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ 11 | self.a = 0 12 | self.inorder(root) 13 | return root 14 | def inorder(self, root): 15 | if not root: 16 | return 17 | self.inorder(root.right) 18 | root.val += self.a 19 | self.a = root.val 20 | self.inorder(root.left) -------------------------------------------------------------------------------- /leetcode/Tree/binary-tree-coloring-game.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool: 10 | # https://leetcode.com/problems/binary-tree-coloring-game/ 11 | c = [0, 0] 12 | def count(node): 13 | if not node: return 0 14 | l, r = count(node.left), count(node.right) 15 | if node.val == x: 16 | c[0], c[1] = l, r 17 | return l + r + 1 18 | return count(root) / 2 < max(max(c), n - sum(c) - 1) -------------------------------------------------------------------------------- /leetcode/Tree/binary-tree-inorder-traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def inorderTraversal(self, root): 10 | """ 11 | https://leetcode.com/problems/binary-tree-inorder-traversal/description/ 12 | :type root: TreeNode 13 | :rtype: List[int] 14 | """ 15 | res, stack = [], [] 16 | while True: 17 | while root: 18 | stack.append(root) 19 | root = root.left 20 | if not stack: 21 | return res 22 | node = stack.pop() 23 | res.append(node.val) 24 | root = node.right 25 | -------------------------------------------------------------------------------- /leetcode/Tree/binary-tree-level-order-traversal-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def levelOrderBottom(self, root): 3 | """ 4 | https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/ 5 | :type root: TreeNode 6 | :rtype: List[List[int]] 7 | """ 8 | if not root: 9 | return [] 10 | ans, level = [], [root] 11 | while level: 12 | ans.append([node.val for node in level]) 13 | temp = [] 14 | for node in level: 15 | temp.extend([node.left, node.right]) 16 | level = [leaf for leaf in temp if leaf] 17 | # print(ans, temp, level) 18 | return ans[::-1] 19 | -------------------------------------------------------------------------------- /leetcode/Tree/binary-tree-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def levelOrder(self, root): 3 | """ 4 | https://leetcode.com/problems/binary-tree-level-order-traversal/description/ 5 | :type root: TreeNode 6 | :rtype: List[List[int]] 7 | """ 8 | if not root: 9 | return [] 10 | ans, level = [], [root] 11 | while level: 12 | ans.append([node.val for node in level]) 13 | temp = [] 14 | for node in level: 15 | temp.extend([node.left, node.right]) 16 | level = [leaf for leaf in temp if leaf] 17 | # print(ans, temp, level) 18 | return ans 19 | -------------------------------------------------------------------------------- /leetcode/Tree/binary-tree-paths.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def binaryTreePaths(self, root): 10 | """ 11 | https://leetcode.com/problems/binary-tree-paths/description/ 12 | :type root: TreeNode 13 | :rtype: List[str] 14 | """ 15 | if not root: 16 | return [] 17 | res, stack = [], [(root, "")] 18 | while stack: 19 | node, ls = stack.pop() 20 | if not node.left and not node.right: 21 | res.append(ls+str(node.val)) 22 | if node.right: 23 | stack.append((node.right, ls+str(node.val)+"->")) 24 | if node.left: 25 | stack.append((node.left, ls+str(node.val)+"->")) 26 | return res 27 | -------------------------------------------------------------------------------- /leetcode/Tree/binary-tree-postorder-traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def postorderTraversal(self, root): 10 | """ 11 | https://leetcode.com/problems/binary-tree-postorder-traversal/description/ 12 | :type root: TreeNode 13 | :rtype: List[int] 14 | """ 15 | traversal, stack = [], [root] 16 | while stack: 17 | node = stack.pop() 18 | if node: 19 | # pre-order, right first 20 | traversal.append(node.val) 21 | stack.append(node.left) 22 | stack.append(node.right) 23 | 24 | # reverse result 25 | return traversal[::-1] 26 | 27 | -------------------------------------------------------------------------------- /leetcode/Tree/binary-tree-preorder-traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def preorderTraversal(self, root): 10 | """ 11 | https://leetcode.com/problems/binary-tree-preorder-traversal/description/ 12 | :type root: TreeNode 13 | :rtype: List[int] 14 | """ 15 | 16 | res = [] 17 | self.dfs(root, res) 18 | return res 19 | 20 | def dfs(self, root, res): 21 | if root: 22 | res.append(root.val) 23 | self.dfs(root.left, res) 24 | self.dfs(root.right, res) 25 | -------------------------------------------------------------------------------- /leetcode/Tree/binary-tree-pruning.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def pruneTree(self, root): 10 | """ 11 | https://leetcode.com/problems/binary-tree-pruning/description/ 12 | :type root: TreeNode 13 | :rtype: TreeNode 14 | """ 15 | if not root: 16 | return [] 17 | if root.left: 18 | root.left = self.pruneTree(root.left) 19 | if root.right: 20 | root.right = self.pruneTree(root.right) 21 | if root.left == None and root.right == None and root.val == 0: 22 | root = None 23 | return root 24 | 25 | -------------------------------------------------------------------------------- /leetcode/Tree/binary-tree-zigzag-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def zigzagLevelOrder(self, root): 3 | """ 4 | https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/ 5 | :type root: TreeNode 6 | :rtype: List[List[int]] 7 | """ 8 | if not root: 9 | return [] 10 | ans, level = [], [root] 11 | while level: 12 | ans.append([node.val for node in level]) 13 | temp = [] 14 | for node in level: 15 | temp.extend([node.left, node.right]) 16 | level = [leaf for leaf in temp if leaf] 17 | for i in range(len(ans)): 18 | if i%2 == 1: 19 | ans[i] = ans[i][::-1] 20 | return ans 21 | -------------------------------------------------------------------------------- /leetcode/Tree/closest-binary-search-tree-value.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def closestValue(self, root, target): 10 | """ 11 | https://leetcode.com/problems/closest-binary-search-tree-value/description/ 12 | :type root: TreeNode 13 | :type target: float 14 | :rtype: int 15 | """ 16 | r = root.val 17 | while root: 18 | if abs(root.val - target) < abs(r - target): 19 | r = root.val 20 | root = root.left if target < root.val else root.right 21 | return r 22 | -------------------------------------------------------------------------------- /leetcode/Tree/deepest-leaves-sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def deepestLeavesSum(self, root: TreeNode) -> int: 10 | # https://leetcode.com/problems/deepest-leaves-sum/ 11 | if not root: 12 | return 0 13 | ans, level = [], [root] 14 | while level: 15 | ans.append([node.val for node in level]) 16 | temp = [] 17 | for node in level: 18 | temp.extend([node.left, node.right]) 19 | level = [leaf for leaf in temp if leaf] 20 | # print(ans, temp, level) 21 | return sum(ans[-1]) -------------------------------------------------------------------------------- /leetcode/Tree/find-bottom-left-tree-value.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def findBottomLeftValue(self, root): 10 | """ 11 | https://leetcode.com/problems/find-bottom-left-tree-value/description/ 12 | :type root: TreeNode 13 | :rtype: int 14 | """ 15 | if not root: 16 | return None 17 | ans, level = [], [root] 18 | while level: 19 | ans.append([node.val for node in level]) 20 | temp = [] 21 | for node in level: 22 | temp.extend([node.left, node.right]) 23 | level = [leaf for leaf in temp if leaf] 24 | # print(ans, temp, level) 25 | return ans[-1][0] 26 | -------------------------------------------------------------------------------- /leetcode/Tree/find-largest-value-in-each-tree-row.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def largestValues(self, root): 10 | """ 11 | https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/ 12 | :type root: TreeNode 13 | :rtype: List[int] 14 | """ 15 | if not root: 16 | return [] 17 | ans, level = [], [root] 18 | while level: 19 | ans.append([node.val for node in level]) 20 | temp = [] 21 | for node in level: 22 | temp.extend([node.left, node.right]) 23 | level = [leaf for leaf in temp if leaf] 24 | # print(ans, temp, level) 25 | k = [] 26 | for i in ans: 27 | k.append(max(i)) 28 | return k 29 | -------------------------------------------------------------------------------- /leetcode/Tree/find-leaves-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def dfs(self, node): 10 | if not node: 11 | return -1 12 | i = max(self.dfs(node.left), self.dfs(node.right)) + 1 13 | if i >= len(self.res): 14 | self.res.append([]) 15 | self.res[i].append(node.val) 16 | return i 17 | def findLeaves(self, root): 18 | """ 19 | https://leetcode.com/problems/find-leaves-of-binary-tree/description/ 20 | :type root: TreeNode 21 | :rtype: List[List[int]] 22 | """ 23 | self.res = [] 24 | self.dfs(root) 25 | return self.res 26 | 27 | -------------------------------------------------------------------------------- /leetcode/Tree/invert-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def invertTree(self, root): 10 | """ 11 | https://leetcode.com/problems/invert-binary-tree/description/ 12 | :type root: TreeNode 13 | :rtype: TreeNode 14 | """ 15 | if root: 16 | root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) 17 | return root 18 | -------------------------------------------------------------------------------- /leetcode/Tree/kill-process.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def killProcess(self, pid, ppid, kill): 3 | """ 4 | https://leetcode.com/problems/kill-process/description/ 5 | :type pid: List[int] 6 | :type ppid: List[int] 7 | :type kill: int 8 | :rtype: List[int] 9 | """ 10 | l = {} 11 | for i in range(len(ppid)): 12 | k = l.get(ppid[i], []) 13 | k.append(pid[i]) 14 | l[ppid[i]] = k 15 | ret = [kill] 16 | for i in ret: 17 | ret.extend(l.get(i,[])) 18 | return ret 19 | -------------------------------------------------------------------------------- /leetcode/Tree/kth-smallest-element-in-a-bst.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def kthSmallest(self, root, k): 3 | """ 4 | https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ 5 | :type root: TreeNode 6 | :type k: int 7 | :rtype: int 8 | """ 9 | if not root: 10 | return [] 11 | ans, level = [], [root] 12 | while level: 13 | ans.append([node.val for node in level]) 14 | temp = [] 15 | for node in level: 16 | temp.extend([node.left, node.right]) 17 | level = [leaf for leaf in temp if leaf] 18 | li = [] 19 | for i in ans: 20 | li.extend(i) 21 | # print(sorted(li)) 22 | return sorted(li)[k-1] 23 | 24 | -------------------------------------------------------------------------------- /leetcode/Tree/leaf-similar-trees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def generateLeafSequence(self, root): 10 | """ 11 | https://leetcode.com/problems/leaf-similar-trees/description/ 12 | :type root: TreeNode 13 | :rtype: List[int] 14 | """ 15 | l1 = [] 16 | st = [] 17 | while root or st: 18 | while root: 19 | st.append(root) 20 | root = root.left 21 | 22 | top = st.pop() 23 | if not top.left and not top.right: 24 | l1.append(top.val) 25 | root = top.right 26 | return l1 27 | def leafSimilar(self, root1, root2): 28 | """ 29 | :type root1: TreeNode 30 | :type root2: TreeNode 31 | :rtype: bool 32 | """ 33 | return self.generateLeafSequence(root1) == self.generateLeafSequence(root2) 34 | 35 | -------------------------------------------------------------------------------- /leetcode/Tree/lowest-common-ancestor-of-a-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 10 | # https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ 11 | if root is None: 12 | return None 13 | if root == p or root == q: 14 | # print('O', root.val, p.val, q.val) 15 | return root 16 | left = self.lowestCommonAncestor(root.left, p, q) 17 | right = self.lowestCommonAncestor(root.right, p, q) 18 | 19 | if left is not None and right is None: 20 | # print('L', left.val, p.val, q.val) 21 | return left 22 | elif right is not None and left is None: 23 | # print('R', right.val, p.val, q.val) 24 | return right 25 | elif left is not None and right is not None: 26 | return root 27 | -------------------------------------------------------------------------------- /leetcode/Tree/maximum-binary-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def constructMaximumBinaryTree(self, nums): 3 | """ 4 | https://leetcode.com/problems/maximum-binary-tree/description/ 5 | :type nums: List[int] 6 | :rtype: TreeNode 7 | """ 8 | if not nums: return None 9 | max_n = max(nums) 10 | max_i = nums.index(max_n) 11 | lnums = nums[:max_i] 12 | rnums = nums[max_i+1:] 13 | node = TreeNode(max_n) 14 | node.left = self.constructMaximumBinaryTree(lnums) 15 | node.right = self.constructMaximumBinaryTree(rnums) 16 | return node 17 | -------------------------------------------------------------------------------- /leetcode/Tree/maximum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def maxDepth(self, root): 10 | """ 11 | https://leetcode.com/problems/maximum-depth-of-binary-tree/description/ 12 | :type root: TreeNode 13 | :rtype: int 14 | """ 15 | if root == None: 16 | return 0 17 | ans, level = 0, [root] 18 | while level: 19 | ans += 1 20 | temp = [] 21 | for node in level: 22 | temp.extend([node.left, node.right]) 23 | level = [node for node in temp if node] 24 | return ans 25 | 26 | -------------------------------------------------------------------------------- /leetcode/Tree/maximum-level-sum-of-a-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def maxLevelSum(self, root: TreeNode) -> int: 10 | # https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/ 11 | if not root: 12 | return [] 13 | _ans, level = [], [root] 14 | while level: 15 | _ans.append([node.val for node in level]) 16 | temp = [] 17 | for node in level: 18 | temp.extend([node.left, node.right]) 19 | level = [leaf for leaf in temp if leaf] 20 | ans = -1 21 | ma = -float('inf') 22 | _ans = list(map(sum, _ans)) 23 | # print(_ans) 24 | for i, x in enumerate(_ans): 25 | if x > ma: 26 | ans = i 27 | ma = x 28 | return ans + 1 -------------------------------------------------------------------------------- /leetcode/Tree/merge-two-binary-trees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def mergeTrees(self, t1, t2): 10 | """ 11 | https://leetcode.com/problems/merge-two-binary-trees/description/ 12 | :type t1: TreeNode 13 | :type t2: TreeNode 14 | :rtype: TreeNode 15 | """ 16 | if t1 and t2: 17 | root = TreeNode(t1.val + t2.val) 18 | root.left = self.mergeTrees(t1.left, t2.left) 19 | root.right = self.mergeTrees(t1.right, t2.right) 20 | return root 21 | else: 22 | return t1 or t2 23 | -------------------------------------------------------------------------------- /leetcode/Tree/minimum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def minDepth(self, root): 10 | """ 11 | https://leetcode.com/problems/minimum-depth-of-binary-tree/description/ 12 | :type root: TreeNode 13 | :rtype: int 14 | """ 15 | if root == None: 16 | return 0 17 | if root.left==None or root.right==None: 18 | return self.minDepth(root.left)+self.minDepth(root.right)+1 19 | return min(self.minDepth(root.right),self.minDepth(root.left))+1 20 | 21 | -------------------------------------------------------------------------------- /leetcode/Tree/n-ary-tree-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node(object): 4 | def __init__(self, val, children): 5 | self.val = val 6 | self.children = children 7 | """ 8 | class Solution(object): 9 | def levelOrder(self, root): 10 | """ 11 | :type root: Node 12 | :rtype: List[List[int]] 13 | """ 14 | if not root: 15 | return [] 16 | ans, level = [], [root] 17 | while level: 18 | ans.append([node.val for node in level]) 19 | level = [child for node in level for child in node.children] 20 | return ans 21 | -------------------------------------------------------------------------------- /leetcode/Tree/n-ary-tree-postorder-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val, children): 5 | self.val = val 6 | self.children = children 7 | """ 8 | class Solution: 9 | def postorder(self, root: 'Node') -> List[int]: 10 | res = [] 11 | 12 | stack = [root] 13 | 14 | while stack: 15 | top = stack[-1] 16 | if top is None: 17 | stack.pop() 18 | continue 19 | if not top.children: 20 | res.append(top.val) 21 | stack.pop() 22 | continue 23 | 24 | stack.append(top.children.pop(0)) 25 | 26 | return res 27 | 28 | def recursive_N_ary_postorder(self, root: 'Node') -> List[int]: 29 | if not root: 30 | return [] 31 | ans = [] 32 | for child in root.children: 33 | ans.extend(self.postorder(child)) 34 | ans.append(root.val) 35 | return ans 36 | -------------------------------------------------------------------------------- /leetcode/Tree/n-ary-tree-preorder-traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val, children): 5 | self.val = val 6 | self.children = children 7 | """ 8 | from typing import List 9 | class Solution: 10 | # https://leetcode.com/problems/n-ary-tree-preorder-traversal/ 11 | def preorder(self, root: 'Node') -> List[int]: 12 | ret, q = [], root and [root] 13 | while q: 14 | node = q.pop() 15 | ret.append(node.val) 16 | q += [child for child in reversed(node.children)] 17 | return ret 18 | def recursive_N_ary_preorder(self, root: 'Node') -> List[int]: 19 | if not root: 20 | return [] 21 | ans = [root.val] 22 | for child in root.children: 23 | ans.extend(self.preorder(child)) 24 | return ans 25 | -------------------------------------------------------------------------------- /leetcode/Tree/second-minimum-node-in-a-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def findSecondMinimumValue(self, root): 10 | """ 11 | https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/ 12 | :type root: TreeNode 13 | :rtype: int 14 | """ 15 | if not root: 16 | return [] 17 | ans, level = [], [root] 18 | while level: 19 | ans.extend([node.val for node in level]) 20 | temp = [] 21 | for node in level: 22 | temp.extend([node.left, node.right]) 23 | level = [leaf for leaf in temp if leaf] 24 | # print(ans, temp, level) 25 | try: 26 | return sorted(set(ans))[1] 27 | except: 28 | return -1 29 | -------------------------------------------------------------------------------- /leetcode/Tree/univalued-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def isUnivalTree(self, root: TreeNode) -> bool: 10 | # https://leetcode.com/problems/univalued-binary-tree 11 | bo = True 12 | val = root.val 13 | level = [root] 14 | while level: 15 | temp = [] 16 | for node in level: 17 | if node.val != val: 18 | return False 19 | if node.left: 20 | temp.append(node.left) 21 | if node.right: 22 | temp.append(node.right) 23 | level = temp 24 | return True 25 | -------------------------------------------------------------------------------- /leetcode/Trie/map-sum-pairs.py: -------------------------------------------------------------------------------- 1 | class MapSum(object): 2 | # https://leetcode.com/problems/map-sum-pairs/description/ 3 | def __init__(self): 4 | """ 5 | Initialize your data structure here. 6 | """ 7 | self.di = {} 8 | 9 | def insert(self, key, val): 10 | """ 11 | :type key: str 12 | :type val: int 13 | :rtype: void 14 | """ 15 | self.di[key] = val 16 | 17 | 18 | def sum(self, prefix): 19 | """ 20 | :type prefix: str 21 | :rtype: int 22 | """ 23 | count = 0 24 | for i in self.di: 25 | if i.startswith(prefix): 26 | count += self.di[i] 27 | return count 28 | 29 | 30 | 31 | # Your MapSum object will be instantiated and called as such: 32 | # obj = MapSum() 33 | # obj.insert(key,val) 34 | # param_2 = obj.sum(prefix) 35 | -------------------------------------------------------------------------------- /leetcode/Two-Pointers/linked-list-cycle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hasCycle(self, head): 3 | """ 4 | :type head: ListNode 5 | :rtype: bool 6 | """ 7 | try: 8 | slow = head 9 | fast = head.next 10 | while slow is not fast: 11 | slow = slow.next 12 | fast = fast.next.next 13 | return True 14 | except: 15 | return False 16 | -------------------------------------------------------------------------------- /leetcode/Two-Pointers/middle-of-the-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def middleNode(self, head): 9 | """ 10 | https://leetcode.com/problems/middle-of-the-linked-list/description/ 11 | :type head: ListNode 12 | :rtype: ListNode 13 | """ 14 | x1, x2 = head, head 15 | while x2 and x2.next: 16 | x1 = x1.next 17 | x2 = x2.next.next 18 | # print(x1.val, x2.val) 19 | return x1 20 | -------------------------------------------------------------------------------- /leetcode/Two-Pointers/remove-nth-node-from-end-of-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 9 | # https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 10 | newHead = ListNode(0) 11 | newHead.next = head 12 | x1, x2 = newHead, newHead 13 | 14 | for i in range(n): 15 | x2 = x2.next 16 | 17 | while x2 and x2.next: 18 | x2 = x2.next 19 | x1 = x1.next 20 | 21 | x1.next = x1.next.next 22 | 23 | return newHead.next -------------------------------------------------------------------------------- /leetcode/Two-Pointers/reverse-vowels-of-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseVowels(self, s: str) -> str: 3 | # https://leetcode.com/problems/reverse-vowels-of-a-string/ 4 | vowels = set(['a','e','i','o','u', 'A', 'E', 'I', 'O', 'U']) 5 | s = list(s) 6 | front, back = 0, len(s) - 1 7 | while front < back: 8 | # print(front, back, s[front], s[back]) 9 | if s[front] in vowels and s[back] in vowels: 10 | s[back], s[front] = s[front], s[back] 11 | front+=1 12 | back-=1 13 | if s[back] not in vowels: 14 | back-=1 15 | if s[front] not in vowels: 16 | front+=1 17 | return ''.join(s) -------------------------------------------------------------------------------- /leetcode/Two-Pointers/valid-palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, s: str) -> bool: 3 | # https://leetcode.com/problems/valid-palindrome/ 4 | l, r = 0, len(s)-1 5 | while l < r: 6 | while l < r and not s[l].isalnum(): 7 | l += 1 8 | while l int: 3 | # https://leetcode.com/problems/longest-consecutive-sequence/ 4 | longest_streak = 0 5 | num_set = set(nums) 6 | 7 | for num in num_set: 8 | if num - 1 not in num_set: 9 | current_num = num 10 | current_streak = 1 11 | 12 | while current_num + 1 in num_set: 13 | current_num += 1 14 | current_streak += 1 15 | 16 | longest_streak = max(longest_streak, current_streak) 17 | 18 | return longest_streak -------------------------------------------------------------------------------- /leetcode/Unsorted/battleships-in-a-board.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBattleships(self, board): 3 | """ 4 | https://leetcode.com/problems/battleships-in-a-board/description/ 5 | :type board: List[List[str]] 6 | :rtype: int 7 | """ 8 | count = 0 9 | for i in range(len(board)): 10 | for j in range(len(board[0])): 11 | if board[i][j] == "X" and (i == 0 or board[i-1][j] == ".") and (j == 0 or board[i][j-1] == "."): 12 | count += 1 13 | return count 14 | -------------------------------------------------------------------------------- /leetcode/Unsorted/diagonal-traverse.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: 3 | # https://leetcode.com/problems/diagonal-traverse/ 4 | if matrix == []: 5 | return [] 6 | di = {} 7 | suList = [] 8 | r = len(matrix) 9 | c = len(matrix[0]) 10 | for i in range(r): 11 | # print(matrix[i]) 12 | for j in range(c): 13 | if i+j in di: 14 | di[i+j].append(matrix[i][j]) 15 | else: 16 | di[i+j] = [matrix[i][j]] 17 | ans = [] 18 | for k in range(r+c-1): 19 | if k%2 == 0: 20 | ans.extend(di[k][::-1]) 21 | else: 22 | ans.extend(di[k]) 23 | return ans -------------------------------------------------------------------------------- /leetcode/Unsorted/license-key-formatting.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def licenseKeyFormatting(self, S, K): 3 | """ 4 | :type S: str 5 | :type K: int 6 | :rtype: str 7 | """ 8 | # return '-'.join(list(filter(None, [("").join(S.split("-")).upper()[::-1][i:i+K][::-1] for i in range(0, len(S), K)][::-1]))) 9 | 10 | S = S.upper().replace('-','') 11 | size = len(S) 12 | s1 = K if size%K==0 else size%K 13 | res = S[:s1] 14 | while s1 100 - currentLine: 12 | lineCount += 1 13 | currentLine = widths[ord(i) - 97] 14 | else: 15 | currentLine += widths[ord(i) - 97] 16 | if currentLine: 17 | lineCount += 1 18 | return [lineCount, currentLine] 19 | -------------------------------------------------------------------------------- /leetcode/Unsorted/permutationSequence.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def getPermutation(n, k): 4 | """ 5 | :type n: int 6 | :type k: int 7 | :rtype: str 8 | """ 9 | i=1 10 | numString="" 11 | while i <= n: 12 | numString += str(i) 13 | i += 1 14 | 15 | perms = list(permutations(numString)) 16 | return str(''.join(perms[k-1])) 17 | print(getPermutation(3,4)) 18 | -------------------------------------------------------------------------------- /leetcode/Unsorted/random.py: -------------------------------------------------------------------------------- 1 | x = 23 2 | epsilon = 0.01 3 | step = 0.1 4 | guess = 0.0 5 | 6 | while abs(guess**2-x) >= epsilon: 7 | if guess <= x: 8 | guess += step 9 | else: 10 | break 11 | 12 | if abs(guess**2 - x) >= epsilon: 13 | print('failed') 14 | else: 15 | print('succeeded: ' + str(guess)) 16 | -------------------------------------------------------------------------------- /leetcode/Unsorted/relative-ranks.py: -------------------------------------------------------------------------------- 1 | def findRelativeRanks(nums): 2 | """ 3 | https://leetcode.com/problems/relative-ranks/#/description 4 | :type nums: List[int] 5 | :rtype: List[str] 6 | """ 7 | return_list = nums[:] 8 | nums.sort(reverse = True) 9 | return_list[return_list.index(nums[0])], return_list[return_list.index(nums[1])], return_list[return_list.index(nums[2])] = "Gold Medal", "Silver Medal", "Bronze Medal" 10 | 11 | for i in range(len(nums)-3): 12 | return_list[return_list.index(nums[i+3])] = str(i+4) 13 | return return_list 14 | 15 | print(findRelativeRanks([5, 4, 3, 2, 1])) 16 | -------------------------------------------------------------------------------- /leetcode/Unsorted/reverse-only-letters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseOnlyLetters(self, S): 3 | """ 4 | https://leetcode.com/problems/reverse-only-letters/description/ 5 | :type S: str 6 | :rtype: str 7 | """ 8 | if S == "": 9 | return "" 10 | S = list(S) 11 | i, j = 0, len(S) - 1 12 | while i < j: 13 | if S[i].isalpha() == False: 14 | i += 1 15 | elif S[j].isalpha() == False: 16 | j -= 1 17 | else: 18 | S[i], S[j] = S[j], S[i] 19 | i += 1 20 | j -= 1 21 | return ''.join(S) 22 | -------------------------------------------------------------------------------- /leetcode/Unsorted/reverse_words_not_string.py: -------------------------------------------------------------------------------- 1 | def reverse_words_not_string(s): 2 | words=s.split() 3 | final_string="" 4 | for i in range(len(words)): 5 | if i!=len(words)-1: 6 | final_string=final_string+words[i][::-1]+" " 7 | else: 8 | final_string=final_string+words[i][::-1] 9 | return final_string 10 | 11 | s="Let's take LeetCode contest" 12 | print(reverse_words_not_string(s)) 13 | -------------------------------------------------------------------------------- /leetcode/Unsorted/smallest-range-i.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def smallestRangeI(self, A, K): 3 | """ 4 | https://leetcode.com/problems/smallest-range-i/description/ 5 | :type A: List[int] 6 | :type K: int 7 | :rtype: int 8 | """ 9 | ma, mi = -float('inf'), float('inf') 10 | for i in A: 11 | ma = max(ma, i) 12 | mi = min(mi, i) 13 | return max(ma - mi - 2 *K, 0) 14 | -------------------------------------------------------------------------------- /leetcode/Unsorted/unique-email-addresses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numUniqueEmails(self, emails): 3 | """ 4 | https://leetcode.com/problems/unique-email-addresses/description/ 5 | :type emails: List[str] 6 | :rtype: int 7 | """ 8 | unique = set() 9 | 10 | for email in emails: 11 | user, domain = email.split("@") 12 | user = user.split("+")[0].replace(".", "") 13 | unique.add(user+domain) 14 | 15 | 16 | return len(unique) 17 | -------------------------------------------------------------------------------- /leetcode/Unsorted/unique-morse-code-words.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniqueMorseRepresentations(self, words): 3 | """ 4 | https://leetcode.com/problems/unique-morse-code-words/description/ 5 | :type words: List[str] 6 | :rtype: int 7 | """ 8 | def morse(s): 9 | k = "" 10 | di = {'a': '.-', 'c': '-.-.', 'b': '-...', 'e': '.', 'd': '-..', 'g': '--.', 'f': '..-.', 'i': '..', 'h': '....', 'k': '-.-', 'j': '.---', 'm': '--', 'l': '.-..', 'o': '---', 'n': '-.', 'q': '--.-', 'p': '.--.', 's': '...', 'r': '.-.', 'u': '..-', 't': '-', 'w': '.--', 'v': '...-', 'y': '-.--', 'x': '-..-', 'z': '--..'} 11 | for i in s: 12 | k += di[str(i)] 13 | return k 14 | return len(set(map(morse, words))) 15 | -------------------------------------------------------------------------------- /leetcode/Virtual-Contest/71/1.txt: -------------------------------------------------------------------------------- 1 | [2,2,6,1,3,null,null] -------------------------------------------------------------------------------- /leetcode/Virtual-Contest/71/2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numRabbits(self, answers: List[int]) -> int: 3 | cnt = collections.Counter() 4 | for answer in answers: 5 | cnt[answer] += 1 6 | ret = cnt.get(0, 0) 7 | # print(cnt) 8 | for key in cnt: 9 | if key == 0: 10 | continue 11 | else: 12 | ret += (key + 1)*math.ceil((cnt[key]/(key+1))) 13 | return ret -------------------------------------------------------------------------------- /leetcode/Virtual-Contest/71/3.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool: 3 | while tx > 0 and ty > 0 and tx != ty and (tx > sx or ty > sy): 4 | if tx > ty: 5 | k = (tx - sx) // ty 6 | tx -= k*ty 7 | else: 8 | k = (ty - sy) // tx 9 | ty -= k*tx 10 | if k < 1: 11 | return False 12 | 13 | if tx == sx and ty == sy: 14 | return True 15 | if tx == ty and ((sx == 0 and sy == tx) or (sy == 0 and sx == tx)): 16 | return True 17 | return False -------------------------------------------------------------------------------- /leetcode/Virtual-Contest/71/4.py: -------------------------------------------------------------------------------- 1 | # SOLUTION https://leetcode.com/problems/transform-to-chessboard/discuss/114847/C%2B%2BJavaPython-Solution-with-Explanation 2 | def movesToChessboard(self, b): 3 | N = len(b) 4 | if any(b[0][0] ^ b[i][0] ^ b[0][j] ^ b[i][j] for i in range(N) for j in range(N)): return -1 5 | if not N / 2 <= sum(b[0]) <= (N + 1) / 2: return -1 6 | if not N / 2 <= sum(b[i][0] for i in range(N)) <= (N + 1) / 2: return -1 7 | col = sum(b[0][i] == i % 2 for i in range(N)) 8 | row = sum(b[i][0] == i % 2 for i in range(N)) 9 | if N % 2: 10 | if col % 2: col = [col, N - col][col % 2] 11 | if row % 2: row = N - row 12 | else: 13 | col = min(N - col, col) 14 | row = min(N - row, row) 15 | return (col + row) / 2 -------------------------------------------------------------------------------- /leetcode/Virtual-Contest/71/readme.txt: -------------------------------------------------------------------------------- 1 | key learnings: 2 | - traversals are easily done by recursion 3 | - spending some more time thinking about the problem before attempting it, leads to more avenues on solution 4 | - going from destination to source instead of source to destination is useful, i.e. think backwards 5 | - the case that broke 3.py was [1,1] --> [1,10000] which led to the involvement of 'k' to subtract all the times when tx > ty or vice versa 6 | - for chessboard problem, way more thought was required to define what a chessboard is, and to check the two things 7 | - is valid board 8 | - minimum number of moves [this one was more tricky based on just selecting the min moves for row 1 and col 1] -------------------------------------------------------------------------------- /projectEuler/problem10.py: -------------------------------------------------------------------------------- 1 | def isPrime(n): 2 | if n == 2 or n == 3: return True 3 | if n < 2 or n%2 == 0: return False 4 | if n < 9: return True 5 | if n%3 == 0: return False 6 | r = int(n**0.5) 7 | f = 5 8 | while f <= r: 9 | if n%f == 0: return False 10 | if n%(f+2) == 0: return False 11 | f +=6 12 | return True 13 | 14 | l = [] 15 | for i in range(2000000): 16 | if isPrime(i): 17 | l.append(i) 18 | 19 | print(sum(l)) 20 | -------------------------------------------------------------------------------- /projectEuler/problem12.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # function to count the divisors 4 | def countDivisors(n) : 5 | cnt = 0 6 | for i in range(1, (int)(math.sqrt(n)) + 1) : 7 | if (n % i == 0) : 8 | 9 | # If divisors are equal, 10 | # count only one 11 | if (n / i == i) : 12 | cnt = cnt + 1 13 | else : # Otherwise count both 14 | cnt = cnt + 2 15 | return cnt 16 | 17 | i = 2 18 | n = i*(i-1)/2 19 | while True: 20 | an = 1 21 | n = n + i 22 | if countDivisors(n) > 500: 23 | print(i,countDivisors(n),n) 24 | i+=1 25 | # break; 26 | -------------------------------------------------------------------------------- /projectEuler/problem14.py: -------------------------------------------------------------------------------- 1 | save = {} 2 | def eval(i, save): 3 | sa = i 4 | le = 1 5 | while i != 1: 6 | if i%2 == 0: 7 | i = i/2 8 | else: 9 | i = (3 * i) + 1 10 | if i in save: 11 | le += save[i] 12 | break; 13 | else: 14 | le+=1 15 | save[sa] = le 16 | return le 17 | ma = 0 18 | for i in range(1,1000000): 19 | lei = eval(i,save) 20 | if ma < lei: 21 | ma = lei 22 | sa = i 23 | # if i%10000 == 0: 24 | # print(save, lei) 25 | print(ma, sa) 26 | -------------------------------------------------------------------------------- /projectEuler/problem15.py: -------------------------------------------------------------------------------- 1 | paths = 1 2 | for i in range(0,20): 3 | paths *= (40)-i; 4 | paths = paths / (i+1) 5 | print(paths) 6 | -------------------------------------------------------------------------------- /projectEuler/problem16.py: -------------------------------------------------------------------------------- 1 | num = pow(2,1000) 2 | su = 0 3 | for i in str(num): 4 | su += int(i) 5 | print(su) 6 | -------------------------------------------------------------------------------- /projectEuler/problem17.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # https://projecteuler.net/problem=17 4 | 5 | # !pip install num2words 6 | from num2words import num2words 7 | cn = 0 8 | for i in range(1,1001): 9 | k = num2words(i, lang='en_GB') 10 | for j in k: 11 | if j != ' ' and j != '-': 12 | cn += 1 13 | print(cn) 14 | -------------------------------------------------------------------------------- /projectEuler/problem18.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=18 2 | 3 | rows = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]] 4 | for row in range(len(rows)-1, 0, -1): 5 | for col in range(0, row): 6 | rows[row-1][col] += max(rows[row][col], rows[row][col+1]) 7 | 8 | print(rows[0][0]) 9 | -------------------------------------------------------------------------------- /projectEuler/problem19.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=19 2 | 3 | import datetime 4 | dt = datetime.datetime(1901, 1, 1) 5 | end = datetime.datetime(2000, 12, 31) 6 | step = datetime.timedelta(days=1) 7 | 8 | cn = 0 9 | 10 | while dt < end: 11 | if(dt.isoweekday() == 7 and dt.day == 1): 12 | cn += 1 13 | dt += step 14 | print(cn) 15 | -------------------------------------------------------------------------------- /projectEuler/problem20.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=19 2 | 3 | k = 1 4 | for i in range(1,101): 5 | k *= i 6 | su = 0 7 | while k: 8 | su += k%10 9 | k = k//10 10 | print(su) 11 | -------------------------------------------------------------------------------- /projectEuler/problem21.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=21 2 | 3 | def genDiv(k): 4 | re = 1 5 | for i in range(2, int(pow(k,0.5))+1): 6 | if k%i == 0: 7 | re += i 8 | re += int(k/i) 9 | return re 10 | 11 | su = 0 12 | di = {} 13 | for i in range(0,10001): 14 | di[i] = genDiv(i) 15 | for i in di: 16 | if di[i] in di and i == di[di[i]] and i != di[i]: 17 | print(i,di[i]) 18 | su += i 19 | print(su) 20 | -------------------------------------------------------------------------------- /projectEuler/problem22.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=22 2 | 3 | import urllib.request 4 | 5 | st = "QWERTYUIOPASDFGHJKLZXCVBNM" 6 | st = sorted(st) 7 | di = {} 8 | for i in range(len(st)): 9 | di[st[i]] = i+1 10 | 11 | 12 | def word(k, di): 13 | su = 0 14 | for i in k: 15 | su += di[i] 16 | return su 17 | 18 | file_url = 'https://projecteuler.net/project/resources/p022_names.txt' 19 | names = sorted(urllib.request.urlopen(file_url).read().rstrip().decode('utf8').replace('"','').split(',')) 20 | 21 | names.index('COLIN') 22 | su = 0 23 | for i in range(len(names)): 24 | su += ((i+1) * word(names[i], di)) 25 | print(su) 26 | -------------------------------------------------------------------------------- /projectEuler/problem23.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=23 2 | def genDiv(n): 3 | i = 2 4 | upper = n 5 | total = 1 6 | while i < upper: 7 | if n%i == 0: 8 | upper = n/i 9 | total += upper 10 | if upper != i: total += i 11 | i += 1 12 | return total 13 | 14 | 15 | def isabundant(n): return genDiv(n) > n 16 | lAbundants = [x for x in range(12, 28123) if isabundant(x) == True] 17 | dAbundants = {x:x for x in lAbundants} 18 | 19 | su = 1 20 | for i in range(2, 28123): 21 | flag = True 22 | for k in lAbundants: 23 | if k < i: 24 | if (i-k) in dAbundants: 25 | flag = False 26 | break 27 | else : break 28 | if flag == True: su += i 29 | 30 | print(su) 31 | -------------------------------------------------------------------------------- /projectEuler/problem25.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=25 2 | 3 | F1 = 1 4 | F2 = 1 5 | F = F1 + F2 6 | count = 2 7 | while len(str(F)) < 1000: 8 | F = F1 + F2 9 | count += 1 10 | # print(F, count) 11 | F1 = F2 12 | F2 = F 13 | print(count) 14 | -------------------------------------------------------------------------------- /projectEuler/problem26.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=26 2 | 3 | import itertools 4 | def countMax(n): 5 | seen = {} 6 | x = 1 7 | for i in itertools.count(): 8 | if x in seen: 9 | return i - seen[x] 10 | else: 11 | seen[x] = i 12 | x = x * 10 % n 13 | 14 | ma = -1 15 | d = -1 16 | for i in range(2,1000): 17 | # print(1/i) 18 | if ma < countMax(i): 19 | d = i 20 | ma = countMax(i) 21 | print(d,ma) 22 | -------------------------------------------------------------------------------- /projectEuler/problem27.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=27 2 | 3 | def isPrime(n): 4 | if n==2 or n==3: return True 5 | if n%2==0 or n<2: return False 6 | for i in range(3,int(n**0.5)+1,2): # only odd numbers 7 | if n%i==0: 8 | return False 9 | return True 10 | 11 | primes = {1:1} 12 | for i in range(2,10000): 13 | if isPrime(i): 14 | primes[i] = 1 15 | 16 | def f(a,b): 17 | i = 0 18 | while i*i + a*i + b in primes: 19 | # print(i*i + a*i + b) 20 | i += 1 21 | return i 22 | 23 | print(f(-79, 1601)) 24 | 25 | ma = 0 26 | A = 0 27 | B = 0 28 | for a in range(-1001,1000): 29 | for b in range(-1002,1001): 30 | k = f(a,b) 31 | if ma < k: 32 | ma = k 33 | A = a 34 | B = b 35 | 36 | print(ma, A, B) 37 | -------------------------------------------------------------------------------- /projectEuler/problem28.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=28 2 | 3 | def spiral_diag_sum(n): 4 | if n < 1: return None 5 | elif n == 1: return 1 6 | elif n % 2 == 0: return None 7 | else: 8 | numbers = [1] 9 | numbers_needed = 2 * n - 1 10 | increment = 2 11 | while len(numbers) < numbers_needed: 12 | for p in range(4): 13 | numbers.append(numbers[-1] + increment) 14 | increment += 2 15 | print(numbers) 16 | return sum(numbers) 17 | print(spiral_diag_sum(1001)) 18 | -------------------------------------------------------------------------------- /projectEuler/problem29.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=29 2 | 3 | di = {} 4 | count = 0 5 | for a in range(2,101): 6 | for b in range(2,101): 7 | k = a**b 8 | if k not in di: 9 | di[k] = 1 10 | count += 1 11 | print(count) 12 | -------------------------------------------------------------------------------- /projectEuler/problem30.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=30 2 | 3 | def checkSum(n): 4 | return sum(int(c)**5 for c in str(n)) == n 5 | 6 | su = 0 7 | for i in range(2, 1000000): 8 | if(checkSum(i)): 9 | print(i, checkSum(i)) 10 | su += i 11 | print(su) 12 | -------------------------------------------------------------------------------- /projectEuler/problem31.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=31 2 | 3 | # BruteForce solution 4 | def dfs(sum, path, paths): 5 | if sum < 0: 6 | pass 7 | elif sum == 0: 8 | paths.append(path) 9 | else: 10 | paths = dfs(sum-1,path+[1], paths) 11 | paths = dfs(sum-2,path+[2], paths) 12 | paths = dfs(sum-5,path+[5], paths) 13 | paths = dfs(sum-10,path+[10], paths) 14 | paths = dfs(sum-20,path+[20], paths) 15 | paths = dfs(sum-50,path+[50], paths) 16 | paths = dfs(sum-100,path+[100], paths) 17 | paths = dfs(sum-200,path+[200], paths) 18 | return paths 19 | 20 | # optimised pro solution 21 | coins = [1,2,5,10,20,50,100,200] 22 | li = [0]*201 23 | li[0] = 1 24 | for i in coins: 25 | for j in range(i,201): 26 | li[j] += li[j - i]; 27 | print(li[200]) 28 | -------------------------------------------------------------------------------- /projectEuler/problem32.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | #time at the start of execution 4 | start = time.time() 5 | 6 | #We will store the products in a set to avoid duplicates 7 | products = set() 8 | 9 | #Digits from 1-9 which will be checking later 10 | to_be_checked = set('123456789') 11 | 12 | #for single digit multiplicand 13 | for i in range(9): 14 | for j in range(999,9999): 15 | s = str(i)+str(j)+str(i*j) 16 | if len(s) == 9 and set(s) == to_be_checked: 17 | products.add(i*j) 18 | elif len(s) > 9:break 19 | 20 | #for double digit multiplicand 21 | for i in range(9,99): 22 | for j in range(99,999): 23 | s = str(i)+str(j)+str(i*j) 24 | if len(s) == 9 and set(s) == to_be_checked: 25 | products.add(i*j) 26 | elif len(s)>9: break 27 | 28 | #printing the result 29 | print(sum(products)) 30 | 31 | #time at the end of execution 32 | end = time.time() 33 | 34 | #total time taken for execution 35 | print(end - start) -------------------------------------------------------------------------------- /projectEuler/problem33.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | ans = [1,1] 3 | 4 | for i in range(10, 99): 5 | for j in range(i+1, 99): 6 | numerator = set(str(i)) 7 | denominator = set(str(j)) 8 | if numerator & denominator and numerator & denominator != {'0'}: 9 | f = Fraction(i, j) 10 | simplified_numerator = f.numerator 11 | simplified_denominator = f.denominator 12 | 13 | common = numerator & denominator 14 | new_numerator = list(numerator - common) 15 | new_denominator = list(denominator - common) 16 | if len(new_numerator) == 1 and len(new_denominator) == 1: 17 | try: 18 | f_new = Fraction(int(new_numerator[0]), int(new_denominator[0])) 19 | if f == f_new: 20 | # print(i,j,f) 21 | # print(i,j,ans) 22 | ans = [ans[0]*i, ans[1]*j] 23 | except: 24 | pass 25 | # print('-'*50+'>',i, j) 26 | print(Fraction(ans[0], ans[1]).denominator) -------------------------------------------------------------------------------- /projectEuler/problem34.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=34 2 | 3 | def fact1(n): 4 | k = 1 5 | for i in range(2,n+1): 6 | k *= i 7 | return k 8 | 9 | fact = {'0':1} 10 | for i in range(1,10): 11 | fact[str(i)] = fact1(i) 12 | print(fact) 13 | 14 | def checkSum(n): 15 | return sum(fact[c] for c in str(n)) == n 16 | 17 | l = [] 18 | for i in range(3,100000000): 19 | if checkSum(i): 20 | l.append(i) 21 | print(l, sum(l)) 22 | -------------------------------------------------------------------------------- /projectEuler/problem35.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=35 2 | 3 | import itertools 4 | primes = {1:1} 5 | for i in range(2,1000000): 6 | if isPrime(i): 7 | primes[i] = 1 8 | 9 | def check(n): 10 | ns = str(n) 11 | for j in range(0,len(ns)): 12 | if int(ns[j:] + ns[:j]) not in primes: 13 | return False 14 | return True 15 | 16 | cn = 0 17 | for i in primes: 18 | if check(i): 19 | cn += 1 20 | -------------------------------------------------------------------------------- /projectEuler/problem36.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=36 2 | 3 | def doubleBasePalindromes(): 4 | su = 0 5 | for i in range(1000000): 6 | st = bin(i)[2:] 7 | si = str(i) 8 | if si == si[::-1] and st == st[::-1]: 9 | su += i 10 | return su 11 | 12 | print(doubleBasePalindromes()) 13 | -------------------------------------------------------------------------------- /projectEuler/problem37.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=37 2 | 3 | import itertools 4 | primes = {} 5 | for i in range(2,1000000): 6 | if isPrime(i): 7 | primes[i] = 1 8 | 9 | def check2(n): 10 | ns = str(n) 11 | for j in range(1,len(ns)): 12 | if int(ns[:j]) not in primes: 13 | return False 14 | for j in range(1,len(ns)): 15 | if int(ns[j:]) not in primes: 16 | return False 17 | return True 18 | 19 | l = [] 20 | for i in primes: 21 | if check2(i): 22 | l.append(i) 23 | print(sum(l[4:])) 24 | -------------------------------------------------------------------------------- /projectEuler/problem39.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=39 2 | 3 | def integerRightTriangles(): 4 | listing = [0]*1001 5 | for i in range(1, 1001): 6 | for j in range(1, 1001): 7 | k = pow(i*i + j*j, 0.5) 8 | if i + j + k > 1000: 9 | continue 10 | if k - int(k) == 0: 11 | k = int(k) 12 | listing[i+j+k] += 1 13 | return max(listing), listing.index(max(listing)) 14 | 15 | print(integerRightTriangles()) 16 | -------------------------------------------------------------------------------- /projectEuler/problem4.py: -------------------------------------------------------------------------------- 1 | max_pal = 0 2 | for i in range(999,99,-1): 3 | for j in range(999,99,-1): 4 | ij = i*j 5 | if str(ij) == str(ij)[::-1]: 6 | if ij > max_pal: 7 | max_pal = ij 8 | print(max_pal) 9 | -------------------------------------------------------------------------------- /projectEuler/problem40.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=40 2 | 3 | def champernowne(): 4 | st = "0" 5 | for i in range(1,1000000): 6 | st += str(i) 7 | print() 8 | print(st[1], st[10], st[100], st[1000], st[10000], st[100000], st[1000000]) 9 | return int(st[1]) * int(st[10]) * int(st[100]) * int(st[1000]) * int(st[10000]) * int(st[100000]) * int(st[1000000]) 10 | 11 | print(champernowne()) 12 | -------------------------------------------------------------------------------- /projectEuler/problem41.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=41 2 | 3 | def isPandigital(x): 4 | x = str(x) 5 | for i in range(1, len(x)+1): 6 | if str(i) not in x: 7 | return False 8 | return True 9 | 10 | def isPrime(n): 11 | if n == 2 or n == 3: return True 12 | if n < 2 or n%2 == 0: return False 13 | if n < 9: return True 14 | if n%3 == 0: return False 15 | r = int(n**0.5) 16 | f = 5 17 | while f <= r: 18 | if n%f == 0: return False 19 | if n%(f+2) == 0: return False 20 | f +=6 21 | return True 22 | 23 | def genPandigital(): 24 | # starting from 7999999 instead of any of the 8 digit or 9 digit 25 | # pandigital, because all of those are multiples of 3 or 9 26 | # proof: sum of digits is ez to test for those numbers 27 | for i in range(7999999, 1, -1): 28 | if isPandigital(i): 29 | if isPrime(i): 30 | print(i) 31 | break 32 | genPandigital() 33 | -------------------------------------------------------------------------------- /projectEuler/problem42.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=42 2 | 3 | def readFile(): 4 | with open('p042_words.txt') as f: 5 | s = f.readline() 6 | s = s.replace("\"", "") 7 | li = s.split(',') 8 | return li 9 | 10 | def isTriangle(k): 11 | a = 0.5*(pow(8*k + 1, 0.5) - 1) 12 | return a == int(a) 13 | 14 | def wordToNum(): 15 | di = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26} 16 | li = readFile() 17 | a = [] 18 | for i in li: 19 | su = 0 20 | for j in i: 21 | su += di[j.lower()] 22 | a.append(su) 23 | return a 24 | 25 | def isWordTriangle(): 26 | a = wordToNum() 27 | count = 0 28 | for i in a: 29 | if isTriangle(i): 30 | count += 1 31 | print(count) 32 | 33 | 34 | isWordTriangle() 35 | -------------------------------------------------------------------------------- /projectEuler/problem43.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=43 2 | 3 | from itertools import permutations 4 | 5 | def getPandigital(): 6 | su = 0 7 | print(len(list(permutations(['1','2','3','4','5','6','7','8','9','0'])))) 8 | for i in permutations(['1','2','3','4','5','6','7','8','9','0']): 9 | s = ''.join(i) 10 | if s[0] != '0': 11 | if int(s[1:4]) % 2 == 0 and int(s[2:5]) % 3 == 0 and \ 12 | int(s[3:6]) % 5 == 0 and int(s[4:7]) % 7 == 0 and \ 13 | int(s[5:8]) % 11 == 0 and int(s[6:9]) % 13 == 0 and\ 14 | int(s[7:10]) % 17 == 0: 15 | su += int(s) 16 | return su 17 | print(getPandigital()) 18 | -------------------------------------------------------------------------------- /projectEuler/problem44.py: -------------------------------------------------------------------------------- 1 | # https://projecteuler.net/problem=43 2 | 3 | import math 4 | 5 | def isPentagonal(x): 6 | r = pow(1 + 24 * x, 0.5) 7 | return r % 6 == 5 8 | 9 | 10 | def answer(): 11 | nums = [1, 5, 12]; 12 | n, Pn = 4, 22 13 | while True: 14 | nums.append(Pn) 15 | n += 3 16 | Pn += n 17 | for i in nums[::-1]: 18 | if isPentagonal(abs(Pn - i)) and isPentagonal(i + Pn): 19 | print(Pn, i, Pn-i) 20 | print(nums) 21 | return 22 | 23 | answer() 24 | -------------------------------------------------------------------------------- /projectEuler/problem45.py: -------------------------------------------------------------------------------- 1 | def triangle(x): 2 | return (x * (x+1))//2 3 | 4 | def pentagonal(x): 5 | return (x * (3*x - 1))//2 6 | 7 | def hexagonal(x): 8 | return x * (2*x - 1) 9 | 10 | triangles = set([triangle(x) for x in range(285 + 1000000)]) 11 | pentagonals = set([pentagonal(x) for x in range(165 + 100000)]) 12 | hexagonals = set([hexagonal(x) for x in range(143 + 100000)]) 13 | 14 | print(list(triangles & pentagonals & hexagonals)[3]) -------------------------------------------------------------------------------- /projectEuler/problem46.py: -------------------------------------------------------------------------------- 1 | def rwh(n): 2 | # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 3 | """ Input n>=6, Returns a list of primes, 2 <= p < n """ 4 | correction = (n%6>1) 5 | n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] 6 | sieve = [True] * (n//3) 7 | sieve[0] = False 8 | for i in range(int(n**0.5)//3+1): 9 | if sieve[i]: 10 | k=3*i+1|1 11 | sieve[int(((k*k)/3))::2*k]=[False]*int((n//6-(k*k)//6-1)//k+1) 12 | sieve[int((k*k+4*k-2*k*(i&1))/3)::2*k]=[False]*int((n/6-(k*k+4*k-2*k*(i&1))//6-1)//k+1) 13 | return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]] 14 | 15 | primes = rwh(10000) 16 | result = 1 17 | notFound = True 18 | 19 | def isTwiceSquare(n): 20 | return int((n/2) ** 0.5) == (n/2) ** 0.5 21 | 22 | 23 | while notFound: 24 | result += 2 25 | j = 0 26 | notFound = False 27 | while result >= primes[j]: 28 | if isTwiceSquare(result-primes[j]): 29 | notFound = True 30 | break 31 | j += 1 32 | print(result) 33 | -------------------------------------------------------------------------------- /projectEuler/problem47.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arora-aditya/competitive-programming/30bfafb6a7727c9305b22933b63d9d645182c633/projectEuler/problem47.py -------------------------------------------------------------------------------- /projectEuler/problem6.py: -------------------------------------------------------------------------------- 1 | n = 100; 2 | 3 | squareSum = n*(n+1)*(2*n + 1)/6 4 | sumSquare = pow(n*(n+1)/2,2) 5 | print(abs(squareSum - sumSquare)) 6 | -------------------------------------------------------------------------------- /projectEuler/problem7.py: -------------------------------------------------------------------------------- 1 | import random 2 | def modulo (a, b, c): 3 | result = 1; 4 | while b != 0: 5 | if (b&1): 6 | result *= a; 7 | result %= c; 8 | 9 | b >>=1 ; 10 | a *= a; 11 | a %= c; 12 | 13 | 14 | return result; 15 | 16 | 17 | def isPrime(n): 18 | if n==2: 19 | return 1 20 | for i in range(10): 21 | x = random.randint(0,1)%n 22 | if (x==0 or x==1): 23 | x+=1 24 | if (modulo(x,n-1,n)!=1): 25 | return 0 26 | 27 | 28 | return 1; 29 | 30 | i = 1 31 | n = 2 32 | while i < 10010: 33 | if(isPrime(n)): 34 | print(i,n) 35 | i+=1 36 | n+=1 37 | print(n) 38 | -------------------------------------------------------------------------------- /projectEuler/problem9.py: -------------------------------------------------------------------------------- 1 | for i in range(1,1000): 2 | for j in range(1,1000-i): 3 | if pow(i,2) + pow(j,2) == pow(1000-i-j,2): 4 | print(i,j,1000-i-j) 5 | --------------------------------------------------------------------------------