From eca05c7091490f92b1b64e3dca97a8e031b5c016 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Wed, 22 Dec 2021 14:21:29 +0800 Subject: [PATCH 01/52] no message --- problems/alien-dictionary.py | 37 +++++++++++++++++ problems/remove-nth-node-from-end-of-list.py | 25 ++++++++++++ problems/rotate-image.py | 16 ++++++++ problems/spiral-matrix.py | 42 ++++++++++++++++++++ 4 files changed, 120 insertions(+) create mode 100644 problems/alien-dictionary.py create mode 100644 problems/remove-nth-node-from-end-of-list.py create mode 100644 problems/rotate-image.py create mode 100644 problems/spiral-matrix.py diff --git a/problems/alien-dictionary.py b/problems/alien-dictionary.py new file mode 100644 index 0000000..5c27918 --- /dev/null +++ b/problems/alien-dictionary.py @@ -0,0 +1,37 @@ +""" +Topological Sort +""" +class Solution(object): + def alienOrder(self, words): + #return true if cycles are detected. + def dfs(c): + if c in path: return True + if c in visited: return False + path.add(c) + for nei in adj[c]: + if dfs(nei): return True + res.append(c) + path.remove(c) + visited.add(c) + return False + + #build adjacency list + adj = {c: set() for word in words for c in word} + for i in xrange(len(words)-1): + w1, w2 = words[i], words[i+1] + minLen = min(len(w1), len(w2)) + if w1[:minLen]==w2[:minLen] and len(w1)>len(w2): return "" + + for j in xrange(minLen): + if w1[j]!=w2[j]: + adj[w1[j]].add(w2[j]) + break + + #topological sort + path = set() #path currently being reversed + visited = set() #done processing + res = [] + for c in adj: + if dfs(c): return "" + + return "".join(reversed(res)) \ No newline at end of file diff --git a/problems/remove-nth-node-from-end-of-list.py b/problems/remove-nth-node-from-end-of-list.py new file mode 100644 index 0000000..d92ddd7 --- /dev/null +++ b/problems/remove-nth-node-from-end-of-list.py @@ -0,0 +1,25 @@ +class Solution(object): + def removeNthFromEnd(self, head, n): + def getCount(node0): + curr = node0 + count = 0 + while curr: + curr = curr.next + count += 1 + return count + + def removeNext(node0): + nextNode = node0.next + if not nextNode: return + node0.next = nextNode.next + + k = getCount(head)-n-1 #need to "curr = curr.next" k times to reach the node that we can call removeNext(curr) + if k==-1: return head.next #remove head + + curr = head + while k>0: + k -= 1 + curr = curr.next + + removeNext(curr) + return head \ No newline at end of file diff --git a/problems/rotate-image.py b/problems/rotate-image.py new file mode 100644 index 0000000..59ce93c --- /dev/null +++ b/problems/rotate-image.py @@ -0,0 +1,16 @@ +class Solution(object): + def rotate(self, matrix): + N = len(matrix) + + #transpose + for i in xrange(N): + for j in xrange(N): + if j<=i: continue + matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] + + #reflect + for i in xrange(N): + for j in xrange(N/2): + matrix[i][j], matrix[i][N-1-j] = matrix[i][N-1-j], matrix[i][j] + + return matrix \ No newline at end of file diff --git a/problems/spiral-matrix.py b/problems/spiral-matrix.py new file mode 100644 index 0000000..96965d2 --- /dev/null +++ b/problems/spiral-matrix.py @@ -0,0 +1,42 @@ +class Solution(object): + def spiralOrder(self, matrix): + ans = [] + i, j = 0, 0 + direction = 'right' + count = 0 + + while count<=len(matrix)*len(matrix[0]): + iNext, jNext = i, j + + if direction=='right': + if j+1=0 and matrix[i][j-1]!='v': + jNext = j-1 + else: + direction = 'up' + elif direction=='up': + if i-1>=0 and matrix[i-1][j]!='v': + iNext = i-1 + else: + direction = 'right' + + if (iNext, jNext)!=(i, j) or count>=len(matrix)*len(matrix[0])-1: + ans.append(matrix[i][j]) + matrix[i][j] = 'v' #visited + count += 1 + i = iNext + j = jNext + + return ans[:-1] + + + \ No newline at end of file From 133c9bcefa5f6dc215307cd95afecf6bb487f468 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sun, 2 Jan 2022 11:01:00 +0800 Subject: [PATCH 02/52] no message --- ...ers-of-all-substrings-of-a-given-string.py | 18 ++++++ problems/decode-ways.py | 19 ++++++ ...longest-repeating-character-replacement.py | 23 +++++++ problems/maximum-product-subarray.py | 57 +++++++++++++++++ problems/maximum-units-on-a-truck.py | 17 ++++++ problems/pacific-atlantic-water-flow.py | 30 +++++++++ problems/palindromic-substrings.py | 61 +++++++++++++++++++ problems/search-suggestions-system.py | 61 ++++++++++++++++++- problems/set-matrix-zeroes.py | 35 +++++++++++ problems/unique-paths.py | 9 +++ problems/word-search-ii.py | 46 ++++++++++++++ 11 files changed, 375 insertions(+), 1 deletion(-) create mode 100644 problems/count-unique-characters-of-all-substrings-of-a-given-string.py create mode 100644 problems/decode-ways.py create mode 100644 problems/longest-repeating-character-replacement.py create mode 100644 problems/maximum-product-subarray.py create mode 100644 problems/maximum-units-on-a-truck.py create mode 100644 problems/pacific-atlantic-water-flow.py create mode 100644 problems/palindromic-substrings.py create mode 100644 problems/set-matrix-zeroes.py create mode 100644 problems/unique-paths.py diff --git a/problems/count-unique-characters-of-all-substrings-of-a-given-string.py b/problems/count-unique-characters-of-all-substrings-of-a-given-string.py new file mode 100644 index 0000000..fe58877 --- /dev/null +++ b/problems/count-unique-characters-of-all-substrings-of-a-given-string.py @@ -0,0 +1,18 @@ +class Solution(object): + def uniqueLetterString(self, s): + index = {} + ans = 0 + for c in 'abcdefghijklmnopqrstuvwxyz': + index[c.upper()] = [-1, -1] + + # count the substring that s[j] is the unique letter + for k, c in enumerate(s): + i, j = index[c] + ans += (j-i) * (k-j) + index[c] = [j, k] + + # count the substring that s[j] is the unique letter, because last iteration did not count the last letter + for c in index: + i, j = index[c] + ans += (j-i) * (len(s)-j) + return ans \ No newline at end of file diff --git a/problems/decode-ways.py b/problems/decode-ways.py new file mode 100644 index 0000000..82f4682 --- /dev/null +++ b/problems/decode-ways.py @@ -0,0 +1,19 @@ +""" +Time: O(N), due to the "memo", the time can reduce from O(2^N) to O(N). +Space: O(N) +""" +class Solution(object): + def numDecodings(self, s): + def helper(s, i): + if (s, i) in memo: return memo[(s, i)] + if i>=len(s): return 1 + if s[i]=='0': return 0 + + count = 0 + count += helper(s, i+1) + if len(s)-i>=2 and int(s[i:i+2])<=26: count += helper(s, i+2) + memo[(s, i)] = count + return count + + memo = {} + return helper(s, 0) \ No newline at end of file diff --git a/problems/longest-repeating-character-replacement.py b/problems/longest-repeating-character-replacement.py new file mode 100644 index 0000000..9546fb9 --- /dev/null +++ b/problems/longest-repeating-character-replacement.py @@ -0,0 +1,23 @@ +""" +Use the sliding window to iterate over the sub-strings. At the same time use a counter to track the count. +The operation needed is the (length of the window) - (count of the max count char in the counter) +Since there are at most 26 char in the counter, `max(counter.values())` can be view as a O(1) operation. + +Time: O(N) +Space: O(N) +""" +class Solution(object): + def characterReplacement(self, s, k): + counter = collections.Counter() + ans = 0 + + l = 0 + for r in xrange(len(s)): + counter[s[r]] += 1 + + while r-l+1-max(counter.values())>k: + counter[s[l]] -= 1 + l += 1 + + ans = max(ans, r-l+1) + return ans \ No newline at end of file diff --git a/problems/maximum-product-subarray.py b/problems/maximum-product-subarray.py new file mode 100644 index 0000000..b48bf12 --- /dev/null +++ b/problems/maximum-product-subarray.py @@ -0,0 +1,57 @@ +""" +Time: O(N) +Space: O(N) + +dp[i][0] := the maximum subarray product that includes nums[i] +dp[i][1] := the minimum subarray product that includes nums[i] +""" +class Solution(object): + def maxProduct(self, nums): + if not nums: return 0 + dp = [[float('-inf'), float('inf')] for _ in xrange(len(nums))] + + dp[0] = [nums[0], nums[0]] + ans = nums[0] + + for i in xrange(1, len(nums)): + if nums[i]==0: + dp[i][0] = 0 + dp[i][1] = 0 + elif nums[i]>0: + dp[i][0] = dp[i-1][0]*nums[i] if dp[i-1][0]>0 else nums[i] + dp[i][1] = dp[i-1][1]*nums[i] if dp[i-1][1]<=0 else nums[i] + else: + dp[i][0] = dp[i-1][1]*nums[i] if dp[i-1][1]<=0 else nums[i] + dp[i][1] = dp[i-1][0]*nums[i] if dp[i-1][0]>0 else nums[i] + + ans = max(ans, dp[i][0]) + + return ans + +""" +The above solution can further reduce the space complexity to O(1). +""" +class Solution(object): + def maxProduct(self, nums): + if not nums: return 0 + + maxLast = nums[0] + minLast = nums[0] + ans = nums[0] + + for i in xrange(1, len(nums)): + if nums[i]==0: + newMax = 0 + newMin = 0 + elif nums[i]>0: + newMax = maxLast*nums[i] if maxLast>0 else nums[i] + newMin = minLast*nums[i] if minLast<=0 else nums[i] + else: + newMax = minLast*nums[i] if minLast<=0 else nums[i] + newMin = maxLast*nums[i] if maxLast>0 else nums[i] + + maxLast = newMax + minLast = newMin + ans = max(ans, maxLast) + + return ans \ No newline at end of file diff --git a/problems/maximum-units-on-a-truck.py b/problems/maximum-units-on-a-truck.py new file mode 100644 index 0000000..4e0ce10 --- /dev/null +++ b/problems/maximum-units-on-a-truck.py @@ -0,0 +1,17 @@ +class Solution(object): + def maximumUnits(self, boxTypes, truckSize): + sortedBox = [] + ans = 0 + + for count, units in boxTypes: + sortedBox.append((units, count)) + + sortedBox.sort() + + while sortedBox and truckSize>0: + units, count = sortedBox.pop() + d = min(count, truckSize) + truckSize -= d + ans += d*units + + return ans \ No newline at end of file diff --git a/problems/pacific-atlantic-water-flow.py b/problems/pacific-atlantic-water-flow.py new file mode 100644 index 0000000..15186ff --- /dev/null +++ b/problems/pacific-atlantic-water-flow.py @@ -0,0 +1,30 @@ +class Solution(object): + def pacificAtlantic(self, heights): + def bfs(q, ocian): + while q: + i0, j0 = q.popleft() + if (i0, j0) in ocian: continue + ocian.add((i0, j0)) + + for i, j in [(i0+1, j0), (i0-1, j0), (i0, j0+1), (i0, j0-1)]: + if i>=len(heights) or i<0 or j>=len(heights[0]) or j<0: continue + if heights[i][j]>=heights[i0][j0]: q.append((i, j)) + + pacific = set() + altalantic = set() + q1 = collections.deque() + q2 = collections.deque() + + #add top, left to pacific + for j in xrange(len(heights[0])): q1.append((0, j)) + for i in xrange(len(heights)): q1.append((i, 0)) + + #add right, bottom to atalantic + for j in xrange(len(heights[0])): q2.append((len(heights)-1, j)) + for i in xrange(len(heights)): q2.append((i, len(heights[0])-1)) + + bfs(q1, pacific) + bfs(q2, altalantic) + + return pacific.intersection(altalantic) + \ No newline at end of file diff --git a/problems/palindromic-substrings.py b/problems/palindromic-substrings.py new file mode 100644 index 0000000..a375af6 --- /dev/null +++ b/problems/palindromic-substrings.py @@ -0,0 +1,61 @@ +""" +dp[i][j] := if s[i:j+1] is palindrome. +1. all length==1 string is palindrome. +2. all length==2 string is palindrome if two are the same. +3. all length>=3 string is palindrome if the outer most two char is the same and have an palindrome string inside. + +Time: O(N^2) +Space: 0(N^2) +""" +class Solution(object): + def countSubstrings(self, s): + N = len(s) + dp = [[False]*N for _ in xrange(N)] + ans = 0 + + #1 + for i in xrange(N): + dp[i][i] = True + ans += 1 + + #2 + for i in xrange(N-1): + if s[i]==s[i+1]: + dp[i][i+1] = True + ans += 1 + + #3 + for l in xrange(3, N+1): + for i in xrange(N): + j = i+l-1 + if j>=N: continue + if dp[i+1][j-1] and s[i]==s[j]: + dp[i][j] = True + ans += 1 + return ans + +""" +Iterate through the string, expand around each character. +Like this solution more since it is more intuitive. + +Time: O(N^2) +Space: O(1) +""" +class Solution(object): + def countSubstrings(self, s): + def count(l, r, N): + count = 0 + + while l>=0 and rword: + r = m-1 + else: + l = m+1 + + return [] + + def getTop3(products, word, i): + suggestion = [] + + while i-1>=0 and products[i-1].startswith(word): + i -= 1 + + for j in xrange(i, min(len(products), i+3)): + if not products[j].startswith(word): break + suggestion.append(products[j]) + return suggestion + + + ans = [] + products.sort() + + currSearchWord = '' + for c in searchWord: + currSearchWord += c + ans.append(search(products, currSearchWord)) + + return ans + + + +""" +Time: O(M) + O(S^2) ~= O(M). M is the number of char in products. S is number of char of a searchWord. +O(M) to build trie. O(len(prefix)) (~= O(S/2)) to get to the prefix node, and it will perform S time. O(1) to get top 3. +Space: O(M) + +Use Trie to store the relation and search it. +""" class Node(object): def __init__(self, c): self.c = c self.nexts = {} + class Solution(object): def suggestedProducts(self, products, searchWord): ans = [] @@ -37,4 +95,5 @@ def helper(prefix, node): top3 = [] helper(prefix, node) - return top3 \ No newline at end of file + return top3 + diff --git a/problems/set-matrix-zeroes.py b/problems/set-matrix-zeroes.py new file mode 100644 index 0000000..94e512d --- /dev/null +++ b/problems/set-matrix-zeroes.py @@ -0,0 +1,35 @@ +""" +Space: O(1) +Time: O(N^2) + +Mark matrix[i][0] as string if all matrix[i][?] needs to be set to 0. +Mark matrix[0][j] as string if all matrix[?][j] needs to be set to 0. +There is an edje case where matrix[0][0] cannot represent for row and col at the same time. +So we need an additional variable, firstRowToZero. + +Explanation: https://www.youtube.com/watch?v=T41rL0L3Pnw +""" +class Solution(object): + def setZeroes(self, matrix): + firstRowToZero = False + + for i in xrange(len(matrix)): + for j in xrange(len(matrix[0])): + if matrix[i][j]==0: + if i!=0: + matrix[i][0] = str(matrix[i][0]) + else: + firstRowToZero = True + matrix[0][j] = str(matrix[0][j]) + + + for i in xrange(1, len(matrix)): + if type(matrix[i][0])!=type(''): continue + for j in xrange(len(matrix[0])): matrix[i][j] = 0 + + for j in xrange(len(matrix[0])): + if type(matrix[0][j])!=type(''): continue + for i in xrange(len(matrix)): matrix[i][j] = 0 + + if firstRowToZero: + for j in xrange(len(matrix[0])): matrix[0][j] = 0 \ No newline at end of file diff --git a/problems/unique-paths.py b/problems/unique-paths.py new file mode 100644 index 0000000..f7f5c5b --- /dev/null +++ b/problems/unique-paths.py @@ -0,0 +1,9 @@ +class Solution(object): + def uniquePaths(self, m, n): + def factorial(n): + ans = 1 + for i in xrange(1, n+1): + ans *= i + return ans + + return factorial((m-1)+(n-1))/(factorial(n-1)*factorial(m-1)) \ No newline at end of file diff --git a/problems/word-search-ii.py b/problems/word-search-ii.py index e7d7b91..e62eba3 100644 --- a/problems/word-search-ii.py +++ b/problems/word-search-ii.py @@ -48,3 +48,49 @@ def dfs(i, j, l, word): words = ["oath","pea","eat","rain"] print Solution().findWords(board, words) + + + + +class Solution(object): + def findWords(self, board, words): + def dfs(i, j, parent): + c = board[i][j] + node = parent[c] + + if '.' in node: ans.append(node.pop('.')) + + board[i][j] = '#' + + for (rowOffset, colOffset) in [(-1, 0), (0, 1), (1, 0), (0, -1)]: + newRow, newCol = i + rowOffset, j + colOffset + if newRow<0 or newRow>=len(board) or newCol<0 or newCol>=len(board[0]): continue + if not board[newRow][newCol] in node: continue + dfs(newRow, newCol, node) + + board[i][j] = c + if not node: parent.pop(c) + + trie = {} + ans = [] + + #build trie + for word in words: + node = trie + for c in word: + if c not in node: + node[c] = {} + node = node[c] + node['.'] = word + print trie + + for i in xrange(len(board)): + for j in xrange(len(board[0])): + if board[i][j] in trie: dfs(i, j, trie) + + + return ans + + + + \ No newline at end of file From fd5bc7c537ecea127018aee3cbc7406ddafff80b Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 11 Jan 2022 11:57:12 +0800 Subject: [PATCH 03/52] no message --- problems/count-binary-substrings.py | 21 +++++++ problems/guess-the-word.py | 32 ++++++++++ .../maximum-number-of-points-with-cost.py | 63 +++++++++++++++++++ .../maximum-subarray-sum-with-one-deletion.py | 2 +- ...th-in-a-grid-with-obstacles-elimination.py | 25 ++++++++ problems/snapshot-array.py | 19 ++++++ 6 files changed, 161 insertions(+), 1 deletion(-) create mode 100644 problems/count-binary-substrings.py create mode 100644 problems/guess-the-word.py create mode 100644 problems/maximum-number-of-points-with-cost.py create mode 100644 problems/shortest-path-in-a-grid-with-obstacles-elimination.py create mode 100644 problems/snapshot-array.py diff --git a/problems/count-binary-substrings.py b/problems/count-binary-substrings.py new file mode 100644 index 0000000..5a2520e --- /dev/null +++ b/problems/count-binary-substrings.py @@ -0,0 +1,21 @@ +class Solution(object): + def countBinarySubstrings(self, s): + groups = [] + count = 0 + last = s[0] + ans = 0 + + for bit in s: + if bit==last: + count += 1 + else: + groups.append(count) + count = 1 + last = bit + + groups.append(count) + + for i in xrange(1, len(groups)): + ans += min(groups[i], groups[i-1]) + + return ans \ No newline at end of file diff --git a/problems/guess-the-word.py b/problems/guess-the-word.py new file mode 100644 index 0000000..278a659 --- /dev/null +++ b/problems/guess-the-word.py @@ -0,0 +1,32 @@ +# """ +# This is Master's API interface. +# You should not implement it, or speculate about its implementation +# """ +#class Master(object): +# def guess(self, word): +# """ +# :type word: str +# :rtype int +# """ + +class Solution(object): + def findSecretWord(self, wordlist, master): + def similarity(w1, w2): + count = 0 + for i in xrange(6): + if w1[i]==w2[i]: count += 1 + return count + + for _ in xrange(10): + + temp = [] + + word = random.choice(wordlist) + k = master.guess(word) + if k==6: return + + for otherWord in wordlist: + if otherWord==word: continue + if similarity(word, otherWord)==k: temp.append(otherWord) + + wordlist = temp \ No newline at end of file diff --git a/problems/maximum-number-of-points-with-cost.py b/problems/maximum-number-of-points-with-cost.py new file mode 100644 index 0000000..c365817 --- /dev/null +++ b/problems/maximum-number-of-points-with-cost.py @@ -0,0 +1,63 @@ +""" +dp[i][j] := considering from points[0]~points[i], the max points if choosing points[i][j] +""" +class Solution(object): + def maxPoints(self, points): + N = len(points) + M = len(points[0]) + dp = [[0]*M for _ in xrange(N)] + + for i in xrange(N): + for j in xrange(M): + if i==0: + dp[i][j] = points[i][j] + else: + dp[i][j] = points[i][j]+max([dp[i-1][k] - abs(k-j) for k in xrange(M)]) + return max(dp[N-1]) + + +""" +The above solution will take O(NM^2) in time. +The bottle neck is for each j we need to traverse the whole last row. +Let us see a little bit closer on `dp[i][j]` + +dp[i][j] = points[i][j]+max([dp[i-1][k] - abs(k-j) for k in xrange(M)]) + +So, if j>=k (Part 1) +points[i][j]+max([dp[i-1][k] - (j-k) for k in xrange(M)]) +points[i][j] - j + max([dp[i-1][k] + k) for k in xrange(M)]) + +if k>=j (Part 2) +points[i][j] + max([dp[i-1][k] - (k-j) for k in xrange(M)]) +points[i][j] + j + max([dp[i-1][k] - k) for k in xrange(M)]) + +Since we cannot do a full scan +why not we update the value from left to right for Part 1 and +right to left for part 2 +With a variable call rollingMax to store the max. + +That way dp[i][j] will be updated as if we do a full scan. + +The time complexity will become O(NM) +""" +class Solution(object): + def maxPoints(self, points): + N = len(points) + M = len(points[0]) + dp = [[0]*M for _ in xrange(N)] + + for j in xrange(M): + dp[0][j] = points[0][j] + + for i in xrange(1, N): + rollingMax = float('-inf') + for j in xrange(M): + rollingMax = max(rollingMax, dp[i-1][j] - j) + dp[i][j] = max(dp[i][j], points[i][j] + j + rollingMax)) + + rollingMax = float('-inf') + for j in xrange(M, -1, -1): + rollingMax = max(rollingMax, dp[i-1][j] + j) + dp[i][j] = max(dp[i][j], points[i][j] - j + rollingMax)) + + return max(dp[N-1]) \ No newline at end of file diff --git a/problems/maximum-subarray-sum-with-one-deletion.py b/problems/maximum-subarray-sum-with-one-deletion.py index d713751..a7b34f2 100644 --- a/problems/maximum-subarray-sum-with-one-deletion.py +++ b/problems/maximum-subarray-sum-with-one-deletion.py @@ -23,7 +23,7 @@ def maximumSum(self, arr): dp[i][1] = arr[i] else: dp[i][0] = max(dp[i-1][0]+arr[i], arr[i]) - dp[i][1] = max(dp[i-1][0], dp[i-1][1]+arr[i], arr[i]) + dp[i][1] = max(dp[i-1][0], dp[i-1][1]+arr[i]) subarrayMaxSum = max(subarrayMaxSum, dp[i][0], dp[i][1]) return subarrayMaxSum \ No newline at end of file diff --git a/problems/shortest-path-in-a-grid-with-obstacles-elimination.py b/problems/shortest-path-in-a-grid-with-obstacles-elimination.py new file mode 100644 index 0000000..9c94c8a --- /dev/null +++ b/problems/shortest-path-in-a-grid-with-obstacles-elimination.py @@ -0,0 +1,25 @@ +class Solution(object): + def shortestPath(self, grid, K): + N = len(grid) + M = len(grid[0]) + + q = collections.deque([(0, 0, 0, K)]) + qNext = collections.deque() + visited = set() + + while q: + step, i0, j0, k0 = q.popleft() + if (i0, j0, k0) in visited: continue + visited.add((i0, j0, k0)) + + if i0==N-1 and j0==M-1: return step + + for i, j in [(i0+1, j0), (i0-1, j0), (i0, j0+1), (i0, j0-1)]: + if i>=N or i<0 or j>=M or j<0: continue + if grid[i][j]==1 and k0>0: + qNext.append((step+1, i, j, k0-1)) + elif grid[i][j]==0: + qNext.append((step+1, i, j, k0)) + if not q: q = qNext + + return -1 \ No newline at end of file diff --git a/problems/snapshot-array.py b/problems/snapshot-array.py new file mode 100644 index 0000000..baa9f15 --- /dev/null +++ b/problems/snapshot-array.py @@ -0,0 +1,19 @@ +class SnapshotArray(object): + + def __init__(self, length): + self.data = [[(-1, 0)] for _ in xrange(length)] + self.snapId = 0 + + + def set(self, index, val): + self.data[index].append((self.snapId, val)) + + + def snap(self): + self.snapId += 1 + return self.snapId - 1 + + + def get(self, index, snapId): + j = bisect.bisect_right(self.data[index], (snapId, float('inf'))) - 1 + return self.data[index][j][1] \ No newline at end of file From 98a3a80101ebd2c2f2c9a08f193b9773ec5fa898 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Thu, 13 Jan 2022 17:10:45 +0800 Subject: [PATCH 04/52] no message --- problems/text-justification.py | 68 ++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 problems/text-justification.py diff --git a/problems/text-justification.py b/problems/text-justification.py new file mode 100644 index 0000000..98eb0be --- /dev/null +++ b/problems/text-justification.py @@ -0,0 +1,68 @@ +""" +The description of this problem is unclear. +"Extra spaces between words should be distributed as evenly as possible." Should be "Extra spaces between words IN EACH LINE should be distributed as evenly as possible." +So the problem in short is: +1. Every line should have as many as word as possible. But they should be separate by space or spaces. +2. Mid align all the line. Except the last line and the lines with one word. +3. For mid align, distribute space evenly, if there are extra spaces, it should be located left. For example 5 spaces distribute to 2 places, it should be 3 2, not 2 3. 7 spaces distribute to 3 places, it should be 3 2 2, not 2 3 2, not 2 2 3. + +Time: O(N), N is the number of words. +Space: O(W), W is maxWidth for keeping strings in currLine. Can further reduce to O(1) using only index. +""" +class Solution(object): + def fullJustify(self, words, maxWidth): + def canAddToCurrLine(word, currLineStringLength): + currWidth = len(currLine)-1 + currLineStringLength # space+currLineStringLength + return currWidth+len(word)+1<=maxWidth + + def leftAlign(currLine): + line = '' + + for word in currLine: + line += word + ' ' + line = line[:-1] #remove last space + + line += ' '*(maxWidth-len(line)) + return line + + def midAlign(currLine, currLineStringLength): + line = '' + + totalSpaceCount = maxWidth-currLineStringLength + extraSpaceCount = totalSpaceCount%(len(currLine)-1) + spaceCount = totalSpaceCount-extraSpaceCount + spaces = ' '*(totalSpaceCount/(len(currLine)-1)) + + for word in currLine: + line += word + if spaceCount>0: + line += spaces + spaceCount -= len(spaces) + + if extraSpaceCount>0: + line += ' ' + extraSpaceCount -= 1 + + return line + + currLineStringLength = 0 + currLine = [] + ans = [] + + i = 0 + while i Date: Fri, 14 Jan 2022 14:36:13 +0800 Subject: [PATCH 05/52] no message --- .../find-original-array-from-doubled-array,py | 26 +++++++++++++++++++ problems/logger-rate-limiter.py | 10 +++++++ 2 files changed, 36 insertions(+) create mode 100644 problems/find-original-array-from-doubled-array,py create mode 100644 problems/logger-rate-limiter.py diff --git a/problems/find-original-array-from-doubled-array,py b/problems/find-original-array-from-doubled-array,py new file mode 100644 index 0000000..e9e2726 --- /dev/null +++ b/problems/find-original-array-from-doubled-array,py @@ -0,0 +1,26 @@ +""" +Time: O(NLogN) +Space: O(N) +""" +class Solution(object): + def findOriginalArray(self, changed): + if len(changed)%2!=0: return [] + + ans = [] + counter = collections.Counter() #store the count of the doubled number + count = 0 #sum of count in counter + + changed.sort() #need to be sorted, otherwise we cannot identify which number is orginal or it is doubled. + + for num in changed: + if counter[num]>0: + #num is a doubled num + counter[num] -= 1 + count -= 1 + ans.append(num/2) + else: + #num is an original num + counter[num*2] += 1 + count += 1 + + return ans if count==0 else [] \ No newline at end of file diff --git a/problems/logger-rate-limiter.py b/problems/logger-rate-limiter.py new file mode 100644 index 0000000..2a1a7e6 --- /dev/null +++ b/problems/logger-rate-limiter.py @@ -0,0 +1,10 @@ +class Logger(object): + def __init__(self): + self.log = collections.Counter() #store the latest timestamp + + def shouldPrintMessage(self, timestamp, message): + if message not in self.log or self.log[message]+10<=timestamp: + self.log[message] = timestamp + return True + else: + return False \ No newline at end of file From 82cd50e998d96342483b9d0f872c0e2149bed0e2 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Fri, 21 Jan 2022 11:04:21 +0800 Subject: [PATCH 06/52] no message --- .../delete-duplicate-folders-in-system.py | 43 +++++++++++++++ problems/find-and-replace-in-string.py | 28 ++++++++++ problems/longest-string-chain.py | 39 ++++++++++++++ problems/maximum-number-of-visible-points.py | 54 +++++++++++++++++++ problems/number-of-matching-subsequences.py | 25 +++++++++ ...move-all-ones-with-row-and-column-flips.py | 28 ++++++++++ problems/stock-price-fluctuation.py | 37 +++++++++++++ problems/student-attendance-record-ii.py | 28 ++++++++++ 8 files changed, 282 insertions(+) create mode 100644 problems/delete-duplicate-folders-in-system.py create mode 100644 problems/maximum-number-of-visible-points.py create mode 100644 problems/number-of-matching-subsequences.py create mode 100644 problems/remove-all-ones-with-row-and-column-flips.py create mode 100644 problems/stock-price-fluctuation.py create mode 100644 problems/student-attendance-record-ii.py diff --git a/problems/delete-duplicate-folders-in-system.py b/problems/delete-duplicate-folders-in-system.py new file mode 100644 index 0000000..721a8b1 --- /dev/null +++ b/problems/delete-duplicate-folders-in-system.py @@ -0,0 +1,43 @@ +from sortedcontainers import SortedDict + +class Node(object): + def __init__(self, val): + self.val = val + self.key = None + self.children = SortedDict() + + +class Solution(object): + def deleteDuplicateFolder(self, paths): + def setKey(node): + if not node.children: + node.key = node.val + else: + node.key = '' + for c in node.children: + setKey(node.children[c]) + node.key += node.children[c].val + '|' + node.children[c].key + '|' + + keyCount[node.key] += 1 + + def addPath(node, path): + if node.children and keyCount[node.key]>1: return + ans.append(path+[node.val]) + for c in node.children: + addPath(node.children[c], path+[node.val]) + + + ans = [] + root = Node('/') + keyCount = collections.Counter() + + #build the tree + for path in paths: + node = root + for c in path: + if c not in node.children: node.children[c] = Node(c) + node = node.children[c] + + setKey(root) + for c in root.children: addPath(root.children[c], []) + return ans \ No newline at end of file diff --git a/problems/find-and-replace-in-string.py b/problems/find-and-replace-in-string.py index ed407d1..4d74203 100644 --- a/problems/find-and-replace-in-string.py +++ b/problems/find-and-replace-in-string.py @@ -20,4 +20,32 @@ def findReplaceString(self, s, indices, sources, targets): ans += s[i] p = i + return ans + +""" +Time: O(N). N is the length of `s`. The replacement won't be more than the length of the string, Let's assume it is N. +Space: O(N). +""" +class Solution(object): + def findReplaceString(self, s, indices, sources, targets): + ans = '' + + replacement = {} + for i in xrange(len(indices)): + index = indices[i] + source = sources[i] + target = targets[i] + + if s[index:index+len(source)]!=source: continue + replacement[index] = (source, target) + + i = 0 + while i0 and y==0: + return 0 + elif x==0 and y>0: + return 90 + elif x<0 and y==0: + return 180 + elif x==0 and y<0: + return 270 + + #4 quadrant + if x>0 and y>0: + return math.degrees(math.atan2(abs(y), abs(x))) + elif x<0 and y>0: + return 180-math.degrees(math.atan2(abs(y), abs(x))) + elif x<0 and y<0: + return 180+math.degrees(math.atan2(abs(y), abs(x))) + else: + return 360-math.degrees(math.atan2(abs(y), abs(x))) + + ans = 0 + onLocation = 0 + angles = [] + + for x, y in points: + if x==location[0] and y==location[1]: + onLocation += 1 + else: + a = getAngle(x-location[0], y-location[1]) + angles.append(a) + if a<=angle: angles.append(360+a) #[1] + + angles.sort() + + i = 0 + for j in xrange(len(angles)): + while angles[j]-angles[i]>angle: + i += 1 + ans = max(ans, j-i+1) + + return ans+onLocation \ No newline at end of file diff --git a/problems/number-of-matching-subsequences.py b/problems/number-of-matching-subsequences.py new file mode 100644 index 0000000..fd97676 --- /dev/null +++ b/problems/number-of-matching-subsequences.py @@ -0,0 +1,25 @@ +""" +Time: O(WL x LogS), W is the length of words, L is the length of word. +LogS is the time for binary search and S should be the count of repetitive words, we can assume it is Log(S/26) ~= LogS. + +Space: O(S) +""" +class Solution(object): + def numMatchingSubseq(self, s, words): + def match(position, word): + prev = -1 + for c in word: + if c not in position: return False + i = bisect.bisect_left(position[c], prev+1) + if i==len(position[c]): return False + prev = position[c][i] + return True + + position = collections.defaultdict(list) + count = 0 + for i, c in enumerate(s): + position[c].append(i) + + for word in words: + if match(position, word): count += 1 + return count \ No newline at end of file diff --git a/problems/remove-all-ones-with-row-and-column-flips.py b/problems/remove-all-ones-with-row-and-column-flips.py new file mode 100644 index 0000000..69093cc --- /dev/null +++ b/problems/remove-all-ones-with-row-and-column-flips.py @@ -0,0 +1,28 @@ +""" +Not sure how to scientifically prove this. +In order to turn all the 1 to 0, every row need to have "the same pattern". Or it is imposible. +This same pattern is means they are 1. identical 2. entirely different. +For example 101 and 101, 101 and 010. +110011 and 110011. 110011 and 001100. + +Time: O(N), N is the number of element in the grid. +Space: O(N) +""" +class Solution(object): + def removeOnes(self, grid): + if not grid: return True + rowStrings = set() + + for row in grid: + rowStrings.add(''.join((str(e) for e in row))) + + if len(rowStrings)>2: return False + if len(rowStrings)==1: return True + + s1 = rowStrings.pop() + s2 = rowStrings.pop() + + for i in xrange(len(s1)): + if (s1[i]=='0' and s2[i]=='1') or (s1[i]=='1' and s2[i]=='0'): continue + return False + return True \ No newline at end of file diff --git a/problems/stock-price-fluctuation.py b/problems/stock-price-fluctuation.py new file mode 100644 index 0000000..e75beb2 --- /dev/null +++ b/problems/stock-price-fluctuation.py @@ -0,0 +1,37 @@ +""" +[0] priceToTime tracks price to timestamps, but since for each timestamp the price might be overridden, the price in priceToTime might not be exsit. So we need to check if the price still have any valid timestamps. +[1] SortedDict is a BST like structure. + +Time: O(LogN) +Space: O(N) +""" +from sortedcontainers import SortedDict #[1] + +class StockPrice(object): + + def __init__(self): + self.timeToPrice = SortedDict() #time will be sorted + self.priceToTime = SortedDict() #the price will be sorted + + + def update(self, timestamp, price): + if timestamp in self.timeToPrice: + prevPrice = self.timeToPrice[timestamp] + self.priceToTime[prevPrice].remove(timestamp) + if len(self.priceToTime[prevPrice])==0: self.priceToTime.pop(prevPrice) #[0] + + if price not in self.priceToTime: self.priceToTime[price] = set() #initialized + self.priceToTime[price].add(timestamp) + self.timeToPrice[timestamp] = price + + + def current(self): + return self.timeToPrice.peekitem(-1)[1] + + + def maximum(self): + return self.priceToTime.peekitem(-1)[0] + + + def minimum(self): + return self.priceToTime.peekitem(0)[0] \ No newline at end of file diff --git a/problems/student-attendance-record-ii.py b/problems/student-attendance-record-ii.py new file mode 100644 index 0000000..ed55473 --- /dev/null +++ b/problems/student-attendance-record-ii.py @@ -0,0 +1,28 @@ +class Solution(object): + def checkRecord(self, n): + """ + dp[l] := number of eligible combination of a length l record without A + """ + + ans = 0 + M = 1000000007 + + dp = [0]*max(n+1, 4) + dp[0] = 1 + dp[1] = 2 + dp[2] = 4 + dp[3] = 7 + + for i in xrange(4, n+1): + dp[i] += dp[i-1]%M #ends at P + dp[i] += (dp[i-1]%M - dp[i-4]%M) #ends at L. All posiblity but the end cannot be PLL + + + ans += dp[n] + + for i in xrange(n): + ans += dp[i] * dp[n-i-1] + ans %= M + + return ans + \ No newline at end of file From 5e28daff0c37856e5d7299d958f5907d0d74bd0d Mon Sep 17 00:00:00 2001 From: wuduhren Date: Fri, 21 Jan 2022 11:08:15 +0800 Subject: [PATCH 07/52] no message --- problems/delete-duplicate-folders-in-system.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/problems/delete-duplicate-folders-in-system.py b/problems/delete-duplicate-folders-in-system.py index 721a8b1..763eefd 100644 --- a/problems/delete-duplicate-folders-in-system.py +++ b/problems/delete-duplicate-folders-in-system.py @@ -21,7 +21,7 @@ def setKey(node): keyCount[node.key] += 1 def addPath(node, path): - if node.children and keyCount[node.key]>1: return + if node.children and keyCount[node.key]>1: return #leaf node does not apply to this rule ans.append(path+[node.val]) for c in node.children: addPath(node.children[c], path+[node.val]) @@ -38,6 +38,11 @@ def addPath(node, path): if c not in node.children: node.children[c] = Node(c) node = node.children[c] + #set all nodes key recursively setKey(root) - for c in root.children: addPath(root.children[c], []) + + #build ans + for c in root.children: + addPath(root.children[c], []) + return ans \ No newline at end of file From a2551c9a3bcff6de96c328b6a8d1b901cd42f49a Mon Sep 17 00:00:00 2001 From: wuduhren Date: Fri, 21 Jan 2022 11:31:10 +0800 Subject: [PATCH 08/52] no message --- problems/delete-duplicate-folders-in-system.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/problems/delete-duplicate-folders-in-system.py b/problems/delete-duplicate-folders-in-system.py index 763eefd..f05d4ff 100644 --- a/problems/delete-duplicate-folders-in-system.py +++ b/problems/delete-duplicate-folders-in-system.py @@ -1,12 +1,10 @@ -from sortedcontainers import SortedDict - class Node(object): def __init__(self, val): self.val = val self.key = None - self.children = SortedDict() - - + self.children = {} + + class Solution(object): def deleteDuplicateFolder(self, paths): def setKey(node): @@ -14,7 +12,7 @@ def setKey(node): node.key = node.val else: node.key = '' - for c in node.children: + for c in sorted(node.children.keys()): setKey(node.children[c]) node.key += node.children[c].val + '|' + node.children[c].key + '|' From 803fb76e20fc2e469f3a7d7d4521b2d799ab632c Mon Sep 17 00:00:00 2001 From: wuduhren Date: Mon, 24 Jan 2022 11:45:02 +0800 Subject: [PATCH 09/52] no message --- problems/binary-subarrays-with-sum.py | 19 ++++++++ problems/coloring-a-border.py | 43 +++++++++++++++++++ problems/count-number-of-nice-subarrays.py | 19 ++++++++ .../delete-duplicate-folders-in-system.py | 12 ++---- problems/fruit-into-baskets.py | 23 ++++++++++ problems/max-consecutive-ones-iii.py | 15 +++++++ problems/minimum-knight-moves.py | 30 +++++++++++++ ...umber-of-substrings-containing-all-thre.py | 22 ++++++++++ ...place-the-substring-for-balanced-string.py | 15 +++++++ .../subarrays-with-k-different-integers.py | 25 +++++++++++ 10 files changed, 215 insertions(+), 8 deletions(-) create mode 100644 problems/binary-subarrays-with-sum.py create mode 100644 problems/coloring-a-border.py create mode 100644 problems/count-number-of-nice-subarrays.py create mode 100644 problems/max-consecutive-ones-iii.py create mode 100644 problems/minimum-knight-moves.py create mode 100644 problems/number-of-substrings-containing-all-thre.py create mode 100644 problems/replace-the-substring-for-balanced-string.py create mode 100644 problems/subarrays-with-k-different-integers.py diff --git a/problems/binary-subarrays-with-sum.py b/problems/binary-subarrays-with-sum.py new file mode 100644 index 0000000..dafb077 --- /dev/null +++ b/problems/binary-subarrays-with-sum.py @@ -0,0 +1,19 @@ +class Solution(object): + def numSubarraysWithSum(self, nums, goal): + #number of subarrays with sum at most "goal" + def atMost(goal): + ans = 0 + total = 0 + i = 0 + + for j, num in enumerate(nums): + if num==1: total += 1 + + while igoal: + if nums[i]==1: total -= 1 + i += 1 + + ans += j-i+1 #number of subarrays that can generate from nums[i~j] + return ans + + return atMost(goal)-atMost(goal-1) if goal>0 else atMost(goal) \ No newline at end of file diff --git a/problems/coloring-a-border.py b/problems/coloring-a-border.py new file mode 100644 index 0000000..0b1ecc9 --- /dev/null +++ b/problems/coloring-a-border.py @@ -0,0 +1,43 @@ +""" +A node is on the "border" if +1. It is on the actual border of the grid. +Or +2. Any of its neighbor has different color. + +BFS the grid starting from (row, col), if the node "isBorder" add it to nodesToColor. +Color the nodes in the nodesToColor. + +Time: O(N) +Space: O(N) +""" +class Solution(object): + def colorBorder(self, grid, row, col, color): + def isValid(i, j): + return i>=0 and j>=0 and ik: + if nums[i]%2!=0: oddCount -= 1 + i += 1 + + ans += j-i+1 + + return ans + + return atMost(K)-atMost(K-1) \ No newline at end of file diff --git a/problems/delete-duplicate-folders-in-system.py b/problems/delete-duplicate-folders-in-system.py index f05d4ff..512cd1a 100644 --- a/problems/delete-duplicate-folders-in-system.py +++ b/problems/delete-duplicate-folders-in-system.py @@ -4,17 +4,13 @@ def __init__(self, val): self.key = None self.children = {} - class Solution(object): def deleteDuplicateFolder(self, paths): def setKey(node): - if not node.children: - node.key = node.val - else: - node.key = '' - for c in sorted(node.children.keys()): - setKey(node.children[c]) - node.key += node.children[c].val + '|' + node.children[c].key + '|' + node.key = '' + for c in sorted(node.children.keys()): #need to be sorted. so when child structs are the same, we won't generate different key from different iteration order. + setKey(node.children[c]) + node.key += node.children[c].val + '|' + node.children[c].key + '|' #generate a key for each node. only considering its children structure. (see the "identical" definition, it does not consider the val of the node itself.) keyCount[node.key] += 1 diff --git a/problems/fruit-into-baskets.py b/problems/fruit-into-baskets.py index 29bb77c..8645ae0 100644 --- a/problems/fruit-into-baskets.py +++ b/problems/fruit-into-baskets.py @@ -44,3 +44,26 @@ def totalFruit(self, tree): counter = max(counter, i-start+1) mark[t] = i return counter + + +""" +Find the length of longest subarray that at most has 2 unique number. +""" +class Solution(object): + def totalFruit(self, fruits): + ans = 0 + uniqueFruits = 0 + i = 0 + counter = collections.Counter() + + for j, fruit in enumerate(fruits): + counter[fruit] += 1 + if counter[fruit]==1: uniqueFruits += 1 + + while uniqueFruits>2: + counter[fruits[i]] -= 1 + if counter[fruits[i]]==0: uniqueFruits -= 1 + i += 1 + + ans = max(ans, j-i+1) + return ans \ No newline at end of file diff --git a/problems/max-consecutive-ones-iii.py b/problems/max-consecutive-ones-iii.py new file mode 100644 index 0000000..2ebd05c --- /dev/null +++ b/problems/max-consecutive-ones-iii.py @@ -0,0 +1,15 @@ +class Solution(object): + def longestOnes(self, nums, k): + ans = 0 + zeroCount = 0 + i = 0 + + for j, num in enumerate(nums): + if num==0: zeroCount += 1 + + while zeroCount>k: + if nums[i]==0: zeroCount -= 1 + i += 1 + ans = max(ans, j-i+1) + + return ans \ No newline at end of file diff --git a/problems/minimum-knight-moves.py b/problems/minimum-knight-moves.py new file mode 100644 index 0000000..84cb400 --- /dev/null +++ b/problems/minimum-knight-moves.py @@ -0,0 +1,30 @@ +# Bidirectional BFS +class Solution(object): + def minKnightMoves(self, x, y): + offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)] + q1 = collections.deque([(0, 0)]) + q2 = collections.deque([(x, y)]) + steps1 = {(0, 0): 0} #steps needed starting from (0, 0) + steps2 = {(x, y): 0} #steps needed starting from (x,y) + + while q1 and q2: + i1, j1 = q1.popleft() + if (i1, j1) in steps2: return steps1[(i1, j1)]+steps2[(i1, j1)] + + i2, j2 = q2.popleft() + if (i2, j2) in steps1: return steps1[(i2, j2)]+steps2[(i2, j2)] + + for ox, oy in offsets: + nextI1 = i1+ox + nextJ1 = j1+oy + if (nextI1, nextJ1) not in steps1: + q1.append((nextI1, nextJ1)) + steps1[(nextI1, nextJ1)] = steps1[(i1, j1)]+1 + + nextI2 = i2+ox + nextJ2 = j2+oy + if (nextI2, nextJ2) not in steps2: + q2.append((nextI2, nextJ2)) + steps2[(nextI2, nextJ2)] = steps2[(i2, j2)]+1 + + return float('inf') \ No newline at end of file diff --git a/problems/number-of-substrings-containing-all-thre.py b/problems/number-of-substrings-containing-all-thre.py new file mode 100644 index 0000000..66d43cc --- /dev/null +++ b/problems/number-of-substrings-containing-all-thre.py @@ -0,0 +1,22 @@ +class Solution(object): + def numberOfSubstrings(self, s): + #number of subarrays that at most have k unique char + def atMost(k): + counter = collections.Counter() + uniqueCount = 0 + ans = 0 + i = 0 + + for j, c in enumerate(s): + counter[c] += 1 + if counter[c]==1: uniqueCount += 1 + + while uniqueCount>k: + counter[s[i]] -= 1 + if counter[s[i]]==0: uniqueCount-= 1 + i += 1 + ans += j-i+1 + return ans + + n = len(s) + return atMost(3) - atMost(2) \ No newline at end of file diff --git a/problems/replace-the-substring-for-balanced-string.py b/problems/replace-the-substring-for-balanced-string.py new file mode 100644 index 0000000..0ce1250 --- /dev/null +++ b/problems/replace-the-substring-for-balanced-string.py @@ -0,0 +1,15 @@ +class Solution(object): + def balancedString(self, s): + n = len(s) + counter = collections.Counter(s) + i = 0 + ans = n + + for j, c in enumerate(s): + counter[c] -= 1 + + while ik: + counter[nums[i]] -= 1 + if counter[nums[i]]==0: uniqueCount -= 1 + i += 1 + + # the logest subarray that ends at j is nums[i:j+1] + # nums[i:j+1] can produce j-i+1 subarrays that at most has k different number. + ans += j-i+1 + + return ans + + return atMost(K)-atMost(K-1) \ No newline at end of file From 5dda17bb500798a3e70f1ac1cf79eab59083b8e2 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Thu, 3 Feb 2022 12:22:33 +0800 Subject: [PATCH 10/52] no message --- problems/backspace-string-compare.py | 22 +++++++- problems/balance-a-binary-search-tree.py | 36 ++++++++++++ problems/binary-search-tree-iterator.py | 26 ++++++++- .../binary-tree-vertical-order-traversal.py | 25 ++++++++- ...earch-tree-to-sorted-doubly-linked-list.py | 4 +- problems/copy-list-with-random-pointer.py | 37 +++++++++++- problems/diameter-of-binary-tree.py | 20 +++++++ problems/find-distance-in-a-binary-tree.py | 28 ++++++++++ problems/find-duplicate-subtrees.py | 16 ++++++ problems/find-k-closest-elements.py | 20 +++++++ ...sert-into-a-sorted-circular-linked-list.py | 42 ++++++++++++++ ...est-common-ancestor-of-a-binary-tree-ii.py | 17 ++++++ ...st-common-ancestor-of-a-binary-tree-iii.py | 56 +++++++++++++++++++ ...est-common-ancestor-of-a-binary-tree-iv.py | 18 ++++++ ...owest-common-ancestor-of-deepest-leaves.py | 41 ++++++++++++++ problems/maximal-square.py | 22 +++++++- problems/random-pick-with-weight.py | 29 ++++++++++ problems/range-sum-of-bst.py | 11 ++++ .../serialize-and-deserialize-binary-tree.py | 23 +++++++- ...ions-from-a-binary-tree-node-to-another.py | 36 ++++++++++++ problems/subarray-sum-equals-k.py | 2 +- problems/top-k-frequent-elements.py | 19 +++++++ problems/two-out-of-three.py | 17 ++++++ 23 files changed, 558 insertions(+), 9 deletions(-) create mode 100644 problems/balance-a-binary-search-tree.py create mode 100644 problems/find-distance-in-a-binary-tree.py create mode 100644 problems/find-duplicate-subtrees.py create mode 100644 problems/find-k-closest-elements.py create mode 100644 problems/insert-into-a-sorted-circular-linked-list.py create mode 100644 problems/lowest-common-ancestor-of-a-binary-tree-ii.py create mode 100644 problems/lowest-common-ancestor-of-a-binary-tree-iii.py create mode 100644 problems/lowest-common-ancestor-of-a-binary-tree-iv.py create mode 100644 problems/lowest-common-ancestor-of-deepest-leaves.py create mode 100644 problems/random-pick-with-weight.py create mode 100644 problems/range-sum-of-bst.py create mode 100644 problems/step-by-step-directions-from-a-binary-tree-node-to-another.py create mode 100644 problems/two-out-of-three.py diff --git a/problems/backspace-string-compare.py b/problems/backspace-string-compare.py index f3df6d2..cec9e8a 100644 --- a/problems/backspace-string-compare.py +++ b/problems/backspace-string-compare.py @@ -82,4 +82,24 @@ def backspaceCompare(self, s1, s2): j -= 1 return True - \ No newline at end of file + + +class Solution(object): + def backspaceCompare(self, s, t): + def helper(S): + ans = '' + i = len(S)-1 + backspaceCount = 0 + + while i>=0: + if S[i]=='#': + backspaceCount += 1 + else: + if backspaceCount>0: + backspaceCount -= 1 + else: + ans += S[i] + i -= 1 + return ans + + return helper(s)==helper(t) \ No newline at end of file diff --git a/problems/balance-a-binary-search-tree.py b/problems/balance-a-binary-search-tree.py new file mode 100644 index 0000000..015934d --- /dev/null +++ b/problems/balance-a-binary-search-tree.py @@ -0,0 +1,36 @@ +""" +Imagine a list of sorted nodes, if we wanted to use the nodes to form a balanced BST, which root should we use? +Yes, the one in the middle, since it can evenly spread two groups of nodes. This is what `getRoot()` does. +And we do the same for the left half and right half. And so on. And so on... + +Time: O(N), N is the number of nodes. +Space: O(N) +""" +class Solution(object): + def balanceBST(self, root): + def getInorderNodes(root): + nodes = [] + stack = [] + node = root + + while node or stack: + while node: + stack.append(node) + node = node.left + + node = stack.pop() + nodes.append(node) + node = node.right + + return nodes + + def getRoot(l, r): + if l>r: return None + m = (l+r)/2 + root = inorderNodes[m] + root.left = getRoot(l, m-1) + root.right = getRoot(m+1, r) + return root + + inorderNodes = getInorderNodes(root) + return getRoot(0, len(inorderNodes)-1) \ No newline at end of file diff --git a/problems/binary-search-tree-iterator.py b/problems/binary-search-tree-iterator.py index 65557ce..48d1458 100644 --- a/problems/binary-search-tree-iterator.py +++ b/problems/binary-search-tree-iterator.py @@ -61,4 +61,28 @@ def inOrderTraverse(root): #do something print node.val - node = node.right \ No newline at end of file + node = node.right + + + +class BSTIterator(object): + + def __init__(self, root): + self.stack = [] + self.node = root + + + + def next(self): + while self.node: + self.stack.append(self.node) + self.node = self.node.left + self.node = self.stack.pop() + returnVal = self.node.val + self.node = self.node.right + return returnVal + + + + def hasNext(self): + return self.node or self.stack \ No newline at end of file diff --git a/problems/binary-tree-vertical-order-traversal.py b/problems/binary-tree-vertical-order-traversal.py index ac0f3c6..1510ac0 100644 --- a/problems/binary-tree-vertical-order-traversal.py +++ b/problems/binary-tree-vertical-order-traversal.py @@ -24,4 +24,27 @@ def verticalOrder(self, root): if node.left: q.append((node.left, x-1)) if node.right: q.append((node.right, x+1)) - return [ans[x] for x in xrange(minX, maxX+1)] \ No newline at end of file + return [ans[x] for x in xrange(minX, maxX+1)] + + +class Solution(object): + def verticalOrder(self, root): + if not root: return [] + ans = [] + minX = float('inf') + maxX = float('-inf') + locations = collections.defaultdict(list) + q = collections.deque([(root, 0)]) + + while q: + node, x = q.popleft() + locations[x].append(node.val) + minX = min(minX, x) + maxX = max(maxX, x) + if node.left: q.append((node.left, x-1)) + if node.right: q.append((node.right, x+1)) + + for x in xrange(minX, maxX+1): + if locations[x]: ans.append(locations[x]) + + return ans \ No newline at end of file diff --git a/problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py b/problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py index cfd441f..a9cd2bf 100644 --- a/problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py +++ b/problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py @@ -101,4 +101,6 @@ def inOrderTraverse(root): #do something print node.val - node = node.right \ No newline at end of file + node = node.right + + \ No newline at end of file diff --git a/problems/copy-list-with-random-pointer.py b/problems/copy-list-with-random-pointer.py index 0790e26..ddf901e 100644 --- a/problems/copy-list-with-random-pointer.py +++ b/problems/copy-list-with-random-pointer.py @@ -55,5 +55,38 @@ def copyRandomList(self, head): """ Time: O(N). Two iteration. First iteration make a the clones. Second iteration setup the links. -Space: O(1). No extra space except the cloned node. -""" \ No newline at end of file +Space: O(N). +""" + + +""" +Time: O(N) +Space: O(1) +""" +class Solution(object): + def copyRandomList(self, head): + if not head: return head + curr = head + while curr: + nextCurr = curr.next + copy = Node(curr.val) + curr.next = copy + copy.next = nextCurr + curr = nextCurr + + copyHead = head.next + + curr = head + while curr: + if curr.random: curr.next.random = curr.random.next + curr = curr.next.next + + curr = head + while curr: + nextCurr = curr.next.next + if nextCurr: + curr.next.next = nextCurr.next + curr.next = nextCurr + curr = nextCurr + + return copyHead \ No newline at end of file diff --git a/problems/diameter-of-binary-tree.py b/problems/diameter-of-binary-tree.py index f30ea33..8af4f9b 100644 --- a/problems/diameter-of-binary-tree.py +++ b/problems/diameter-of-binary-tree.py @@ -83,3 +83,23 @@ def getMaxDepth(node): # return ans + +""" +For each route in the binary tree, we can view it from the highest node in the route. +So the length will be helper(node.left) + 1 + helper(node.right). +""" +class Solution(object): + def __init__(self): + self.ans = 0 #number of nodes in the longest route + + def diameterOfBinaryTree(self, root): + #return the longest length to the leaf including itself + #also update self.ans + def helper(node): + r = helper(node.right) if node.right else 0 + l = helper(node.left) if node.left else 0 + self.ans = max(self.ans, l+1+r) + return max(l+1, r+1) + + helper(root) + return self.ans-1 \ No newline at end of file diff --git a/problems/find-distance-in-a-binary-tree.py b/problems/find-distance-in-a-binary-tree.py new file mode 100644 index 0000000..b87dd1b --- /dev/null +++ b/problems/find-distance-in-a-binary-tree.py @@ -0,0 +1,28 @@ +class Solution(object): + def __init__(self): + self.lca = None + self.pHeight = 0 + self.qHeight = 0 + + def findDistance(self, root, p, q): + #find the count of p or q in node's subtree, set the first node we found that has count>=2 as lca. + def findCount(node): + if not node: return 0 + count = 0 + if node.val==p or node.val==q: count += 1 + count += findPQCount(node.left) + count += findPQCount(node.right) + if count>=2 and not self.lca: self.lca = node + return count + + def findHeight(node, h): + if not node: return + if node.val==p: self.pHeight = h + if node.val==q: self.qHeight = h + if self.pHeight and self.qHeight: return + findHeight(node.left, h+1) + findHeight(node.right, h+1) + + findCount(root) + findHeight(self.lca, 0) + return self.qHeight + self.pHeight \ No newline at end of file diff --git a/problems/find-duplicate-subtrees.py b/problems/find-duplicate-subtrees.py new file mode 100644 index 0000000..5729e8e --- /dev/null +++ b/problems/find-duplicate-subtrees.py @@ -0,0 +1,16 @@ +class Solution(object): + def findDuplicateSubtrees(self, root): + def dfs(node): + if not node: return '#' + string = str(node.val) + ',' + dfs(node.left) + ',' + dfs(node.right) + data[string].append(node) + return string + + data = collections.defaultdict(list) + ans = [] + + dfs(root) + + for s in data: + if len(data[s])>=2: ans.append(data[s][0]) + return ans \ No newline at end of file diff --git a/problems/find-k-closest-elements.py b/problems/find-k-closest-elements.py new file mode 100644 index 0000000..802279f --- /dev/null +++ b/problems/find-k-closest-elements.py @@ -0,0 +1,20 @@ +class Solution(object): + def findClosestElements(self, arr, K, X): + def isCloserThan(n1, n2, x): + return abs(x-n1)=len(arr) or (l>=0 and isCloserThan(arr[l], arr[r], X)): + output1.append(arr[l]) + l -= 1 + else: + output2.append(arr[r]) + r += 1 + + return output1[::-1]+output2 diff --git a/problems/insert-into-a-sorted-circular-linked-list.py b/problems/insert-into-a-sorted-circular-linked-list.py new file mode 100644 index 0000000..9a4a067 --- /dev/null +++ b/problems/insert-into-a-sorted-circular-linked-list.py @@ -0,0 +1,42 @@ +class Solution(object): + def insert(self, random, insertVal): + def allValSame(node): + curr = node.next + while curr!=node: + if curr.val!=node.val: return False + curr = curr.next + return True + + newNode = Node(insertVal) + + #handle null linked list + if not random: + newNode.next = newNode + return newNode + + #handle linked list with val all the same + if allValSame(random): + temp = random.next + random.next = newNode + newNode.next = temp + return random + + #find head and tail, head is the min val node, tail is the max val node. + curr = random + while curr.val<=curr.next.val: + curr = curr.next + tail = curr + head = curr.next + + #insert new node + if insertVal>=tail.val or insertVal<=head.val: + tail.next = newNode + newNode.next = head + else: + curr = head + while not curr.val<=insertVal<=curr.next.val: curr = curr.next + temp = curr.next + curr.next = newNode + newNode.next = temp + + return random \ No newline at end of file diff --git a/problems/lowest-common-ancestor-of-a-binary-tree-ii.py b/problems/lowest-common-ancestor-of-a-binary-tree-ii.py new file mode 100644 index 0000000..8f07177 --- /dev/null +++ b/problems/lowest-common-ancestor-of-a-binary-tree-ii.py @@ -0,0 +1,17 @@ +class Solution(object): + def __init__(self): + self.ans = None + + def lowestCommonAncestor(self, root, p, q): + def dfs(node): + if not node: return 0 + + count = 0 + if node is p or node is q: count += 1 + count += dfs(node.left) + count += dfs(node.right) + if count>=2 and not self.ans: self.ans = node + return count + + dfs(root) + return self.ans diff --git a/problems/lowest-common-ancestor-of-a-binary-tree-iii.py b/problems/lowest-common-ancestor-of-a-binary-tree-iii.py new file mode 100644 index 0000000..cfd14f7 --- /dev/null +++ b/problems/lowest-common-ancestor-of-a-binary-tree-iii.py @@ -0,0 +1,56 @@ +""" +Time: O(H), H is the height of the tree. +Space: O(1) +""" +class Solution(object): + def lowestCommonAncestor(self, p, q): + ancestorP = set() + ancestorQ = set() + + temp = p + while temp: + ancestorP.add(temp) + temp = temp.parent + + temp = q + while temp: + ancestorQ.add(temp) + temp = temp.parent + + commonAncestor = ancestorQ.intersection(ancestorP) + temp = q + while temp: + if temp in commonAncestor: return temp + temp = temp.parent + return None + + +""" +Time: O(LogN) +Space: O(LogN) + +Looking from backward, parents1 and parents2 will be the same at first, since they must have a common ancestor. +Find the last the same parents. +""" +class Solution(object): + def lowestCommonAncestor(self, p, q): + parents1 = [] + parents2 = [] + + curr = p + while curr: + parents1.append(curr) + curr = curr.parent + + curr = q + while curr: + parents2.append(curr) + curr = curr.parent + + i = len(parents1)-1 + j = len(parents2)-1 + while i>=0 and j>=0 and parents1[i]==parents2[j]: + i -= 1 + j -= 1 + return parents1[i+1] + diff --git a/problems/lowest-common-ancestor-of-a-binary-tree-iv.py b/problems/lowest-common-ancestor-of-a-binary-tree-iv.py new file mode 100644 index 0000000..f7458a3 --- /dev/null +++ b/problems/lowest-common-ancestor-of-a-binary-tree-iv.py @@ -0,0 +1,18 @@ +class Solution(object): + def __init__(self): + self.ans = None + + def lowestCommonAncestor(self, root, nodes): + def dfs(node): + if not node: return 0 + + count = 0 + if node in nodes: count += 1 + count += dfs(node.left) + count += dfs(node.right) + if count>=len(nodes) and not self.ans: self.ans = node + return count + + nodes = set(nodes) + dfs(root) + return self.ans \ No newline at end of file diff --git a/problems/lowest-common-ancestor-of-deepest-leaves.py b/problems/lowest-common-ancestor-of-deepest-leaves.py new file mode 100644 index 0000000..cffade3 --- /dev/null +++ b/problems/lowest-common-ancestor-of-deepest-leaves.py @@ -0,0 +1,41 @@ +class Solution(object): + def __init__(self): + self.ans = None + + def lcaDeepestLeaves(self, root): + def checkCount(node, deepestNode): + if not node: + count = 0 + if count==len(deepestNode) and not self.ans: self.ans = node + return 0 + + if node in deepestNode: + count = 1 + if count==len(deepestNode) and not self.ans: self.ans = node + return count + + leftCount = checkCount(node.left, deepestNode) + rightCount = checkCount(node.right, deepestNode) + + if leftCount+rightCount==len(deepestNode) and not self.ans: self.ans = node + return leftCount+rightCount + + q = collections.deque([(root, 0)]) + q2 = collections.deque() + deepestNode = set([node for node, h in q]) + + while q: + node, d = q.popleft() + if node.left: q2.append((node.left, d+1)) + if node.right: q2.append((node.right, d+1)) + if not q: + q = q2 + if q: deepestNode = set([node for node, h in q]) + q2 = collections.deque() + + checkCount(root, deepestNode) + return self.ans + + + + \ No newline at end of file diff --git a/problems/maximal-square.py b/problems/maximal-square.py index 4ba17d6..9e6711b 100644 --- a/problems/maximal-square.py +++ b/problems/maximal-square.py @@ -10,4 +10,24 @@ def maximalSquare(self, grid): if grid[i][j]=='1': dp[i+1][j+1] = min(dp[i][j], dp[i][j+1], dp[i+1][j])+1 ans = max(ans, dp[i+1][j+1]) - return ans**2 \ No newline at end of file + return ans**2 + + + +class Solution(object): + def maximalSquare(self, matrix): + """ + dp[i][j] := maximal square length with matrix[i-1][j-1] at the bottom right corner in the square + """ + ans = 0 + N = len(matrix) + M = len(matrix[0]) + + dp = [[0 for _ in xrange(M+1)] for _ in xrange(N+1)] + + for i in xrange(1, N+1): + for j in xrange(1, M+1): + if matrix[i-1][j-1]=='1': + dp[i][j] = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1])+1 + ans = max(ans, dp[i][j]**2) + return ans \ No newline at end of file diff --git a/problems/random-pick-with-weight.py b/problems/random-pick-with-weight.py new file mode 100644 index 0000000..9c88bd0 --- /dev/null +++ b/problems/random-pick-with-weight.py @@ -0,0 +1,29 @@ +""" +For W = [1,3,2,4] (total 10, 1+2+3+4) +Think of a line _,___,__,____ ([1,4,6,10]) +Now we randomly throw a ball on the line the probability to land on the first section will be 1/10. +the second section, 3/10. +the third section, 2/10. +the forth section, 4/10. + +Above is equivilant to we randomly pick a number [0~10) and see which section it is in. +And since the cumulative probability in the "line" is strictly increasing, we can use binary search. + +Time: O(LogN), N is the number of W. +Space: O(N). +""" +from random import randrange + +class Solution(object): + + def __init__(self, W): + self.line = [] #cumulative probability distribution + self.total = 0 + + for w in W: + self.total += w + self.line.append(self.total) + + def pickIndex(self): + rand = random.randrange(self.total) + return bisect.bisect(self.line, rand) \ No newline at end of file diff --git a/problems/range-sum-of-bst.py b/problems/range-sum-of-bst.py new file mode 100644 index 0000000..0ca07ed --- /dev/null +++ b/problems/range-sum-of-bst.py @@ -0,0 +1,11 @@ +class Solution(object): + def rangeSumBST(self, root, low, high): + def helper(node, low, high): + total = 0 + if not node: return total + if low<=node.val<=high: total += node.val + if node.val<=high: total += helper(node.right, low, high) + if node.val>=low: total += helper(node.left, low, high) + return total + + return helper(root, low, high) \ No newline at end of file diff --git a/problems/serialize-and-deserialize-binary-tree.py b/problems/serialize-and-deserialize-binary-tree.py index 9519b74..e48f9d2 100644 --- a/problems/serialize-and-deserialize-binary-tree.py +++ b/problems/serialize-and-deserialize-binary-tree.py @@ -39,4 +39,25 @@ def deserialize(self, data): q.append(node.right) i += 1 - return root \ No newline at end of file + return root + + + +#Preorder traversal +class Codec: + def serialize(self, root): + if not root: return '#,' + return str(root.val) + ',' + self.serialize(root.left) + self.serialize(root.right) + + def deserialize(self, data): + data = data.split(',')[::-1] + return self.getNode(data) + + def getNode(self, data): + if not data: return None + val = data.pop() + if val=='#': return None + node = TreeNode(val) + node.left = self.getNode(data) + node.right = self.getNode(data) + return node \ No newline at end of file diff --git a/problems/step-by-step-directions-from-a-binary-tree-node-to-another.py b/problems/step-by-step-directions-from-a-binary-tree-node-to-another.py new file mode 100644 index 0000000..a9177d4 --- /dev/null +++ b/problems/step-by-step-directions-from-a-binary-tree-node-to-another.py @@ -0,0 +1,36 @@ +class Solution(object): + def __init__(self): + self.lca = None + + def getDirections(self, root, startValue, destValue): + def findPath(node, path, val): + if not node: return False + if node.val==val: return True + + path.append('L') + if findPath(node.left, path, val): return True + path.pop() + + path.append('R') + if findPath(node.right, path, val): return True + path.pop() + + return False + + def findCount(node, startValue, destValue): + if not node: return 0 + count = 0 + if node.val==startValue or node.val==destValue: count += 1 + count += findCount(node.left, startValue, destValue) + count += findCount(node.right, startValue, destValue) + if count>=2 and not self.lca: self.lca = node + return count + + findCount(root, startValue, destValue) + + path1 = [] + findPath(self.lca, path1, startValue) + path2 = [] + findPath(self.lca, path2, destValue) + + return 'U'*len(path1) + ''.join(path2) \ No newline at end of file diff --git a/problems/subarray-sum-equals-k.py b/problems/subarray-sum-equals-k.py index 3220cff..3ed67dc 100644 --- a/problems/subarray-sum-equals-k.py +++ b/problems/subarray-sum-equals-k.py @@ -52,4 +52,4 @@ def subarraySum(self, nums, k): ans += prefixSumCount[I] #there are "prefixSumCount[I]" combinations of J-I that equals to k. prefixSumCount[J] += 1 - return ans \ No newline at end of file + return ans diff --git a/problems/top-k-frequent-elements.py b/problems/top-k-frequent-elements.py index fbb68a6..d2cb1a5 100644 --- a/problems/top-k-frequent-elements.py +++ b/problems/top-k-frequent-elements.py @@ -88,4 +88,23 @@ def topKFrequent(self, nums, k): ans.append(num) k -= 1 + return ans + +""" +Bucket sort for counts. +Space/Time: O(N) +""" +class Solution(object): + def topKFrequent(self, nums, k): + counter = collections.Counter(nums) + count2Nums = [[] for _ in xrange(len(nums)+1)] #count2Nums[i] := elements with count i + + for num in counter: + count2Nums[counter[num]].append(num) + + ans = [] + for i in xrange(len(count2Nums)-1, -1, -1): + ans += count2Nums[i] + if len(ans)>=k: break + return ans \ No newline at end of file diff --git a/problems/two-out-of-three.py b/problems/two-out-of-three.py new file mode 100644 index 0000000..8518903 --- /dev/null +++ b/problems/two-out-of-three.py @@ -0,0 +1,17 @@ +class Solution(object): + def twoOutOfThree(self, nums1, nums2, nums3): + ans = [] + + counter = collections.Counter() + + for num in list(set(nums1)): + counter[num] += 1 + for num in list(set(nums2)): + counter[num] += 1 + for num in list(set(nums3)): + counter[num] += 1 + + for num in counter: + if counter[num]>=2: ans.append(num) + + return ans \ No newline at end of file From 13fbec9603dbb4dbab725cb38842f9e0008a5bfb Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 15 Feb 2022 17:38:32 +0800 Subject: [PATCH 11/52] no message --- problems/campus-bikes-ii.py | 35 ++++++++ ...ee-from-inorder-and-postorder-traversal.py | 33 ++++++- ...binary-tree-to-match-preorder-traversal.py | 23 +++++ problems/kth-largest-element-in-an-array.py | 32 ++++++- problems/maximum-compatibility-score-sum.py | 44 +++++++++ ...-make-at-least-one-valid-path-in-a-grid.py | 32 +++++++ problems/minimum-xor-sum-of-two-arrays.py | 24 +++++ problems/network-delay-time.py | 90 ++++++++++++++++++- ...number-of-ways-to-arrive-at-destination.py | 33 +++++++ problems/path-with-maximum-probability.py | 24 +++++ problems/reverse-linked-list.py | 16 ++++ problems/the-maze-ii.py | 45 ++++++++++ problems/top-k-frequent-elements.py | 39 ++++++++ problems/trapping-rain-water-ii.py | 28 ++++++ 14 files changed, 493 insertions(+), 5 deletions(-) create mode 100644 problems/campus-bikes-ii.py create mode 100644 problems/flip-binary-tree-to-match-preorder-traversal.py create mode 100644 problems/maximum-compatibility-score-sum.py create mode 100644 problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py create mode 100644 problems/minimum-xor-sum-of-two-arrays.py create mode 100644 problems/number-of-ways-to-arrive-at-destination.py create mode 100644 problems/path-with-maximum-probability.py create mode 100644 problems/the-maze-ii.py create mode 100644 problems/trapping-rain-water-ii.py diff --git a/problems/campus-bikes-ii.py b/problems/campus-bikes-ii.py new file mode 100644 index 0000000..a292d91 --- /dev/null +++ b/problems/campus-bikes-ii.py @@ -0,0 +1,35 @@ +""" +state[i] := ith bike has been selected. +For example, there are M bikes, 0000, 0100, 0110, 1111..... + +Time: O(ELogE) +Space: O(E) +""" +class Solution(object): + def assignBikes(self, workers, bikes): + M = len(bikes) + N = len(workers) + costs = [[0]*N for _ in xrange(M)] + + for i in xrange(M): + for j in xrange(N): + costs[i][j] = abs(workers[j][0]-bikes[i][0])+abs(workers[j][1]-bikes[i][1]) + + pq = [(0, '0'*M)] + visited = set() + while pq: + cost, state = heapq.heappop(pq) + if state in visited: continue + visited.add(state) + + j = state.count('1') #j users have selected bikes + if j>=N: return cost + + for i in xrange(M): + if state[i]=='1': continue + + nextState = state[:i] + '1' + state[i+1:] + if nextState in visited: continue + heapq.heappush(pq, (cost+costs[i][j], nextState)) + + return float('inf') \ No newline at end of file diff --git a/problems/construct-binary-tree-from-inorder-and-postorder-traversal.py b/problems/construct-binary-tree-from-inorder-and-postorder-traversal.py index 1a46912..f8304fc 100644 --- a/problems/construct-binary-tree-from-inorder-and-postorder-traversal.py +++ b/problems/construct-binary-tree-from-inorder-and-postorder-traversal.py @@ -68,4 +68,35 @@ def helper(i, j, k, l): index = {} #the index of inorder for i, n in enumerate(inorder): index[n] = i - return helper(0, len(inorder), 0, len(postorder)) \ No newline at end of file + return helper(0, len(inorder), 0, len(postorder)) + + + + + +""" +Inorder: [LEFT]root[RIGHT] +Postorder: [LEFT][RIGHT]root +As you can see, rootVal is the last val in postorder. + +i and j is the range of the inorder +k and l is the range of the postorder +Get the root +Also recursively use the same method to get the left and right node, but this time we change the inorder and postorder. +""" +class Solution(object): + def buildTree(self, inorder, postorder): + def helper(i, j, k, l): + if i>j or k>l: return None + rootVal = postorder[l] + root = TreeNode(rootVal) + r = inorderIndex[rootVal] + leftLength = r-i + rightLength = j-r + root.left = helper(i, r-1, k, k+leftLength-1) + root.right = helper(r+1, j, k+leftLength, k+leftLength+rightLength-1) + return root + + inorderIndex = {} + for i, n in enumerate(inorder): inorderIndex[n] = i + return helper(0, len(inorder)-1, 0, len(postorder)-1) diff --git a/problems/flip-binary-tree-to-match-preorder-traversal.py b/problems/flip-binary-tree-to-match-preorder-traversal.py new file mode 100644 index 0000000..8727e28 --- /dev/null +++ b/problems/flip-binary-tree-to-match-preorder-traversal.py @@ -0,0 +1,23 @@ +class Solution(object): + def flipMatchVoyage(self, root, voyage): + def helper(node): + if not node: return + if node.val!=voyage[self.i]: + self.valid = False + return + + self.i += 1 + if node.left and node.left.val!=voyage[self.i]: + self.ans.append(node.val) + helper(node.right) + helper(node.left) + + else: + helper(node.left) + helper(node.right) + + self.ans = [] + self.i = 0 + self.valid = True + helper(root) + return self.ans if self.valid else [-1] \ No newline at end of file diff --git a/problems/kth-largest-element-in-an-array.py b/problems/kth-largest-element-in-an-array.py index d12f59c..27c4b72 100644 --- a/problems/kth-largest-element-in-an-array.py +++ b/problems/kth-largest-element-in-an-array.py @@ -63,4 +63,34 @@ def partition(A, l, r, p): k = len(nums)-k #redefine the problem to find the kth nums when sorted sortRange(nums, 0, len(nums)-1) - return nums[k] \ No newline at end of file + return nums[k] + + +#Quick Select +class Solution(object): + def findKthLargest(self, nums, K): + def quickSelect(A, s, e, K): + pivot = A[(s+e)/2] + i = s + t = s + j = e + + while t<=j: + if A[t]=K: + return quickSelect(A, j+1, e, K) + elif e-i+1>=K: + return pivot + else: + return quickSelect(A, s, i-1, K-(e-(i-1))) + + return quickSelect(nums, 0, len(nums)-1, K) \ No newline at end of file diff --git a/problems/maximum-compatibility-score-sum.py b/problems/maximum-compatibility-score-sum.py new file mode 100644 index 0000000..a0f744c --- /dev/null +++ b/problems/maximum-compatibility-score-sum.py @@ -0,0 +1,44 @@ +""" +Time: O(ELogE), E is the edge of the graph. +Note that state[i] means if the ith student is matched or not. (for example M=4, 0000, 0010, 0111, 1111...) +2^M is the number of states. So in this case E will be 2^M x M. + +Space: O(2^M) +""" +class Solution(object): + def maxCompatibilitySum(self, students, mentors): + M = len(students) + N = len(students[0]) + + #initialize reverseScores + reverseScores = [[0]*M for _ in xrange(M)] + for i in xrange(M): + for j in xrange(M): + reverseScore = 0 + for k in xrange(N): + if students[i][k]!=mentors[j][k]: + reverseScore += 1 + reverseScores[i][j] = reverseScore + + #Dijkstra + startState = '0'*M + endState = '1'*M + visited = set() + pq = [(0, startState)] + + while pq: + cost, state = heapq.heappop(pq) + if state in visited: continue + visited.add(state) + + if state==endState: return M*N-cost + + j = state.count('1') + for i in xrange(M): + if state[i]=='1': continue + + nextState = state[:i]+'1'+state[i+1:] + if nextState in visited: continue + heapq.heappush(pq, (cost+reverseScores[i][j], nextState)) + + return -1 \ No newline at end of file diff --git a/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py b/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py new file mode 100644 index 0000000..2188f4a --- /dev/null +++ b/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py @@ -0,0 +1,32 @@ +class Solution(object): + def minCost(self, grid): + pq = [(0, False, 0, 0, 0)] + visited = set() + M = len(grid) + N = len(grid[0]) + + while pq: + cost, modified, direction, x, y = heapq.heappop(pq) + if x<0 or x>=M or y<0 or y>=N: continue + if (direction, x, y) in visited: continue + visited.add((direction, x, y)) + + if x==M-1 and y==N-1: return cost + + if direction==0: direction = grid[x][y] + + if direction==1: + heapq.heappush(pq, (cost, False, 0, x, y+1)) + elif direction==2: + heapq.heappush(pq, (cost, False, 0, x, y-1)) + elif direction==3: + heapq.heappush(pq, (cost, False, 0, x+1, y)) + elif direction==4: + heapq.heappush(pq, (cost, False, 0, x-1, y)) + + if not modified: + for d in [1,2,3,4]: + if d==grid[x][y]: continue + heapq.heappush(pq, (cost+1, True, d, x, y)) + + return float('inf') \ No newline at end of file diff --git a/problems/minimum-xor-sum-of-two-arrays.py b/problems/minimum-xor-sum-of-two-arrays.py new file mode 100644 index 0000000..7c3a195 --- /dev/null +++ b/problems/minimum-xor-sum-of-two-arrays.py @@ -0,0 +1,24 @@ +""" +state[i] := nums1[i] has been matched. +""" +class Solution(object): + def minimumXORSum(self, nums1, nums2): + N = len(nums1) + + pq = [(0, '0'*N)] + visited = set() + while pq: + s, state = heapq.heappop(pq) + if state in visited: continue + visited.add(state) + + j = state.count('1') + if j==N: return s + + for i in xrange(N): + if state[i]=='1': continue + nextState = state[:i]+'1'+state[i+1:] + if nextState in visited: continue + heapq.heappush(pq, ((s+(nums1[i]^nums2[j-1]), nextState))) + + return float('inf') \ No newline at end of file diff --git a/problems/network-delay-time.py b/problems/network-delay-time.py index 8098a31..aa67bb0 100644 --- a/problems/network-delay-time.py +++ b/problems/network-delay-time.py @@ -118,12 +118,96 @@ def networkDelayTime(self, times, n, k): +""" +Dijkstra BFS+Priority Queue Implementation +Time: O(ELogE), E is the edges count in the graph. +""" +class Solution(object): + def networkDelayTime(self, times, N, K): + ans = -1 #max time from K to any + visited = set() + pq = [(0, K)] #[(node's distance to K, node)] + + #construct adjacency list + adj = collections.defaultdict(list) + for u, v, w in times: + adj[u].append((w, v)) + + while pq: + dis, node = heapq.heappop(pq) + if node in visited: continue + visited.add(node) + + ans = max(ans, dis) + + for d2, nei in adj[node]: + heapq.heappush(pq, (d2+dis, nei)) + + return ans if len(visited)==N else -1 +""" +Dijkstra Normal Implementation +Time: O(N^2), N is the nodes count in the graph. +""" +class Solution(object): + def networkDelayTime(self, times, N, K): + #construct dis. dis[n] := node n distance to K + dis = {} + for n in xrange(1, N+1): + dis[n] = float('inf') + dis[K] = 0 + + visited = set() + + #construct adjacency list + adj = collections.defaultdict(list) + for u, v, w in times: + adj[u].append((w, v)) + + while len(visited)=N or j<0 or j>=M: continue + if maze[i][j]==1: continue + + if i==destination[0] and j==destination[1] and direction=='stop': return dis + + if direction=='stop': + heapq.heappush(pq, (dis+1, i-1, j, 'left')) + heapq.heappush(pq, (dis+1, i+1, j, 'right')) + heapq.heappush(pq, (dis+1, i, j-1, 'down')) + heapq.heappush(pq, (dis+1, i, j+1, 'up')) + elif direction=='left': + if i-1<0 or i-1>=N or j<0 or j>=M or maze[i-1][j]==1: + heapq.heappush(pq, (dis, i, j, 'stop')) + else: + heapq.heappush(pq, (dis+1, i-1, j, direction)) + elif direction=='right': + if i+1<0 or i+1>=N or j<0 or j>=M or maze[i+1][j]==1: + heapq.heappush(pq, (dis, i, j, 'stop')) + else: + heapq.heappush(pq, (dis+1, i+1, j, direction)) + elif direction=='down': + if i<0 or i>=N or j-1<0 or j-1>=M or maze[i][j-1]==1: + heapq.heappush(pq, (dis, i, j, 'stop')) + else: + heapq.heappush(pq, (dis+1, i, j-1, direction)) + elif direction=='up': + if i<0 or i>=N or j+1<0 or j+1>=M or maze[i][j+1]==1: + heapq.heappush(pq, (dis, i, j, 'stop')) + else: + heapq.heappush(pq, (dis+1, i, j+1, direction)) + + return -1 \ No newline at end of file diff --git a/problems/top-k-frequent-elements.py b/problems/top-k-frequent-elements.py index d2cb1a5..e1dea8c 100644 --- a/problems/top-k-frequent-elements.py +++ b/problems/top-k-frequent-elements.py @@ -107,4 +107,43 @@ def topKFrequent(self, nums, k): ans += count2Nums[i] if len(ans)>=k: break + return ans + + +# Quick Select +class Solution(object): + def topKFrequent(self, nums, K): + def quickselect(A, s, e, K): + i = s + t = s + j = e + + pivot = A[(s+e)/2][0] + while t<=j: + if A[t][0]=K: + return quickselect(A, j+1, e, K) + elif e-(i-1)>=K: + return pivot + else: + return quickselect(A, s, i-1, K-(e-i+1)) + + ans = [] + counter = collections.Counter(nums) + freqs = [(counter[num], num) for num in counter] + + KthLargestFreq = quickselect(freqs, 0, len(freqs)-1, K) + + for freq, num in freqs: + if freq>=KthLargestFreq: ans.append(num) + return ans \ No newline at end of file diff --git a/problems/trapping-rain-water-ii.py b/problems/trapping-rain-water-ii.py new file mode 100644 index 0000000..dd14bc7 --- /dev/null +++ b/problems/trapping-rain-water-ii.py @@ -0,0 +1,28 @@ +class Solution(object): + def trapRainWater(self, heightMap): + pq = [] + N = len(heightMap) + M = len(heightMap[0]) + visited = set() + ans = 0 + curr = float('-inf') + + for i in xrange(N): + for j in xrange(M): + if i==0 or i==N-1 or j==0 or j==M-1: + heapq.heappush(pq, (heightMap[i][j], i, j)) + + while pq: + h, i, j = heapq.heappop(pq) + if (i, j) in visited: continue + visited.add((i, j)) + + if h>curr: curr = h + ans += (curr-h) + + for iNext, jNext in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: + if iNext<0 or iNext>=N or jNext<0 or jNext>=M: continue + if (iNext, jNext) in visited: continue + heapq.heappush(pq, (heightMap[iNext][jNext], iNext, jNext)) + + return ans \ No newline at end of file From 0de2fcff4588bec862c266b090d52b8b24f39b83 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sun, 20 Feb 2022 17:41:52 +0800 Subject: [PATCH 12/52] no message --- problems/combinations.py | 15 ++++++ ...ount-all-valid-pickup-and-delivery-opti.py | 5 ++ problems/logger-rate-limiter.py | 22 +++++++++ ...nimum-cost-to-reach-city-with-discounts.py | 25 ++++++++++ ...to-convert-binary-matrix-to-zero-matrix.py | 46 +++++++++++++++++++ problems/permutation-sequence.py | 14 ++++++ problems/permutations-ii.py | 25 ++++++++++ problems/permutations.py | 26 ++++++++++- problems/profitable-schemes.py | 28 ++++++++++- problems/single-threaded-cpu.py | 22 +++++++++ problems/target-sum.py | 21 ++++++++- 11 files changed, 246 insertions(+), 3 deletions(-) create mode 100644 problems/count-all-valid-pickup-and-delivery-opti.py create mode 100644 problems/minimum-cost-to-reach-city-with-discounts.py create mode 100644 problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py create mode 100644 problems/permutation-sequence.py create mode 100644 problems/single-threaded-cpu.py diff --git a/problems/combinations.py b/problems/combinations.py index 49f7ebf..f3a0937 100644 --- a/problems/combinations.py +++ b/problems/combinations.py @@ -83,6 +83,21 @@ def dfs(n_min, path): +class Solution(object): + def combine(self, N, K): + def dfs(comb, start, N, K): + if len(comb)==K: ans.append(comb[:]) + + for n in xrange(start, N+1): + comb.append(n) + dfs(comb, n+1, N, K) + comb.pop() + + ans = [] + dfs([], 1, N, K) + return ans + + diff --git a/problems/count-all-valid-pickup-and-delivery-opti.py b/problems/count-all-valid-pickup-and-delivery-opti.py new file mode 100644 index 0000000..8bfe82a --- /dev/null +++ b/problems/count-all-valid-pickup-and-delivery-opti.py @@ -0,0 +1,5 @@ +class Solution(object): + def countOrders(self, n): + d = 1 + for i in xrange(1, 2*n, 2): d*=i + return math.factorial(n)*d % (10**9 + 7) \ No newline at end of file diff --git a/problems/logger-rate-limiter.py b/problems/logger-rate-limiter.py index 2a1a7e6..0f5f7ad 100644 --- a/problems/logger-rate-limiter.py +++ b/problems/logger-rate-limiter.py @@ -6,5 +6,27 @@ def shouldPrintMessage(self, timestamp, message): if message not in self.log or self.log[message]+10<=timestamp: self.log[message] = timestamp return True + else: + return False + + + +class Logger(object): + + def __init__(self): + #stores the messages within 10 seconds + self.q = collections.deque() + self.set = set() + + + def shouldPrintMessage(self, timestamp, message): + while self.q and timestamp-self.q[0][0]>=10: + time, msg = self.q.popleft() + self.set.remove(msg) + + if message not in self.set: + self.q.append((timestamp, message)) + self.set.add(message) + return True else: return False \ No newline at end of file diff --git a/problems/minimum-cost-to-reach-city-with-discounts.py b/problems/minimum-cost-to-reach-city-with-discounts.py new file mode 100644 index 0000000..93205f3 --- /dev/null +++ b/problems/minimum-cost-to-reach-city-with-discounts.py @@ -0,0 +1,25 @@ +class Solution(object): + def minimumCost(self, n, highways, discounts): + pq = [(0, discounts, 0)] + visited = set() + + adj = collections.defaultdict(list) + for city1, city2, toll in highways: + adj[city1].append((city2, toll)) + adj[city2].append((city1, toll)) + + + while pq: + toll, d, city = heapq.heappop(pq) + if (d, city) in visited: continue + visited.add((d, city)) + + if city==n-1: return toll + + for nei, toll2 in adj[city]: + if (d, nei) not in visited: + heapq.heappush(pq, (toll+toll2, d, nei)) + if d>0 and (d-1, nei) not in visited: + heapq.heappush(pq, (toll+toll2/2, d-1, nei)) + + return -1 \ No newline at end of file diff --git a/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py b/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py new file mode 100644 index 0000000..2c07805 --- /dev/null +++ b/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py @@ -0,0 +1,46 @@ +class Solution(object): + def minFlips(self, mat): + def flip(mat, m, n): + mat[m][n] = 0 if mat[m][n]==1 else 1 + if m+1=0: mat[m-1][n] = 0 if mat[m-1][n]==1 else 1 + if n-1>=0: mat[m][n-1] = 0 if mat[m][n-1]==1 else 1 + + def check(mat, state): + for i, b in enumerate(state): + if b=='1': + m = i/len(mat[0]) + n = i%len(mat[0]) + flip(mat, m, n) + + for i in xrange(len(mat)): + for j in xrange(len(mat[0])): + if mat[i][j]==1: return False + + return True + + + M = len(mat) + N = len(mat[0]) + q = collections.deque(['0'*(M*N)]) + visited = set() + + while q: + state = q.popleft() + if state in visited: continue + visited.add(state) + + if check([row[:] for row in mat], state): return state.count('1') + + for i in xrange(len(state)): + if state[i]=='1': continue + nextState = state[:i] + '1' +state[i+1:] + q.append(nextState) + + return -1 + + + + + \ No newline at end of file diff --git a/problems/permutation-sequence.py b/problems/permutation-sequence.py new file mode 100644 index 0000000..f7e5be2 --- /dev/null +++ b/problems/permutation-sequence.py @@ -0,0 +1,14 @@ +class Solution(object): + def getPermutation(self, N, K): + K = K-1 #make it 0-index + nums = range(1, N+1) + ans = '' + + while N>0: + a = K/math.factorial(N-1) + ans += str(nums[a]) + nums.pop(a) + + K -= math.factorial(N-1)*(a+1) + N -= 1 + return ans \ No newline at end of file diff --git a/problems/permutations-ii.py b/problems/permutations-ii.py index e4aa3c2..a6c9ff7 100644 --- a/problems/permutations-ii.py +++ b/problems/permutations-ii.py @@ -53,3 +53,28 @@ def helper(path): counter = collections.Counter(nums) helper([]) return ans + + +""" +差板法 +""" +class Solution(object): + def permuteUnique(self, nums): + if not nums: return [] + + permutations = collections.deque([[nums[0]]]) + + for i in xrange(1, len(nums)): + num = nums[i] + l = len(permutations) + + while l: + permutation = permutations.popleft() + for j in xrange(len(permutation)+1): + if 0=0 and n-group[i-1]>=0 else 0) + dp[i-1][n][p] if i==len(profit) and p>=minProfit and n<=maxMember: count += dp[i][n][p] return count - \ No newline at end of file + + + +""" +dp[i][g][p] := consider only crime[:i] the scheme that can generate profit p using man power g. +""" +class Solution(object): + def profitableSchemes(self, n, minProfit, group, profit): + N = len(profit) + + dp = [[[0]*(n+2) for _ in xrange(minProfit+1)] for _ in xrange(N+1)] + dp[0][0][0] = 1 + + for i in xrange(1, N+1): + for p in xrange(minProfit+1): + for g in xrange(n+1): + pi = profit[i-1] + gi = group[i-1] + + #considerting last round using p and g + dp[i][p][g] += dp[i-1][p][g] + dp[i][min(pi+p, minProfit)][min(gi+g, n+1)] += dp[i-1][p][g] + + ans = 0 + for g in xrange(n+1): + ans += dp[N][minProfit][g] + return ans % (10**9 + 7) \ No newline at end of file diff --git a/problems/single-threaded-cpu.py b/problems/single-threaded-cpu.py new file mode 100644 index 0000000..fe30e21 --- /dev/null +++ b/problems/single-threaded-cpu.py @@ -0,0 +1,22 @@ +class Solution(object): + def getOrder(self, tasks): + ans = [] + tasks = sorted([(task[0], task[1], i) for i, task in enumerate(tasks)], reverse=True) + pq = [] #tasks available + now = 0 + + + while tasks or pq: + #check if the task is availiable, if yes, add to pq + while tasks and tasks[-1][0]<=now: + startTime, processTime, i = tasks.pop() + heapq.heappush(pq, (processTime, i)) + + if pq: + processTime, i = heapq.heappop(pq) + ans.append(i) + now += processTime + else: + now = tasks[-1][0] + + return ans \ No newline at end of file diff --git a/problems/target-sum.py b/problems/target-sum.py index 75d9abe..c216522 100644 --- a/problems/target-sum.py +++ b/problems/target-sum.py @@ -55,4 +55,23 @@ def findTargetSumWays(self, nums, target): for t in xrange(minTarget, maxTarget+1): dp[i][t] = (dp[i-1][t-nums[i-1]] if t-nums[i-1]>=minTarget else 0) + (dp[i-1][t+nums[i-1]] if t+nums[i-1]<=maxTarget else 0) - return dp[N][target] \ No newline at end of file + return dp[N][target] + + +""" +dp[i][s] := considerting nums[:i] how many expressions can sum up to s. +dp[0][0] = 1 +""" +class Solution(object): + def findTargetSumWays(self, nums, target): + S = sum(nums) + if not -S<=target<=S: return 0 + + dp = [{s:0 for s in xrange(-S, S+1)} for _ in xrange(len(nums)+1)] + dp[0][0] = 1 + + for i in xrange(1, len(nums)+1): + for s in xrange(-S, S+1): + dp[i][s] = (dp[i-1][s+nums[i-1]] if s+nums[i-1]<=S else 0) + (dp[i-1][s-nums[i-1]] if s-nums[i-1]>=-S else 0) + + return dp[-1][target] \ No newline at end of file From 2191a5373def2d31ee450db15032179ecc43f11c Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 1 Mar 2022 17:01:54 +0800 Subject: [PATCH 13/52] no message --- .../amount-of-new-area-painted-each-day.py | 40 ++++++ problems/basic-calculator-ii.py | 31 +++++ problems/buildings-with-an-ocean-view.py | 16 +++ ...earch-tree-to-sorted-doubly-linked-list.py | 26 +++- problems/custom-sort-string.py | 20 +++ problems/dot-product-of-two-sparse-vectors.py | 16 +++ ...ll-possible-recipes-from-given-supplies.py | 33 +++++ problems/k-closest-points-to-origin.py | 118 +++++++++++++++++- .../longest-increasing-path-in-a-matrix.py | 31 +++++ problems/making-a-large-island.py | 44 +++++++ ...to-convert-binary-matrix-to-zero-matrix.py | 4 - problems/minimum-time-difference.py | 32 +++++ problems/next-permutation.py | 31 ++++- problems/powx-n.py | 12 ++ problems/simplify-path.py | 18 +++ problems/student-attendance-record-ii.py | 1 - problems/swap-adjacent-in-lr-string.py | 18 +++ problems/valid-number.py | 44 +++++++ problems/valid-palindrome-ii.py | 29 +++++ problems/valid-word-abbreviation.py | 30 +++++ ...rtical-order-traversal-of-a-binary-tree.py | 41 +++++- 21 files changed, 626 insertions(+), 9 deletions(-) create mode 100644 problems/amount-of-new-area-painted-each-day.py create mode 100644 problems/basic-calculator-ii.py create mode 100644 problems/buildings-with-an-ocean-view.py create mode 100644 problems/custom-sort-string.py create mode 100644 problems/dot-product-of-two-sparse-vectors.py create mode 100644 problems/find-all-possible-recipes-from-given-supplies.py create mode 100644 problems/longest-increasing-path-in-a-matrix.py create mode 100644 problems/making-a-large-island.py create mode 100644 problems/minimum-time-difference.py create mode 100644 problems/powx-n.py create mode 100644 problems/simplify-path.py create mode 100644 problems/swap-adjacent-in-lr-string.py create mode 100644 problems/valid-number.py create mode 100644 problems/valid-palindrome-ii.py create mode 100644 problems/valid-word-abbreviation.py diff --git a/problems/amount-of-new-area-painted-each-day.py b/problems/amount-of-new-area-painted-each-day.py new file mode 100644 index 0000000..a5504d5 --- /dev/null +++ b/problems/amount-of-new-area-painted-each-day.py @@ -0,0 +1,40 @@ +""" +1. Build sorted records = [(position, index, isStart)...] +2. Iterate through all positions and maintain a box with all the "index" of the records its position is in start ~ end +3. The smallest index in the box is the actual one that is paiting. + +Time: O(NLogN+P), N is the count of paint. Sorting the records takes NLogN. P is the max position. +Although there is a while loop when iterate through P, each record is only being iterated once. +O(NLogN + P + NLogN) ~= O(NLogN + P) +Space: O(N) +""" +from sortedcontainers import SortedList + +class Solution(object): + def amountPainted(self, paint): + ans = [0]*len(paint) + box = SortedList() + records = [] + maxPos = float('-inf') + + #[1] + for i, (start, end) in enumerate(paint): + records.append((start, i, -1)) + records.append((end, i, 1)) + maxPos = max(maxPos, end) + + records.sort() + + #[2] + i = 0 + for pos in xrange(maxPos+1): + while icurrMaxHeight: ans.append(i) + currMaxHeight = max(currMaxHeight, h) + + return reversed(ans) \ No newline at end of file diff --git a/problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py b/problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py index a9cd2bf..f813a37 100644 --- a/problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py +++ b/problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py @@ -103,4 +103,28 @@ def inOrderTraverse(root): node = node.right - \ No newline at end of file +""" +Time: O(N) +Space: O(LogN) +""" +class Solution(object): + def treeToDoublyList(self, root): + def helper(node): + ll = rr = node + if node.left: + ll, lr = helper(node.left) + node.left = lr + lr.right = node + + if node.right: + rl, rr = helper(node.right) + node.right = rl + rl.left = node + + return ll, rr + + if not root: return root + left, right = helper(root) + right.right = left + left.left = right + return left \ No newline at end of file diff --git a/problems/custom-sort-string.py b/problems/custom-sort-string.py new file mode 100644 index 0000000..2e63523 --- /dev/null +++ b/problems/custom-sort-string.py @@ -0,0 +1,20 @@ +""" +Take a look at the char in s. +For the char that is in the order, rearrange them to sortedChars with respect to the "order". +For the char that is in not the order, put them in postString. +""" +class Solution(object): + def customSortString(self, order, s): + sortedChars = '' + counter = collections.Counter(s) + for c in order: + if c in order: + sortedChars += c*counter[c] + + orderSet = set(order) + postString = '' + for c in s: + if c not in orderSet: + postString += c + + return sortedChars+postString \ No newline at end of file diff --git a/problems/dot-product-of-two-sparse-vectors.py b/problems/dot-product-of-two-sparse-vectors.py new file mode 100644 index 0000000..be69714 --- /dev/null +++ b/problems/dot-product-of-two-sparse-vectors.py @@ -0,0 +1,16 @@ +class SparseVector: + def __init__(self, nums): + self.indices = set() + self.values = {} + + for i, n in enumerate(nums): + if n!=0: + self.indices.add(i) + self.values[i] = n + + def dotProduct(self, vec): + products = 0 + indices = self.indices.intersection(vec.indices) + for i in indices: + products += self.values[i]*vec.values[i] + return products \ No newline at end of file diff --git a/problems/find-all-possible-recipes-from-given-supplies.py b/problems/find-all-possible-recipes-from-given-supplies.py new file mode 100644 index 0000000..13772ac --- /dev/null +++ b/problems/find-all-possible-recipes-from-given-supplies.py @@ -0,0 +1,33 @@ +""" +Use Topological Sort +1. Build an adj list and inbound. +2. Starts from supplies topologically traverse the map. +3. For each node popping up, if it is in recipes, add it to ans. + +Time: O(N), N is the number of "nodes" (ingredients+recipes) +Space: O(N). +""" +class Solution(object): + def findAllRecipes(self, recipes, ingredients, supplies): + N = len(recipes) + adj = collections.defaultdict(list) + inbounds = collections.Counter() + q = collections.deque(supplies) + recipeSet = set(recipes) + ans = [] + + for i, recipe in enumerate(recipes): + for ingredient in ingredients[i]: + adj[ingredient].append(recipe) + inbounds[recipe] += 1 + + while q: + node = q.popleft() + + if node in recipeSet: ans.append(node) + + for nei in adj[node]: + inbounds[nei] -= 1 + if inbounds[nei]==0: q.append(nei) + + return ans \ No newline at end of file diff --git a/problems/k-closest-points-to-origin.py b/problems/k-closest-points-to-origin.py index 8af9889..1f536c1 100644 --- a/problems/k-closest-points-to-origin.py +++ b/problems/k-closest-points-to-origin.py @@ -12,4 +12,120 @@ def kClosest(self, points, k): else: heapq.heappush(h, (-d, x, y)) - return [(x, y) for _, x, y in h] \ No newline at end of file + return [(x, y) for _, x, y in h] + + +""" +1. Process `points` into `distances`. + +2. Binary search the "distance". For every distance: +Split the elements in `distances` by distance +Put the ones smaller to smaller. +Put the ones larger to larger. +If len(smaller)<=k, then all the elements in the smaller must belong to the `ans`, do the same thing to the larger. +Else we ignore the larger and do the same thing to the smaller again. + +Time: O(N) +The binary search range in average is N, N/2, N/4... = 2N +Space: O(N) +""" +class Solution(object): + def kClosest(self, points, K): + #[1] + maxD = float('-inf') + minD = float('inf') + distances = [] + for x, y in points: + distance = ((x**2+y**2)**0.5) + distances.append((distance, x, y)) + maxD = max(maxD, distance) + minD = min(minD, distance) + + #[2] + ans = [] + smaller = [] + larger = [] + while K>0: + #split distances into smaller and larger + distance = (maxD+minD)/2 + for d, x, y in distances: + if d<=distance: + smaller.append((d, x, y)) + else: + larger.append((d, x, y)) + + if len(smaller)<=K: + ans += smaller + K -= len(smaller) + distances = larger + minD = distance + larger = [] + smaller = [] + else: + distances = smaller + maxD = distance + larger = [] + smaller = [] + + return [(x, y) for _, x, y in ans] + + + +""" +Quick Select +Time: O(N) +Space: O(N), can be optimize to O(1). +""" +class Solution(object): + def kClosest(self, points, K): + """ + Start State: + i = s #next element after "SSS"s + t = s #unprocessed elements + j = e #next element after "LLLL"s + + SSSPP?????LLL + i t j + + End State: + SSSPPPPPLLLLL + i jt + """ + def quickSelect(distances, s, e, k): + + pivot = distances[(s+e)/2][0] + i = s + j = e + t = s + + while t<=j: + if pivotdistances[t][0]: + distances[t], distances[i] = distances[i], distances[t] + i += 1 + t += 1 + else: + t += 1 + + if i-s>=k: + return quickSelect(distances, s, i, k) + elif j-s+1>=k: + return pivot + else: + return quickSelect(distances, t, e, k-(t-s)) + + distances = [] + for x, y in points: + distance = ((x**2+y**2)**0.5) + distances.append((distance, x, y)) + + kthSmallestDistance = quickSelect(distances, 0, len(distances)-1, K) + + ans = [] + for d, x, y in distances: + if len(ans)==K: break + if d<=kthSmallestDistance: ans.append((x, y)) + + return ans \ No newline at end of file diff --git a/problems/longest-increasing-path-in-a-matrix.py b/problems/longest-increasing-path-in-a-matrix.py new file mode 100644 index 0000000..cd446d9 --- /dev/null +++ b/problems/longest-increasing-path-in-a-matrix.py @@ -0,0 +1,31 @@ +class Solution(object): + def longestIncreasingPath(self, matrix): + def getLongest(i, j): + if (i, j) in longest: return longest[(i, j)] + l = 1 + + #call getLongest to the neighbors that are larger than itself. + if i+1=0 and matrix[i][j]=0 and matrix[i][j]1: + neiGroupId.add(grid[iNext][jNext]) + + for groupId in list(neiGroupId): + neiSize += groupIdToSize[groupId] + + ans = max(ans, 1+neiSize) + + return ans \ No newline at end of file diff --git a/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py b/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py index 2c07805..5559c80 100644 --- a/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py +++ b/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py @@ -39,8 +39,4 @@ def check(mat, state): q.append(nextState) return -1 - - - - \ No newline at end of file diff --git a/problems/minimum-time-difference.py b/problems/minimum-time-difference.py new file mode 100644 index 0000000..1645692 --- /dev/null +++ b/problems/minimum-time-difference.py @@ -0,0 +1,32 @@ +""" +Time: O(1440) +Space: O(1440) +""" +class Solution(object): + def findMinDifference(self, timeStrings): + def timeStringToMinutes(timeString): + time = timeString.split(':') + h = int(time[0]) + m = int(time[1]) + return h*60+m + + ans = float('inf') + minTime = float('inf') + maxTime = float('-inf') + timeSet = set() + for timeString in timeStrings: + t = timeStringToMinutes(timeString) + if t in timeSet: return 0 + minTime = min(minTime, t) + maxTime = max(maxTime, t) + timeSet.add(t) + + + prev = None + for t in xrange(minTime, maxTime+1): + if t not in timeSet: continue + if prev!=None: ans = min(ans, t-prev) + prev = t + + ans = min(ans, 1440+minTime-maxTime) #compare minTime and maxTime + return ans \ No newline at end of file diff --git a/problems/next-permutation.py b/problems/next-permutation.py index f228cc4..0a816ee 100644 --- a/problems/next-permutation.py +++ b/problems/next-permutation.py @@ -29,4 +29,33 @@ def swap(i, j): swap(i, j) reverse(i+1) - return nums \ No newline at end of file + return nums + +""" +Next Permutation means find the next (slightly) larger number using nums. + +1. Iterate from right, find the first num that is smaller. That's the one we are going to swap. => nums[i] +2. From the nums right to nums[i], find the smallest num that is larger than nums[i] => nums[j] +Since the right of the i must be an increasing sequence (looking from right), the first one that larger than nums[i] is the smallest one that is larger than nums[i] +3. Swap nums[i] and nums[j] +4. sort nums[i+1:] it will be the smallest permutaion. +5. Note that when an list is in increasing order looking from right, we can use `reverse` to sort it. +""" +class Solution(object): + def nextPermutation(self, nums): + def reverse(nums, l, r): + while l<=r: + nums[l], nums[r] = nums[r], nums[l] + l += 1 + r -= 1 + + i = len(nums)-2 + while i>=0 and nums[i]>=nums[i+1]: i -= 1 #[1] + + if i==-1: + return reverse(nums, 0, len(nums)-1) #nums is the largest permutation, sort nums + else: + j = len(nums)-1 + while j>i and nums[j]<=nums[i]: j -= 1 #[2] + nums[i], nums[j] = nums[j], nums[i] #[3] + reverse(nums, i+1, len(nums)-1) #[4] \ No newline at end of file diff --git a/problems/powx-n.py b/problems/powx-n.py new file mode 100644 index 0000000..d0fac2b --- /dev/null +++ b/problems/powx-n.py @@ -0,0 +1,12 @@ +class Solution(object): + def myPow(self, x, n): + if n==0: + return 1 + elif n<0: + return 1/self.myPow(x, -n) + elif n%2>0: + half = self.myPow(x, n-1) + return x*half + elif n%2==0: + half = self.myPow(x, n/2) + return half*half \ No newline at end of file diff --git a/problems/simplify-path.py b/problems/simplify-path.py new file mode 100644 index 0000000..46589cf --- /dev/null +++ b/problems/simplify-path.py @@ -0,0 +1,18 @@ +class Solution(object): + def simplifyPath(self, path): + ans = '' + skip = 0 + + for directory in reversed(path.split('/')): + if directory=='' or directory=='.': + continue + elif directory=='..': + skip += 1 + else: + if skip>0: + skip -= 1 + continue + else: + ans = '/'+directory+ans + + return ans if ans!='' else '/' \ No newline at end of file diff --git a/problems/student-attendance-record-ii.py b/problems/student-attendance-record-ii.py index ed55473..efc2923 100644 --- a/problems/student-attendance-record-ii.py +++ b/problems/student-attendance-record-ii.py @@ -17,7 +17,6 @@ def checkRecord(self, n): dp[i] += dp[i-1]%M #ends at P dp[i] += (dp[i-1]%M - dp[i-4]%M) #ends at L. All posiblity but the end cannot be PLL - ans += dp[n] for i in xrange(n): diff --git a/problems/swap-adjacent-in-lr-string.py b/problems/swap-adjacent-in-lr-string.py new file mode 100644 index 0000000..a8acf65 --- /dev/null +++ b/problems/swap-adjacent-in-lr-string.py @@ -0,0 +1,18 @@ +class Solution(object): + def canTransform(self, start, end): + if len(start)!=len(end): return False + if start.replace('X', '')!=end.replace('X', ''): return False + + startLIndex = [i for i, c in enumerate(start) if c=='L'] + endLIndex = [i for i, c in enumerate(end) if c=='L'] + for i in xrange(len(startLIndex)): + if startLIndex[i]endRIndex[i]: + return False + + return True \ No newline at end of file diff --git a/problems/valid-number.py b/problems/valid-number.py new file mode 100644 index 0000000..81a71b3 --- /dev/null +++ b/problems/valid-number.py @@ -0,0 +1,44 @@ +class Solution(object): + def isNumber(self, s): + def isOK(s, maxDots): + if not s: return False + + #check and remove +/- + for i, c in enumerate(s): + if (c=='+' or c=='-') and i!=0: + return False + if s[0]=='+' or s[0]=='-': s = s[1:] + + #check dot and if there is digit + dotCount = 0 + dotPos = 0 + digitCount = 0 + for i, c in enumerate(s): + if c=='.': + dotCount += 1 + dotPos = i + elif c.isdigit(): + digitCount += 1 + + if dotCount>maxDots: return False + if digitCount==0: return False + + return True + + #get e's position. Also check if all char is in validChar + validChar = set(['1','2', '3', '4', '5', '6', '7', '8', '9', '0', 'e', 'E', '.', '+', '-']) + eCount = 0 + ePos = 0 + for i, c in enumerate(s): + if c not in validChar: + return False + if c=='e' or c=='E': + eCount += 1 + ePos = i + + if eCount>1: + return False + elif eCount==1: + return isOK(s[:ePos], 1) and isOK(s[ePos+1:], 0) + else: + return isOK(s, 1) \ No newline at end of file diff --git a/problems/valid-palindrome-ii.py b/problems/valid-palindrome-ii.py new file mode 100644 index 0000000..84bce52 --- /dev/null +++ b/problems/valid-palindrome-ii.py @@ -0,0 +1,29 @@ +""" +When seeing the first different chars in the string. +Check if anyone of the string is palindrome if we remove one of them. + +Time: O(N) +Space: O(1) +""" +class Solution(object): + def validPalindrome(self, s): + def isPalindrome(s): + i = 0 + j = len(s)-1 + while i1: + temp += sorted(data[(x, y)]) + else: + temp.append(data[(x, y)][0]) + ans.append(temp) + return ans \ No newline at end of file From a9671e8430d8449d39aa611995b6808c6fb7ff95 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Wed, 2 Mar 2022 18:28:53 +0800 Subject: [PATCH 14/52] no message --- README.md | 2 +- problems/accounts-merge.py | 116 +++++++++++++++++++++++++----- problems/diagonal-traverse.py | 25 +++++++ problems/group-shifted-strings.py | 20 ++++++ problems/making-a-large-island.py | 7 ++ problems/maximum-swap.py | 23 ++++++ problems/valid-number.py | 2 +- 7 files changed, 176 insertions(+), 19 deletions(-) create mode 100644 problems/diagonal-traverse.py create mode 100644 problems/group-shifted-strings.py create mode 100644 problems/maximum-swap.py diff --git a/README.md b/README.md index dd42196..f076d25 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ I found it makes sense to solve similar problems together, so that we can recogn 3. [What should I know from the CLRS 3rd edition book if my aim is to get into Google?](https://www.quora.com/What-should-I-know-from-the-CLRS-3rd-edition-book-if-my-aim-is-to-get-into-Google/answer/Jimmy-Saade) ## Data Structures and Algorithms for beginners -If you are new or know nothing about data structures and algorithms, I recommend [this course](). This course is taught in Python and design to help you find job and do well in the interview. +If you are new or know nothing about data structures and algorithms, I recommend [this course](). This course is taught in Python and design to help you find job and do well in the interview. # System Design diff --git a/problems/accounts-merge.py b/problems/accounts-merge.py index 30e4787..91e03ef 100644 --- a/problems/accounts-merge.py +++ b/problems/accounts-merge.py @@ -1,3 +1,22 @@ +""" +Treat each email as a node. +Build an adjacency graph. [0] + +For every account's data +First, lets check if the first email is already merged. [1] +If the first email is already merged to other groups, then other emails will be in another group as well. +So don't need to check. + +Second, do a DFS starting from the first email. Put all the connected nodes into visited. [2] +And append the sorted(visited) to the ans with name. [3] + +Let N be the total number of emails. M be the total number of final groups. +Build the graph takes O(N). +For each final groups, we make a DFS to all nodes, taking O(MN). +Sort the group takes O((N/M)*Log(N/M)) -> O((N/M)*(logN-LogM)) +Time: O(MN) +Space: O(N) +""" from collections import defaultdict class Solution(object): @@ -31,22 +50,85 @@ def accountsMerge(self, accounts): return ans -""" -Treat each email as a node. -Build an adjacency graph. [0] - -For every account's data -First, lets check if the first email is already merged. [1] -If the first email is already merged to other groups, then other emails will be in another group as well. -So don't need to check. -Second, do a DFS starting from the first email. Put all the connected nodes into visited. [2] -And append the sorted(visited) to the ans with name. [3] +#Union Find +class Solution(object): + def accountsMerge(self, accounts): + def find(x): + p = parents[x] + while p!=parents[p]: + p = find(p) + parents[x] = p + return p + + def union(x, y): + p1, p2 = find(x), find(y) + if p1==p2: return + parents[p2] = p1 + + parents = {} + mailToName = {} + + for account in accounts: + name = account[0] + root = account[1] + if root not in parents: parents[root] = root + root = find(root) + mailToName[root] = name + + for i in xrange(2, len(account)): + email = account[i] + if email in parents: + union(parents[email], root) + root = find(root) + parents[email] = root + + rootToMails = collections.defaultdict(list) + for email in parents: + rootToMails[find(email)].append(email) + + ans = [] + for root in rootToMails: + name = mailToName[root] + mails = rootToMails[root] + ans.append([name]+sorted(mails)) + + return ans -Let N be the total number of emails. M be the total number of final groups. -Build the graph takes O(N). -For each final groups, we make a DFS to all nodes, taking O(MN). -Sort the group takes O((N/M)*Log(N/M)) -> O((N/M)*(logN-LogM)) -Time: O(MN) -Space: O(N) -""" \ No newline at end of file +#DFS +class Solution(object): + def accountsMerge(self, accounts): + + #build adjacency list + adj = collections.defaultdict(list) + for account in accounts: + name = account[0] + email0 = account[1] + for i in xrange(2, len(account)): + email = account[i] + adj[email0].append(email) + adj[email].append(email0) + + #iterate accounts and dfs each email group + ans = [] + visited = set() #store all the visited email + for account in accounts: + name = account[0] + email0 = account[1] + if email0 in visited: continue + + #dfs + group = set() #store the email group related to email0 + stack = [email0] + while stack: + email = stack.pop() + if email in group or email in visited: continue + group.add(email) + visited.add(email) + for nei in adj[email]: + stack.append(nei) + + ans.append([name]+sorted(list(group))) + + return ans + \ No newline at end of file diff --git a/problems/diagonal-traverse.py b/problems/diagonal-traverse.py new file mode 100644 index 0000000..0510201 --- /dev/null +++ b/problems/diagonal-traverse.py @@ -0,0 +1,25 @@ +class Solution(object): + def findDiagonalOrder(self, mat): + def helper(i, j, reverse): + output = [] + while 0<=i=0 else 26+(getNumByChar(c)+offset)) + return h + + def getNumByChar(letter): + return ord(letter) - 97 + + def getCharByNum(pos): + return chr(pos + 97) + + groups = collections.defaultdict(list) + for string in strings: + h = getHash(string) + groups[h].append(string) + return groups.values() \ No newline at end of file diff --git a/problems/making-a-large-island.py b/problems/making-a-large-island.py index 0df3ac0..215aa2a 100644 --- a/problems/making-a-large-island.py +++ b/problems/making-a-large-island.py @@ -1,3 +1,10 @@ +""" +For each "island" asign them a group id. Also calculate the group's size. +Iterate all the zeros, update the ans. + +Time:O(MN) +Space: O(MN) in the worst case. +""" class Solution(object): def largestIsland(self, grid): def isValid(i, j, M, N): diff --git a/problems/maximum-swap.py b/problems/maximum-swap.py new file mode 100644 index 0000000..ffca66a --- /dev/null +++ b/problems/maximum-swap.py @@ -0,0 +1,23 @@ +""" +1. Generate positions. Storing the mapping between number to indices. +2. Iterate from left, for each n1, find the largest number larger than n1 (searching from 9, 8, 7 to n1+1). +3. Since we need to find the max output. There might be multiple the same number, we need to find the index of the rightest number. +4. Remove n1 when it is done. Because right of the n1 should not consider it anymore. +""" +class Solution(object): + def maximumSwap(self, num): + numList = [int(n) for n in str(num)] + positions = collections.defaultdict(list) + for i, n in enumerate(numList): positions[n].append(i) #[1] + + i = 0 + for i, n1 in enumerate(numList): #[2] + n1 = numList[i] + for n2 in xrange(9, n1, -1): + if n2 in positions and len(positions[n2])>0: + j = positions[n2][-1] #[3] + numList[i], numList[j] = numList[j], numList[i] + return int(''.join([str(n) for n in numList])) + positions[n1].pop(0) #[4] + + return num \ No newline at end of file diff --git a/problems/valid-number.py b/problems/valid-number.py index 81a71b3..9d0793a 100644 --- a/problems/valid-number.py +++ b/problems/valid-number.py @@ -41,4 +41,4 @@ def isOK(s, maxDots): elif eCount==1: return isOK(s[:ePos], 1) and isOK(s[ePos+1:], 0) else: - return isOK(s, 1) \ No newline at end of file + return isOK(s, 1) From 6f00d183b5ec1bf4888eb20ab164c5e1ec32ef5f Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sat, 5 Mar 2022 09:49:07 +0800 Subject: [PATCH 15/52] no message --- problems/add-strings.py | 34 ++++++++++++++++ problems/cheapest-flights-within-k-stops.py | 3 ++ problems/continuous-subarray-sum.py | 35 +++++++++++++++++ problems/cutting-ribbons.py | 13 +++++++ problems/exclusive-time-of-functions.py | 24 ++++++++++++ problems/expression-add-operators.py | 23 +++++++++++ problems/find-peak-element.py | 21 +++++++++- ...emove-all-adjacent-duplicates-in-string.py | 12 ++++++ problems/remove-invalid-parentheses.py | 38 ++++++++++++++++++ .../shortest-distance-from-all-buildings.py | 39 +++++++++++++++++++ problems/shortest-path-in-binary-matrix.py | 17 ++++++++ problems/subarray-sum-equals-k.py | 1 - problems/toeplitz-matrix.py | 22 +++++++++++ 13 files changed, 280 insertions(+), 2 deletions(-) create mode 100644 problems/add-strings.py create mode 100644 problems/continuous-subarray-sum.py create mode 100644 problems/cutting-ribbons.py create mode 100644 problems/exclusive-time-of-functions.py create mode 100644 problems/expression-add-operators.py create mode 100644 problems/remove-all-adjacent-duplicates-in-string.py create mode 100644 problems/remove-invalid-parentheses.py create mode 100644 problems/shortest-distance-from-all-buildings.py create mode 100644 problems/shortest-path-in-binary-matrix.py create mode 100644 problems/toeplitz-matrix.py diff --git a/problems/add-strings.py b/problems/add-strings.py new file mode 100644 index 0000000..9cdd7f9 --- /dev/null +++ b/problems/add-strings.py @@ -0,0 +1,34 @@ +class Solution(object): + def addStrings(self, nums1, nums2): + ans = '' + i = len(nums1)-1 + j = len(nums2)-1 + + carry = 0 + while 0<=i and 0<=j: + n1 = int(nums1[i]) + n2 = int(nums2[j]) + total = n1+n2+carry + n = total%10 + carry = 1 if total>=10 else 0 + ans = str(n)+ans + i -= 1 + j -= 1 + + while 0<=i: + total = int(nums1[i])+carry + n = total%10 + carry = 1 if total>=10 else 0 + ans = str(n)+ans + i -= 1 + + while 0<=j: + total = int(nums2[j])+carry + n = total%10 + carry = 1 if total>=10 else 0 + ans = str(n)+ans + j -= 1 + + if carry: ans = str(carry)+ans + + return ans \ No newline at end of file diff --git a/problems/cheapest-flights-within-k-stops.py b/problems/cheapest-flights-within-k-stops.py index 28b2927..eb785b3 100644 --- a/problems/cheapest-flights-within-k-stops.py +++ b/problems/cheapest-flights-within-k-stops.py @@ -23,16 +23,19 @@ class Solution1(object): def findCheapestPrice(self, n, flights, src, dst, K): graph = collections.defaultdict(list) pq = [] + visited = set() for u, v, w in flights: graph[u].append((w, v)) heapq.heappush(pq, (0, K+1, src)) while pq: price, stops, city = heapq.heappop(pq) + visited.add(city) if city is dst: return price if stops>0: for price_to_nei, nei in graph[city]: + if nei in visited: continue heapq.heappush(pq, (price+price_to_nei, stops-1, nei)) return -1 diff --git a/problems/continuous-subarray-sum.py b/problems/continuous-subarray-sum.py new file mode 100644 index 0000000..75dd08b --- /dev/null +++ b/problems/continuous-subarray-sum.py @@ -0,0 +1,35 @@ +class Solution(object): + def checkSubarraySum(self, nums, k): + prefixSumEndings = collections.defaultdict(list) + prefixSumEndings[0].append(-1) + + prefixSum = 0 + for i, n in enumerate(nums): + prefixSum += n + + x = prefixSum/k + while x>=0: + p2 = prefixSum-k*x + if len(prefixSumEndings[p2])>0 and prefixSumEndings[p2][0]=1: return True + if len(prefixSumKRemain[remain])>0 and prefixSumKRemain[remain][0]=k: + minLen = l + else: + maxLen = l-1 + return maxLen \ No newline at end of file diff --git a/problems/exclusive-time-of-functions.py b/problems/exclusive-time-of-functions.py new file mode 100644 index 0000000..0f4fc4d --- /dev/null +++ b/problems/exclusive-time-of-functions.py @@ -0,0 +1,24 @@ +class Solution(object): + def exclusiveTime(self, n, logs): + ans = [0]*n + data = [] + for log in logs: + fid, action, t = log.split(':') + data.append([int(t), -1 if action=='start' else 1, int(fid)]) + + data.sort() + + stack = [] + for t, action, fid in data: + if action==-1: + if stack: + prevT, _, prevFid = stack[-1] + ans[prevFid] += t-prevT + elif action==1: + prevT, _, prevFid = stack.pop() + ans[fid] += t+1-prevT + if stack: stack[-1][0] = t+1 + + if action==-1: stack.append([t, action, fid]) + + return ans \ No newline at end of file diff --git a/problems/expression-add-operators.py b/problems/expression-add-operators.py new file mode 100644 index 0000000..64421a7 --- /dev/null +++ b/problems/expression-add-operators.py @@ -0,0 +1,23 @@ +class Solution(object): + def addOperators(self, num, target): + def dfs(num, curr, i): + if i==len(num): + if eval(curr[1:])==target: ans.append(curr[1:]) + return + + if curr and curr[-1] in operators: + dfs(num, curr+num[i], i+1) + elif curr and curr[-1]=='0': + dfs(num, curr+'+', i) + dfs(num, curr+'-', i) + dfs(num, curr+'*', i) + else: + dfs(num, curr+'+', i) + dfs(num, curr+'-', i) + dfs(num, curr+'*', i) + dfs(num, curr+num[i], i+1) + + operators = set(['+', '-', '*']) + ans = [] + dfs(num, '+', 0) + return ans \ No newline at end of file diff --git a/problems/find-peak-element.py b/problems/find-peak-element.py index 5b9a8b3..aeb4726 100644 --- a/problems/find-peak-element.py +++ b/problems/find-peak-element.py @@ -54,5 +54,24 @@ def findPeakElement(self, nums): return l - + +""" +[l, r] is the possible range. +Keep decreasing the range unsing binary search until l==r. +Pay attention to +m = l+(r-l+1)/2 +Sometimes you need m = l+(r-l)/2 to avoid infinite loop. +""" +class Solution(object): + def findPeakElement(self, nums): + l = 0 + r = len(nums)-1 + + while lself.maxLen: return + + if i>=len(s): + if len(curr)==self.maxLen and count==0: + self.ans.append(curr) + return + + if s[i]!='(' and s[i]!=')': + dfs(s, curr+s[i], i+1, count) + elif not curr or s[i]!=curr[-1]: + dfs(s, curr+s[i], i+1, count + (1 if s[i]=='(' else -1)) + dfs(s, curr, i+1, count) + elif s[i]==curr[-1]: + dfs(s, curr+s[i], i+1, count + (1 if s[i]=='(' else -1)) + + def getMaxLen(s): + openCount = removeCount = 0 + for c in s: + if c=='(': + openCount += 1 + elif c==')': + openCount -= 1 + + if openCount<0: + removeCount += abs(openCount) + openCount = 0 + removeCount += openCount + return len(s)-removeCount + + self.ans = [] + self.maxLen = getMaxLen(s) + + dfs(s, "", 0, 0) + return self.ans \ No newline at end of file diff --git a/problems/shortest-distance-from-all-buildings.py b/problems/shortest-distance-from-all-buildings.py new file mode 100644 index 0000000..490e6a2 --- /dev/null +++ b/problems/shortest-distance-from-all-buildings.py @@ -0,0 +1,39 @@ +class Solution(object): + def shortestDistance(self, grid): + def bfs(i0, j0): + q = collections.deque([(i0, j0, 0)]) + visited = set() + while q: + i, j, dis = q.popleft() + if (i, j) in visited: continue + visited.add((i, j)) + + reach[i][j] += 1 + distances[i][j] += dis + + for iNext, jNext in ((i+1, j), (i-1, j), (i, j+1), (i, j-1)): + if not (0<=iNext Date: Mon, 25 Apr 2022 18:49:04 +0800 Subject: [PATCH 16/52] no message --- README.md | 6 +++--- problems/{ => python}/01-matrix.py | 0 problems/{ => python}/3sum-closest.py | 0 problems/{ => python}/3sum.py | 0 problems/{ => python}/4sum.py | 0 problems/{ => python}/accounts-merge.py | 0 problems/{ => python}/add-binary.py | 0 problems/{ => python}/add-digits.py | 0 problems/{ => python}/add-strings.py | 0 problems/{ => python}/add-two-numbers-ii.py | 0 problems/{ => python}/add-two-numbers.py | 0 problems/{ => python}/alien-dictionary.py | 0 .../{ => python}/all-nodes-distance-k-in-binary-tree.py | 0 .../{ => python}/amount-of-new-area-painted-each-day.py | 0 problems/{ => python}/analyze-user-website-visit-pattern.py | 0 problems/{ => python}/backspace-string-compare.py | 0 problems/{ => python}/balance-a-binary-search-tree.py | 0 problems/{ => python}/balanced-binary-tree.py | 0 problems/{ => python}/basic-calculator-ii.py | 0 problems/{ => python}/best-time-to-buy-an-stock.py | 0 .../{ => python}/best-time-to-buy-and-sell-stock-iii.py | 0 .../best-time-to-buy-and-sell-stock-with-cooldown.py | 0 problems/{ => python}/best-time-to-buy-and-sell-stock.py | 0 problems/{ => python}/big-countries.sql | 0 problems/{ => python}/binary-search-tree-iterator.py | 0 problems/{ => python}/binary-search.py | 0 problems/{ => python}/binary-subarrays-with-sum.py | 0 problems/{ => python}/binary-tree-inorder-traversal.py | 0 .../{ => python}/binary-tree-level-order-traversal-ii.py | 0 problems/{ => python}/binary-tree-level-order-traversal.py | 0 .../binary-tree-longest-consecutive-sequence.py | 0 problems/{ => python}/binary-tree-maximum-path-sum.py | 0 problems/{ => python}/binary-tree-paths.py | 0 problems/{ => python}/binary-tree-pruning.py | 0 problems/{ => python}/binary-tree-right-side-view.py | 0 .../{ => python}/binary-tree-vertical-order-traversal.py | 0 problems/{ => python}/binary-watch.py | 0 problems/{ => python}/buildings-with-an-ocean-view.py | 0 problems/{ => python}/burst-balloons.py | 0 problems/{ => python}/campus-bikes-ii.py | 0 problems/{ => python}/candy.py | 0 .../{ => python}/capacity-to-ship-packages-within-d-days.py | 0 problems/{ => python}/cheapest-flights-within-k-stops.py | 0 problems/{ => python}/climbing-stairs.py | 0 problems/{ => python}/clone-graph.py | 0 problems/{ => python}/closest-binary-search-tree-value.py | 0 problems/{ => python}/coin-change.py | 0 problems/{ => python}/coloring-a-border.py | 0 problems/{ => python}/combination-sum-ii.py | 0 problems/{ => python}/combination-sum-iii.py | 0 problems/{ => python}/combination-sum-iv.py | 0 problems/{ => python}/combination-sum.py | 0 problems/{ => python}/combinations.py | 0 problems/{ => python}/combine-two-tables.sql | 0 problems/{ => python}/compare-version-numbers.py | 0 .../{ => python}/connecting-cities-with-minimum-cost.py | 0 problems/{ => python}/consecutive-numbers-sum.py | 0 ...ruct-binary-tree-from-inorder-and-postorder-traversal.py | 0 ...truct-binary-tree-from-preorder-and-inorder-traversal.py | 0 problems/{ => python}/container-with-most-water.py | 0 problems/{ => python}/contains-duplicate-ii.py | 0 problems/{ => python}/contains-duplicate-iii.py | 0 problems/{ => python}/contains-duplicate.py | 0 problems/{ => python}/continuous-subarray-sum.py | 0 ...nvert-binary-search-tree-to-sorted-doubly-linked-list.py | 0 .../convert-sorted-array-to-binary-search-tree.py | 0 .../convert-sorted-list-to-binary-search-tree.py | 0 problems/{ => python}/copy-list-with-random-pointer.py | 0 .../count-all-valid-pickup-and-delivery-opti.py | 0 problems/{ => python}/count-binary-substrings.py | 0 problems/{ => python}/count-complete-tree-nodes.py | 0 problems/{ => python}/count-number-of-nice-subarrays.py | 0 ...unique-characters-of-all-substrings-of-a-given-string.py | 0 problems/{ => python}/course-schedule-ii.py | 0 problems/{ => python}/course-schedule.py | 0 problems/{ => python}/custom-sort-string.py | 0 problems/{ => python}/cutting-ribbons.py | 0 problems/{ => python}/data-stream-as-disjoint-intervals.py | 0 problems/{ => python}/decode-string.py | 0 problems/{ => python}/decode-ways.py | 0 problems/{ => python}/delete-and-earn.py | 0 problems/{ => python}/delete-duplicate-folders-in-system.py | 0 problems/{ => python}/delete-node-in-a-bst.py | 0 problems/{ => python}/delete-operation-for-two-strings.py | 0 .../design-add-and-search-words-data-structure.py | 0 problems/{ => python}/design-in-memory-file-system.py | 0 problems/{ => python}/design-linked-list.py | 0 problems/{ => python}/design-tic-tac-toe.py | 0 problems/{ => python}/diagonal-traverse.py | 0 problems/{ => python}/diameter-of-binary-tree.py | 0 problems/{ => python}/different-ways-to-add-parentheses.py | 0 problems/{ => python}/distinct-subsequences.py | 0 problems/{ => python}/distribute-coins-in-binary-tree.py | 0 problems/{ => python}/domino-and-tromino-tiling.py | 0 problems/{ => python}/dot-product-of-two-sparse-vectors.py | 0 problems/{ => python}/dungeon-game.py | 0 problems/{ => python}/edit-distance.py | 0 problems/{ => python}/egions-cut-by-slashes.py | 0 problems/{ => python}/evaluate-division.py | 0 problems/{ => python}/evaluate-reverse-polish-notation.py | 0 problems/{ => python}/exclusive-time-of-functions.py | 0 problems/{ => python}/expression-add-operators.py | 0 problems/{ => python}/filling-bookcase-shelves.py | 0 .../find-all-possible-recipes-from-given-supplies.py | 0 problems/{ => python}/find-and-replace-in-string.py | 0 problems/{ => python}/find-distance-in-a-binary-tree.py | 0 problems/{ => python}/find-duplicate-subtrees.py | 0 problems/{ => python}/find-eventual-safe-states.py | 0 ...nd-first-and-last-position-of-element-in-sorted-array.py | 0 problems/{ => python}/find-k-closest-elements.py | 0 problems/{ => python}/find-k-pairs-with-smallest-sums.py | 0 problems/{ => python}/find-leaves-of-binary-tree.py | 0 problems/{ => python}/find-median-from-data-stream.py | 0 .../{ => python}/find-minimum-in-rotated-sorted-array-ii.py | 0 .../{ => python}/find-minimum-in-rotated-sorted-array.py | 0 problems/{ => python}/find-mode-in-binary-search-tree.py | 0 .../{ => python}/find-original-array-from-doubled-array,py | 0 problems/{ => python}/find-peak-element.py | 0 problems/{ => python}/find-the-duplicate-number.py | 0 problems/{ => python}/first-bad-version.py | 0 problems/{ => python}/first-missing-positive.py | 0 problems/{ => python}/first-unique-character-in-a-string.py | 0 problems/{ => python}/fizz-buzz.py | 0 problems/{ => python}/flatten-binary-tree-to-linked-list.py | 0 .../flip-binary-tree-to-match-preorder-traversal.py | 0 problems/{ => python}/flip-string-to-monotone-increasing.py | 0 problems/{ => python}/flood-fill.py | 0 problems/{ => python}/friend-circles.py | 0 problems/{ => python}/fruit-into-baskets.py | 0 problems/{ => python}/game-of-life.py | 0 problems/{ => python}/generate-parentheses.py | 0 problems/{ => python}/graph-valid-tree.py | 0 problems/{ => python}/greatest-sum-divisible-by-three.py | 0 problems/{ => python}/group-anagrams.py | 0 problems/{ => python}/group-shifted-strings.py | 0 problems/{ => python}/guess-number-higher-or-lower-ii.py | 0 problems/{ => python}/guess-number-higher-or-lower.py | 0 problems/{ => python}/guess-the-word.py | 0 problems/{ => python}/h-index-ii.py | 0 problems/{ => python}/h-index.py | 0 problems/{ => python}/hamming-distance.py | 0 problems/{ => python}/house-robber-ii.py | 0 problems/{ => python}/house-robber-iii.py | 0 problems/{ => python}/house-robber.py | 0 problems/{ => python}/implement-trie-prefix-tree.py | 0 problems/{ => python}/increasing-triplet-subsequence.py | 0 problems/{ => python}/inorder-successor-in-bst-ii.py | 0 problems/{ => python}/inorder-successor-in-bst.py | 0 problems/{ => python}/insert-interval.py | 0 problems/{ => python}/insert-into-a-binary-search-tree.py | 0 .../insert-into-a-sorted-circular-linked-list.py | 0 problems/{ => python}/insertion-sort-list.py | 0 problems/{ => python}/integer-to-english-words.py | 0 problems/{ => python}/interleaving-string.py | 0 problems/{ => python}/intersection-of-two-arrays-ii.py | 0 problems/{ => python}/intersection-of-two-arrays.py | 0 problems/{ => python}/invert-binary-tree.py | 0 problems/{ => python}/is-graph-bipartite.py | 0 problems/{ => python}/is-subsequence.py | 0 problems/{ => python}/isomorphic-strings.py | 0 problems/{ => python}/jewels-and-stones.py | 0 problems/{ => python}/jump-game.py | 0 problems/{ => python}/k-closest-points-to-origin.py | 0 problems/{ => python}/k-empty-slots.py | 0 problems/{ => python}/keys-and-rooms.py | 0 problems/{ => python}/knight-dialer.py | 0 problems/{ => python}/knight-probability-in-chessboard.py | 0 problems/{ => python}/koko-eating-bananas.py | 0 problems/{ => python}/kth-largest-element-in-an-array.py | 0 problems/{ => python}/kth-smallest-element-in-a-bst.py | 0 .../{ => python}/kth-smallest-element-in-a-sorted-matrix.py | 0 problems/{ => python}/largest-1-bordered-square.py | 0 problems/{ => python}/largest-bst-subtree.py | 0 problems/{ => python}/largest-sum-of-averages.py | 0 problems/{ => python}/last-stone-weight-ii.py | 0 problems/{ => python}/last-stone-weight.py | 0 .../least-number-of-unique-integers-after-k-removals.py | 0 problems/{ => python}/letter-case-permutation.py | 0 .../{ => python}/letter-combinations-of-a-phone-number.py | 0 problems/{ => python}/license-key-formatting.py | 0 problems/{ => python}/linked-list-cycle-ii.py | 0 problems/{ => python}/linked-list-cycle.py | 0 problems/{ => python}/linked-list-random-node.py | 0 problems/{ => python}/logger-rate-limiter.py | 0 problems/{ => python}/longest-common-prefix.py | 0 problems/{ => python}/longest-common-subsequence.py | 0 problems/{ => python}/longest-consecutive-sequence.py | 0 .../{ => python}/longest-increasing-path-in-a-matrix.py | 0 problems/{ => python}/longest-increasing-subsequence.py | 0 problems/{ => python}/longest-palindromic-subsequence.py | 0 problems/{ => python}/longest-palindromic-substring.py | 0 .../{ => python}/longest-repeating-character-replacement.py | 0 problems/{ => python}/longest-string-chain.py | 0 ...ongest-substring-with-at-least-k-repeating-characters.py | 0 .../longest-substring-without-repeating-characters.py | 0 problems/{ => python}/longest-univalue-path.py | 0 .../lowest-common-ancestor-of-a-binary-search-tree.py | 0 .../lowest-common-ancestor-of-a-binary-search.py | 0 .../lowest-common-ancestor-of-a-binary-tree-ii.py | 0 .../lowest-common-ancestor-of-a-binary-tree-iii.py | 0 .../lowest-common-ancestor-of-a-binary-tree-iv.py | 0 .../{ => python}/lowest-common-ancestor-of-a-binary-tree.py | 0 .../lowest-common-ancestor-of-deepest-leaves.py | 0 problems/{ => python}/lru-cache.py | 0 problems/{ => python}/majority-element-ii.py | 0 problems/{ => python}/majority-element.py | 0 problems/{ => python}/making-a-large-island.py | 0 problems/{ => python}/max-area-of-island.py | 0 problems/{ => python}/max-consecutive-ones-iii.py | 0 problems/{ => python}/max-stack.py | 0 .../{ => python}/max-sum-of-rectangle-no-larger-than-k.py | 0 problems/{ => python}/maximal-square.py | 0 problems/{ => python}/maximum-average-subtree.py | 0 problems/{ => python}/maximum-compatibility-score-sum.py | 0 problems/{ => python}/maximum-depth-of-binary-tree.py | 0 problems/{ => python}/maximum-gap.py | 0 .../{ => python}/maximum-length-of-repeated-subarray.py | 0 .../maximum-number-of-events-that-can-be-attended.py | 0 problems/{ => python}/maximum-number-of-points-with-cost.py | 0 problems/{ => python}/maximum-number-of-visible-points.py | 0 problems/{ => python}/maximum-product-of-three-numbers.py | 0 problems/{ => python}/maximum-product-subarray.py | 0 .../{ => python}/maximum-subarray-sum-with-one-deletion.py | 0 problems/{ => python}/maximum-subarray.py | 0 problems/{ => python}/maximum-swap.py | 0 problems/{ => python}/maximum-units-on-a-truck.py | 0 problems/{ => python}/median-of-two-sorted-arrays.py | 0 problems/{ => python}/meeting-rooms-ii.py | 0 problems/{ => python}/meeting-rooms.py | 0 problems/{ => python}/merge-intervals.py | 0 problems/{ => python}/merge-k-sorted-lists.py | 0 problems/{ => python}/merge-sorted-array.py | 0 problems/{ => python}/merge-two-sorted-lists.py | 0 problems/{ => python}/min-cost-climbing-stairs.py | 0 problems/{ => python}/min-stack.py | 0 problems/{ => python}/minimize-malware-spread.py | 0 problems/{ => python}/minimum-absolute-difference-in-bst.py | 0 .../minimum-ascii-delete-sum-for-two-strings.py | 0 problems/{ => python}/minimum-cost-to-connect-sticks.py | 0 problems/{ => python}/minimum-cost-to-hire-k-workers.py | 0 ...inimum-cost-to-make-at-least-one-valid-path-in-a-grid.py | 0 .../minimum-cost-to-reach-city-with-discounts.py | 0 problems/{ => python}/minimum-depth-of-binary-tree.py | 0 .../{ => python}/minimum-difficulty-of-a-job-schedule.py | 0 problems/{ => python}/minimum-falling-path-sum-ii.py | 0 problems/{ => python}/minimum-knight-moves.py | 0 ...mber-of-flips-to-convert-binary-matrix-to-zero-matrix.py | 0 problems/{ => python}/minimum-path-sum.py | 0 .../{ => python}/minimum-score-triangulation-of-polygon.py | 0 problems/{ => python}/minimum-size-subarray-sum.py | 0 .../{ => python}/minimum-swaps-to-group-all-1s-together.py | 0 .../minimum-swaps-to-make-sequences-increasing.py | 0 problems/{ => python}/minimum-time-difference.py | 0 problems/{ => python}/minimum-window-substring.py | 0 problems/{ => python}/minimum-xor-sum-of-two-arrays.py | 0 problems/{ => python}/missing-number.py | 0 problems/{ => python}/most-frequent-subtree-sum.py | 0 .../most-stones-removed-with-same-row-or-column.py | 0 problems/{ => python}/move-zeroes.py | 0 problems/{ => python}/moving-average-from-data-stream.py | 0 problems/{ => python}/my-calendar-ii.py | 0 problems/{ => python}/n-ary-tree-level-order-traversal.py | 0 problems/{ => python}/n-ary-tree-postorder-traversal.py | 0 problems/{ => python}/n-ary-tree-preorder-traversal.py | 0 problems/{ => python}/nested-list-weight-sum.py | 0 problems/{ => python}/network-delay-time.py | 0 problems/{ => python}/next-closest-time.py | 0 problems/{ => python}/next-permutation.py | 0 problems/{ => python}/number-complement.py | 0 ...number-of-connected-components-in-an-undirected-graph.py | 0 problems/{ => python}/number-of-islands-ii.py | 0 problems/{ => python}/number-of-islands.py | 0 .../number-of-longest-increasing-subsequence.py | 0 problems/{ => python}/number-of-matching-subsequences.py | 0 problems/{ => python}/number-of-provinces.py | 0 problems/{ => python}/number-of-recent-calls.py | 0 problems/{ => python}/number-of-squareful-arrays.py | 0 .../number-of-substrings-containing-all-thre.py | 0 .../{ => python}/number-of-ways-to-arrive-at-destination.py | 0 problems/{ => python}/odd-even-jump.py | 0 problems/{ => python}/ones-and-zeroes.py | 0 problems/{ => python}/open-the-lock.py | 0 problems/{ => python}/out-of-boundary-paths.py | 0 problems/{ => python}/pacific-atlantic-water-flow.py | 0 .../pairs-of-songs-with-total-durations-divisible-by-60.py | 0 problems/{ => python}/palindrome-number.py | 0 problems/{ => python}/palindrome-pairs.py | 0 problems/{ => python}/palindrome-partitioning-iii.py | 0 problems/{ => python}/palindrome-partitioning.py | 0 problems/{ => python}/palindromic-substrings.py | 0 problems/{ => python}/partition-array-for-maximum-sum.py | 0 problems/{ => python}/partition-labels.py | 0 problems/{ => python}/partition-to-k-equal-sum-subsets.py | 0 problems/{ => python}/path-sum-ii.py | 0 problems/{ => python}/path-sum-iii.py | 0 problems/{ => python}/path-sum.py | 0 problems/{ => python}/path-with-maximum-probability.py | 0 .../peak-index-in-a-mountain-array.py} | 0 problems/{ => python}/perfect-squares.py | 0 problems/{ => python}/permutation-in-string.py | 0 problems/{ => python}/permutation-sequence.py | 0 problems/{ => python}/permutations-ii.py | 0 problems/{ => python}/permutations.py | 0 .../populating-next-right-pointers-in-each-node-ii.py | 0 .../populating-next-right-pointers-in-each-node.py | 0 problems/{ => python}/powx-n.py | 0 problems/{ => python}/product-of-array-except-self.py | 0 problems/{ => python}/profitable-schemes.py | 0 problems/{ => python}/queue-reconstruction-by-height.py | 0 problems/{ => python}/random-pick-with-weight.py | 0 problems/{ => python}/range-addition.py | 0 problems/{ => python}/range-sum-of-bst.py | 0 problems/{ => python}/range-sum-query-immutable.py | 0 problems/{ => python}/range-sum-query-mutable.py | 0 problems/{ => python}/rearrange-string-k-distance-apart.py | 0 problems/{ => python}/reconstruct-itinerary.py | 0 problems/{ => python}/recover-binary-search-tree.py | 0 problems/{ => python}/redundant-connection.py | 0 .../remove-all-adjacent-duplicates-in-string.py | 0 .../remove-all-ones-with-row-and-column-flips.py | 0 .../{ => python}/remove-duplicates-from-sorted-array-ii.py | 0 .../{ => python}/remove-duplicates-from-sorted-array.py | 0 problems/{ => python}/remove-duplicates-from-sorted-list.py | 0 problems/{ => python}/remove-element.py | 0 problems/{ => python}/remove-invalid-parentheses.py | 0 problems/{ => python}/remove-linked-list-elements.py | 0 problems/{ => python}/remove-nth-node-from-end-of-list.py | 0 problems/{ => python}/reorder-list.py | 0 problems/{ => python}/repeated-string-match.py | 0 .../replace-the-substring-for-balanced-string.py | 0 problems/{ => python}/restore-ip-addresses.py | 0 problems/{ => python}/reverse-integer.py | 0 problems/{ => python}/reverse-linked-list.py | 0 problems/{ => python}/reverse-string.py | 0 problems/{ => python}/reverse-vowels-of-a-string.py | 0 problems/{ => python}/reverse-words-in-a-string.py | 0 problems/{ => python}/robot-bounded-in-circle.py | 0 problems/{ => python}/roman-to-integer.py | 0 problems/{ => python}/rotate-array.py | 0 problems/{ => python}/rotate-image.py | 0 problems/{ => python}/russian-doll-envelopes.py | 0 problems/{ => python}/same-tree.py | 0 .../{ => python}/satisfiability-of-equality-equations.py | 0 problems/{ => python}/score-of-parentheses.py | 0 problems/{ => python}/search-a-2d-matrix.py | 0 problems/{ => python}/search-in-a-binary-search-tree.py | 0 problems/{ => python}/search-in-rotated-sorted-array-ii.py | 0 problems/{ => python}/search-in-rotated-sorted-array.py | 0 problems/{ => python}/search-insert-position.py | 0 problems/{ => python}/search-suggestions-system.py | 0 problems/{ => python}/second-highest-salary.sql | 0 .../{ => python}/sell-diminishing-valued-colored-balls.py | 0 .../{ => python}/serialize-and-deserialize-binary-tree.py | 0 problems/{ => python}/serialize-and-deserialize-bst.py | 0 problems/{ => python}/set-matrix-zeroes.py | 0 problems/{ => python}/shortest-bridge.py | 0 problems/{ => python}/shortest-common-supersequence.py | 0 .../{ => python}/shortest-distance-from-all-buildings.py | 0 .../shortest-path-in-a-grid-with-obstacles-elimination.py | 0 problems/{ => python}/shortest-path-in-binary-matrix.py | 0 problems/{ => python}/shortest-path-to-get-food.py | 0 problems/{ => python}/shuffle-an-array.py | 0 problems/{ => python}/simplify-path.py | 0 problems/{ => python}/single-threaded-cpu.py | 0 problems/{ => python}/sliding-window-maximum.py | 0 problems/{ => python}/snapshot-array.py | 0 problems/{ => python}/sort-colors.py | 0 problems/{ => python}/sort-list.py | 0 problems/{ => python}/spiral-matrix.py | 0 .../{ => python}/split-array-into-fibonacci-sequence.py | 0 problems/{ => python}/split-array-largest-sum.py | 0 problems/{ => python}/sqrtx.py | 0 problems/{ => python}/squares-of-a-sorted-array.py | 0 ...by-step-directions-from-a-binary-tree-node-to-another.py | 0 problems/{ => python}/stock-price-fluctuation.py | 0 problems/{ => python}/stone-game-ii.py | 0 problems/{ => python}/student-attendance-record-ii.py | 0 problems/{ => python}/subarray-sum-equals-k.py | 0 .../{ => python}/subarrays-with-k-different-integers.py | 0 problems/{ => python}/subdomain-visit-count.py | 0 problems/{ => python}/subsets-ii.py | 0 problems/{ => python}/subsets.py | 0 .../substring-with-concatenation-of-all-words.py | 0 problems/{ => python}/subtree-of-another-tree.py | 0 problems/{ => python}/sum-of-subarray-minimums.py | 0 problems/{ => python}/sum-root-to-leaf-numbers.py | 0 problems/{ => python}/summary-ranges.py | 0 problems/{ => python}/super-ugly-number.py | 0 problems/{ => python}/swap-adjacent-in-lr-string.py | 0 problems/{ => python}/swap-nodes-in-pairs.py | 0 problems/{ => python}/swim-in-rising-water.py | 0 problems/{ => python}/symmetric-tree.py | 0 problems/{ => python}/tallest-billboard.py | 0 problems/{ => python}/target-sum.py | 0 problems/{ => python}/task-scheduler.py | 0 problems/{ => python}/text-justification.py | 0 problems/{ => python}/the-kth-factor-of-n.py | 0 problems/{ => python}/the-maze-ii.py | 0 problems/{ => python}/time-based-key-value-store.py | 0 problems/{ => python}/to-lower-case.py | 0 problems/{ => python}/toeplitz-matrix.py | 0 problems/{ => python}/top-k-frequent-elements.py | 0 problems/{ => python}/trapping-rain-water-ii.py | 0 problems/{ => python}/trapping-rain-water.py | 0 problems/{ => python}/trim-a-binary-search-tree.py | 0 problems/{ => python}/two-out-of-three.py | 0 problems/{ => python}/two-sum-ii-input-array-is-sorted.py | 0 problems/{ => python}/two-sum.py | 0 problems/{ => python}/ugly-number-ii.py | 0 problems/{ => python}/ugly-number.py | 0 problems/{ => python}/umber-of-islands-ii.py | 0 problems/{ => python}/unique-binary-search-trees-ii,py | 0 problems/{ => python}/unique-binary-search-trees.py | 0 problems/{ => python}/unique-email-addres.py | 0 problems/{ => python}/unique-paths.py | 0 problems/{ => python}/univalued-binary-tree.py | 0 problems/{ => python}/valid-anagram.py | 0 problems/{ => python}/valid-number.py | 0 problems/{ => python}/valid-palindrome-ii.py | 0 problems/{ => python}/valid-palindrome.py | 0 problems/{ => python}/valid-parentheses.py | 0 problems/{ => python}/valid-word-abbreviation.py | 0 problems/{ => python}/validate-binary-search-tree.py | 0 .../verify-preorder-serialization-of-a-binary-tree.py | 0 .../vertical-order-traversal-of-a-binary-tree.py | 0 problems/{ => python}/wiggle-subsequence.py | 0 problems/{ => python}/word-break.py | 0 problems/{ => python}/word-ladder-ii.py | 0 problems/{ => python}/word-ladder.py | 0 problems/{ => python}/word-search-ii.py | 0 problems/{ => python}/word-search.py | 0 431 files changed, 3 insertions(+), 3 deletions(-) rename problems/{ => python}/01-matrix.py (100%) rename problems/{ => python}/3sum-closest.py (100%) rename problems/{ => python}/3sum.py (100%) rename problems/{ => python}/4sum.py (100%) rename problems/{ => python}/accounts-merge.py (100%) rename problems/{ => python}/add-binary.py (100%) rename problems/{ => python}/add-digits.py (100%) rename problems/{ => python}/add-strings.py (100%) rename problems/{ => python}/add-two-numbers-ii.py (100%) rename problems/{ => python}/add-two-numbers.py (100%) rename problems/{ => python}/alien-dictionary.py (100%) rename problems/{ => python}/all-nodes-distance-k-in-binary-tree.py (100%) rename problems/{ => python}/amount-of-new-area-painted-each-day.py (100%) rename problems/{ => python}/analyze-user-website-visit-pattern.py (100%) rename problems/{ => python}/backspace-string-compare.py (100%) rename problems/{ => python}/balance-a-binary-search-tree.py (100%) rename problems/{ => python}/balanced-binary-tree.py (100%) rename problems/{ => python}/basic-calculator-ii.py (100%) rename problems/{ => python}/best-time-to-buy-an-stock.py (100%) rename problems/{ => python}/best-time-to-buy-and-sell-stock-iii.py (100%) rename problems/{ => python}/best-time-to-buy-and-sell-stock-with-cooldown.py (100%) rename problems/{ => python}/best-time-to-buy-and-sell-stock.py (100%) rename problems/{ => python}/big-countries.sql (100%) rename problems/{ => python}/binary-search-tree-iterator.py (100%) rename problems/{ => python}/binary-search.py (100%) rename problems/{ => python}/binary-subarrays-with-sum.py (100%) rename problems/{ => python}/binary-tree-inorder-traversal.py (100%) rename problems/{ => python}/binary-tree-level-order-traversal-ii.py (100%) rename problems/{ => python}/binary-tree-level-order-traversal.py (100%) rename problems/{ => python}/binary-tree-longest-consecutive-sequence.py (100%) rename problems/{ => python}/binary-tree-maximum-path-sum.py (100%) rename problems/{ => python}/binary-tree-paths.py (100%) rename problems/{ => python}/binary-tree-pruning.py (100%) rename problems/{ => python}/binary-tree-right-side-view.py (100%) rename problems/{ => python}/binary-tree-vertical-order-traversal.py (100%) rename problems/{ => python}/binary-watch.py (100%) rename problems/{ => python}/buildings-with-an-ocean-view.py (100%) rename problems/{ => python}/burst-balloons.py (100%) rename problems/{ => python}/campus-bikes-ii.py (100%) rename problems/{ => python}/candy.py (100%) rename problems/{ => python}/capacity-to-ship-packages-within-d-days.py (100%) rename problems/{ => python}/cheapest-flights-within-k-stops.py (100%) rename problems/{ => python}/climbing-stairs.py (100%) rename problems/{ => python}/clone-graph.py (100%) rename problems/{ => python}/closest-binary-search-tree-value.py (100%) rename problems/{ => python}/coin-change.py (100%) rename problems/{ => python}/coloring-a-border.py (100%) rename problems/{ => python}/combination-sum-ii.py (100%) rename problems/{ => python}/combination-sum-iii.py (100%) rename problems/{ => python}/combination-sum-iv.py (100%) rename problems/{ => python}/combination-sum.py (100%) rename problems/{ => python}/combinations.py (100%) rename problems/{ => python}/combine-two-tables.sql (100%) rename problems/{ => python}/compare-version-numbers.py (100%) rename problems/{ => python}/connecting-cities-with-minimum-cost.py (100%) rename problems/{ => python}/consecutive-numbers-sum.py (100%) rename problems/{ => python}/construct-binary-tree-from-inorder-and-postorder-traversal.py (100%) rename problems/{ => python}/construct-binary-tree-from-preorder-and-inorder-traversal.py (100%) rename problems/{ => python}/container-with-most-water.py (100%) rename problems/{ => python}/contains-duplicate-ii.py (100%) rename problems/{ => python}/contains-duplicate-iii.py (100%) rename problems/{ => python}/contains-duplicate.py (100%) rename problems/{ => python}/continuous-subarray-sum.py (100%) rename problems/{ => python}/convert-binary-search-tree-to-sorted-doubly-linked-list.py (100%) rename problems/{ => python}/convert-sorted-array-to-binary-search-tree.py (100%) rename problems/{ => python}/convert-sorted-list-to-binary-search-tree.py (100%) rename problems/{ => python}/copy-list-with-random-pointer.py (100%) rename problems/{ => python}/count-all-valid-pickup-and-delivery-opti.py (100%) rename problems/{ => python}/count-binary-substrings.py (100%) rename problems/{ => python}/count-complete-tree-nodes.py (100%) rename problems/{ => python}/count-number-of-nice-subarrays.py (100%) rename problems/{ => python}/count-unique-characters-of-all-substrings-of-a-given-string.py (100%) rename problems/{ => python}/course-schedule-ii.py (100%) rename problems/{ => python}/course-schedule.py (100%) rename problems/{ => python}/custom-sort-string.py (100%) rename problems/{ => python}/cutting-ribbons.py (100%) rename problems/{ => python}/data-stream-as-disjoint-intervals.py (100%) rename problems/{ => python}/decode-string.py (100%) rename problems/{ => python}/decode-ways.py (100%) rename problems/{ => python}/delete-and-earn.py (100%) rename problems/{ => python}/delete-duplicate-folders-in-system.py (100%) rename problems/{ => python}/delete-node-in-a-bst.py (100%) rename problems/{ => python}/delete-operation-for-two-strings.py (100%) rename problems/{ => python}/design-add-and-search-words-data-structure.py (100%) rename problems/{ => python}/design-in-memory-file-system.py (100%) rename problems/{ => python}/design-linked-list.py (100%) rename problems/{ => python}/design-tic-tac-toe.py (100%) rename problems/{ => python}/diagonal-traverse.py (100%) rename problems/{ => python}/diameter-of-binary-tree.py (100%) rename problems/{ => python}/different-ways-to-add-parentheses.py (100%) rename problems/{ => python}/distinct-subsequences.py (100%) rename problems/{ => python}/distribute-coins-in-binary-tree.py (100%) rename problems/{ => python}/domino-and-tromino-tiling.py (100%) rename problems/{ => python}/dot-product-of-two-sparse-vectors.py (100%) rename problems/{ => python}/dungeon-game.py (100%) rename problems/{ => python}/edit-distance.py (100%) rename problems/{ => python}/egions-cut-by-slashes.py (100%) rename problems/{ => python}/evaluate-division.py (100%) rename problems/{ => python}/evaluate-reverse-polish-notation.py (100%) rename problems/{ => python}/exclusive-time-of-functions.py (100%) rename problems/{ => python}/expression-add-operators.py (100%) rename problems/{ => python}/filling-bookcase-shelves.py (100%) rename problems/{ => python}/find-all-possible-recipes-from-given-supplies.py (100%) rename problems/{ => python}/find-and-replace-in-string.py (100%) rename problems/{ => python}/find-distance-in-a-binary-tree.py (100%) rename problems/{ => python}/find-duplicate-subtrees.py (100%) rename problems/{ => python}/find-eventual-safe-states.py (100%) rename problems/{ => python}/find-first-and-last-position-of-element-in-sorted-array.py (100%) rename problems/{ => python}/find-k-closest-elements.py (100%) rename problems/{ => python}/find-k-pairs-with-smallest-sums.py (100%) rename problems/{ => python}/find-leaves-of-binary-tree.py (100%) rename problems/{ => python}/find-median-from-data-stream.py (100%) rename problems/{ => python}/find-minimum-in-rotated-sorted-array-ii.py (100%) rename problems/{ => python}/find-minimum-in-rotated-sorted-array.py (100%) rename problems/{ => python}/find-mode-in-binary-search-tree.py (100%) rename problems/{ => python}/find-original-array-from-doubled-array,py (100%) rename problems/{ => python}/find-peak-element.py (100%) rename problems/{ => python}/find-the-duplicate-number.py (100%) rename problems/{ => python}/first-bad-version.py (100%) rename problems/{ => python}/first-missing-positive.py (100%) rename problems/{ => python}/first-unique-character-in-a-string.py (100%) rename problems/{ => python}/fizz-buzz.py (100%) rename problems/{ => python}/flatten-binary-tree-to-linked-list.py (100%) rename problems/{ => python}/flip-binary-tree-to-match-preorder-traversal.py (100%) rename problems/{ => python}/flip-string-to-monotone-increasing.py (100%) rename problems/{ => python}/flood-fill.py (100%) rename problems/{ => python}/friend-circles.py (100%) rename problems/{ => python}/fruit-into-baskets.py (100%) rename problems/{ => python}/game-of-life.py (100%) rename problems/{ => python}/generate-parentheses.py (100%) rename problems/{ => python}/graph-valid-tree.py (100%) rename problems/{ => python}/greatest-sum-divisible-by-three.py (100%) rename problems/{ => python}/group-anagrams.py (100%) rename problems/{ => python}/group-shifted-strings.py (100%) rename problems/{ => python}/guess-number-higher-or-lower-ii.py (100%) rename problems/{ => python}/guess-number-higher-or-lower.py (100%) rename problems/{ => python}/guess-the-word.py (100%) rename problems/{ => python}/h-index-ii.py (100%) rename problems/{ => python}/h-index.py (100%) rename problems/{ => python}/hamming-distance.py (100%) rename problems/{ => python}/house-robber-ii.py (100%) rename problems/{ => python}/house-robber-iii.py (100%) rename problems/{ => python}/house-robber.py (100%) rename problems/{ => python}/implement-trie-prefix-tree.py (100%) rename problems/{ => python}/increasing-triplet-subsequence.py (100%) rename problems/{ => python}/inorder-successor-in-bst-ii.py (100%) rename problems/{ => python}/inorder-successor-in-bst.py (100%) rename problems/{ => python}/insert-interval.py (100%) rename problems/{ => python}/insert-into-a-binary-search-tree.py (100%) rename problems/{ => python}/insert-into-a-sorted-circular-linked-list.py (100%) rename problems/{ => python}/insertion-sort-list.py (100%) rename problems/{ => python}/integer-to-english-words.py (100%) rename problems/{ => python}/interleaving-string.py (100%) rename problems/{ => python}/intersection-of-two-arrays-ii.py (100%) rename problems/{ => python}/intersection-of-two-arrays.py (100%) rename problems/{ => python}/invert-binary-tree.py (100%) rename problems/{ => python}/is-graph-bipartite.py (100%) rename problems/{ => python}/is-subsequence.py (100%) rename problems/{ => python}/isomorphic-strings.py (100%) rename problems/{ => python}/jewels-and-stones.py (100%) rename problems/{ => python}/jump-game.py (100%) rename problems/{ => python}/k-closest-points-to-origin.py (100%) rename problems/{ => python}/k-empty-slots.py (100%) rename problems/{ => python}/keys-and-rooms.py (100%) rename problems/{ => python}/knight-dialer.py (100%) rename problems/{ => python}/knight-probability-in-chessboard.py (100%) rename problems/{ => python}/koko-eating-bananas.py (100%) rename problems/{ => python}/kth-largest-element-in-an-array.py (100%) rename problems/{ => python}/kth-smallest-element-in-a-bst.py (100%) rename problems/{ => python}/kth-smallest-element-in-a-sorted-matrix.py (100%) rename problems/{ => python}/largest-1-bordered-square.py (100%) rename problems/{ => python}/largest-bst-subtree.py (100%) rename problems/{ => python}/largest-sum-of-averages.py (100%) rename problems/{ => python}/last-stone-weight-ii.py (100%) rename problems/{ => python}/last-stone-weight.py (100%) rename problems/{ => python}/least-number-of-unique-integers-after-k-removals.py (100%) rename problems/{ => python}/letter-case-permutation.py (100%) rename problems/{ => python}/letter-combinations-of-a-phone-number.py (100%) rename problems/{ => python}/license-key-formatting.py (100%) rename problems/{ => python}/linked-list-cycle-ii.py (100%) rename problems/{ => python}/linked-list-cycle.py (100%) rename problems/{ => python}/linked-list-random-node.py (100%) rename problems/{ => python}/logger-rate-limiter.py (100%) rename problems/{ => python}/longest-common-prefix.py (100%) rename problems/{ => python}/longest-common-subsequence.py (100%) rename problems/{ => python}/longest-consecutive-sequence.py (100%) rename problems/{ => python}/longest-increasing-path-in-a-matrix.py (100%) rename problems/{ => python}/longest-increasing-subsequence.py (100%) rename problems/{ => python}/longest-palindromic-subsequence.py (100%) rename problems/{ => python}/longest-palindromic-substring.py (100%) rename problems/{ => python}/longest-repeating-character-replacement.py (100%) rename problems/{ => python}/longest-string-chain.py (100%) rename problems/{ => python}/longest-substring-with-at-least-k-repeating-characters.py (100%) rename problems/{ => python}/longest-substring-without-repeating-characters.py (100%) rename problems/{ => python}/longest-univalue-path.py (100%) rename problems/{ => python}/lowest-common-ancestor-of-a-binary-search-tree.py (100%) rename problems/{ => python}/lowest-common-ancestor-of-a-binary-search.py (100%) rename problems/{ => python}/lowest-common-ancestor-of-a-binary-tree-ii.py (100%) rename problems/{ => python}/lowest-common-ancestor-of-a-binary-tree-iii.py (100%) rename problems/{ => python}/lowest-common-ancestor-of-a-binary-tree-iv.py (100%) rename problems/{ => python}/lowest-common-ancestor-of-a-binary-tree.py (100%) rename problems/{ => python}/lowest-common-ancestor-of-deepest-leaves.py (100%) rename problems/{ => python}/lru-cache.py (100%) rename problems/{ => python}/majority-element-ii.py (100%) rename problems/{ => python}/majority-element.py (100%) rename problems/{ => python}/making-a-large-island.py (100%) rename problems/{ => python}/max-area-of-island.py (100%) rename problems/{ => python}/max-consecutive-ones-iii.py (100%) rename problems/{ => python}/max-stack.py (100%) rename problems/{ => python}/max-sum-of-rectangle-no-larger-than-k.py (100%) rename problems/{ => python}/maximal-square.py (100%) rename problems/{ => python}/maximum-average-subtree.py (100%) rename problems/{ => python}/maximum-compatibility-score-sum.py (100%) rename problems/{ => python}/maximum-depth-of-binary-tree.py (100%) rename problems/{ => python}/maximum-gap.py (100%) rename problems/{ => python}/maximum-length-of-repeated-subarray.py (100%) rename problems/{ => python}/maximum-number-of-events-that-can-be-attended.py (100%) rename problems/{ => python}/maximum-number-of-points-with-cost.py (100%) rename problems/{ => python}/maximum-number-of-visible-points.py (100%) rename problems/{ => python}/maximum-product-of-three-numbers.py (100%) rename problems/{ => python}/maximum-product-subarray.py (100%) rename problems/{ => python}/maximum-subarray-sum-with-one-deletion.py (100%) rename problems/{ => python}/maximum-subarray.py (100%) rename problems/{ => python}/maximum-swap.py (100%) rename problems/{ => python}/maximum-units-on-a-truck.py (100%) rename problems/{ => python}/median-of-two-sorted-arrays.py (100%) rename problems/{ => python}/meeting-rooms-ii.py (100%) rename problems/{ => python}/meeting-rooms.py (100%) rename problems/{ => python}/merge-intervals.py (100%) rename problems/{ => python}/merge-k-sorted-lists.py (100%) rename problems/{ => python}/merge-sorted-array.py (100%) rename problems/{ => python}/merge-two-sorted-lists.py (100%) rename problems/{ => python}/min-cost-climbing-stairs.py (100%) rename problems/{ => python}/min-stack.py (100%) rename problems/{ => python}/minimize-malware-spread.py (100%) rename problems/{ => python}/minimum-absolute-difference-in-bst.py (100%) rename problems/{ => python}/minimum-ascii-delete-sum-for-two-strings.py (100%) rename problems/{ => python}/minimum-cost-to-connect-sticks.py (100%) rename problems/{ => python}/minimum-cost-to-hire-k-workers.py (100%) rename problems/{ => python}/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py (100%) rename problems/{ => python}/minimum-cost-to-reach-city-with-discounts.py (100%) rename problems/{ => python}/minimum-depth-of-binary-tree.py (100%) rename problems/{ => python}/minimum-difficulty-of-a-job-schedule.py (100%) rename problems/{ => python}/minimum-falling-path-sum-ii.py (100%) rename problems/{ => python}/minimum-knight-moves.py (100%) rename problems/{ => python}/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py (100%) rename problems/{ => python}/minimum-path-sum.py (100%) rename problems/{ => python}/minimum-score-triangulation-of-polygon.py (100%) rename problems/{ => python}/minimum-size-subarray-sum.py (100%) rename problems/{ => python}/minimum-swaps-to-group-all-1s-together.py (100%) rename problems/{ => python}/minimum-swaps-to-make-sequences-increasing.py (100%) rename problems/{ => python}/minimum-time-difference.py (100%) rename problems/{ => python}/minimum-window-substring.py (100%) rename problems/{ => python}/minimum-xor-sum-of-two-arrays.py (100%) rename problems/{ => python}/missing-number.py (100%) rename problems/{ => python}/most-frequent-subtree-sum.py (100%) rename problems/{ => python}/most-stones-removed-with-same-row-or-column.py (100%) rename problems/{ => python}/move-zeroes.py (100%) rename problems/{ => python}/moving-average-from-data-stream.py (100%) rename problems/{ => python}/my-calendar-ii.py (100%) rename problems/{ => python}/n-ary-tree-level-order-traversal.py (100%) rename problems/{ => python}/n-ary-tree-postorder-traversal.py (100%) rename problems/{ => python}/n-ary-tree-preorder-traversal.py (100%) rename problems/{ => python}/nested-list-weight-sum.py (100%) rename problems/{ => python}/network-delay-time.py (100%) rename problems/{ => python}/next-closest-time.py (100%) rename problems/{ => python}/next-permutation.py (100%) rename problems/{ => python}/number-complement.py (100%) rename problems/{ => python}/number-of-connected-components-in-an-undirected-graph.py (100%) rename problems/{ => python}/number-of-islands-ii.py (100%) rename problems/{ => python}/number-of-islands.py (100%) rename problems/{ => python}/number-of-longest-increasing-subsequence.py (100%) rename problems/{ => python}/number-of-matching-subsequences.py (100%) rename problems/{ => python}/number-of-provinces.py (100%) rename problems/{ => python}/number-of-recent-calls.py (100%) rename problems/{ => python}/number-of-squareful-arrays.py (100%) rename problems/{ => python}/number-of-substrings-containing-all-thre.py (100%) rename problems/{ => python}/number-of-ways-to-arrive-at-destination.py (100%) rename problems/{ => python}/odd-even-jump.py (100%) rename problems/{ => python}/ones-and-zeroes.py (100%) rename problems/{ => python}/open-the-lock.py (100%) rename problems/{ => python}/out-of-boundary-paths.py (100%) rename problems/{ => python}/pacific-atlantic-water-flow.py (100%) rename problems/{ => python}/pairs-of-songs-with-total-durations-divisible-by-60.py (100%) rename problems/{ => python}/palindrome-number.py (100%) rename problems/{ => python}/palindrome-pairs.py (100%) rename problems/{ => python}/palindrome-partitioning-iii.py (100%) rename problems/{ => python}/palindrome-partitioning.py (100%) rename problems/{ => python}/palindromic-substrings.py (100%) rename problems/{ => python}/partition-array-for-maximum-sum.py (100%) rename problems/{ => python}/partition-labels.py (100%) rename problems/{ => python}/partition-to-k-equal-sum-subsets.py (100%) rename problems/{ => python}/path-sum-ii.py (100%) rename problems/{ => python}/path-sum-iii.py (100%) rename problems/{ => python}/path-sum.py (100%) rename problems/{ => python}/path-with-maximum-probability.py (100%) rename problems/{peak-index-in-a-mountain-array.PY => python/peak-index-in-a-mountain-array.py} (100%) rename problems/{ => python}/perfect-squares.py (100%) rename problems/{ => python}/permutation-in-string.py (100%) rename problems/{ => python}/permutation-sequence.py (100%) rename problems/{ => python}/permutations-ii.py (100%) rename problems/{ => python}/permutations.py (100%) rename problems/{ => python}/populating-next-right-pointers-in-each-node-ii.py (100%) rename problems/{ => python}/populating-next-right-pointers-in-each-node.py (100%) rename problems/{ => python}/powx-n.py (100%) rename problems/{ => python}/product-of-array-except-self.py (100%) rename problems/{ => python}/profitable-schemes.py (100%) rename problems/{ => python}/queue-reconstruction-by-height.py (100%) rename problems/{ => python}/random-pick-with-weight.py (100%) rename problems/{ => python}/range-addition.py (100%) rename problems/{ => python}/range-sum-of-bst.py (100%) rename problems/{ => python}/range-sum-query-immutable.py (100%) rename problems/{ => python}/range-sum-query-mutable.py (100%) rename problems/{ => python}/rearrange-string-k-distance-apart.py (100%) rename problems/{ => python}/reconstruct-itinerary.py (100%) rename problems/{ => python}/recover-binary-search-tree.py (100%) rename problems/{ => python}/redundant-connection.py (100%) rename problems/{ => python}/remove-all-adjacent-duplicates-in-string.py (100%) rename problems/{ => python}/remove-all-ones-with-row-and-column-flips.py (100%) rename problems/{ => python}/remove-duplicates-from-sorted-array-ii.py (100%) rename problems/{ => python}/remove-duplicates-from-sorted-array.py (100%) rename problems/{ => python}/remove-duplicates-from-sorted-list.py (100%) rename problems/{ => python}/remove-element.py (100%) rename problems/{ => python}/remove-invalid-parentheses.py (100%) rename problems/{ => python}/remove-linked-list-elements.py (100%) rename problems/{ => python}/remove-nth-node-from-end-of-list.py (100%) rename problems/{ => python}/reorder-list.py (100%) rename problems/{ => python}/repeated-string-match.py (100%) rename problems/{ => python}/replace-the-substring-for-balanced-string.py (100%) rename problems/{ => python}/restore-ip-addresses.py (100%) rename problems/{ => python}/reverse-integer.py (100%) rename problems/{ => python}/reverse-linked-list.py (100%) rename problems/{ => python}/reverse-string.py (100%) rename problems/{ => python}/reverse-vowels-of-a-string.py (100%) rename problems/{ => python}/reverse-words-in-a-string.py (100%) rename problems/{ => python}/robot-bounded-in-circle.py (100%) rename problems/{ => python}/roman-to-integer.py (100%) rename problems/{ => python}/rotate-array.py (100%) rename problems/{ => python}/rotate-image.py (100%) rename problems/{ => python}/russian-doll-envelopes.py (100%) rename problems/{ => python}/same-tree.py (100%) rename problems/{ => python}/satisfiability-of-equality-equations.py (100%) rename problems/{ => python}/score-of-parentheses.py (100%) rename problems/{ => python}/search-a-2d-matrix.py (100%) rename problems/{ => python}/search-in-a-binary-search-tree.py (100%) rename problems/{ => python}/search-in-rotated-sorted-array-ii.py (100%) rename problems/{ => python}/search-in-rotated-sorted-array.py (100%) rename problems/{ => python}/search-insert-position.py (100%) rename problems/{ => python}/search-suggestions-system.py (100%) rename problems/{ => python}/second-highest-salary.sql (100%) rename problems/{ => python}/sell-diminishing-valued-colored-balls.py (100%) rename problems/{ => python}/serialize-and-deserialize-binary-tree.py (100%) rename problems/{ => python}/serialize-and-deserialize-bst.py (100%) rename problems/{ => python}/set-matrix-zeroes.py (100%) rename problems/{ => python}/shortest-bridge.py (100%) rename problems/{ => python}/shortest-common-supersequence.py (100%) rename problems/{ => python}/shortest-distance-from-all-buildings.py (100%) rename problems/{ => python}/shortest-path-in-a-grid-with-obstacles-elimination.py (100%) rename problems/{ => python}/shortest-path-in-binary-matrix.py (100%) rename problems/{ => python}/shortest-path-to-get-food.py (100%) rename problems/{ => python}/shuffle-an-array.py (100%) rename problems/{ => python}/simplify-path.py (100%) rename problems/{ => python}/single-threaded-cpu.py (100%) rename problems/{ => python}/sliding-window-maximum.py (100%) rename problems/{ => python}/snapshot-array.py (100%) rename problems/{ => python}/sort-colors.py (100%) rename problems/{ => python}/sort-list.py (100%) rename problems/{ => python}/spiral-matrix.py (100%) rename problems/{ => python}/split-array-into-fibonacci-sequence.py (100%) rename problems/{ => python}/split-array-largest-sum.py (100%) rename problems/{ => python}/sqrtx.py (100%) rename problems/{ => python}/squares-of-a-sorted-array.py (100%) rename problems/{ => python}/step-by-step-directions-from-a-binary-tree-node-to-another.py (100%) rename problems/{ => python}/stock-price-fluctuation.py (100%) rename problems/{ => python}/stone-game-ii.py (100%) rename problems/{ => python}/student-attendance-record-ii.py (100%) rename problems/{ => python}/subarray-sum-equals-k.py (100%) rename problems/{ => python}/subarrays-with-k-different-integers.py (100%) rename problems/{ => python}/subdomain-visit-count.py (100%) rename problems/{ => python}/subsets-ii.py (100%) rename problems/{ => python}/subsets.py (100%) rename problems/{ => python}/substring-with-concatenation-of-all-words.py (100%) rename problems/{ => python}/subtree-of-another-tree.py (100%) rename problems/{ => python}/sum-of-subarray-minimums.py (100%) rename problems/{ => python}/sum-root-to-leaf-numbers.py (100%) rename problems/{ => python}/summary-ranges.py (100%) rename problems/{ => python}/super-ugly-number.py (100%) rename problems/{ => python}/swap-adjacent-in-lr-string.py (100%) rename problems/{ => python}/swap-nodes-in-pairs.py (100%) rename problems/{ => python}/swim-in-rising-water.py (100%) rename problems/{ => python}/symmetric-tree.py (100%) rename problems/{ => python}/tallest-billboard.py (100%) rename problems/{ => python}/target-sum.py (100%) rename problems/{ => python}/task-scheduler.py (100%) rename problems/{ => python}/text-justification.py (100%) rename problems/{ => python}/the-kth-factor-of-n.py (100%) rename problems/{ => python}/the-maze-ii.py (100%) rename problems/{ => python}/time-based-key-value-store.py (100%) rename problems/{ => python}/to-lower-case.py (100%) rename problems/{ => python}/toeplitz-matrix.py (100%) rename problems/{ => python}/top-k-frequent-elements.py (100%) rename problems/{ => python}/trapping-rain-water-ii.py (100%) rename problems/{ => python}/trapping-rain-water.py (100%) rename problems/{ => python}/trim-a-binary-search-tree.py (100%) rename problems/{ => python}/two-out-of-three.py (100%) rename problems/{ => python}/two-sum-ii-input-array-is-sorted.py (100%) rename problems/{ => python}/two-sum.py (100%) rename problems/{ => python}/ugly-number-ii.py (100%) rename problems/{ => python}/ugly-number.py (100%) rename problems/{ => python}/umber-of-islands-ii.py (100%) rename problems/{ => python}/unique-binary-search-trees-ii,py (100%) rename problems/{ => python}/unique-binary-search-trees.py (100%) rename problems/{ => python}/unique-email-addres.py (100%) rename problems/{ => python}/unique-paths.py (100%) rename problems/{ => python}/univalued-binary-tree.py (100%) rename problems/{ => python}/valid-anagram.py (100%) rename problems/{ => python}/valid-number.py (100%) rename problems/{ => python}/valid-palindrome-ii.py (100%) rename problems/{ => python}/valid-palindrome.py (100%) rename problems/{ => python}/valid-parentheses.py (100%) rename problems/{ => python}/valid-word-abbreviation.py (100%) rename problems/{ => python}/validate-binary-search-tree.py (100%) rename problems/{ => python}/verify-preorder-serialization-of-a-binary-tree.py (100%) rename problems/{ => python}/vertical-order-traversal-of-a-binary-tree.py (100%) rename problems/{ => python}/wiggle-subsequence.py (100%) rename problems/{ => python}/word-break.py (100%) rename problems/{ => python}/word-ladder-ii.py (100%) rename problems/{ => python}/word-ladder.py (100%) rename problems/{ => python}/word-search-ii.py (100%) rename problems/{ => python}/word-search.py (100%) diff --git a/README.md b/README.md index f076d25..8e05de7 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Overview -1. This is my Python (2.7) Leetcode solution. +1. This is my Python Leetcode solution. As time grows, this also become a guide to prepare for software engineer interview. -2. The solution is at `problems/the-file-name/`. -For example, `merge-sorted-array.py`'s solution is at `https://leetcode.com/problems/merge-sorted-array/`. +1. The solution is at `problems/python/` or `problems/python3/`. +For example, `merge-sorted-array.py`'s solution is at `https://leetcode.com/problems/python/merge-sorted-array/`. 2. I really take time tried to make the best solution and collect the best resource that I found. Because I wanted to help others like me. diff --git a/problems/01-matrix.py b/problems/python/01-matrix.py similarity index 100% rename from problems/01-matrix.py rename to problems/python/01-matrix.py diff --git a/problems/3sum-closest.py b/problems/python/3sum-closest.py similarity index 100% rename from problems/3sum-closest.py rename to problems/python/3sum-closest.py diff --git a/problems/3sum.py b/problems/python/3sum.py similarity index 100% rename from problems/3sum.py rename to problems/python/3sum.py diff --git a/problems/4sum.py b/problems/python/4sum.py similarity index 100% rename from problems/4sum.py rename to problems/python/4sum.py diff --git a/problems/accounts-merge.py b/problems/python/accounts-merge.py similarity index 100% rename from problems/accounts-merge.py rename to problems/python/accounts-merge.py diff --git a/problems/add-binary.py b/problems/python/add-binary.py similarity index 100% rename from problems/add-binary.py rename to problems/python/add-binary.py diff --git a/problems/add-digits.py b/problems/python/add-digits.py similarity index 100% rename from problems/add-digits.py rename to problems/python/add-digits.py diff --git a/problems/add-strings.py b/problems/python/add-strings.py similarity index 100% rename from problems/add-strings.py rename to problems/python/add-strings.py diff --git a/problems/add-two-numbers-ii.py b/problems/python/add-two-numbers-ii.py similarity index 100% rename from problems/add-two-numbers-ii.py rename to problems/python/add-two-numbers-ii.py diff --git a/problems/add-two-numbers.py b/problems/python/add-two-numbers.py similarity index 100% rename from problems/add-two-numbers.py rename to problems/python/add-two-numbers.py diff --git a/problems/alien-dictionary.py b/problems/python/alien-dictionary.py similarity index 100% rename from problems/alien-dictionary.py rename to problems/python/alien-dictionary.py diff --git a/problems/all-nodes-distance-k-in-binary-tree.py b/problems/python/all-nodes-distance-k-in-binary-tree.py similarity index 100% rename from problems/all-nodes-distance-k-in-binary-tree.py rename to problems/python/all-nodes-distance-k-in-binary-tree.py diff --git a/problems/amount-of-new-area-painted-each-day.py b/problems/python/amount-of-new-area-painted-each-day.py similarity index 100% rename from problems/amount-of-new-area-painted-each-day.py rename to problems/python/amount-of-new-area-painted-each-day.py diff --git a/problems/analyze-user-website-visit-pattern.py b/problems/python/analyze-user-website-visit-pattern.py similarity index 100% rename from problems/analyze-user-website-visit-pattern.py rename to problems/python/analyze-user-website-visit-pattern.py diff --git a/problems/backspace-string-compare.py b/problems/python/backspace-string-compare.py similarity index 100% rename from problems/backspace-string-compare.py rename to problems/python/backspace-string-compare.py diff --git a/problems/balance-a-binary-search-tree.py b/problems/python/balance-a-binary-search-tree.py similarity index 100% rename from problems/balance-a-binary-search-tree.py rename to problems/python/balance-a-binary-search-tree.py diff --git a/problems/balanced-binary-tree.py b/problems/python/balanced-binary-tree.py similarity index 100% rename from problems/balanced-binary-tree.py rename to problems/python/balanced-binary-tree.py diff --git a/problems/basic-calculator-ii.py b/problems/python/basic-calculator-ii.py similarity index 100% rename from problems/basic-calculator-ii.py rename to problems/python/basic-calculator-ii.py diff --git a/problems/best-time-to-buy-an-stock.py b/problems/python/best-time-to-buy-an-stock.py similarity index 100% rename from problems/best-time-to-buy-an-stock.py rename to problems/python/best-time-to-buy-an-stock.py diff --git a/problems/best-time-to-buy-and-sell-stock-iii.py b/problems/python/best-time-to-buy-and-sell-stock-iii.py similarity index 100% rename from problems/best-time-to-buy-and-sell-stock-iii.py rename to problems/python/best-time-to-buy-and-sell-stock-iii.py diff --git a/problems/best-time-to-buy-and-sell-stock-with-cooldown.py b/problems/python/best-time-to-buy-and-sell-stock-with-cooldown.py similarity index 100% rename from problems/best-time-to-buy-and-sell-stock-with-cooldown.py rename to problems/python/best-time-to-buy-and-sell-stock-with-cooldown.py diff --git a/problems/best-time-to-buy-and-sell-stock.py b/problems/python/best-time-to-buy-and-sell-stock.py similarity index 100% rename from problems/best-time-to-buy-and-sell-stock.py rename to problems/python/best-time-to-buy-and-sell-stock.py diff --git a/problems/big-countries.sql b/problems/python/big-countries.sql similarity index 100% rename from problems/big-countries.sql rename to problems/python/big-countries.sql diff --git a/problems/binary-search-tree-iterator.py b/problems/python/binary-search-tree-iterator.py similarity index 100% rename from problems/binary-search-tree-iterator.py rename to problems/python/binary-search-tree-iterator.py diff --git a/problems/binary-search.py b/problems/python/binary-search.py similarity index 100% rename from problems/binary-search.py rename to problems/python/binary-search.py diff --git a/problems/binary-subarrays-with-sum.py b/problems/python/binary-subarrays-with-sum.py similarity index 100% rename from problems/binary-subarrays-with-sum.py rename to problems/python/binary-subarrays-with-sum.py diff --git a/problems/binary-tree-inorder-traversal.py b/problems/python/binary-tree-inorder-traversal.py similarity index 100% rename from problems/binary-tree-inorder-traversal.py rename to problems/python/binary-tree-inorder-traversal.py diff --git a/problems/binary-tree-level-order-traversal-ii.py b/problems/python/binary-tree-level-order-traversal-ii.py similarity index 100% rename from problems/binary-tree-level-order-traversal-ii.py rename to problems/python/binary-tree-level-order-traversal-ii.py diff --git a/problems/binary-tree-level-order-traversal.py b/problems/python/binary-tree-level-order-traversal.py similarity index 100% rename from problems/binary-tree-level-order-traversal.py rename to problems/python/binary-tree-level-order-traversal.py diff --git a/problems/binary-tree-longest-consecutive-sequence.py b/problems/python/binary-tree-longest-consecutive-sequence.py similarity index 100% rename from problems/binary-tree-longest-consecutive-sequence.py rename to problems/python/binary-tree-longest-consecutive-sequence.py diff --git a/problems/binary-tree-maximum-path-sum.py b/problems/python/binary-tree-maximum-path-sum.py similarity index 100% rename from problems/binary-tree-maximum-path-sum.py rename to problems/python/binary-tree-maximum-path-sum.py diff --git a/problems/binary-tree-paths.py b/problems/python/binary-tree-paths.py similarity index 100% rename from problems/binary-tree-paths.py rename to problems/python/binary-tree-paths.py diff --git a/problems/binary-tree-pruning.py b/problems/python/binary-tree-pruning.py similarity index 100% rename from problems/binary-tree-pruning.py rename to problems/python/binary-tree-pruning.py diff --git a/problems/binary-tree-right-side-view.py b/problems/python/binary-tree-right-side-view.py similarity index 100% rename from problems/binary-tree-right-side-view.py rename to problems/python/binary-tree-right-side-view.py diff --git a/problems/binary-tree-vertical-order-traversal.py b/problems/python/binary-tree-vertical-order-traversal.py similarity index 100% rename from problems/binary-tree-vertical-order-traversal.py rename to problems/python/binary-tree-vertical-order-traversal.py diff --git a/problems/binary-watch.py b/problems/python/binary-watch.py similarity index 100% rename from problems/binary-watch.py rename to problems/python/binary-watch.py diff --git a/problems/buildings-with-an-ocean-view.py b/problems/python/buildings-with-an-ocean-view.py similarity index 100% rename from problems/buildings-with-an-ocean-view.py rename to problems/python/buildings-with-an-ocean-view.py diff --git a/problems/burst-balloons.py b/problems/python/burst-balloons.py similarity index 100% rename from problems/burst-balloons.py rename to problems/python/burst-balloons.py diff --git a/problems/campus-bikes-ii.py b/problems/python/campus-bikes-ii.py similarity index 100% rename from problems/campus-bikes-ii.py rename to problems/python/campus-bikes-ii.py diff --git a/problems/candy.py b/problems/python/candy.py similarity index 100% rename from problems/candy.py rename to problems/python/candy.py diff --git a/problems/capacity-to-ship-packages-within-d-days.py b/problems/python/capacity-to-ship-packages-within-d-days.py similarity index 100% rename from problems/capacity-to-ship-packages-within-d-days.py rename to problems/python/capacity-to-ship-packages-within-d-days.py diff --git a/problems/cheapest-flights-within-k-stops.py b/problems/python/cheapest-flights-within-k-stops.py similarity index 100% rename from problems/cheapest-flights-within-k-stops.py rename to problems/python/cheapest-flights-within-k-stops.py diff --git a/problems/climbing-stairs.py b/problems/python/climbing-stairs.py similarity index 100% rename from problems/climbing-stairs.py rename to problems/python/climbing-stairs.py diff --git a/problems/clone-graph.py b/problems/python/clone-graph.py similarity index 100% rename from problems/clone-graph.py rename to problems/python/clone-graph.py diff --git a/problems/closest-binary-search-tree-value.py b/problems/python/closest-binary-search-tree-value.py similarity index 100% rename from problems/closest-binary-search-tree-value.py rename to problems/python/closest-binary-search-tree-value.py diff --git a/problems/coin-change.py b/problems/python/coin-change.py similarity index 100% rename from problems/coin-change.py rename to problems/python/coin-change.py diff --git a/problems/coloring-a-border.py b/problems/python/coloring-a-border.py similarity index 100% rename from problems/coloring-a-border.py rename to problems/python/coloring-a-border.py diff --git a/problems/combination-sum-ii.py b/problems/python/combination-sum-ii.py similarity index 100% rename from problems/combination-sum-ii.py rename to problems/python/combination-sum-ii.py diff --git a/problems/combination-sum-iii.py b/problems/python/combination-sum-iii.py similarity index 100% rename from problems/combination-sum-iii.py rename to problems/python/combination-sum-iii.py diff --git a/problems/combination-sum-iv.py b/problems/python/combination-sum-iv.py similarity index 100% rename from problems/combination-sum-iv.py rename to problems/python/combination-sum-iv.py diff --git a/problems/combination-sum.py b/problems/python/combination-sum.py similarity index 100% rename from problems/combination-sum.py rename to problems/python/combination-sum.py diff --git a/problems/combinations.py b/problems/python/combinations.py similarity index 100% rename from problems/combinations.py rename to problems/python/combinations.py diff --git a/problems/combine-two-tables.sql b/problems/python/combine-two-tables.sql similarity index 100% rename from problems/combine-two-tables.sql rename to problems/python/combine-two-tables.sql diff --git a/problems/compare-version-numbers.py b/problems/python/compare-version-numbers.py similarity index 100% rename from problems/compare-version-numbers.py rename to problems/python/compare-version-numbers.py diff --git a/problems/connecting-cities-with-minimum-cost.py b/problems/python/connecting-cities-with-minimum-cost.py similarity index 100% rename from problems/connecting-cities-with-minimum-cost.py rename to problems/python/connecting-cities-with-minimum-cost.py diff --git a/problems/consecutive-numbers-sum.py b/problems/python/consecutive-numbers-sum.py similarity index 100% rename from problems/consecutive-numbers-sum.py rename to problems/python/consecutive-numbers-sum.py diff --git a/problems/construct-binary-tree-from-inorder-and-postorder-traversal.py b/problems/python/construct-binary-tree-from-inorder-and-postorder-traversal.py similarity index 100% rename from problems/construct-binary-tree-from-inorder-and-postorder-traversal.py rename to problems/python/construct-binary-tree-from-inorder-and-postorder-traversal.py diff --git a/problems/construct-binary-tree-from-preorder-and-inorder-traversal.py b/problems/python/construct-binary-tree-from-preorder-and-inorder-traversal.py similarity index 100% rename from problems/construct-binary-tree-from-preorder-and-inorder-traversal.py rename to problems/python/construct-binary-tree-from-preorder-and-inorder-traversal.py diff --git a/problems/container-with-most-water.py b/problems/python/container-with-most-water.py similarity index 100% rename from problems/container-with-most-water.py rename to problems/python/container-with-most-water.py diff --git a/problems/contains-duplicate-ii.py b/problems/python/contains-duplicate-ii.py similarity index 100% rename from problems/contains-duplicate-ii.py rename to problems/python/contains-duplicate-ii.py diff --git a/problems/contains-duplicate-iii.py b/problems/python/contains-duplicate-iii.py similarity index 100% rename from problems/contains-duplicate-iii.py rename to problems/python/contains-duplicate-iii.py diff --git a/problems/contains-duplicate.py b/problems/python/contains-duplicate.py similarity index 100% rename from problems/contains-duplicate.py rename to problems/python/contains-duplicate.py diff --git a/problems/continuous-subarray-sum.py b/problems/python/continuous-subarray-sum.py similarity index 100% rename from problems/continuous-subarray-sum.py rename to problems/python/continuous-subarray-sum.py diff --git a/problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py b/problems/python/convert-binary-search-tree-to-sorted-doubly-linked-list.py similarity index 100% rename from problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py rename to problems/python/convert-binary-search-tree-to-sorted-doubly-linked-list.py diff --git a/problems/convert-sorted-array-to-binary-search-tree.py b/problems/python/convert-sorted-array-to-binary-search-tree.py similarity index 100% rename from problems/convert-sorted-array-to-binary-search-tree.py rename to problems/python/convert-sorted-array-to-binary-search-tree.py diff --git a/problems/convert-sorted-list-to-binary-search-tree.py b/problems/python/convert-sorted-list-to-binary-search-tree.py similarity index 100% rename from problems/convert-sorted-list-to-binary-search-tree.py rename to problems/python/convert-sorted-list-to-binary-search-tree.py diff --git a/problems/copy-list-with-random-pointer.py b/problems/python/copy-list-with-random-pointer.py similarity index 100% rename from problems/copy-list-with-random-pointer.py rename to problems/python/copy-list-with-random-pointer.py diff --git a/problems/count-all-valid-pickup-and-delivery-opti.py b/problems/python/count-all-valid-pickup-and-delivery-opti.py similarity index 100% rename from problems/count-all-valid-pickup-and-delivery-opti.py rename to problems/python/count-all-valid-pickup-and-delivery-opti.py diff --git a/problems/count-binary-substrings.py b/problems/python/count-binary-substrings.py similarity index 100% rename from problems/count-binary-substrings.py rename to problems/python/count-binary-substrings.py diff --git a/problems/count-complete-tree-nodes.py b/problems/python/count-complete-tree-nodes.py similarity index 100% rename from problems/count-complete-tree-nodes.py rename to problems/python/count-complete-tree-nodes.py diff --git a/problems/count-number-of-nice-subarrays.py b/problems/python/count-number-of-nice-subarrays.py similarity index 100% rename from problems/count-number-of-nice-subarrays.py rename to problems/python/count-number-of-nice-subarrays.py diff --git a/problems/count-unique-characters-of-all-substrings-of-a-given-string.py b/problems/python/count-unique-characters-of-all-substrings-of-a-given-string.py similarity index 100% rename from problems/count-unique-characters-of-all-substrings-of-a-given-string.py rename to problems/python/count-unique-characters-of-all-substrings-of-a-given-string.py diff --git a/problems/course-schedule-ii.py b/problems/python/course-schedule-ii.py similarity index 100% rename from problems/course-schedule-ii.py rename to problems/python/course-schedule-ii.py diff --git a/problems/course-schedule.py b/problems/python/course-schedule.py similarity index 100% rename from problems/course-schedule.py rename to problems/python/course-schedule.py diff --git a/problems/custom-sort-string.py b/problems/python/custom-sort-string.py similarity index 100% rename from problems/custom-sort-string.py rename to problems/python/custom-sort-string.py diff --git a/problems/cutting-ribbons.py b/problems/python/cutting-ribbons.py similarity index 100% rename from problems/cutting-ribbons.py rename to problems/python/cutting-ribbons.py diff --git a/problems/data-stream-as-disjoint-intervals.py b/problems/python/data-stream-as-disjoint-intervals.py similarity index 100% rename from problems/data-stream-as-disjoint-intervals.py rename to problems/python/data-stream-as-disjoint-intervals.py diff --git a/problems/decode-string.py b/problems/python/decode-string.py similarity index 100% rename from problems/decode-string.py rename to problems/python/decode-string.py diff --git a/problems/decode-ways.py b/problems/python/decode-ways.py similarity index 100% rename from problems/decode-ways.py rename to problems/python/decode-ways.py diff --git a/problems/delete-and-earn.py b/problems/python/delete-and-earn.py similarity index 100% rename from problems/delete-and-earn.py rename to problems/python/delete-and-earn.py diff --git a/problems/delete-duplicate-folders-in-system.py b/problems/python/delete-duplicate-folders-in-system.py similarity index 100% rename from problems/delete-duplicate-folders-in-system.py rename to problems/python/delete-duplicate-folders-in-system.py diff --git a/problems/delete-node-in-a-bst.py b/problems/python/delete-node-in-a-bst.py similarity index 100% rename from problems/delete-node-in-a-bst.py rename to problems/python/delete-node-in-a-bst.py diff --git a/problems/delete-operation-for-two-strings.py b/problems/python/delete-operation-for-two-strings.py similarity index 100% rename from problems/delete-operation-for-two-strings.py rename to problems/python/delete-operation-for-two-strings.py diff --git a/problems/design-add-and-search-words-data-structure.py b/problems/python/design-add-and-search-words-data-structure.py similarity index 100% rename from problems/design-add-and-search-words-data-structure.py rename to problems/python/design-add-and-search-words-data-structure.py diff --git a/problems/design-in-memory-file-system.py b/problems/python/design-in-memory-file-system.py similarity index 100% rename from problems/design-in-memory-file-system.py rename to problems/python/design-in-memory-file-system.py diff --git a/problems/design-linked-list.py b/problems/python/design-linked-list.py similarity index 100% rename from problems/design-linked-list.py rename to problems/python/design-linked-list.py diff --git a/problems/design-tic-tac-toe.py b/problems/python/design-tic-tac-toe.py similarity index 100% rename from problems/design-tic-tac-toe.py rename to problems/python/design-tic-tac-toe.py diff --git a/problems/diagonal-traverse.py b/problems/python/diagonal-traverse.py similarity index 100% rename from problems/diagonal-traverse.py rename to problems/python/diagonal-traverse.py diff --git a/problems/diameter-of-binary-tree.py b/problems/python/diameter-of-binary-tree.py similarity index 100% rename from problems/diameter-of-binary-tree.py rename to problems/python/diameter-of-binary-tree.py diff --git a/problems/different-ways-to-add-parentheses.py b/problems/python/different-ways-to-add-parentheses.py similarity index 100% rename from problems/different-ways-to-add-parentheses.py rename to problems/python/different-ways-to-add-parentheses.py diff --git a/problems/distinct-subsequences.py b/problems/python/distinct-subsequences.py similarity index 100% rename from problems/distinct-subsequences.py rename to problems/python/distinct-subsequences.py diff --git a/problems/distribute-coins-in-binary-tree.py b/problems/python/distribute-coins-in-binary-tree.py similarity index 100% rename from problems/distribute-coins-in-binary-tree.py rename to problems/python/distribute-coins-in-binary-tree.py diff --git a/problems/domino-and-tromino-tiling.py b/problems/python/domino-and-tromino-tiling.py similarity index 100% rename from problems/domino-and-tromino-tiling.py rename to problems/python/domino-and-tromino-tiling.py diff --git a/problems/dot-product-of-two-sparse-vectors.py b/problems/python/dot-product-of-two-sparse-vectors.py similarity index 100% rename from problems/dot-product-of-two-sparse-vectors.py rename to problems/python/dot-product-of-two-sparse-vectors.py diff --git a/problems/dungeon-game.py b/problems/python/dungeon-game.py similarity index 100% rename from problems/dungeon-game.py rename to problems/python/dungeon-game.py diff --git a/problems/edit-distance.py b/problems/python/edit-distance.py similarity index 100% rename from problems/edit-distance.py rename to problems/python/edit-distance.py diff --git a/problems/egions-cut-by-slashes.py b/problems/python/egions-cut-by-slashes.py similarity index 100% rename from problems/egions-cut-by-slashes.py rename to problems/python/egions-cut-by-slashes.py diff --git a/problems/evaluate-division.py b/problems/python/evaluate-division.py similarity index 100% rename from problems/evaluate-division.py rename to problems/python/evaluate-division.py diff --git a/problems/evaluate-reverse-polish-notation.py b/problems/python/evaluate-reverse-polish-notation.py similarity index 100% rename from problems/evaluate-reverse-polish-notation.py rename to problems/python/evaluate-reverse-polish-notation.py diff --git a/problems/exclusive-time-of-functions.py b/problems/python/exclusive-time-of-functions.py similarity index 100% rename from problems/exclusive-time-of-functions.py rename to problems/python/exclusive-time-of-functions.py diff --git a/problems/expression-add-operators.py b/problems/python/expression-add-operators.py similarity index 100% rename from problems/expression-add-operators.py rename to problems/python/expression-add-operators.py diff --git a/problems/filling-bookcase-shelves.py b/problems/python/filling-bookcase-shelves.py similarity index 100% rename from problems/filling-bookcase-shelves.py rename to problems/python/filling-bookcase-shelves.py diff --git a/problems/find-all-possible-recipes-from-given-supplies.py b/problems/python/find-all-possible-recipes-from-given-supplies.py similarity index 100% rename from problems/find-all-possible-recipes-from-given-supplies.py rename to problems/python/find-all-possible-recipes-from-given-supplies.py diff --git a/problems/find-and-replace-in-string.py b/problems/python/find-and-replace-in-string.py similarity index 100% rename from problems/find-and-replace-in-string.py rename to problems/python/find-and-replace-in-string.py diff --git a/problems/find-distance-in-a-binary-tree.py b/problems/python/find-distance-in-a-binary-tree.py similarity index 100% rename from problems/find-distance-in-a-binary-tree.py rename to problems/python/find-distance-in-a-binary-tree.py diff --git a/problems/find-duplicate-subtrees.py b/problems/python/find-duplicate-subtrees.py similarity index 100% rename from problems/find-duplicate-subtrees.py rename to problems/python/find-duplicate-subtrees.py diff --git a/problems/find-eventual-safe-states.py b/problems/python/find-eventual-safe-states.py similarity index 100% rename from problems/find-eventual-safe-states.py rename to problems/python/find-eventual-safe-states.py diff --git a/problems/find-first-and-last-position-of-element-in-sorted-array.py b/problems/python/find-first-and-last-position-of-element-in-sorted-array.py similarity index 100% rename from problems/find-first-and-last-position-of-element-in-sorted-array.py rename to problems/python/find-first-and-last-position-of-element-in-sorted-array.py diff --git a/problems/find-k-closest-elements.py b/problems/python/find-k-closest-elements.py similarity index 100% rename from problems/find-k-closest-elements.py rename to problems/python/find-k-closest-elements.py diff --git a/problems/find-k-pairs-with-smallest-sums.py b/problems/python/find-k-pairs-with-smallest-sums.py similarity index 100% rename from problems/find-k-pairs-with-smallest-sums.py rename to problems/python/find-k-pairs-with-smallest-sums.py diff --git a/problems/find-leaves-of-binary-tree.py b/problems/python/find-leaves-of-binary-tree.py similarity index 100% rename from problems/find-leaves-of-binary-tree.py rename to problems/python/find-leaves-of-binary-tree.py diff --git a/problems/find-median-from-data-stream.py b/problems/python/find-median-from-data-stream.py similarity index 100% rename from problems/find-median-from-data-stream.py rename to problems/python/find-median-from-data-stream.py diff --git a/problems/find-minimum-in-rotated-sorted-array-ii.py b/problems/python/find-minimum-in-rotated-sorted-array-ii.py similarity index 100% rename from problems/find-minimum-in-rotated-sorted-array-ii.py rename to problems/python/find-minimum-in-rotated-sorted-array-ii.py diff --git a/problems/find-minimum-in-rotated-sorted-array.py b/problems/python/find-minimum-in-rotated-sorted-array.py similarity index 100% rename from problems/find-minimum-in-rotated-sorted-array.py rename to problems/python/find-minimum-in-rotated-sorted-array.py diff --git a/problems/find-mode-in-binary-search-tree.py b/problems/python/find-mode-in-binary-search-tree.py similarity index 100% rename from problems/find-mode-in-binary-search-tree.py rename to problems/python/find-mode-in-binary-search-tree.py diff --git a/problems/find-original-array-from-doubled-array,py b/problems/python/find-original-array-from-doubled-array,py similarity index 100% rename from problems/find-original-array-from-doubled-array,py rename to problems/python/find-original-array-from-doubled-array,py diff --git a/problems/find-peak-element.py b/problems/python/find-peak-element.py similarity index 100% rename from problems/find-peak-element.py rename to problems/python/find-peak-element.py diff --git a/problems/find-the-duplicate-number.py b/problems/python/find-the-duplicate-number.py similarity index 100% rename from problems/find-the-duplicate-number.py rename to problems/python/find-the-duplicate-number.py diff --git a/problems/first-bad-version.py b/problems/python/first-bad-version.py similarity index 100% rename from problems/first-bad-version.py rename to problems/python/first-bad-version.py diff --git a/problems/first-missing-positive.py b/problems/python/first-missing-positive.py similarity index 100% rename from problems/first-missing-positive.py rename to problems/python/first-missing-positive.py diff --git a/problems/first-unique-character-in-a-string.py b/problems/python/first-unique-character-in-a-string.py similarity index 100% rename from problems/first-unique-character-in-a-string.py rename to problems/python/first-unique-character-in-a-string.py diff --git a/problems/fizz-buzz.py b/problems/python/fizz-buzz.py similarity index 100% rename from problems/fizz-buzz.py rename to problems/python/fizz-buzz.py diff --git a/problems/flatten-binary-tree-to-linked-list.py b/problems/python/flatten-binary-tree-to-linked-list.py similarity index 100% rename from problems/flatten-binary-tree-to-linked-list.py rename to problems/python/flatten-binary-tree-to-linked-list.py diff --git a/problems/flip-binary-tree-to-match-preorder-traversal.py b/problems/python/flip-binary-tree-to-match-preorder-traversal.py similarity index 100% rename from problems/flip-binary-tree-to-match-preorder-traversal.py rename to problems/python/flip-binary-tree-to-match-preorder-traversal.py diff --git a/problems/flip-string-to-monotone-increasing.py b/problems/python/flip-string-to-monotone-increasing.py similarity index 100% rename from problems/flip-string-to-monotone-increasing.py rename to problems/python/flip-string-to-monotone-increasing.py diff --git a/problems/flood-fill.py b/problems/python/flood-fill.py similarity index 100% rename from problems/flood-fill.py rename to problems/python/flood-fill.py diff --git a/problems/friend-circles.py b/problems/python/friend-circles.py similarity index 100% rename from problems/friend-circles.py rename to problems/python/friend-circles.py diff --git a/problems/fruit-into-baskets.py b/problems/python/fruit-into-baskets.py similarity index 100% rename from problems/fruit-into-baskets.py rename to problems/python/fruit-into-baskets.py diff --git a/problems/game-of-life.py b/problems/python/game-of-life.py similarity index 100% rename from problems/game-of-life.py rename to problems/python/game-of-life.py diff --git a/problems/generate-parentheses.py b/problems/python/generate-parentheses.py similarity index 100% rename from problems/generate-parentheses.py rename to problems/python/generate-parentheses.py diff --git a/problems/graph-valid-tree.py b/problems/python/graph-valid-tree.py similarity index 100% rename from problems/graph-valid-tree.py rename to problems/python/graph-valid-tree.py diff --git a/problems/greatest-sum-divisible-by-three.py b/problems/python/greatest-sum-divisible-by-three.py similarity index 100% rename from problems/greatest-sum-divisible-by-three.py rename to problems/python/greatest-sum-divisible-by-three.py diff --git a/problems/group-anagrams.py b/problems/python/group-anagrams.py similarity index 100% rename from problems/group-anagrams.py rename to problems/python/group-anagrams.py diff --git a/problems/group-shifted-strings.py b/problems/python/group-shifted-strings.py similarity index 100% rename from problems/group-shifted-strings.py rename to problems/python/group-shifted-strings.py diff --git a/problems/guess-number-higher-or-lower-ii.py b/problems/python/guess-number-higher-or-lower-ii.py similarity index 100% rename from problems/guess-number-higher-or-lower-ii.py rename to problems/python/guess-number-higher-or-lower-ii.py diff --git a/problems/guess-number-higher-or-lower.py b/problems/python/guess-number-higher-or-lower.py similarity index 100% rename from problems/guess-number-higher-or-lower.py rename to problems/python/guess-number-higher-or-lower.py diff --git a/problems/guess-the-word.py b/problems/python/guess-the-word.py similarity index 100% rename from problems/guess-the-word.py rename to problems/python/guess-the-word.py diff --git a/problems/h-index-ii.py b/problems/python/h-index-ii.py similarity index 100% rename from problems/h-index-ii.py rename to problems/python/h-index-ii.py diff --git a/problems/h-index.py b/problems/python/h-index.py similarity index 100% rename from problems/h-index.py rename to problems/python/h-index.py diff --git a/problems/hamming-distance.py b/problems/python/hamming-distance.py similarity index 100% rename from problems/hamming-distance.py rename to problems/python/hamming-distance.py diff --git a/problems/house-robber-ii.py b/problems/python/house-robber-ii.py similarity index 100% rename from problems/house-robber-ii.py rename to problems/python/house-robber-ii.py diff --git a/problems/house-robber-iii.py b/problems/python/house-robber-iii.py similarity index 100% rename from problems/house-robber-iii.py rename to problems/python/house-robber-iii.py diff --git a/problems/house-robber.py b/problems/python/house-robber.py similarity index 100% rename from problems/house-robber.py rename to problems/python/house-robber.py diff --git a/problems/implement-trie-prefix-tree.py b/problems/python/implement-trie-prefix-tree.py similarity index 100% rename from problems/implement-trie-prefix-tree.py rename to problems/python/implement-trie-prefix-tree.py diff --git a/problems/increasing-triplet-subsequence.py b/problems/python/increasing-triplet-subsequence.py similarity index 100% rename from problems/increasing-triplet-subsequence.py rename to problems/python/increasing-triplet-subsequence.py diff --git a/problems/inorder-successor-in-bst-ii.py b/problems/python/inorder-successor-in-bst-ii.py similarity index 100% rename from problems/inorder-successor-in-bst-ii.py rename to problems/python/inorder-successor-in-bst-ii.py diff --git a/problems/inorder-successor-in-bst.py b/problems/python/inorder-successor-in-bst.py similarity index 100% rename from problems/inorder-successor-in-bst.py rename to problems/python/inorder-successor-in-bst.py diff --git a/problems/insert-interval.py b/problems/python/insert-interval.py similarity index 100% rename from problems/insert-interval.py rename to problems/python/insert-interval.py diff --git a/problems/insert-into-a-binary-search-tree.py b/problems/python/insert-into-a-binary-search-tree.py similarity index 100% rename from problems/insert-into-a-binary-search-tree.py rename to problems/python/insert-into-a-binary-search-tree.py diff --git a/problems/insert-into-a-sorted-circular-linked-list.py b/problems/python/insert-into-a-sorted-circular-linked-list.py similarity index 100% rename from problems/insert-into-a-sorted-circular-linked-list.py rename to problems/python/insert-into-a-sorted-circular-linked-list.py diff --git a/problems/insertion-sort-list.py b/problems/python/insertion-sort-list.py similarity index 100% rename from problems/insertion-sort-list.py rename to problems/python/insertion-sort-list.py diff --git a/problems/integer-to-english-words.py b/problems/python/integer-to-english-words.py similarity index 100% rename from problems/integer-to-english-words.py rename to problems/python/integer-to-english-words.py diff --git a/problems/interleaving-string.py b/problems/python/interleaving-string.py similarity index 100% rename from problems/interleaving-string.py rename to problems/python/interleaving-string.py diff --git a/problems/intersection-of-two-arrays-ii.py b/problems/python/intersection-of-two-arrays-ii.py similarity index 100% rename from problems/intersection-of-two-arrays-ii.py rename to problems/python/intersection-of-two-arrays-ii.py diff --git a/problems/intersection-of-two-arrays.py b/problems/python/intersection-of-two-arrays.py similarity index 100% rename from problems/intersection-of-two-arrays.py rename to problems/python/intersection-of-two-arrays.py diff --git a/problems/invert-binary-tree.py b/problems/python/invert-binary-tree.py similarity index 100% rename from problems/invert-binary-tree.py rename to problems/python/invert-binary-tree.py diff --git a/problems/is-graph-bipartite.py b/problems/python/is-graph-bipartite.py similarity index 100% rename from problems/is-graph-bipartite.py rename to problems/python/is-graph-bipartite.py diff --git a/problems/is-subsequence.py b/problems/python/is-subsequence.py similarity index 100% rename from problems/is-subsequence.py rename to problems/python/is-subsequence.py diff --git a/problems/isomorphic-strings.py b/problems/python/isomorphic-strings.py similarity index 100% rename from problems/isomorphic-strings.py rename to problems/python/isomorphic-strings.py diff --git a/problems/jewels-and-stones.py b/problems/python/jewels-and-stones.py similarity index 100% rename from problems/jewels-and-stones.py rename to problems/python/jewels-and-stones.py diff --git a/problems/jump-game.py b/problems/python/jump-game.py similarity index 100% rename from problems/jump-game.py rename to problems/python/jump-game.py diff --git a/problems/k-closest-points-to-origin.py b/problems/python/k-closest-points-to-origin.py similarity index 100% rename from problems/k-closest-points-to-origin.py rename to problems/python/k-closest-points-to-origin.py diff --git a/problems/k-empty-slots.py b/problems/python/k-empty-slots.py similarity index 100% rename from problems/k-empty-slots.py rename to problems/python/k-empty-slots.py diff --git a/problems/keys-and-rooms.py b/problems/python/keys-and-rooms.py similarity index 100% rename from problems/keys-and-rooms.py rename to problems/python/keys-and-rooms.py diff --git a/problems/knight-dialer.py b/problems/python/knight-dialer.py similarity index 100% rename from problems/knight-dialer.py rename to problems/python/knight-dialer.py diff --git a/problems/knight-probability-in-chessboard.py b/problems/python/knight-probability-in-chessboard.py similarity index 100% rename from problems/knight-probability-in-chessboard.py rename to problems/python/knight-probability-in-chessboard.py diff --git a/problems/koko-eating-bananas.py b/problems/python/koko-eating-bananas.py similarity index 100% rename from problems/koko-eating-bananas.py rename to problems/python/koko-eating-bananas.py diff --git a/problems/kth-largest-element-in-an-array.py b/problems/python/kth-largest-element-in-an-array.py similarity index 100% rename from problems/kth-largest-element-in-an-array.py rename to problems/python/kth-largest-element-in-an-array.py diff --git a/problems/kth-smallest-element-in-a-bst.py b/problems/python/kth-smallest-element-in-a-bst.py similarity index 100% rename from problems/kth-smallest-element-in-a-bst.py rename to problems/python/kth-smallest-element-in-a-bst.py diff --git a/problems/kth-smallest-element-in-a-sorted-matrix.py b/problems/python/kth-smallest-element-in-a-sorted-matrix.py similarity index 100% rename from problems/kth-smallest-element-in-a-sorted-matrix.py rename to problems/python/kth-smallest-element-in-a-sorted-matrix.py diff --git a/problems/largest-1-bordered-square.py b/problems/python/largest-1-bordered-square.py similarity index 100% rename from problems/largest-1-bordered-square.py rename to problems/python/largest-1-bordered-square.py diff --git a/problems/largest-bst-subtree.py b/problems/python/largest-bst-subtree.py similarity index 100% rename from problems/largest-bst-subtree.py rename to problems/python/largest-bst-subtree.py diff --git a/problems/largest-sum-of-averages.py b/problems/python/largest-sum-of-averages.py similarity index 100% rename from problems/largest-sum-of-averages.py rename to problems/python/largest-sum-of-averages.py diff --git a/problems/last-stone-weight-ii.py b/problems/python/last-stone-weight-ii.py similarity index 100% rename from problems/last-stone-weight-ii.py rename to problems/python/last-stone-weight-ii.py diff --git a/problems/last-stone-weight.py b/problems/python/last-stone-weight.py similarity index 100% rename from problems/last-stone-weight.py rename to problems/python/last-stone-weight.py diff --git a/problems/least-number-of-unique-integers-after-k-removals.py b/problems/python/least-number-of-unique-integers-after-k-removals.py similarity index 100% rename from problems/least-number-of-unique-integers-after-k-removals.py rename to problems/python/least-number-of-unique-integers-after-k-removals.py diff --git a/problems/letter-case-permutation.py b/problems/python/letter-case-permutation.py similarity index 100% rename from problems/letter-case-permutation.py rename to problems/python/letter-case-permutation.py diff --git a/problems/letter-combinations-of-a-phone-number.py b/problems/python/letter-combinations-of-a-phone-number.py similarity index 100% rename from problems/letter-combinations-of-a-phone-number.py rename to problems/python/letter-combinations-of-a-phone-number.py diff --git a/problems/license-key-formatting.py b/problems/python/license-key-formatting.py similarity index 100% rename from problems/license-key-formatting.py rename to problems/python/license-key-formatting.py diff --git a/problems/linked-list-cycle-ii.py b/problems/python/linked-list-cycle-ii.py similarity index 100% rename from problems/linked-list-cycle-ii.py rename to problems/python/linked-list-cycle-ii.py diff --git a/problems/linked-list-cycle.py b/problems/python/linked-list-cycle.py similarity index 100% rename from problems/linked-list-cycle.py rename to problems/python/linked-list-cycle.py diff --git a/problems/linked-list-random-node.py b/problems/python/linked-list-random-node.py similarity index 100% rename from problems/linked-list-random-node.py rename to problems/python/linked-list-random-node.py diff --git a/problems/logger-rate-limiter.py b/problems/python/logger-rate-limiter.py similarity index 100% rename from problems/logger-rate-limiter.py rename to problems/python/logger-rate-limiter.py diff --git a/problems/longest-common-prefix.py b/problems/python/longest-common-prefix.py similarity index 100% rename from problems/longest-common-prefix.py rename to problems/python/longest-common-prefix.py diff --git a/problems/longest-common-subsequence.py b/problems/python/longest-common-subsequence.py similarity index 100% rename from problems/longest-common-subsequence.py rename to problems/python/longest-common-subsequence.py diff --git a/problems/longest-consecutive-sequence.py b/problems/python/longest-consecutive-sequence.py similarity index 100% rename from problems/longest-consecutive-sequence.py rename to problems/python/longest-consecutive-sequence.py diff --git a/problems/longest-increasing-path-in-a-matrix.py b/problems/python/longest-increasing-path-in-a-matrix.py similarity index 100% rename from problems/longest-increasing-path-in-a-matrix.py rename to problems/python/longest-increasing-path-in-a-matrix.py diff --git a/problems/longest-increasing-subsequence.py b/problems/python/longest-increasing-subsequence.py similarity index 100% rename from problems/longest-increasing-subsequence.py rename to problems/python/longest-increasing-subsequence.py diff --git a/problems/longest-palindromic-subsequence.py b/problems/python/longest-palindromic-subsequence.py similarity index 100% rename from problems/longest-palindromic-subsequence.py rename to problems/python/longest-palindromic-subsequence.py diff --git a/problems/longest-palindromic-substring.py b/problems/python/longest-palindromic-substring.py similarity index 100% rename from problems/longest-palindromic-substring.py rename to problems/python/longest-palindromic-substring.py diff --git a/problems/longest-repeating-character-replacement.py b/problems/python/longest-repeating-character-replacement.py similarity index 100% rename from problems/longest-repeating-character-replacement.py rename to problems/python/longest-repeating-character-replacement.py diff --git a/problems/longest-string-chain.py b/problems/python/longest-string-chain.py similarity index 100% rename from problems/longest-string-chain.py rename to problems/python/longest-string-chain.py diff --git a/problems/longest-substring-with-at-least-k-repeating-characters.py b/problems/python/longest-substring-with-at-least-k-repeating-characters.py similarity index 100% rename from problems/longest-substring-with-at-least-k-repeating-characters.py rename to problems/python/longest-substring-with-at-least-k-repeating-characters.py diff --git a/problems/longest-substring-without-repeating-characters.py b/problems/python/longest-substring-without-repeating-characters.py similarity index 100% rename from problems/longest-substring-without-repeating-characters.py rename to problems/python/longest-substring-without-repeating-characters.py diff --git a/problems/longest-univalue-path.py b/problems/python/longest-univalue-path.py similarity index 100% rename from problems/longest-univalue-path.py rename to problems/python/longest-univalue-path.py diff --git a/problems/lowest-common-ancestor-of-a-binary-search-tree.py b/problems/python/lowest-common-ancestor-of-a-binary-search-tree.py similarity index 100% rename from problems/lowest-common-ancestor-of-a-binary-search-tree.py rename to problems/python/lowest-common-ancestor-of-a-binary-search-tree.py diff --git a/problems/lowest-common-ancestor-of-a-binary-search.py b/problems/python/lowest-common-ancestor-of-a-binary-search.py similarity index 100% rename from problems/lowest-common-ancestor-of-a-binary-search.py rename to problems/python/lowest-common-ancestor-of-a-binary-search.py diff --git a/problems/lowest-common-ancestor-of-a-binary-tree-ii.py b/problems/python/lowest-common-ancestor-of-a-binary-tree-ii.py similarity index 100% rename from problems/lowest-common-ancestor-of-a-binary-tree-ii.py rename to problems/python/lowest-common-ancestor-of-a-binary-tree-ii.py diff --git a/problems/lowest-common-ancestor-of-a-binary-tree-iii.py b/problems/python/lowest-common-ancestor-of-a-binary-tree-iii.py similarity index 100% rename from problems/lowest-common-ancestor-of-a-binary-tree-iii.py rename to problems/python/lowest-common-ancestor-of-a-binary-tree-iii.py diff --git a/problems/lowest-common-ancestor-of-a-binary-tree-iv.py b/problems/python/lowest-common-ancestor-of-a-binary-tree-iv.py similarity index 100% rename from problems/lowest-common-ancestor-of-a-binary-tree-iv.py rename to problems/python/lowest-common-ancestor-of-a-binary-tree-iv.py diff --git a/problems/lowest-common-ancestor-of-a-binary-tree.py b/problems/python/lowest-common-ancestor-of-a-binary-tree.py similarity index 100% rename from problems/lowest-common-ancestor-of-a-binary-tree.py rename to problems/python/lowest-common-ancestor-of-a-binary-tree.py diff --git a/problems/lowest-common-ancestor-of-deepest-leaves.py b/problems/python/lowest-common-ancestor-of-deepest-leaves.py similarity index 100% rename from problems/lowest-common-ancestor-of-deepest-leaves.py rename to problems/python/lowest-common-ancestor-of-deepest-leaves.py diff --git a/problems/lru-cache.py b/problems/python/lru-cache.py similarity index 100% rename from problems/lru-cache.py rename to problems/python/lru-cache.py diff --git a/problems/majority-element-ii.py b/problems/python/majority-element-ii.py similarity index 100% rename from problems/majority-element-ii.py rename to problems/python/majority-element-ii.py diff --git a/problems/majority-element.py b/problems/python/majority-element.py similarity index 100% rename from problems/majority-element.py rename to problems/python/majority-element.py diff --git a/problems/making-a-large-island.py b/problems/python/making-a-large-island.py similarity index 100% rename from problems/making-a-large-island.py rename to problems/python/making-a-large-island.py diff --git a/problems/max-area-of-island.py b/problems/python/max-area-of-island.py similarity index 100% rename from problems/max-area-of-island.py rename to problems/python/max-area-of-island.py diff --git a/problems/max-consecutive-ones-iii.py b/problems/python/max-consecutive-ones-iii.py similarity index 100% rename from problems/max-consecutive-ones-iii.py rename to problems/python/max-consecutive-ones-iii.py diff --git a/problems/max-stack.py b/problems/python/max-stack.py similarity index 100% rename from problems/max-stack.py rename to problems/python/max-stack.py diff --git a/problems/max-sum-of-rectangle-no-larger-than-k.py b/problems/python/max-sum-of-rectangle-no-larger-than-k.py similarity index 100% rename from problems/max-sum-of-rectangle-no-larger-than-k.py rename to problems/python/max-sum-of-rectangle-no-larger-than-k.py diff --git a/problems/maximal-square.py b/problems/python/maximal-square.py similarity index 100% rename from problems/maximal-square.py rename to problems/python/maximal-square.py diff --git a/problems/maximum-average-subtree.py b/problems/python/maximum-average-subtree.py similarity index 100% rename from problems/maximum-average-subtree.py rename to problems/python/maximum-average-subtree.py diff --git a/problems/maximum-compatibility-score-sum.py b/problems/python/maximum-compatibility-score-sum.py similarity index 100% rename from problems/maximum-compatibility-score-sum.py rename to problems/python/maximum-compatibility-score-sum.py diff --git a/problems/maximum-depth-of-binary-tree.py b/problems/python/maximum-depth-of-binary-tree.py similarity index 100% rename from problems/maximum-depth-of-binary-tree.py rename to problems/python/maximum-depth-of-binary-tree.py diff --git a/problems/maximum-gap.py b/problems/python/maximum-gap.py similarity index 100% rename from problems/maximum-gap.py rename to problems/python/maximum-gap.py diff --git a/problems/maximum-length-of-repeated-subarray.py b/problems/python/maximum-length-of-repeated-subarray.py similarity index 100% rename from problems/maximum-length-of-repeated-subarray.py rename to problems/python/maximum-length-of-repeated-subarray.py diff --git a/problems/maximum-number-of-events-that-can-be-attended.py b/problems/python/maximum-number-of-events-that-can-be-attended.py similarity index 100% rename from problems/maximum-number-of-events-that-can-be-attended.py rename to problems/python/maximum-number-of-events-that-can-be-attended.py diff --git a/problems/maximum-number-of-points-with-cost.py b/problems/python/maximum-number-of-points-with-cost.py similarity index 100% rename from problems/maximum-number-of-points-with-cost.py rename to problems/python/maximum-number-of-points-with-cost.py diff --git a/problems/maximum-number-of-visible-points.py b/problems/python/maximum-number-of-visible-points.py similarity index 100% rename from problems/maximum-number-of-visible-points.py rename to problems/python/maximum-number-of-visible-points.py diff --git a/problems/maximum-product-of-three-numbers.py b/problems/python/maximum-product-of-three-numbers.py similarity index 100% rename from problems/maximum-product-of-three-numbers.py rename to problems/python/maximum-product-of-three-numbers.py diff --git a/problems/maximum-product-subarray.py b/problems/python/maximum-product-subarray.py similarity index 100% rename from problems/maximum-product-subarray.py rename to problems/python/maximum-product-subarray.py diff --git a/problems/maximum-subarray-sum-with-one-deletion.py b/problems/python/maximum-subarray-sum-with-one-deletion.py similarity index 100% rename from problems/maximum-subarray-sum-with-one-deletion.py rename to problems/python/maximum-subarray-sum-with-one-deletion.py diff --git a/problems/maximum-subarray.py b/problems/python/maximum-subarray.py similarity index 100% rename from problems/maximum-subarray.py rename to problems/python/maximum-subarray.py diff --git a/problems/maximum-swap.py b/problems/python/maximum-swap.py similarity index 100% rename from problems/maximum-swap.py rename to problems/python/maximum-swap.py diff --git a/problems/maximum-units-on-a-truck.py b/problems/python/maximum-units-on-a-truck.py similarity index 100% rename from problems/maximum-units-on-a-truck.py rename to problems/python/maximum-units-on-a-truck.py diff --git a/problems/median-of-two-sorted-arrays.py b/problems/python/median-of-two-sorted-arrays.py similarity index 100% rename from problems/median-of-two-sorted-arrays.py rename to problems/python/median-of-two-sorted-arrays.py diff --git a/problems/meeting-rooms-ii.py b/problems/python/meeting-rooms-ii.py similarity index 100% rename from problems/meeting-rooms-ii.py rename to problems/python/meeting-rooms-ii.py diff --git a/problems/meeting-rooms.py b/problems/python/meeting-rooms.py similarity index 100% rename from problems/meeting-rooms.py rename to problems/python/meeting-rooms.py diff --git a/problems/merge-intervals.py b/problems/python/merge-intervals.py similarity index 100% rename from problems/merge-intervals.py rename to problems/python/merge-intervals.py diff --git a/problems/merge-k-sorted-lists.py b/problems/python/merge-k-sorted-lists.py similarity index 100% rename from problems/merge-k-sorted-lists.py rename to problems/python/merge-k-sorted-lists.py diff --git a/problems/merge-sorted-array.py b/problems/python/merge-sorted-array.py similarity index 100% rename from problems/merge-sorted-array.py rename to problems/python/merge-sorted-array.py diff --git a/problems/merge-two-sorted-lists.py b/problems/python/merge-two-sorted-lists.py similarity index 100% rename from problems/merge-two-sorted-lists.py rename to problems/python/merge-two-sorted-lists.py diff --git a/problems/min-cost-climbing-stairs.py b/problems/python/min-cost-climbing-stairs.py similarity index 100% rename from problems/min-cost-climbing-stairs.py rename to problems/python/min-cost-climbing-stairs.py diff --git a/problems/min-stack.py b/problems/python/min-stack.py similarity index 100% rename from problems/min-stack.py rename to problems/python/min-stack.py diff --git a/problems/minimize-malware-spread.py b/problems/python/minimize-malware-spread.py similarity index 100% rename from problems/minimize-malware-spread.py rename to problems/python/minimize-malware-spread.py diff --git a/problems/minimum-absolute-difference-in-bst.py b/problems/python/minimum-absolute-difference-in-bst.py similarity index 100% rename from problems/minimum-absolute-difference-in-bst.py rename to problems/python/minimum-absolute-difference-in-bst.py diff --git a/problems/minimum-ascii-delete-sum-for-two-strings.py b/problems/python/minimum-ascii-delete-sum-for-two-strings.py similarity index 100% rename from problems/minimum-ascii-delete-sum-for-two-strings.py rename to problems/python/minimum-ascii-delete-sum-for-two-strings.py diff --git a/problems/minimum-cost-to-connect-sticks.py b/problems/python/minimum-cost-to-connect-sticks.py similarity index 100% rename from problems/minimum-cost-to-connect-sticks.py rename to problems/python/minimum-cost-to-connect-sticks.py diff --git a/problems/minimum-cost-to-hire-k-workers.py b/problems/python/minimum-cost-to-hire-k-workers.py similarity index 100% rename from problems/minimum-cost-to-hire-k-workers.py rename to problems/python/minimum-cost-to-hire-k-workers.py diff --git a/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py b/problems/python/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py similarity index 100% rename from problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py rename to problems/python/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py diff --git a/problems/minimum-cost-to-reach-city-with-discounts.py b/problems/python/minimum-cost-to-reach-city-with-discounts.py similarity index 100% rename from problems/minimum-cost-to-reach-city-with-discounts.py rename to problems/python/minimum-cost-to-reach-city-with-discounts.py diff --git a/problems/minimum-depth-of-binary-tree.py b/problems/python/minimum-depth-of-binary-tree.py similarity index 100% rename from problems/minimum-depth-of-binary-tree.py rename to problems/python/minimum-depth-of-binary-tree.py diff --git a/problems/minimum-difficulty-of-a-job-schedule.py b/problems/python/minimum-difficulty-of-a-job-schedule.py similarity index 100% rename from problems/minimum-difficulty-of-a-job-schedule.py rename to problems/python/minimum-difficulty-of-a-job-schedule.py diff --git a/problems/minimum-falling-path-sum-ii.py b/problems/python/minimum-falling-path-sum-ii.py similarity index 100% rename from problems/minimum-falling-path-sum-ii.py rename to problems/python/minimum-falling-path-sum-ii.py diff --git a/problems/minimum-knight-moves.py b/problems/python/minimum-knight-moves.py similarity index 100% rename from problems/minimum-knight-moves.py rename to problems/python/minimum-knight-moves.py diff --git a/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py b/problems/python/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py similarity index 100% rename from problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py rename to problems/python/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py diff --git a/problems/minimum-path-sum.py b/problems/python/minimum-path-sum.py similarity index 100% rename from problems/minimum-path-sum.py rename to problems/python/minimum-path-sum.py diff --git a/problems/minimum-score-triangulation-of-polygon.py b/problems/python/minimum-score-triangulation-of-polygon.py similarity index 100% rename from problems/minimum-score-triangulation-of-polygon.py rename to problems/python/minimum-score-triangulation-of-polygon.py diff --git a/problems/minimum-size-subarray-sum.py b/problems/python/minimum-size-subarray-sum.py similarity index 100% rename from problems/minimum-size-subarray-sum.py rename to problems/python/minimum-size-subarray-sum.py diff --git a/problems/minimum-swaps-to-group-all-1s-together.py b/problems/python/minimum-swaps-to-group-all-1s-together.py similarity index 100% rename from problems/minimum-swaps-to-group-all-1s-together.py rename to problems/python/minimum-swaps-to-group-all-1s-together.py diff --git a/problems/minimum-swaps-to-make-sequences-increasing.py b/problems/python/minimum-swaps-to-make-sequences-increasing.py similarity index 100% rename from problems/minimum-swaps-to-make-sequences-increasing.py rename to problems/python/minimum-swaps-to-make-sequences-increasing.py diff --git a/problems/minimum-time-difference.py b/problems/python/minimum-time-difference.py similarity index 100% rename from problems/minimum-time-difference.py rename to problems/python/minimum-time-difference.py diff --git a/problems/minimum-window-substring.py b/problems/python/minimum-window-substring.py similarity index 100% rename from problems/minimum-window-substring.py rename to problems/python/minimum-window-substring.py diff --git a/problems/minimum-xor-sum-of-two-arrays.py b/problems/python/minimum-xor-sum-of-two-arrays.py similarity index 100% rename from problems/minimum-xor-sum-of-two-arrays.py rename to problems/python/minimum-xor-sum-of-two-arrays.py diff --git a/problems/missing-number.py b/problems/python/missing-number.py similarity index 100% rename from problems/missing-number.py rename to problems/python/missing-number.py diff --git a/problems/most-frequent-subtree-sum.py b/problems/python/most-frequent-subtree-sum.py similarity index 100% rename from problems/most-frequent-subtree-sum.py rename to problems/python/most-frequent-subtree-sum.py diff --git a/problems/most-stones-removed-with-same-row-or-column.py b/problems/python/most-stones-removed-with-same-row-or-column.py similarity index 100% rename from problems/most-stones-removed-with-same-row-or-column.py rename to problems/python/most-stones-removed-with-same-row-or-column.py diff --git a/problems/move-zeroes.py b/problems/python/move-zeroes.py similarity index 100% rename from problems/move-zeroes.py rename to problems/python/move-zeroes.py diff --git a/problems/moving-average-from-data-stream.py b/problems/python/moving-average-from-data-stream.py similarity index 100% rename from problems/moving-average-from-data-stream.py rename to problems/python/moving-average-from-data-stream.py diff --git a/problems/my-calendar-ii.py b/problems/python/my-calendar-ii.py similarity index 100% rename from problems/my-calendar-ii.py rename to problems/python/my-calendar-ii.py diff --git a/problems/n-ary-tree-level-order-traversal.py b/problems/python/n-ary-tree-level-order-traversal.py similarity index 100% rename from problems/n-ary-tree-level-order-traversal.py rename to problems/python/n-ary-tree-level-order-traversal.py diff --git a/problems/n-ary-tree-postorder-traversal.py b/problems/python/n-ary-tree-postorder-traversal.py similarity index 100% rename from problems/n-ary-tree-postorder-traversal.py rename to problems/python/n-ary-tree-postorder-traversal.py diff --git a/problems/n-ary-tree-preorder-traversal.py b/problems/python/n-ary-tree-preorder-traversal.py similarity index 100% rename from problems/n-ary-tree-preorder-traversal.py rename to problems/python/n-ary-tree-preorder-traversal.py diff --git a/problems/nested-list-weight-sum.py b/problems/python/nested-list-weight-sum.py similarity index 100% rename from problems/nested-list-weight-sum.py rename to problems/python/nested-list-weight-sum.py diff --git a/problems/network-delay-time.py b/problems/python/network-delay-time.py similarity index 100% rename from problems/network-delay-time.py rename to problems/python/network-delay-time.py diff --git a/problems/next-closest-time.py b/problems/python/next-closest-time.py similarity index 100% rename from problems/next-closest-time.py rename to problems/python/next-closest-time.py diff --git a/problems/next-permutation.py b/problems/python/next-permutation.py similarity index 100% rename from problems/next-permutation.py rename to problems/python/next-permutation.py diff --git a/problems/number-complement.py b/problems/python/number-complement.py similarity index 100% rename from problems/number-complement.py rename to problems/python/number-complement.py diff --git a/problems/number-of-connected-components-in-an-undirected-graph.py b/problems/python/number-of-connected-components-in-an-undirected-graph.py similarity index 100% rename from problems/number-of-connected-components-in-an-undirected-graph.py rename to problems/python/number-of-connected-components-in-an-undirected-graph.py diff --git a/problems/number-of-islands-ii.py b/problems/python/number-of-islands-ii.py similarity index 100% rename from problems/number-of-islands-ii.py rename to problems/python/number-of-islands-ii.py diff --git a/problems/number-of-islands.py b/problems/python/number-of-islands.py similarity index 100% rename from problems/number-of-islands.py rename to problems/python/number-of-islands.py diff --git a/problems/number-of-longest-increasing-subsequence.py b/problems/python/number-of-longest-increasing-subsequence.py similarity index 100% rename from problems/number-of-longest-increasing-subsequence.py rename to problems/python/number-of-longest-increasing-subsequence.py diff --git a/problems/number-of-matching-subsequences.py b/problems/python/number-of-matching-subsequences.py similarity index 100% rename from problems/number-of-matching-subsequences.py rename to problems/python/number-of-matching-subsequences.py diff --git a/problems/number-of-provinces.py b/problems/python/number-of-provinces.py similarity index 100% rename from problems/number-of-provinces.py rename to problems/python/number-of-provinces.py diff --git a/problems/number-of-recent-calls.py b/problems/python/number-of-recent-calls.py similarity index 100% rename from problems/number-of-recent-calls.py rename to problems/python/number-of-recent-calls.py diff --git a/problems/number-of-squareful-arrays.py b/problems/python/number-of-squareful-arrays.py similarity index 100% rename from problems/number-of-squareful-arrays.py rename to problems/python/number-of-squareful-arrays.py diff --git a/problems/number-of-substrings-containing-all-thre.py b/problems/python/number-of-substrings-containing-all-thre.py similarity index 100% rename from problems/number-of-substrings-containing-all-thre.py rename to problems/python/number-of-substrings-containing-all-thre.py diff --git a/problems/number-of-ways-to-arrive-at-destination.py b/problems/python/number-of-ways-to-arrive-at-destination.py similarity index 100% rename from problems/number-of-ways-to-arrive-at-destination.py rename to problems/python/number-of-ways-to-arrive-at-destination.py diff --git a/problems/odd-even-jump.py b/problems/python/odd-even-jump.py similarity index 100% rename from problems/odd-even-jump.py rename to problems/python/odd-even-jump.py diff --git a/problems/ones-and-zeroes.py b/problems/python/ones-and-zeroes.py similarity index 100% rename from problems/ones-and-zeroes.py rename to problems/python/ones-and-zeroes.py diff --git a/problems/open-the-lock.py b/problems/python/open-the-lock.py similarity index 100% rename from problems/open-the-lock.py rename to problems/python/open-the-lock.py diff --git a/problems/out-of-boundary-paths.py b/problems/python/out-of-boundary-paths.py similarity index 100% rename from problems/out-of-boundary-paths.py rename to problems/python/out-of-boundary-paths.py diff --git a/problems/pacific-atlantic-water-flow.py b/problems/python/pacific-atlantic-water-flow.py similarity index 100% rename from problems/pacific-atlantic-water-flow.py rename to problems/python/pacific-atlantic-water-flow.py diff --git a/problems/pairs-of-songs-with-total-durations-divisible-by-60.py b/problems/python/pairs-of-songs-with-total-durations-divisible-by-60.py similarity index 100% rename from problems/pairs-of-songs-with-total-durations-divisible-by-60.py rename to problems/python/pairs-of-songs-with-total-durations-divisible-by-60.py diff --git a/problems/palindrome-number.py b/problems/python/palindrome-number.py similarity index 100% rename from problems/palindrome-number.py rename to problems/python/palindrome-number.py diff --git a/problems/palindrome-pairs.py b/problems/python/palindrome-pairs.py similarity index 100% rename from problems/palindrome-pairs.py rename to problems/python/palindrome-pairs.py diff --git a/problems/palindrome-partitioning-iii.py b/problems/python/palindrome-partitioning-iii.py similarity index 100% rename from problems/palindrome-partitioning-iii.py rename to problems/python/palindrome-partitioning-iii.py diff --git a/problems/palindrome-partitioning.py b/problems/python/palindrome-partitioning.py similarity index 100% rename from problems/palindrome-partitioning.py rename to problems/python/palindrome-partitioning.py diff --git a/problems/palindromic-substrings.py b/problems/python/palindromic-substrings.py similarity index 100% rename from problems/palindromic-substrings.py rename to problems/python/palindromic-substrings.py diff --git a/problems/partition-array-for-maximum-sum.py b/problems/python/partition-array-for-maximum-sum.py similarity index 100% rename from problems/partition-array-for-maximum-sum.py rename to problems/python/partition-array-for-maximum-sum.py diff --git a/problems/partition-labels.py b/problems/python/partition-labels.py similarity index 100% rename from problems/partition-labels.py rename to problems/python/partition-labels.py diff --git a/problems/partition-to-k-equal-sum-subsets.py b/problems/python/partition-to-k-equal-sum-subsets.py similarity index 100% rename from problems/partition-to-k-equal-sum-subsets.py rename to problems/python/partition-to-k-equal-sum-subsets.py diff --git a/problems/path-sum-ii.py b/problems/python/path-sum-ii.py similarity index 100% rename from problems/path-sum-ii.py rename to problems/python/path-sum-ii.py diff --git a/problems/path-sum-iii.py b/problems/python/path-sum-iii.py similarity index 100% rename from problems/path-sum-iii.py rename to problems/python/path-sum-iii.py diff --git a/problems/path-sum.py b/problems/python/path-sum.py similarity index 100% rename from problems/path-sum.py rename to problems/python/path-sum.py diff --git a/problems/path-with-maximum-probability.py b/problems/python/path-with-maximum-probability.py similarity index 100% rename from problems/path-with-maximum-probability.py rename to problems/python/path-with-maximum-probability.py diff --git a/problems/peak-index-in-a-mountain-array.PY b/problems/python/peak-index-in-a-mountain-array.py similarity index 100% rename from problems/peak-index-in-a-mountain-array.PY rename to problems/python/peak-index-in-a-mountain-array.py diff --git a/problems/perfect-squares.py b/problems/python/perfect-squares.py similarity index 100% rename from problems/perfect-squares.py rename to problems/python/perfect-squares.py diff --git a/problems/permutation-in-string.py b/problems/python/permutation-in-string.py similarity index 100% rename from problems/permutation-in-string.py rename to problems/python/permutation-in-string.py diff --git a/problems/permutation-sequence.py b/problems/python/permutation-sequence.py similarity index 100% rename from problems/permutation-sequence.py rename to problems/python/permutation-sequence.py diff --git a/problems/permutations-ii.py b/problems/python/permutations-ii.py similarity index 100% rename from problems/permutations-ii.py rename to problems/python/permutations-ii.py diff --git a/problems/permutations.py b/problems/python/permutations.py similarity index 100% rename from problems/permutations.py rename to problems/python/permutations.py diff --git a/problems/populating-next-right-pointers-in-each-node-ii.py b/problems/python/populating-next-right-pointers-in-each-node-ii.py similarity index 100% rename from problems/populating-next-right-pointers-in-each-node-ii.py rename to problems/python/populating-next-right-pointers-in-each-node-ii.py diff --git a/problems/populating-next-right-pointers-in-each-node.py b/problems/python/populating-next-right-pointers-in-each-node.py similarity index 100% rename from problems/populating-next-right-pointers-in-each-node.py rename to problems/python/populating-next-right-pointers-in-each-node.py diff --git a/problems/powx-n.py b/problems/python/powx-n.py similarity index 100% rename from problems/powx-n.py rename to problems/python/powx-n.py diff --git a/problems/product-of-array-except-self.py b/problems/python/product-of-array-except-self.py similarity index 100% rename from problems/product-of-array-except-self.py rename to problems/python/product-of-array-except-self.py diff --git a/problems/profitable-schemes.py b/problems/python/profitable-schemes.py similarity index 100% rename from problems/profitable-schemes.py rename to problems/python/profitable-schemes.py diff --git a/problems/queue-reconstruction-by-height.py b/problems/python/queue-reconstruction-by-height.py similarity index 100% rename from problems/queue-reconstruction-by-height.py rename to problems/python/queue-reconstruction-by-height.py diff --git a/problems/random-pick-with-weight.py b/problems/python/random-pick-with-weight.py similarity index 100% rename from problems/random-pick-with-weight.py rename to problems/python/random-pick-with-weight.py diff --git a/problems/range-addition.py b/problems/python/range-addition.py similarity index 100% rename from problems/range-addition.py rename to problems/python/range-addition.py diff --git a/problems/range-sum-of-bst.py b/problems/python/range-sum-of-bst.py similarity index 100% rename from problems/range-sum-of-bst.py rename to problems/python/range-sum-of-bst.py diff --git a/problems/range-sum-query-immutable.py b/problems/python/range-sum-query-immutable.py similarity index 100% rename from problems/range-sum-query-immutable.py rename to problems/python/range-sum-query-immutable.py diff --git a/problems/range-sum-query-mutable.py b/problems/python/range-sum-query-mutable.py similarity index 100% rename from problems/range-sum-query-mutable.py rename to problems/python/range-sum-query-mutable.py diff --git a/problems/rearrange-string-k-distance-apart.py b/problems/python/rearrange-string-k-distance-apart.py similarity index 100% rename from problems/rearrange-string-k-distance-apart.py rename to problems/python/rearrange-string-k-distance-apart.py diff --git a/problems/reconstruct-itinerary.py b/problems/python/reconstruct-itinerary.py similarity index 100% rename from problems/reconstruct-itinerary.py rename to problems/python/reconstruct-itinerary.py diff --git a/problems/recover-binary-search-tree.py b/problems/python/recover-binary-search-tree.py similarity index 100% rename from problems/recover-binary-search-tree.py rename to problems/python/recover-binary-search-tree.py diff --git a/problems/redundant-connection.py b/problems/python/redundant-connection.py similarity index 100% rename from problems/redundant-connection.py rename to problems/python/redundant-connection.py diff --git a/problems/remove-all-adjacent-duplicates-in-string.py b/problems/python/remove-all-adjacent-duplicates-in-string.py similarity index 100% rename from problems/remove-all-adjacent-duplicates-in-string.py rename to problems/python/remove-all-adjacent-duplicates-in-string.py diff --git a/problems/remove-all-ones-with-row-and-column-flips.py b/problems/python/remove-all-ones-with-row-and-column-flips.py similarity index 100% rename from problems/remove-all-ones-with-row-and-column-flips.py rename to problems/python/remove-all-ones-with-row-and-column-flips.py diff --git a/problems/remove-duplicates-from-sorted-array-ii.py b/problems/python/remove-duplicates-from-sorted-array-ii.py similarity index 100% rename from problems/remove-duplicates-from-sorted-array-ii.py rename to problems/python/remove-duplicates-from-sorted-array-ii.py diff --git a/problems/remove-duplicates-from-sorted-array.py b/problems/python/remove-duplicates-from-sorted-array.py similarity index 100% rename from problems/remove-duplicates-from-sorted-array.py rename to problems/python/remove-duplicates-from-sorted-array.py diff --git a/problems/remove-duplicates-from-sorted-list.py b/problems/python/remove-duplicates-from-sorted-list.py similarity index 100% rename from problems/remove-duplicates-from-sorted-list.py rename to problems/python/remove-duplicates-from-sorted-list.py diff --git a/problems/remove-element.py b/problems/python/remove-element.py similarity index 100% rename from problems/remove-element.py rename to problems/python/remove-element.py diff --git a/problems/remove-invalid-parentheses.py b/problems/python/remove-invalid-parentheses.py similarity index 100% rename from problems/remove-invalid-parentheses.py rename to problems/python/remove-invalid-parentheses.py diff --git a/problems/remove-linked-list-elements.py b/problems/python/remove-linked-list-elements.py similarity index 100% rename from problems/remove-linked-list-elements.py rename to problems/python/remove-linked-list-elements.py diff --git a/problems/remove-nth-node-from-end-of-list.py b/problems/python/remove-nth-node-from-end-of-list.py similarity index 100% rename from problems/remove-nth-node-from-end-of-list.py rename to problems/python/remove-nth-node-from-end-of-list.py diff --git a/problems/reorder-list.py b/problems/python/reorder-list.py similarity index 100% rename from problems/reorder-list.py rename to problems/python/reorder-list.py diff --git a/problems/repeated-string-match.py b/problems/python/repeated-string-match.py similarity index 100% rename from problems/repeated-string-match.py rename to problems/python/repeated-string-match.py diff --git a/problems/replace-the-substring-for-balanced-string.py b/problems/python/replace-the-substring-for-balanced-string.py similarity index 100% rename from problems/replace-the-substring-for-balanced-string.py rename to problems/python/replace-the-substring-for-balanced-string.py diff --git a/problems/restore-ip-addresses.py b/problems/python/restore-ip-addresses.py similarity index 100% rename from problems/restore-ip-addresses.py rename to problems/python/restore-ip-addresses.py diff --git a/problems/reverse-integer.py b/problems/python/reverse-integer.py similarity index 100% rename from problems/reverse-integer.py rename to problems/python/reverse-integer.py diff --git a/problems/reverse-linked-list.py b/problems/python/reverse-linked-list.py similarity index 100% rename from problems/reverse-linked-list.py rename to problems/python/reverse-linked-list.py diff --git a/problems/reverse-string.py b/problems/python/reverse-string.py similarity index 100% rename from problems/reverse-string.py rename to problems/python/reverse-string.py diff --git a/problems/reverse-vowels-of-a-string.py b/problems/python/reverse-vowels-of-a-string.py similarity index 100% rename from problems/reverse-vowels-of-a-string.py rename to problems/python/reverse-vowels-of-a-string.py diff --git a/problems/reverse-words-in-a-string.py b/problems/python/reverse-words-in-a-string.py similarity index 100% rename from problems/reverse-words-in-a-string.py rename to problems/python/reverse-words-in-a-string.py diff --git a/problems/robot-bounded-in-circle.py b/problems/python/robot-bounded-in-circle.py similarity index 100% rename from problems/robot-bounded-in-circle.py rename to problems/python/robot-bounded-in-circle.py diff --git a/problems/roman-to-integer.py b/problems/python/roman-to-integer.py similarity index 100% rename from problems/roman-to-integer.py rename to problems/python/roman-to-integer.py diff --git a/problems/rotate-array.py b/problems/python/rotate-array.py similarity index 100% rename from problems/rotate-array.py rename to problems/python/rotate-array.py diff --git a/problems/rotate-image.py b/problems/python/rotate-image.py similarity index 100% rename from problems/rotate-image.py rename to problems/python/rotate-image.py diff --git a/problems/russian-doll-envelopes.py b/problems/python/russian-doll-envelopes.py similarity index 100% rename from problems/russian-doll-envelopes.py rename to problems/python/russian-doll-envelopes.py diff --git a/problems/same-tree.py b/problems/python/same-tree.py similarity index 100% rename from problems/same-tree.py rename to problems/python/same-tree.py diff --git a/problems/satisfiability-of-equality-equations.py b/problems/python/satisfiability-of-equality-equations.py similarity index 100% rename from problems/satisfiability-of-equality-equations.py rename to problems/python/satisfiability-of-equality-equations.py diff --git a/problems/score-of-parentheses.py b/problems/python/score-of-parentheses.py similarity index 100% rename from problems/score-of-parentheses.py rename to problems/python/score-of-parentheses.py diff --git a/problems/search-a-2d-matrix.py b/problems/python/search-a-2d-matrix.py similarity index 100% rename from problems/search-a-2d-matrix.py rename to problems/python/search-a-2d-matrix.py diff --git a/problems/search-in-a-binary-search-tree.py b/problems/python/search-in-a-binary-search-tree.py similarity index 100% rename from problems/search-in-a-binary-search-tree.py rename to problems/python/search-in-a-binary-search-tree.py diff --git a/problems/search-in-rotated-sorted-array-ii.py b/problems/python/search-in-rotated-sorted-array-ii.py similarity index 100% rename from problems/search-in-rotated-sorted-array-ii.py rename to problems/python/search-in-rotated-sorted-array-ii.py diff --git a/problems/search-in-rotated-sorted-array.py b/problems/python/search-in-rotated-sorted-array.py similarity index 100% rename from problems/search-in-rotated-sorted-array.py rename to problems/python/search-in-rotated-sorted-array.py diff --git a/problems/search-insert-position.py b/problems/python/search-insert-position.py similarity index 100% rename from problems/search-insert-position.py rename to problems/python/search-insert-position.py diff --git a/problems/search-suggestions-system.py b/problems/python/search-suggestions-system.py similarity index 100% rename from problems/search-suggestions-system.py rename to problems/python/search-suggestions-system.py diff --git a/problems/second-highest-salary.sql b/problems/python/second-highest-salary.sql similarity index 100% rename from problems/second-highest-salary.sql rename to problems/python/second-highest-salary.sql diff --git a/problems/sell-diminishing-valued-colored-balls.py b/problems/python/sell-diminishing-valued-colored-balls.py similarity index 100% rename from problems/sell-diminishing-valued-colored-balls.py rename to problems/python/sell-diminishing-valued-colored-balls.py diff --git a/problems/serialize-and-deserialize-binary-tree.py b/problems/python/serialize-and-deserialize-binary-tree.py similarity index 100% rename from problems/serialize-and-deserialize-binary-tree.py rename to problems/python/serialize-and-deserialize-binary-tree.py diff --git a/problems/serialize-and-deserialize-bst.py b/problems/python/serialize-and-deserialize-bst.py similarity index 100% rename from problems/serialize-and-deserialize-bst.py rename to problems/python/serialize-and-deserialize-bst.py diff --git a/problems/set-matrix-zeroes.py b/problems/python/set-matrix-zeroes.py similarity index 100% rename from problems/set-matrix-zeroes.py rename to problems/python/set-matrix-zeroes.py diff --git a/problems/shortest-bridge.py b/problems/python/shortest-bridge.py similarity index 100% rename from problems/shortest-bridge.py rename to problems/python/shortest-bridge.py diff --git a/problems/shortest-common-supersequence.py b/problems/python/shortest-common-supersequence.py similarity index 100% rename from problems/shortest-common-supersequence.py rename to problems/python/shortest-common-supersequence.py diff --git a/problems/shortest-distance-from-all-buildings.py b/problems/python/shortest-distance-from-all-buildings.py similarity index 100% rename from problems/shortest-distance-from-all-buildings.py rename to problems/python/shortest-distance-from-all-buildings.py diff --git a/problems/shortest-path-in-a-grid-with-obstacles-elimination.py b/problems/python/shortest-path-in-a-grid-with-obstacles-elimination.py similarity index 100% rename from problems/shortest-path-in-a-grid-with-obstacles-elimination.py rename to problems/python/shortest-path-in-a-grid-with-obstacles-elimination.py diff --git a/problems/shortest-path-in-binary-matrix.py b/problems/python/shortest-path-in-binary-matrix.py similarity index 100% rename from problems/shortest-path-in-binary-matrix.py rename to problems/python/shortest-path-in-binary-matrix.py diff --git a/problems/shortest-path-to-get-food.py b/problems/python/shortest-path-to-get-food.py similarity index 100% rename from problems/shortest-path-to-get-food.py rename to problems/python/shortest-path-to-get-food.py diff --git a/problems/shuffle-an-array.py b/problems/python/shuffle-an-array.py similarity index 100% rename from problems/shuffle-an-array.py rename to problems/python/shuffle-an-array.py diff --git a/problems/simplify-path.py b/problems/python/simplify-path.py similarity index 100% rename from problems/simplify-path.py rename to problems/python/simplify-path.py diff --git a/problems/single-threaded-cpu.py b/problems/python/single-threaded-cpu.py similarity index 100% rename from problems/single-threaded-cpu.py rename to problems/python/single-threaded-cpu.py diff --git a/problems/sliding-window-maximum.py b/problems/python/sliding-window-maximum.py similarity index 100% rename from problems/sliding-window-maximum.py rename to problems/python/sliding-window-maximum.py diff --git a/problems/snapshot-array.py b/problems/python/snapshot-array.py similarity index 100% rename from problems/snapshot-array.py rename to problems/python/snapshot-array.py diff --git a/problems/sort-colors.py b/problems/python/sort-colors.py similarity index 100% rename from problems/sort-colors.py rename to problems/python/sort-colors.py diff --git a/problems/sort-list.py b/problems/python/sort-list.py similarity index 100% rename from problems/sort-list.py rename to problems/python/sort-list.py diff --git a/problems/spiral-matrix.py b/problems/python/spiral-matrix.py similarity index 100% rename from problems/spiral-matrix.py rename to problems/python/spiral-matrix.py diff --git a/problems/split-array-into-fibonacci-sequence.py b/problems/python/split-array-into-fibonacci-sequence.py similarity index 100% rename from problems/split-array-into-fibonacci-sequence.py rename to problems/python/split-array-into-fibonacci-sequence.py diff --git a/problems/split-array-largest-sum.py b/problems/python/split-array-largest-sum.py similarity index 100% rename from problems/split-array-largest-sum.py rename to problems/python/split-array-largest-sum.py diff --git a/problems/sqrtx.py b/problems/python/sqrtx.py similarity index 100% rename from problems/sqrtx.py rename to problems/python/sqrtx.py diff --git a/problems/squares-of-a-sorted-array.py b/problems/python/squares-of-a-sorted-array.py similarity index 100% rename from problems/squares-of-a-sorted-array.py rename to problems/python/squares-of-a-sorted-array.py diff --git a/problems/step-by-step-directions-from-a-binary-tree-node-to-another.py b/problems/python/step-by-step-directions-from-a-binary-tree-node-to-another.py similarity index 100% rename from problems/step-by-step-directions-from-a-binary-tree-node-to-another.py rename to problems/python/step-by-step-directions-from-a-binary-tree-node-to-another.py diff --git a/problems/stock-price-fluctuation.py b/problems/python/stock-price-fluctuation.py similarity index 100% rename from problems/stock-price-fluctuation.py rename to problems/python/stock-price-fluctuation.py diff --git a/problems/stone-game-ii.py b/problems/python/stone-game-ii.py similarity index 100% rename from problems/stone-game-ii.py rename to problems/python/stone-game-ii.py diff --git a/problems/student-attendance-record-ii.py b/problems/python/student-attendance-record-ii.py similarity index 100% rename from problems/student-attendance-record-ii.py rename to problems/python/student-attendance-record-ii.py diff --git a/problems/subarray-sum-equals-k.py b/problems/python/subarray-sum-equals-k.py similarity index 100% rename from problems/subarray-sum-equals-k.py rename to problems/python/subarray-sum-equals-k.py diff --git a/problems/subarrays-with-k-different-integers.py b/problems/python/subarrays-with-k-different-integers.py similarity index 100% rename from problems/subarrays-with-k-different-integers.py rename to problems/python/subarrays-with-k-different-integers.py diff --git a/problems/subdomain-visit-count.py b/problems/python/subdomain-visit-count.py similarity index 100% rename from problems/subdomain-visit-count.py rename to problems/python/subdomain-visit-count.py diff --git a/problems/subsets-ii.py b/problems/python/subsets-ii.py similarity index 100% rename from problems/subsets-ii.py rename to problems/python/subsets-ii.py diff --git a/problems/subsets.py b/problems/python/subsets.py similarity index 100% rename from problems/subsets.py rename to problems/python/subsets.py diff --git a/problems/substring-with-concatenation-of-all-words.py b/problems/python/substring-with-concatenation-of-all-words.py similarity index 100% rename from problems/substring-with-concatenation-of-all-words.py rename to problems/python/substring-with-concatenation-of-all-words.py diff --git a/problems/subtree-of-another-tree.py b/problems/python/subtree-of-another-tree.py similarity index 100% rename from problems/subtree-of-another-tree.py rename to problems/python/subtree-of-another-tree.py diff --git a/problems/sum-of-subarray-minimums.py b/problems/python/sum-of-subarray-minimums.py similarity index 100% rename from problems/sum-of-subarray-minimums.py rename to problems/python/sum-of-subarray-minimums.py diff --git a/problems/sum-root-to-leaf-numbers.py b/problems/python/sum-root-to-leaf-numbers.py similarity index 100% rename from problems/sum-root-to-leaf-numbers.py rename to problems/python/sum-root-to-leaf-numbers.py diff --git a/problems/summary-ranges.py b/problems/python/summary-ranges.py similarity index 100% rename from problems/summary-ranges.py rename to problems/python/summary-ranges.py diff --git a/problems/super-ugly-number.py b/problems/python/super-ugly-number.py similarity index 100% rename from problems/super-ugly-number.py rename to problems/python/super-ugly-number.py diff --git a/problems/swap-adjacent-in-lr-string.py b/problems/python/swap-adjacent-in-lr-string.py similarity index 100% rename from problems/swap-adjacent-in-lr-string.py rename to problems/python/swap-adjacent-in-lr-string.py diff --git a/problems/swap-nodes-in-pairs.py b/problems/python/swap-nodes-in-pairs.py similarity index 100% rename from problems/swap-nodes-in-pairs.py rename to problems/python/swap-nodes-in-pairs.py diff --git a/problems/swim-in-rising-water.py b/problems/python/swim-in-rising-water.py similarity index 100% rename from problems/swim-in-rising-water.py rename to problems/python/swim-in-rising-water.py diff --git a/problems/symmetric-tree.py b/problems/python/symmetric-tree.py similarity index 100% rename from problems/symmetric-tree.py rename to problems/python/symmetric-tree.py diff --git a/problems/tallest-billboard.py b/problems/python/tallest-billboard.py similarity index 100% rename from problems/tallest-billboard.py rename to problems/python/tallest-billboard.py diff --git a/problems/target-sum.py b/problems/python/target-sum.py similarity index 100% rename from problems/target-sum.py rename to problems/python/target-sum.py diff --git a/problems/task-scheduler.py b/problems/python/task-scheduler.py similarity index 100% rename from problems/task-scheduler.py rename to problems/python/task-scheduler.py diff --git a/problems/text-justification.py b/problems/python/text-justification.py similarity index 100% rename from problems/text-justification.py rename to problems/python/text-justification.py diff --git a/problems/the-kth-factor-of-n.py b/problems/python/the-kth-factor-of-n.py similarity index 100% rename from problems/the-kth-factor-of-n.py rename to problems/python/the-kth-factor-of-n.py diff --git a/problems/the-maze-ii.py b/problems/python/the-maze-ii.py similarity index 100% rename from problems/the-maze-ii.py rename to problems/python/the-maze-ii.py diff --git a/problems/time-based-key-value-store.py b/problems/python/time-based-key-value-store.py similarity index 100% rename from problems/time-based-key-value-store.py rename to problems/python/time-based-key-value-store.py diff --git a/problems/to-lower-case.py b/problems/python/to-lower-case.py similarity index 100% rename from problems/to-lower-case.py rename to problems/python/to-lower-case.py diff --git a/problems/toeplitz-matrix.py b/problems/python/toeplitz-matrix.py similarity index 100% rename from problems/toeplitz-matrix.py rename to problems/python/toeplitz-matrix.py diff --git a/problems/top-k-frequent-elements.py b/problems/python/top-k-frequent-elements.py similarity index 100% rename from problems/top-k-frequent-elements.py rename to problems/python/top-k-frequent-elements.py diff --git a/problems/trapping-rain-water-ii.py b/problems/python/trapping-rain-water-ii.py similarity index 100% rename from problems/trapping-rain-water-ii.py rename to problems/python/trapping-rain-water-ii.py diff --git a/problems/trapping-rain-water.py b/problems/python/trapping-rain-water.py similarity index 100% rename from problems/trapping-rain-water.py rename to problems/python/trapping-rain-water.py diff --git a/problems/trim-a-binary-search-tree.py b/problems/python/trim-a-binary-search-tree.py similarity index 100% rename from problems/trim-a-binary-search-tree.py rename to problems/python/trim-a-binary-search-tree.py diff --git a/problems/two-out-of-three.py b/problems/python/two-out-of-three.py similarity index 100% rename from problems/two-out-of-three.py rename to problems/python/two-out-of-three.py diff --git a/problems/two-sum-ii-input-array-is-sorted.py b/problems/python/two-sum-ii-input-array-is-sorted.py similarity index 100% rename from problems/two-sum-ii-input-array-is-sorted.py rename to problems/python/two-sum-ii-input-array-is-sorted.py diff --git a/problems/two-sum.py b/problems/python/two-sum.py similarity index 100% rename from problems/two-sum.py rename to problems/python/two-sum.py diff --git a/problems/ugly-number-ii.py b/problems/python/ugly-number-ii.py similarity index 100% rename from problems/ugly-number-ii.py rename to problems/python/ugly-number-ii.py diff --git a/problems/ugly-number.py b/problems/python/ugly-number.py similarity index 100% rename from problems/ugly-number.py rename to problems/python/ugly-number.py diff --git a/problems/umber-of-islands-ii.py b/problems/python/umber-of-islands-ii.py similarity index 100% rename from problems/umber-of-islands-ii.py rename to problems/python/umber-of-islands-ii.py diff --git a/problems/unique-binary-search-trees-ii,py b/problems/python/unique-binary-search-trees-ii,py similarity index 100% rename from problems/unique-binary-search-trees-ii,py rename to problems/python/unique-binary-search-trees-ii,py diff --git a/problems/unique-binary-search-trees.py b/problems/python/unique-binary-search-trees.py similarity index 100% rename from problems/unique-binary-search-trees.py rename to problems/python/unique-binary-search-trees.py diff --git a/problems/unique-email-addres.py b/problems/python/unique-email-addres.py similarity index 100% rename from problems/unique-email-addres.py rename to problems/python/unique-email-addres.py diff --git a/problems/unique-paths.py b/problems/python/unique-paths.py similarity index 100% rename from problems/unique-paths.py rename to problems/python/unique-paths.py diff --git a/problems/univalued-binary-tree.py b/problems/python/univalued-binary-tree.py similarity index 100% rename from problems/univalued-binary-tree.py rename to problems/python/univalued-binary-tree.py diff --git a/problems/valid-anagram.py b/problems/python/valid-anagram.py similarity index 100% rename from problems/valid-anagram.py rename to problems/python/valid-anagram.py diff --git a/problems/valid-number.py b/problems/python/valid-number.py similarity index 100% rename from problems/valid-number.py rename to problems/python/valid-number.py diff --git a/problems/valid-palindrome-ii.py b/problems/python/valid-palindrome-ii.py similarity index 100% rename from problems/valid-palindrome-ii.py rename to problems/python/valid-palindrome-ii.py diff --git a/problems/valid-palindrome.py b/problems/python/valid-palindrome.py similarity index 100% rename from problems/valid-palindrome.py rename to problems/python/valid-palindrome.py diff --git a/problems/valid-parentheses.py b/problems/python/valid-parentheses.py similarity index 100% rename from problems/valid-parentheses.py rename to problems/python/valid-parentheses.py diff --git a/problems/valid-word-abbreviation.py b/problems/python/valid-word-abbreviation.py similarity index 100% rename from problems/valid-word-abbreviation.py rename to problems/python/valid-word-abbreviation.py diff --git a/problems/validate-binary-search-tree.py b/problems/python/validate-binary-search-tree.py similarity index 100% rename from problems/validate-binary-search-tree.py rename to problems/python/validate-binary-search-tree.py diff --git a/problems/verify-preorder-serialization-of-a-binary-tree.py b/problems/python/verify-preorder-serialization-of-a-binary-tree.py similarity index 100% rename from problems/verify-preorder-serialization-of-a-binary-tree.py rename to problems/python/verify-preorder-serialization-of-a-binary-tree.py diff --git a/problems/vertical-order-traversal-of-a-binary-tree.py b/problems/python/vertical-order-traversal-of-a-binary-tree.py similarity index 100% rename from problems/vertical-order-traversal-of-a-binary-tree.py rename to problems/python/vertical-order-traversal-of-a-binary-tree.py diff --git a/problems/wiggle-subsequence.py b/problems/python/wiggle-subsequence.py similarity index 100% rename from problems/wiggle-subsequence.py rename to problems/python/wiggle-subsequence.py diff --git a/problems/word-break.py b/problems/python/word-break.py similarity index 100% rename from problems/word-break.py rename to problems/python/word-break.py diff --git a/problems/word-ladder-ii.py b/problems/python/word-ladder-ii.py similarity index 100% rename from problems/word-ladder-ii.py rename to problems/python/word-ladder-ii.py diff --git a/problems/word-ladder.py b/problems/python/word-ladder.py similarity index 100% rename from problems/word-ladder.py rename to problems/python/word-ladder.py diff --git a/problems/word-search-ii.py b/problems/python/word-search-ii.py similarity index 100% rename from problems/word-search-ii.py rename to problems/python/word-search-ii.py diff --git a/problems/word-search.py b/problems/python/word-search.py similarity index 100% rename from problems/word-search.py rename to problems/python/word-search.py From 54dd56f812405539a86e67f8b983db77850b62dd Mon Sep 17 00:00:00 2001 From: wuduhren Date: Mon, 25 Apr 2022 19:22:59 +0800 Subject: [PATCH 17/52] no message --- problems/python3/container-with-most-water.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 problems/python3/container-with-most-water.py diff --git a/problems/python3/container-with-most-water.py b/problems/python3/container-with-most-water.py new file mode 100644 index 0000000..e69de29 From 740f1600b60a7b8f5f3d50828b245ca984446ce3 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Mon, 25 Apr 2022 19:43:25 +0800 Subject: [PATCH 18/52] no message --- problems/python3/container-with-most-water.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/python3/container-with-most-water.py b/problems/python3/container-with-most-water.py index e69de29..c24f0c9 100644 --- a/problems/python3/container-with-most-water.py +++ b/problems/python3/container-with-most-water.py @@ -0,0 +1,25 @@ +""" +Time: O(N) +Space: O(1) + +i and j starts from the leftest and rightest. Move the one that has less height. + +Why we won't miss any i and j? +For example, currently i is heigher than j. +If between i~j, there are no height that is larger or equal to i, than since the area is `min(height[i], height[j]) * (j-i)`, you cannot find any area that is larger than the current one. +If between i~j, there is a height that is larger or equal to i, j will on it, and it will be tested. +Thus, given any i and j, any other future i and j that have the potential of forming larger area will be tested. +""" +class Solution: + def maxArea(self, height: List[int]) -> int: + i = 0 + j = len(height)-1 + ans = 0 + + while iheight[j]: + j -= 1 + else: + i += 1 + return ans \ No newline at end of file From b9c2a701c30e025e0150c83004b45d0f807e2567 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 26 Apr 2022 10:42:50 +0800 Subject: [PATCH 19/52] no message --- problems/python3/3sum.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 problems/python3/3sum.py diff --git a/problems/python3/3sum.py b/problems/python3/3sum.py new file mode 100644 index 0000000..c29d989 --- /dev/null +++ b/problems/python3/3sum.py @@ -0,0 +1,40 @@ +""" +Time: O(N^2) +Space: O(1) + +First of all, we need to sort the list, so that it is easier to know where to move the pointers. +(Keep in mind that sorting takes O(NLogN) of time, but since judging from the problem this solution might takes at least O(N^2), so it is ok to sort.) + +Now, we have 3 unique pointers at the list. i, j, k, where i List[List[int]]: + ans = [] + nums.sort() + + for i in range(len(nums)): + if 00: break #[1] + + j, k = i+1, len(nums)-1 + while j0: + k -= 1 + elif nums[i]+nums[j]+nums[k]<0: + j += 1 + else: + ans.append((nums[i], nums[j], nums[k])) + while 0 Date: Thu, 28 Apr 2022 18:16:35 +0800 Subject: [PATCH 20/52] no message --- common/heap-sort.py | 56 +++++++++++++++----------------- problems/python3/3sum-closest.py | 24 ++++++++++++++ 2 files changed, 51 insertions(+), 29 deletions(-) create mode 100644 problems/python3/3sum-closest.py diff --git a/common/heap-sort.py b/common/heap-sort.py index eb2e11c..3d56e39 100644 --- a/common/heap-sort.py +++ b/common/heap-sort.py @@ -1,35 +1,33 @@ +#O(LogN), used when part of the array is already heapified. +def heapify(A, N, i): + largest = i + l = i*2+1 + r = i*2+2 + + if lA[largest]: largest = l + if rA[largest]: largest = r + if largest!=i: + A[largest], A[i] = A[i], A[largest] + heapify(A, N, largest) + +#O(NLogN) def heapSort(A): - #build max heap - def heapify(A, n, i): - if i>=n: return - l, r = i*2+1, i*2+2 - left = A[l] if lA[i] or right>A[i]: - if left>right: - A[i], A[l] = A[l], A[i] - heapify(A, n, l) - else: - A[i], A[r] = A[r], A[i] - heapify(A, n, r) - - n = len(A) - - for i in reversed(xrange(n)): - heapify(A, n, i) - - for i in reversed(xrange(1, n)): - A[i], A[0] = A[0], A[i] + N = len(A) + + #build max heap, O(NLogN). Can be optimized to the O(N). + for i in range(N//2-1, -1, -1): + heapify(A, N, i) + + #keep swapping the largest + for i in range(N-1, -1, -1): + A[0], A[i] = A[i], A[0] heapify(A, i, 0) - -A = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14] +A = [12, 11, 13, 5, 6, 7] heapSort(A) -print A +print(A) -""" -Time Complexity O(NLogN) in best, average, worst case. -Space Complexity O(1) -""" \ No newline at end of file +A = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17] +heapSort(A) +print(A) \ No newline at end of file diff --git a/problems/python3/3sum-closest.py b/problems/python3/3sum-closest.py new file mode 100644 index 0000000..472c80f --- /dev/null +++ b/problems/python3/3sum-closest.py @@ -0,0 +1,24 @@ +""" +Time: O(N^2) +Space: O(1) +""" +class Solution: + def threeSumClosest(self, nums: List[int], target: int) -> int: + nums.sort() + + N = len(nums) + ans = float('inf') + + for i in range(N): + j = i+1 + k = N-1 + + while jabs(target-total): ans = total + if total>target: + k -= 1 + elif total Date: Thu, 5 May 2022 09:29:22 +0800 Subject: [PATCH 21/52] no message --- ...bstring-with-concatenation-of-all-words.py | 4 +- problems/python3/3sum-smaller.py | 18 ++++++++ problems/python3/3sum.py | 24 ++++++++++ problems/python3/4sum.py | 33 +++++++++++++ problems/python3/balanced-binary-tree.py | 18 ++++++++ problems/python3/diameter-of-binary-tree.py | 17 +++++++ problems/python3/invert-binary-tree.py | 36 +++++++++++++++ .../python3/maximum-depth-of-binary-tree.py | 8 ++++ ...bstring-with-concatenation-of-all-words.py | 46 +++++++++++++++++++ 9 files changed, 203 insertions(+), 1 deletion(-) create mode 100644 problems/python3/3sum-smaller.py create mode 100644 problems/python3/4sum.py create mode 100644 problems/python3/balanced-binary-tree.py create mode 100644 problems/python3/diameter-of-binary-tree.py create mode 100644 problems/python3/invert-binary-tree.py create mode 100644 problems/python3/maximum-depth-of-binary-tree.py create mode 100644 problems/python3/substring-with-concatenation-of-all-words.py diff --git a/problems/python/substring-with-concatenation-of-all-words.py b/problems/python/substring-with-concatenation-of-all-words.py index b11bb81..e3e6420 100644 --- a/problems/python/substring-with-concatenation-of-all-words.py +++ b/problems/python/substring-with-concatenation-of-all-words.py @@ -47,4 +47,6 @@ def test(self, s, wl, countExpected): return True - \ No newline at end of file + + + diff --git a/problems/python3/3sum-smaller.py b/problems/python3/3sum-smaller.py new file mode 100644 index 0000000..3291586 --- /dev/null +++ b/problems/python3/3sum-smaller.py @@ -0,0 +1,18 @@ +class Solution: + def threeSumSmaller(self, nums: List[int], target: int) -> int: + N = len(nums) + ans = 0 + + nums.sort() + + + for i in range(N): + j = i+1 + k = N-1 + while j List[List[int]]: k -= 1 j += 1 + return ans + + +""" +No Sort. +Use set to dedupe and check needed. + +Time: O(N^2) +Space: O(N) +""" +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + ans = set() + seen = set() + N = len(nums) + + for i, v1 in enumerate(nums): + if v1 in seen: continue + seen.add(v1) + needed = set() + for j, v2 in enumerate(nums[i+1:]): + if v2 in needed: + ans.add(tuple(sorted((v1, v2, -v1-v2)))) + needed.add(-v1-v2) return ans \ No newline at end of file diff --git a/problems/python3/4sum.py b/problems/python3/4sum.py new file mode 100644 index 0000000..4757233 --- /dev/null +++ b/problems/python3/4sum.py @@ -0,0 +1,33 @@ +""" +Time: O(N^(K-1)) -> O(N^3) +Space: O(K) -> O(1) +""" +class Solution: + def fourSum(self, nums: List[int], target: int) -> List[List[int]]: + def kSum(k, start, target): + if k>2: + for i in range(start, len(nums)-k+1): + if i!=start and nums[i]==nums[i-1]: continue + temp.append(nums[i]) + kSum(k-1, i+1, target-nums[i]) + temp.pop() + else: + l, r = start, len(nums)-1 + + while ltarget: + r -= 1 + elif nums[l]+nums[r] bool: + def getHeight(node) -> (bool, int): + if not node: return True, 0 + leftIsBalanced, leftHeight = getHeight(node.left) + if not leftIsBalanced: return False, 0 + + rightIsBalanced, rightHeight = getHeight(node.right) + if not rightIsBalanced: return False, 0 + + return abs(leftHeight-rightHeight)<2, 1+max(leftHeight, rightHeight) + + isBalanced, h = getHeight(root) + return isBalanced \ No newline at end of file diff --git a/problems/python3/diameter-of-binary-tree.py b/problems/python3/diameter-of-binary-tree.py new file mode 100644 index 0000000..1f9704d --- /dev/null +++ b/problems/python3/diameter-of-binary-tree.py @@ -0,0 +1,17 @@ +""" +Time: O(N) +Space: O(LogN) for the recursion stack. If the tree is balanced. +""" +class Solution: + def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: + def helper(node): + if not node: return 0 + l = helper(node.left) + r = helper(node.right) + self.ans = max(self.ans, 1+l+r) + return 1+max(l, r) + + self.ans = 0 + + helper(root) + return self.ans-1 \ No newline at end of file diff --git a/problems/python3/invert-binary-tree.py b/problems/python3/invert-binary-tree.py new file mode 100644 index 0000000..d69daec --- /dev/null +++ b/problems/python3/invert-binary-tree.py @@ -0,0 +1,36 @@ +""" +Recursive +Time: O(N) +Space: O(LogN) +""" +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if not root: return root + left = root.left + right = root.right + root.left = self.invertTree(right) + root.right = self.invertTree(left) + return root + + +""" +Iterative +Time: O(N) +Space: O(N) +""" +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if not root: return root + q = collections.deque([root]) + + while q: + node = q.popleft() + left = node.left + right = node.right + node.right = left + node.left = right + + if node.left: q.append(node.left) + if node.right: q.append(node.right) + + return root \ No newline at end of file diff --git a/problems/python3/maximum-depth-of-binary-tree.py b/problems/python3/maximum-depth-of-binary-tree.py new file mode 100644 index 0000000..3146dcf --- /dev/null +++ b/problems/python3/maximum-depth-of-binary-tree.py @@ -0,0 +1,8 @@ +""" +Time: O(N) +Space:O(LogN), for recursion stack space. +""" +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + if not root: return 0 + return 1+max(self.maxDepth(root.left), self.maxDepth(root.right)) \ No newline at end of file diff --git a/problems/python3/substring-with-concatenation-of-all-words.py b/problems/python3/substring-with-concatenation-of-all-words.py new file mode 100644 index 0000000..164dfa6 --- /dev/null +++ b/problems/python3/substring-with-concatenation-of-all-words.py @@ -0,0 +1,46 @@ +""" +Time: O(W * N/W * W), there will be W time of iteration in the first loop ([0]), N/W of iteration in the second loop ([1]). In each loop, creating substring "word" and "popWord" takes O(W). +Space: O(MW) for "wordSet". +""" +class Solution: + def findSubstring(self, s: str, words: List[str]) -> List[int]: + N = len(s) + M = len(words) + W = len(words[0]) + wordSet = set(words) + ans = [] + counter = collections.Counter(words) + + for i in range(W): #[0] + windowCounter = collections.Counter() #counter for the word in words + notInWords = 0 #number of word not in the wordSet + theSame = 0 #number of word with the same count with "counter" + j = i + + while jcounter[word]: + theSame -= 1 + else: + notInWords += 1 + + popStart = j-M*W + if popStart>=0: + popWord = s[popStart:popStart+W] + if popWord in wordSet: + windowCounter[popWord] -= 1 + if windowCounter[popWord]==counter[popWord]: + theSame += 1 + elif windowCounter[popWord] Date: Sat, 14 May 2022 09:15:48 +0800 Subject: [PATCH 22/52] no message --- .../binary-tree-level-order-traversal.py | 39 +++++++++++++++++++ ...common-ancestor-of-a-binary-search-tree.py | 28 +++++++++++++ problems/python3/same-tree.py | 16 ++++++++ problems/python3/subtree-of-another-tree.py | 10 +++++ 4 files changed, 93 insertions(+) create mode 100644 problems/python3/binary-tree-level-order-traversal.py create mode 100644 problems/python3/lowest-common-ancestor-of-a-binary-search-tree.py create mode 100644 problems/python3/same-tree.py create mode 100644 problems/python3/subtree-of-another-tree.py diff --git a/problems/python3/binary-tree-level-order-traversal.py b/problems/python3/binary-tree-level-order-traversal.py new file mode 100644 index 0000000..2ddb875 --- /dev/null +++ b/problems/python3/binary-tree-level-order-traversal.py @@ -0,0 +1,39 @@ +""" +Time: O(N), since we need to go through all the nodes. +Space: O(LogN) for recursion stack. (if the tree is balanced). This do not take the output into account. +""" +class Solution: + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + def helper(node, level): + if not node: return + if level==len(ans): ans.append([]) + ans[level].append(node.val) + helper(node.left, level+1) + helper(node.right, level+1) + + ans = [] + helper(root, 0) + + return ans + + +""" +Time: O(N), since we need to go through all the nodes. +Space: O(N) for queue. +""" +class Solution: + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if not root: return [] + + q = collections.deque([(root, 0)]) + ans = [] + + while q: + node, level = q.popleft() + + if level==len(ans): ans.append([]) + ans[level].append(node.val) + if node.left: q.append((node.left, level+1)) + if node.right: q.append((node.right, level+1)) + + return ans \ No newline at end of file diff --git a/problems/python3/lowest-common-ancestor-of-a-binary-search-tree.py b/problems/python3/lowest-common-ancestor-of-a-binary-search-tree.py new file mode 100644 index 0000000..12e1743 --- /dev/null +++ b/problems/python3/lowest-common-ancestor-of-a-binary-search-tree.py @@ -0,0 +1,28 @@ +""" +Recursive +Time: O(LogN) if the tree is balanced. +Space: O(LogN) for the recursion stack. +""" +class Solution: + def lowestCommonAncestor(self, node: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if q.val<=node.val<=p.val or p.val<=node.val<=q.val: + return node + elif q.val 'TreeNode': + while not (q.val<=node.val<=p.val or p.val<=node.val<=q.val): + if q.val bool: + if not node1 and not node2: + return True + + if (not node1 and node2) or (node1 and not node2): + return False + + if node1.val!=node2.val: + return False + + return self.isSameTree(node1.left, node2.left) and self.isSameTree(node1.right, node2.right) \ No newline at end of file diff --git a/problems/python3/subtree-of-another-tree.py b/problems/python3/subtree-of-another-tree.py new file mode 100644 index 0000000..7871f8c --- /dev/null +++ b/problems/python3/subtree-of-another-tree.py @@ -0,0 +1,10 @@ +class Solution: + def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: + if not root or not subRoot: return root==subRoot + if self.isSame(root, subRoot): return True + return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) + + def isSame(self, p, q): + if not p or not q: return p==q + if p.val!=q.val: return False + return self.isSame(p.left, q.left) and self.isSame(p.right, q.right) \ No newline at end of file From c6ba939032264fe976069706354196181d1a9e3d Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 17 May 2022 08:58:35 +0800 Subject: [PATCH 23/52] no message --- .../python3/binary-tree-right-side-view.py | 18 ++++++++++++++ .../count-good-nodes-in-binary-tree.py | 16 +++++++++++++ .../python3/validate-binary-search-tree.py | 24 +++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 problems/python3/binary-tree-right-side-view.py create mode 100644 problems/python3/count-good-nodes-in-binary-tree.py create mode 100644 problems/python3/validate-binary-search-tree.py diff --git a/problems/python3/binary-tree-right-side-view.py b/problems/python3/binary-tree-right-side-view.py new file mode 100644 index 0000000..53b4d13 --- /dev/null +++ b/problems/python3/binary-tree-right-side-view.py @@ -0,0 +1,18 @@ +""" +Time: O(N) +Space: O(LogN) if the tree is balanced. + +BFS is a more intuitive way to do this, but the time complexity will be at least O(N). +Using recursion instead, will take O(LogN) for the recursion stack size. +""" +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + def helper(node, level): + if not node: return + if len(ans) int: + def helper(node, maxVal): + nonlocal count + if not node: return + if node.val>=maxVal: count += 1 + helper(node.left, max(maxVal, node.val)) + helper(node.right, max(maxVal, node.val)) + + count = 0 + helper(root, float('-inf')) + return count \ No newline at end of file diff --git a/problems/python3/validate-binary-search-tree.py b/problems/python3/validate-binary-search-tree.py new file mode 100644 index 0000000..4185bc6 --- /dev/null +++ b/problems/python3/validate-binary-search-tree.py @@ -0,0 +1,24 @@ +""" +The inorder travsersal of a BST is always increasing. + +Time: O(N) +Space: O(N) +""" +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + lastVal = float('-inf') + stack = [] + + node = root + while stack or node: + while node: + stack.append(node) + node = node.left + + node = stack.pop() + + if not lastVal Date: Mon, 30 May 2022 07:39:09 +0800 Subject: [PATCH 24/52] 20220530 --- .gitignore | 0 README.md | 0 "common/bellman\342\200\223ford.py" | 0 common/binary-search-tree.py | 0 common/bst-in-order.py | 0 common/dijkstra.py | 0 common/heap-sort.py | 0 common/insertion-sort.py | 0 common/knapsack.py | 0 common/merge-sort-in-place.py | 0 common/merge-sort.py | 0 common/min-heap.py | 0 common/quick-sort.py | 0 common/radix-sort.py | 0 common/trie.py | 0 problems/python/01-matrix.py | 0 problems/python/3sum-closest.py | 0 problems/python/3sum.py | 0 problems/python/4sum.py | 0 problems/python/accounts-merge.py | 0 problems/python/add-binary.py | 0 problems/python/add-digits.py | 0 problems/python/add-strings.py | 0 problems/python/add-two-numbers-ii.py | 0 problems/python/add-two-numbers.py | 0 problems/python/alien-dictionary.py | 0 .../all-nodes-distance-k-in-binary-tree.py | 0 .../amount-of-new-area-painted-each-day.py | 0 .../analyze-user-website-visit-pattern.py | 0 problems/python/backspace-string-compare.py | 0 .../python/balance-a-binary-search-tree.py | 0 problems/python/balanced-binary-tree.py | 0 problems/python/basic-calculator-ii.py | 0 problems/python/best-time-to-buy-an-stock.py | 0 .../best-time-to-buy-and-sell-stock-iii.py | 0 ...ime-to-buy-and-sell-stock-with-cooldown.py | 0 .../python/best-time-to-buy-and-sell-stock.py | 0 problems/python/big-countries.sql | 0 .../python/binary-search-tree-iterator.py | 0 problems/python/binary-search.py | 0 problems/python/binary-subarrays-with-sum.py | 0 .../python/binary-tree-inorder-traversal.py | 0 .../binary-tree-level-order-traversal-ii.py | 0 .../binary-tree-level-order-traversal.py | 0 ...inary-tree-longest-consecutive-sequence.py | 0 .../python/binary-tree-maximum-path-sum.py | 0 problems/python/binary-tree-paths.py | 0 problems/python/binary-tree-pruning.py | 0 .../python/binary-tree-right-side-view.py | 0 .../binary-tree-vertical-order-traversal.py | 0 problems/python/binary-watch.py | 0 .../python/buildings-with-an-ocean-view.py | 0 problems/python/burst-balloons.py | 0 problems/python/campus-bikes-ii.py | 0 problems/python/candy.py | 0 ...capacity-to-ship-packages-within-d-days.py | 0 .../python/cheapest-flights-within-k-stops.py | 0 problems/python/climbing-stairs.py | 0 problems/python/clone-graph.py | 0 .../closest-binary-search-tree-value.py | 0 problems/python/coin-change.py | 0 problems/python/coloring-a-border.py | 0 problems/python/combination-sum-ii.py | 0 problems/python/combination-sum-iii.py | 0 problems/python/combination-sum-iv.py | 0 problems/python/combination-sum.py | 0 problems/python/combinations.py | 0 problems/python/combine-two-tables.sql | 0 problems/python/compare-version-numbers.py | 0 .../connecting-cities-with-minimum-cost.py | 0 problems/python/consecutive-numbers-sum.py | 0 ...ee-from-inorder-and-postorder-traversal.py | 0 ...ree-from-preorder-and-inorder-traversal.py | 0 problems/python/container-with-most-water.py | 0 problems/python/contains-duplicate-ii.py | 0 problems/python/contains-duplicate-iii.py | 0 problems/python/contains-duplicate.py | 0 problems/python/continuous-subarray-sum.py | 0 ...earch-tree-to-sorted-doubly-linked-list.py | 0 ...vert-sorted-array-to-binary-search-tree.py | 0 ...nvert-sorted-list-to-binary-search-tree.py | 0 .../python/copy-list-with-random-pointer.py | 0 ...ount-all-valid-pickup-and-delivery-opti.py | 0 problems/python/count-binary-substrings.py | 0 problems/python/count-complete-tree-nodes.py | 0 .../python/count-number-of-nice-subarrays.py | 0 ...ers-of-all-substrings-of-a-given-string.py | 0 problems/python/course-schedule-ii.py | 0 problems/python/course-schedule.py | 0 problems/python/custom-sort-string.py | 0 problems/python/cutting-ribbons.py | 0 .../data-stream-as-disjoint-intervals.py | 0 problems/python/decode-string.py | 0 problems/python/decode-ways.py | 0 problems/python/delete-and-earn.py | 0 .../delete-duplicate-folders-in-system.py | 0 problems/python/delete-node-in-a-bst.py | 0 .../delete-operation-for-two-strings.py | 0 ...ign-add-and-search-words-data-structure.py | 0 .../python/design-in-memory-file-system.py | 0 problems/python/design-linked-list.py | 0 problems/python/design-tic-tac-toe.py | 0 problems/python/diagonal-traverse.py | 0 problems/python/diameter-of-binary-tree.py | 0 .../different-ways-to-add-parentheses.py | 0 problems/python/distinct-subsequences.py | 0 .../python/distribute-coins-in-binary-tree.py | 0 problems/python/domino-and-tromino-tiling.py | 0 .../dot-product-of-two-sparse-vectors.py | 0 problems/python/dungeon-game.py | 0 problems/python/edit-distance.py | 0 problems/python/egions-cut-by-slashes.py | 0 problems/python/evaluate-division.py | 0 .../evaluate-reverse-polish-notation.py | 0 .../python/exclusive-time-of-functions.py | 0 problems/python/expression-add-operators.py | 0 problems/python/filling-bookcase-shelves.py | 0 ...ll-possible-recipes-from-given-supplies.py | 0 problems/python/find-and-replace-in-string.py | 0 .../python/find-distance-in-a-binary-tree.py | 0 problems/python/find-duplicate-subtrees.py | 0 problems/python/find-eventual-safe-states.py | 0 ...ast-position-of-element-in-sorted-array.py | 0 problems/python/find-k-closest-elements.py | 0 .../python/find-k-pairs-with-smallest-sums.py | 0 problems/python/find-leaves-of-binary-tree.py | 0 .../python/find-median-from-data-stream.py | 0 ...find-minimum-in-rotated-sorted-array-ii.py | 0 .../find-minimum-in-rotated-sorted-array.py | 0 .../python/find-mode-in-binary-search-tree.py | 0 .../find-original-array-from-doubled-array,py | 0 problems/python/find-peak-element.py | 0 problems/python/find-the-duplicate-number.py | 0 problems/python/first-bad-version.py | 0 problems/python/first-missing-positive.py | 0 .../first-unique-character-in-a-string.py | 0 problems/python/fizz-buzz.py | 0 .../flatten-binary-tree-to-linked-list.py | 0 ...binary-tree-to-match-preorder-traversal.py | 0 .../flip-string-to-monotone-increasing.py | 0 problems/python/flood-fill.py | 0 problems/python/friend-circles.py | 0 problems/python/fruit-into-baskets.py | 0 problems/python/game-of-life.py | 0 problems/python/generate-parentheses.py | 0 problems/python/graph-valid-tree.py | 0 .../python/greatest-sum-divisible-by-three.py | 0 problems/python/group-anagrams.py | 0 problems/python/group-shifted-strings.py | 0 .../python/guess-number-higher-or-lower-ii.py | 0 .../python/guess-number-higher-or-lower.py | 0 problems/python/guess-the-word.py | 0 problems/python/h-index-ii.py | 0 problems/python/h-index.py | 0 problems/python/hamming-distance.py | 0 problems/python/house-robber-ii.py | 0 problems/python/house-robber-iii.py | 0 problems/python/house-robber.py | 0 problems/python/implement-trie-prefix-tree.py | 0 .../python/increasing-triplet-subsequence.py | 0 .../python/inorder-successor-in-bst-ii.py | 0 problems/python/inorder-successor-in-bst.py | 0 problems/python/insert-interval.py | 0 .../insert-into-a-binary-search-tree.py | 0 ...sert-into-a-sorted-circular-linked-list.py | 0 problems/python/insertion-sort-list.py | 0 problems/python/integer-to-english-words.py | 0 problems/python/interleaving-string.py | 0 .../python/intersection-of-two-arrays-ii.py | 0 problems/python/intersection-of-two-arrays.py | 0 problems/python/invert-binary-tree.py | 0 problems/python/is-graph-bipartite.py | 0 problems/python/is-subsequence.py | 0 problems/python/isomorphic-strings.py | 0 problems/python/jewels-and-stones.py | 0 problems/python/jump-game.py | 0 problems/python/k-closest-points-to-origin.py | 0 problems/python/k-empty-slots.py | 0 problems/python/keys-and-rooms.py | 0 problems/python/knight-dialer.py | 0 .../knight-probability-in-chessboard.py | 0 problems/python/koko-eating-bananas.py | 0 .../python/kth-largest-element-in-an-array.py | 0 .../python/kth-smallest-element-in-a-bst.py | 0 ...kth-smallest-element-in-a-sorted-matrix.py | 0 problems/python/largest-1-bordered-square.py | 0 problems/python/largest-bst-subtree.py | 0 problems/python/largest-sum-of-averages.py | 0 problems/python/last-stone-weight-ii.py | 0 problems/python/last-stone-weight.py | 0 ...ber-of-unique-integers-after-k-removals.py | 0 problems/python/letter-case-permutation.py | 0 .../letter-combinations-of-a-phone-number.py | 0 problems/python/license-key-formatting.py | 0 problems/python/linked-list-cycle-ii.py | 0 problems/python/linked-list-cycle.py | 0 problems/python/linked-list-random-node.py | 0 problems/python/logger-rate-limiter.py | 0 problems/python/longest-common-prefix.py | 0 problems/python/longest-common-subsequence.py | 0 .../python/longest-consecutive-sequence.py | 0 .../longest-increasing-path-in-a-matrix.py | 0 .../python/longest-increasing-subsequence.py | 0 .../python/longest-palindromic-subsequence.py | 0 .../python/longest-palindromic-substring.py | 0 ...longest-repeating-character-replacement.py | 0 problems/python/longest-string-chain.py | 0 ...ng-with-at-least-k-repeating-characters.py | 0 ...-substring-without-repeating-characters.py | 0 problems/python/longest-univalue-path.py | 0 ...common-ancestor-of-a-binary-search-tree.py | 0 ...west-common-ancestor-of-a-binary-search.py | 0 ...est-common-ancestor-of-a-binary-tree-ii.py | 0 ...st-common-ancestor-of-a-binary-tree-iii.py | 0 ...est-common-ancestor-of-a-binary-tree-iv.py | 0 ...lowest-common-ancestor-of-a-binary-tree.py | 0 ...owest-common-ancestor-of-deepest-leaves.py | 0 problems/python/lru-cache.py | 0 problems/python/majority-element-ii.py | 0 problems/python/majority-element.py | 0 problems/python/making-a-large-island.py | 0 problems/python/max-area-of-island.py | 0 problems/python/max-consecutive-ones-iii.py | 0 problems/python/max-stack.py | 0 .../max-sum-of-rectangle-no-larger-than-k.py | 0 problems/python/maximal-square.py | 0 problems/python/maximum-average-subtree.py | 0 .../python/maximum-compatibility-score-sum.py | 0 .../python/maximum-depth-of-binary-tree.py | 0 problems/python/maximum-gap.py | 0 .../maximum-length-of-repeated-subarray.py | 0 ...m-number-of-events-that-can-be-attended.py | 0 .../maximum-number-of-points-with-cost.py | 0 .../maximum-number-of-visible-points.py | 0 .../maximum-product-of-three-numbers.py | 0 problems/python/maximum-product-subarray.py | 0 .../maximum-subarray-sum-with-one-deletion.py | 0 problems/python/maximum-subarray.py | 0 problems/python/maximum-swap.py | 0 problems/python/maximum-units-on-a-truck.py | 0 .../python/median-of-two-sorted-arrays.py | 0 problems/python/meeting-rooms-ii.py | 0 problems/python/meeting-rooms.py | 0 problems/python/merge-intervals.py | 0 problems/python/merge-k-sorted-lists.py | 0 problems/python/merge-sorted-array.py | 0 problems/python/merge-two-sorted-lists.py | 0 problems/python/min-cost-climbing-stairs.py | 0 problems/python/min-stack.py | 0 problems/python/minimize-malware-spread.py | 0 .../minimum-absolute-difference-in-bst.py | 0 ...inimum-ascii-delete-sum-for-two-strings.py | 0 .../python/minimum-cost-to-connect-sticks.py | 0 .../python/minimum-cost-to-hire-k-workers.py | 0 ...-make-at-least-one-valid-path-in-a-grid.py | 0 ...nimum-cost-to-reach-city-with-discounts.py | 0 .../python/minimum-depth-of-binary-tree.py | 0 .../minimum-difficulty-of-a-job-schedule.py | 0 .../python/minimum-falling-path-sum-ii.py | 0 problems/python/minimum-knight-moves.py | 0 ...to-convert-binary-matrix-to-zero-matrix.py | 0 problems/python/minimum-path-sum.py | 0 .../minimum-score-triangulation-of-polygon.py | 0 problems/python/minimum-size-subarray-sum.py | 0 .../minimum-swaps-to-group-all-1s-together.py | 0 ...imum-swaps-to-make-sequences-increasing.py | 0 problems/python/minimum-time-difference.py | 0 problems/python/minimum-window-substring.py | 0 .../python/minimum-xor-sum-of-two-arrays.py | 0 problems/python/missing-number.py | 0 problems/python/most-frequent-subtree-sum.py | 0 ...-stones-removed-with-same-row-or-column.py | 0 problems/python/move-zeroes.py | 0 .../python/moving-average-from-data-stream.py | 0 problems/python/my-calendar-ii.py | 0 .../n-ary-tree-level-order-traversal.py | 0 .../python/n-ary-tree-postorder-traversal.py | 0 .../python/n-ary-tree-preorder-traversal.py | 0 problems/python/nested-list-weight-sum.py | 0 problems/python/network-delay-time.py | 0 problems/python/next-closest-time.py | 0 problems/python/next-permutation.py | 0 problems/python/number-complement.py | 0 ...ected-components-in-an-undirected-graph.py | 0 problems/python/number-of-islands-ii.py | 0 problems/python/number-of-islands.py | 0 ...umber-of-longest-increasing-subsequence.py | 0 .../python/number-of-matching-subsequences.py | 0 problems/python/number-of-provinces.py | 0 problems/python/number-of-recent-calls.py | 0 problems/python/number-of-squareful-arrays.py | 0 ...umber-of-substrings-containing-all-thre.py | 0 ...number-of-ways-to-arrive-at-destination.py | 0 problems/python/odd-even-jump.py | 0 problems/python/ones-and-zeroes.py | 0 problems/python/open-the-lock.py | 0 problems/python/out-of-boundary-paths.py | 0 .../python/pacific-atlantic-water-flow.py | 0 ...gs-with-total-durations-divisible-by-60.py | 0 problems/python/palindrome-number.py | 0 problems/python/palindrome-pairs.py | 0 .../python/palindrome-partitioning-iii.py | 0 problems/python/palindrome-partitioning.py | 0 problems/python/palindromic-substrings.py | 0 .../python/partition-array-for-maximum-sum.py | 0 problems/python/partition-labels.py | 0 .../partition-to-k-equal-sum-subsets.py | 0 problems/python/path-sum-ii.py | 0 problems/python/path-sum-iii.py | 0 problems/python/path-sum.py | 0 .../python/path-with-maximum-probability.py | 0 .../python/peak-index-in-a-mountain-array.py | 0 problems/python/perfect-squares.py | 0 problems/python/permutation-in-string.py | 0 problems/python/permutation-sequence.py | 0 problems/python/permutations-ii.py | 0 problems/python/permutations.py | 0 ...ing-next-right-pointers-in-each-node-ii.py | 0 ...lating-next-right-pointers-in-each-node.py | 0 problems/python/powx-n.py | 0 .../python/product-of-array-except-self.py | 0 problems/python/profitable-schemes.py | 0 .../python/queue-reconstruction-by-height.py | 0 problems/python/random-pick-with-weight.py | 0 problems/python/range-addition.py | 0 problems/python/range-sum-of-bst.py | 0 problems/python/range-sum-query-immutable.py | 0 problems/python/range-sum-query-mutable.py | 0 .../rearrange-string-k-distance-apart.py | 0 problems/python/reconstruct-itinerary.py | 0 problems/python/recover-binary-search-tree.py | 0 problems/python/redundant-connection.py | 0 ...emove-all-adjacent-duplicates-in-string.py | 0 ...move-all-ones-with-row-and-column-flips.py | 0 .../remove-duplicates-from-sorted-array-ii.py | 0 .../remove-duplicates-from-sorted-array.py | 0 .../remove-duplicates-from-sorted-list.py | 0 problems/python/remove-element.py | 0 problems/python/remove-invalid-parentheses.py | 0 .../python/remove-linked-list-elements.py | 0 .../remove-nth-node-from-end-of-list.py | 0 problems/python/reorder-list.py | 0 problems/python/repeated-string-match.py | 0 ...place-the-substring-for-balanced-string.py | 0 problems/python/restore-ip-addresses.py | 0 problems/python/reverse-integer.py | 0 problems/python/reverse-linked-list.py | 0 problems/python/reverse-string.py | 0 problems/python/reverse-vowels-of-a-string.py | 0 problems/python/reverse-words-in-a-string.py | 0 problems/python/robot-bounded-in-circle.py | 0 problems/python/roman-to-integer.py | 0 problems/python/rotate-array.py | 0 problems/python/rotate-image.py | 0 problems/python/russian-doll-envelopes.py | 0 problems/python/same-tree.py | 0 .../satisfiability-of-equality-equations.py | 0 problems/python/score-of-parentheses.py | 0 problems/python/search-a-2d-matrix.py | 0 .../python/search-in-a-binary-search-tree.py | 0 .../search-in-rotated-sorted-array-ii.py | 0 .../python/search-in-rotated-sorted-array.py | 0 problems/python/search-insert-position.py | 0 problems/python/search-suggestions-system.py | 0 problems/python/second-highest-salary.sql | 0 .../sell-diminishing-valued-colored-balls.py | 0 .../serialize-and-deserialize-binary-tree.py | 0 .../python/serialize-and-deserialize-bst.py | 0 problems/python/set-matrix-zeroes.py | 0 problems/python/shortest-bridge.py | 0 .../python/shortest-common-supersequence.py | 0 .../shortest-distance-from-all-buildings.py | 0 ...th-in-a-grid-with-obstacles-elimination.py | 0 .../python/shortest-path-in-binary-matrix.py | 0 problems/python/shortest-path-to-get-food.py | 0 problems/python/shuffle-an-array.py | 0 problems/python/simplify-path.py | 0 problems/python/single-threaded-cpu.py | 0 problems/python/sliding-window-maximum.py | 0 problems/python/snapshot-array.py | 0 problems/python/sort-colors.py | 0 problems/python/sort-list.py | 0 problems/python/spiral-matrix.py | 0 .../split-array-into-fibonacci-sequence.py | 0 problems/python/split-array-largest-sum.py | 0 problems/python/sqrtx.py | 0 problems/python/squares-of-a-sorted-array.py | 0 ...ions-from-a-binary-tree-node-to-another.py | 0 problems/python/stock-price-fluctuation.py | 0 problems/python/stone-game-ii.py | 0 .../python/student-attendance-record-ii.py | 0 problems/python/subarray-sum-equals-k.py | 0 .../subarrays-with-k-different-integers.py | 0 problems/python/subdomain-visit-count.py | 0 problems/python/subsets-ii.py | 0 problems/python/subsets.py | 0 ...bstring-with-concatenation-of-all-words.py | 0 problems/python/subtree-of-another-tree.py | 0 problems/python/sum-of-subarray-minimums.py | 0 problems/python/sum-root-to-leaf-numbers.py | 0 problems/python/summary-ranges.py | 0 problems/python/super-ugly-number.py | 0 problems/python/swap-adjacent-in-lr-string.py | 0 problems/python/swap-nodes-in-pairs.py | 0 problems/python/swim-in-rising-water.py | 0 problems/python/symmetric-tree.py | 0 problems/python/tallest-billboard.py | 0 problems/python/target-sum.py | 0 problems/python/task-scheduler.py | 0 problems/python/text-justification.py | 0 problems/python/the-kth-factor-of-n.py | 0 problems/python/the-maze-ii.py | 0 problems/python/time-based-key-value-store.py | 0 problems/python/to-lower-case.py | 0 problems/python/toeplitz-matrix.py | 0 problems/python/top-k-frequent-elements.py | 0 problems/python/trapping-rain-water-ii.py | 0 problems/python/trapping-rain-water.py | 0 problems/python/trim-a-binary-search-tree.py | 0 problems/python/two-out-of-three.py | 0 .../two-sum-ii-input-array-is-sorted.py | 0 problems/python/two-sum.py | 0 problems/python/ugly-number-ii.py | 0 problems/python/ugly-number.py | 0 problems/python/umber-of-islands-ii.py | 0 .../python/unique-binary-search-trees-ii,py | 0 problems/python/unique-binary-search-trees.py | 0 problems/python/unique-email-addres.py | 0 problems/python/unique-paths.py | 0 problems/python/univalued-binary-tree.py | 0 problems/python/valid-anagram.py | 0 problems/python/valid-number.py | 0 problems/python/valid-palindrome-ii.py | 0 problems/python/valid-palindrome.py | 0 problems/python/valid-parentheses.py | 0 problems/python/valid-word-abbreviation.py | 0 .../python/validate-binary-search-tree.py | 0 ...preorder-serialization-of-a-binary-tree.py | 0 ...rtical-order-traversal-of-a-binary-tree.py | 0 problems/python/wiggle-subsequence.py | 0 problems/python/word-break.py | 0 problems/python/word-ladder-ii.py | 0 problems/python/word-ladder.py | 0 problems/python/word-search-ii.py | 0 problems/python/word-search.py | 0 problems/python3/3sum-closest.py | 0 problems/python3/3sum-smaller.py | 0 problems/python3/3sum.py | 28 +++++++++++++++ problems/python3/4sum.py | 0 problems/python3/balanced-binary-tree.py | 0 .../binary-tree-level-order-traversal.py | 0 .../python3/binary-tree-maximum-path-sum.py | 27 ++++++++++++++ .../python3/binary-tree-right-side-view.py | 0 ...ree-from-preorder-and-inorder-traversal.py | 34 ++++++++++++++++++ problems/python3/container-with-most-water.py | 17 +++++++++ .../count-good-nodes-in-binary-tree.py | 0 problems/python3/diameter-of-binary-tree.py | 0 problems/python3/invert-binary-tree.py | 0 .../python3/kth-smallest-element-in-a-bst.py | 21 +++++++++++ ...common-ancestor-of-a-binary-search-tree.py | 0 .../python3/maximum-depth-of-binary-tree.py | 0 problems/python3/same-tree.py | 0 .../serialize-and-deserialize-binary-tree.py | 22 ++++++++++++ problems/python3/subsets.py | 22 ++++++++++++ ...bstring-with-concatenation-of-all-words.py | 0 problems/python3/subtree-of-another-tree.py | 0 problems/python3/trapping-rain-water.py | 35 +++++++++++++++++++ .../two-sum-ii-input-array-is-sorted.py | 11 ++++++ problems/python3/valid-palindrome.py | 15 ++++++++ .../python3/validate-binary-search-tree.py | 0 470 files changed, 232 insertions(+) mode change 100644 => 100755 .gitignore mode change 100644 => 100755 README.md mode change 100644 => 100755 "common/bellman\342\200\223ford.py" mode change 100644 => 100755 common/binary-search-tree.py mode change 100644 => 100755 common/bst-in-order.py mode change 100644 => 100755 common/dijkstra.py mode change 100644 => 100755 common/heap-sort.py mode change 100644 => 100755 common/insertion-sort.py mode change 100644 => 100755 common/knapsack.py mode change 100644 => 100755 common/merge-sort-in-place.py mode change 100644 => 100755 common/merge-sort.py mode change 100644 => 100755 common/min-heap.py mode change 100644 => 100755 common/quick-sort.py mode change 100644 => 100755 common/radix-sort.py mode change 100644 => 100755 common/trie.py mode change 100644 => 100755 problems/python/01-matrix.py mode change 100644 => 100755 problems/python/3sum-closest.py mode change 100644 => 100755 problems/python/3sum.py mode change 100644 => 100755 problems/python/4sum.py mode change 100644 => 100755 problems/python/accounts-merge.py mode change 100644 => 100755 problems/python/add-binary.py mode change 100644 => 100755 problems/python/add-digits.py mode change 100644 => 100755 problems/python/add-strings.py mode change 100644 => 100755 problems/python/add-two-numbers-ii.py mode change 100644 => 100755 problems/python/add-two-numbers.py mode change 100644 => 100755 problems/python/alien-dictionary.py mode change 100644 => 100755 problems/python/all-nodes-distance-k-in-binary-tree.py mode change 100644 => 100755 problems/python/amount-of-new-area-painted-each-day.py mode change 100644 => 100755 problems/python/analyze-user-website-visit-pattern.py mode change 100644 => 100755 problems/python/backspace-string-compare.py mode change 100644 => 100755 problems/python/balance-a-binary-search-tree.py mode change 100644 => 100755 problems/python/balanced-binary-tree.py mode change 100644 => 100755 problems/python/basic-calculator-ii.py mode change 100644 => 100755 problems/python/best-time-to-buy-an-stock.py mode change 100644 => 100755 problems/python/best-time-to-buy-and-sell-stock-iii.py mode change 100644 => 100755 problems/python/best-time-to-buy-and-sell-stock-with-cooldown.py mode change 100644 => 100755 problems/python/best-time-to-buy-and-sell-stock.py mode change 100644 => 100755 problems/python/big-countries.sql mode change 100644 => 100755 problems/python/binary-search-tree-iterator.py mode change 100644 => 100755 problems/python/binary-search.py mode change 100644 => 100755 problems/python/binary-subarrays-with-sum.py mode change 100644 => 100755 problems/python/binary-tree-inorder-traversal.py mode change 100644 => 100755 problems/python/binary-tree-level-order-traversal-ii.py mode change 100644 => 100755 problems/python/binary-tree-level-order-traversal.py mode change 100644 => 100755 problems/python/binary-tree-longest-consecutive-sequence.py mode change 100644 => 100755 problems/python/binary-tree-maximum-path-sum.py mode change 100644 => 100755 problems/python/binary-tree-paths.py mode change 100644 => 100755 problems/python/binary-tree-pruning.py mode change 100644 => 100755 problems/python/binary-tree-right-side-view.py mode change 100644 => 100755 problems/python/binary-tree-vertical-order-traversal.py mode change 100644 => 100755 problems/python/binary-watch.py mode change 100644 => 100755 problems/python/buildings-with-an-ocean-view.py mode change 100644 => 100755 problems/python/burst-balloons.py mode change 100644 => 100755 problems/python/campus-bikes-ii.py mode change 100644 => 100755 problems/python/candy.py mode change 100644 => 100755 problems/python/capacity-to-ship-packages-within-d-days.py mode change 100644 => 100755 problems/python/cheapest-flights-within-k-stops.py mode change 100644 => 100755 problems/python/climbing-stairs.py mode change 100644 => 100755 problems/python/clone-graph.py mode change 100644 => 100755 problems/python/closest-binary-search-tree-value.py mode change 100644 => 100755 problems/python/coin-change.py mode change 100644 => 100755 problems/python/coloring-a-border.py mode change 100644 => 100755 problems/python/combination-sum-ii.py mode change 100644 => 100755 problems/python/combination-sum-iii.py mode change 100644 => 100755 problems/python/combination-sum-iv.py mode change 100644 => 100755 problems/python/combination-sum.py mode change 100644 => 100755 problems/python/combinations.py mode change 100644 => 100755 problems/python/combine-two-tables.sql mode change 100644 => 100755 problems/python/compare-version-numbers.py mode change 100644 => 100755 problems/python/connecting-cities-with-minimum-cost.py mode change 100644 => 100755 problems/python/consecutive-numbers-sum.py mode change 100644 => 100755 problems/python/construct-binary-tree-from-inorder-and-postorder-traversal.py mode change 100644 => 100755 problems/python/construct-binary-tree-from-preorder-and-inorder-traversal.py mode change 100644 => 100755 problems/python/container-with-most-water.py mode change 100644 => 100755 problems/python/contains-duplicate-ii.py mode change 100644 => 100755 problems/python/contains-duplicate-iii.py mode change 100644 => 100755 problems/python/contains-duplicate.py mode change 100644 => 100755 problems/python/continuous-subarray-sum.py mode change 100644 => 100755 problems/python/convert-binary-search-tree-to-sorted-doubly-linked-list.py mode change 100644 => 100755 problems/python/convert-sorted-array-to-binary-search-tree.py mode change 100644 => 100755 problems/python/convert-sorted-list-to-binary-search-tree.py mode change 100644 => 100755 problems/python/copy-list-with-random-pointer.py mode change 100644 => 100755 problems/python/count-all-valid-pickup-and-delivery-opti.py mode change 100644 => 100755 problems/python/count-binary-substrings.py mode change 100644 => 100755 problems/python/count-complete-tree-nodes.py mode change 100644 => 100755 problems/python/count-number-of-nice-subarrays.py mode change 100644 => 100755 problems/python/count-unique-characters-of-all-substrings-of-a-given-string.py mode change 100644 => 100755 problems/python/course-schedule-ii.py mode change 100644 => 100755 problems/python/course-schedule.py mode change 100644 => 100755 problems/python/custom-sort-string.py mode change 100644 => 100755 problems/python/cutting-ribbons.py mode change 100644 => 100755 problems/python/data-stream-as-disjoint-intervals.py mode change 100644 => 100755 problems/python/decode-string.py mode change 100644 => 100755 problems/python/decode-ways.py mode change 100644 => 100755 problems/python/delete-and-earn.py mode change 100644 => 100755 problems/python/delete-duplicate-folders-in-system.py mode change 100644 => 100755 problems/python/delete-node-in-a-bst.py mode change 100644 => 100755 problems/python/delete-operation-for-two-strings.py mode change 100644 => 100755 problems/python/design-add-and-search-words-data-structure.py mode change 100644 => 100755 problems/python/design-in-memory-file-system.py mode change 100644 => 100755 problems/python/design-linked-list.py mode change 100644 => 100755 problems/python/design-tic-tac-toe.py mode change 100644 => 100755 problems/python/diagonal-traverse.py mode change 100644 => 100755 problems/python/diameter-of-binary-tree.py mode change 100644 => 100755 problems/python/different-ways-to-add-parentheses.py mode change 100644 => 100755 problems/python/distinct-subsequences.py mode change 100644 => 100755 problems/python/distribute-coins-in-binary-tree.py mode change 100644 => 100755 problems/python/domino-and-tromino-tiling.py mode change 100644 => 100755 problems/python/dot-product-of-two-sparse-vectors.py mode change 100644 => 100755 problems/python/dungeon-game.py mode change 100644 => 100755 problems/python/edit-distance.py mode change 100644 => 100755 problems/python/egions-cut-by-slashes.py mode change 100644 => 100755 problems/python/evaluate-division.py mode change 100644 => 100755 problems/python/evaluate-reverse-polish-notation.py mode change 100644 => 100755 problems/python/exclusive-time-of-functions.py mode change 100644 => 100755 problems/python/expression-add-operators.py mode change 100644 => 100755 problems/python/filling-bookcase-shelves.py mode change 100644 => 100755 problems/python/find-all-possible-recipes-from-given-supplies.py mode change 100644 => 100755 problems/python/find-and-replace-in-string.py mode change 100644 => 100755 problems/python/find-distance-in-a-binary-tree.py mode change 100644 => 100755 problems/python/find-duplicate-subtrees.py mode change 100644 => 100755 problems/python/find-eventual-safe-states.py mode change 100644 => 100755 problems/python/find-first-and-last-position-of-element-in-sorted-array.py mode change 100644 => 100755 problems/python/find-k-closest-elements.py mode change 100644 => 100755 problems/python/find-k-pairs-with-smallest-sums.py mode change 100644 => 100755 problems/python/find-leaves-of-binary-tree.py mode change 100644 => 100755 problems/python/find-median-from-data-stream.py mode change 100644 => 100755 problems/python/find-minimum-in-rotated-sorted-array-ii.py mode change 100644 => 100755 problems/python/find-minimum-in-rotated-sorted-array.py mode change 100644 => 100755 problems/python/find-mode-in-binary-search-tree.py mode change 100644 => 100755 problems/python/find-original-array-from-doubled-array,py mode change 100644 => 100755 problems/python/find-peak-element.py mode change 100644 => 100755 problems/python/find-the-duplicate-number.py mode change 100644 => 100755 problems/python/first-bad-version.py mode change 100644 => 100755 problems/python/first-missing-positive.py mode change 100644 => 100755 problems/python/first-unique-character-in-a-string.py mode change 100644 => 100755 problems/python/fizz-buzz.py mode change 100644 => 100755 problems/python/flatten-binary-tree-to-linked-list.py mode change 100644 => 100755 problems/python/flip-binary-tree-to-match-preorder-traversal.py mode change 100644 => 100755 problems/python/flip-string-to-monotone-increasing.py mode change 100644 => 100755 problems/python/flood-fill.py mode change 100644 => 100755 problems/python/friend-circles.py mode change 100644 => 100755 problems/python/fruit-into-baskets.py mode change 100644 => 100755 problems/python/game-of-life.py mode change 100644 => 100755 problems/python/generate-parentheses.py mode change 100644 => 100755 problems/python/graph-valid-tree.py mode change 100644 => 100755 problems/python/greatest-sum-divisible-by-three.py mode change 100644 => 100755 problems/python/group-anagrams.py mode change 100644 => 100755 problems/python/group-shifted-strings.py mode change 100644 => 100755 problems/python/guess-number-higher-or-lower-ii.py mode change 100644 => 100755 problems/python/guess-number-higher-or-lower.py mode change 100644 => 100755 problems/python/guess-the-word.py mode change 100644 => 100755 problems/python/h-index-ii.py mode change 100644 => 100755 problems/python/h-index.py mode change 100644 => 100755 problems/python/hamming-distance.py mode change 100644 => 100755 problems/python/house-robber-ii.py mode change 100644 => 100755 problems/python/house-robber-iii.py mode change 100644 => 100755 problems/python/house-robber.py mode change 100644 => 100755 problems/python/implement-trie-prefix-tree.py mode change 100644 => 100755 problems/python/increasing-triplet-subsequence.py mode change 100644 => 100755 problems/python/inorder-successor-in-bst-ii.py mode change 100644 => 100755 problems/python/inorder-successor-in-bst.py mode change 100644 => 100755 problems/python/insert-interval.py mode change 100644 => 100755 problems/python/insert-into-a-binary-search-tree.py mode change 100644 => 100755 problems/python/insert-into-a-sorted-circular-linked-list.py mode change 100644 => 100755 problems/python/insertion-sort-list.py mode change 100644 => 100755 problems/python/integer-to-english-words.py mode change 100644 => 100755 problems/python/interleaving-string.py mode change 100644 => 100755 problems/python/intersection-of-two-arrays-ii.py mode change 100644 => 100755 problems/python/intersection-of-two-arrays.py mode change 100644 => 100755 problems/python/invert-binary-tree.py mode change 100644 => 100755 problems/python/is-graph-bipartite.py mode change 100644 => 100755 problems/python/is-subsequence.py mode change 100644 => 100755 problems/python/isomorphic-strings.py mode change 100644 => 100755 problems/python/jewels-and-stones.py mode change 100644 => 100755 problems/python/jump-game.py mode change 100644 => 100755 problems/python/k-closest-points-to-origin.py mode change 100644 => 100755 problems/python/k-empty-slots.py mode change 100644 => 100755 problems/python/keys-and-rooms.py mode change 100644 => 100755 problems/python/knight-dialer.py mode change 100644 => 100755 problems/python/knight-probability-in-chessboard.py mode change 100644 => 100755 problems/python/koko-eating-bananas.py mode change 100644 => 100755 problems/python/kth-largest-element-in-an-array.py mode change 100644 => 100755 problems/python/kth-smallest-element-in-a-bst.py mode change 100644 => 100755 problems/python/kth-smallest-element-in-a-sorted-matrix.py mode change 100644 => 100755 problems/python/largest-1-bordered-square.py mode change 100644 => 100755 problems/python/largest-bst-subtree.py mode change 100644 => 100755 problems/python/largest-sum-of-averages.py mode change 100644 => 100755 problems/python/last-stone-weight-ii.py mode change 100644 => 100755 problems/python/last-stone-weight.py mode change 100644 => 100755 problems/python/least-number-of-unique-integers-after-k-removals.py mode change 100644 => 100755 problems/python/letter-case-permutation.py mode change 100644 => 100755 problems/python/letter-combinations-of-a-phone-number.py mode change 100644 => 100755 problems/python/license-key-formatting.py mode change 100644 => 100755 problems/python/linked-list-cycle-ii.py mode change 100644 => 100755 problems/python/linked-list-cycle.py mode change 100644 => 100755 problems/python/linked-list-random-node.py mode change 100644 => 100755 problems/python/logger-rate-limiter.py mode change 100644 => 100755 problems/python/longest-common-prefix.py mode change 100644 => 100755 problems/python/longest-common-subsequence.py mode change 100644 => 100755 problems/python/longest-consecutive-sequence.py mode change 100644 => 100755 problems/python/longest-increasing-path-in-a-matrix.py mode change 100644 => 100755 problems/python/longest-increasing-subsequence.py mode change 100644 => 100755 problems/python/longest-palindromic-subsequence.py mode change 100644 => 100755 problems/python/longest-palindromic-substring.py mode change 100644 => 100755 problems/python/longest-repeating-character-replacement.py mode change 100644 => 100755 problems/python/longest-string-chain.py mode change 100644 => 100755 problems/python/longest-substring-with-at-least-k-repeating-characters.py mode change 100644 => 100755 problems/python/longest-substring-without-repeating-characters.py mode change 100644 => 100755 problems/python/longest-univalue-path.py mode change 100644 => 100755 problems/python/lowest-common-ancestor-of-a-binary-search-tree.py mode change 100644 => 100755 problems/python/lowest-common-ancestor-of-a-binary-search.py mode change 100644 => 100755 problems/python/lowest-common-ancestor-of-a-binary-tree-ii.py mode change 100644 => 100755 problems/python/lowest-common-ancestor-of-a-binary-tree-iii.py mode change 100644 => 100755 problems/python/lowest-common-ancestor-of-a-binary-tree-iv.py mode change 100644 => 100755 problems/python/lowest-common-ancestor-of-a-binary-tree.py mode change 100644 => 100755 problems/python/lowest-common-ancestor-of-deepest-leaves.py mode change 100644 => 100755 problems/python/lru-cache.py mode change 100644 => 100755 problems/python/majority-element-ii.py mode change 100644 => 100755 problems/python/majority-element.py mode change 100644 => 100755 problems/python/making-a-large-island.py mode change 100644 => 100755 problems/python/max-area-of-island.py mode change 100644 => 100755 problems/python/max-consecutive-ones-iii.py mode change 100644 => 100755 problems/python/max-stack.py mode change 100644 => 100755 problems/python/max-sum-of-rectangle-no-larger-than-k.py mode change 100644 => 100755 problems/python/maximal-square.py mode change 100644 => 100755 problems/python/maximum-average-subtree.py mode change 100644 => 100755 problems/python/maximum-compatibility-score-sum.py mode change 100644 => 100755 problems/python/maximum-depth-of-binary-tree.py mode change 100644 => 100755 problems/python/maximum-gap.py mode change 100644 => 100755 problems/python/maximum-length-of-repeated-subarray.py mode change 100644 => 100755 problems/python/maximum-number-of-events-that-can-be-attended.py mode change 100644 => 100755 problems/python/maximum-number-of-points-with-cost.py mode change 100644 => 100755 problems/python/maximum-number-of-visible-points.py mode change 100644 => 100755 problems/python/maximum-product-of-three-numbers.py mode change 100644 => 100755 problems/python/maximum-product-subarray.py mode change 100644 => 100755 problems/python/maximum-subarray-sum-with-one-deletion.py mode change 100644 => 100755 problems/python/maximum-subarray.py mode change 100644 => 100755 problems/python/maximum-swap.py mode change 100644 => 100755 problems/python/maximum-units-on-a-truck.py mode change 100644 => 100755 problems/python/median-of-two-sorted-arrays.py mode change 100644 => 100755 problems/python/meeting-rooms-ii.py mode change 100644 => 100755 problems/python/meeting-rooms.py mode change 100644 => 100755 problems/python/merge-intervals.py mode change 100644 => 100755 problems/python/merge-k-sorted-lists.py mode change 100644 => 100755 problems/python/merge-sorted-array.py mode change 100644 => 100755 problems/python/merge-two-sorted-lists.py mode change 100644 => 100755 problems/python/min-cost-climbing-stairs.py mode change 100644 => 100755 problems/python/min-stack.py mode change 100644 => 100755 problems/python/minimize-malware-spread.py mode change 100644 => 100755 problems/python/minimum-absolute-difference-in-bst.py mode change 100644 => 100755 problems/python/minimum-ascii-delete-sum-for-two-strings.py mode change 100644 => 100755 problems/python/minimum-cost-to-connect-sticks.py mode change 100644 => 100755 problems/python/minimum-cost-to-hire-k-workers.py mode change 100644 => 100755 problems/python/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py mode change 100644 => 100755 problems/python/minimum-cost-to-reach-city-with-discounts.py mode change 100644 => 100755 problems/python/minimum-depth-of-binary-tree.py mode change 100644 => 100755 problems/python/minimum-difficulty-of-a-job-schedule.py mode change 100644 => 100755 problems/python/minimum-falling-path-sum-ii.py mode change 100644 => 100755 problems/python/minimum-knight-moves.py mode change 100644 => 100755 problems/python/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py mode change 100644 => 100755 problems/python/minimum-path-sum.py mode change 100644 => 100755 problems/python/minimum-score-triangulation-of-polygon.py mode change 100644 => 100755 problems/python/minimum-size-subarray-sum.py mode change 100644 => 100755 problems/python/minimum-swaps-to-group-all-1s-together.py mode change 100644 => 100755 problems/python/minimum-swaps-to-make-sequences-increasing.py mode change 100644 => 100755 problems/python/minimum-time-difference.py mode change 100644 => 100755 problems/python/minimum-window-substring.py mode change 100644 => 100755 problems/python/minimum-xor-sum-of-two-arrays.py mode change 100644 => 100755 problems/python/missing-number.py mode change 100644 => 100755 problems/python/most-frequent-subtree-sum.py mode change 100644 => 100755 problems/python/most-stones-removed-with-same-row-or-column.py mode change 100644 => 100755 problems/python/move-zeroes.py mode change 100644 => 100755 problems/python/moving-average-from-data-stream.py mode change 100644 => 100755 problems/python/my-calendar-ii.py mode change 100644 => 100755 problems/python/n-ary-tree-level-order-traversal.py mode change 100644 => 100755 problems/python/n-ary-tree-postorder-traversal.py mode change 100644 => 100755 problems/python/n-ary-tree-preorder-traversal.py mode change 100644 => 100755 problems/python/nested-list-weight-sum.py mode change 100644 => 100755 problems/python/network-delay-time.py mode change 100644 => 100755 problems/python/next-closest-time.py mode change 100644 => 100755 problems/python/next-permutation.py mode change 100644 => 100755 problems/python/number-complement.py mode change 100644 => 100755 problems/python/number-of-connected-components-in-an-undirected-graph.py mode change 100644 => 100755 problems/python/number-of-islands-ii.py mode change 100644 => 100755 problems/python/number-of-islands.py mode change 100644 => 100755 problems/python/number-of-longest-increasing-subsequence.py mode change 100644 => 100755 problems/python/number-of-matching-subsequences.py mode change 100644 => 100755 problems/python/number-of-provinces.py mode change 100644 => 100755 problems/python/number-of-recent-calls.py mode change 100644 => 100755 problems/python/number-of-squareful-arrays.py mode change 100644 => 100755 problems/python/number-of-substrings-containing-all-thre.py mode change 100644 => 100755 problems/python/number-of-ways-to-arrive-at-destination.py mode change 100644 => 100755 problems/python/odd-even-jump.py mode change 100644 => 100755 problems/python/ones-and-zeroes.py mode change 100644 => 100755 problems/python/open-the-lock.py mode change 100644 => 100755 problems/python/out-of-boundary-paths.py mode change 100644 => 100755 problems/python/pacific-atlantic-water-flow.py mode change 100644 => 100755 problems/python/pairs-of-songs-with-total-durations-divisible-by-60.py mode change 100644 => 100755 problems/python/palindrome-number.py mode change 100644 => 100755 problems/python/palindrome-pairs.py mode change 100644 => 100755 problems/python/palindrome-partitioning-iii.py mode change 100644 => 100755 problems/python/palindrome-partitioning.py mode change 100644 => 100755 problems/python/palindromic-substrings.py mode change 100644 => 100755 problems/python/partition-array-for-maximum-sum.py mode change 100644 => 100755 problems/python/partition-labels.py mode change 100644 => 100755 problems/python/partition-to-k-equal-sum-subsets.py mode change 100644 => 100755 problems/python/path-sum-ii.py mode change 100644 => 100755 problems/python/path-sum-iii.py mode change 100644 => 100755 problems/python/path-sum.py mode change 100644 => 100755 problems/python/path-with-maximum-probability.py mode change 100644 => 100755 problems/python/peak-index-in-a-mountain-array.py mode change 100644 => 100755 problems/python/perfect-squares.py mode change 100644 => 100755 problems/python/permutation-in-string.py mode change 100644 => 100755 problems/python/permutation-sequence.py mode change 100644 => 100755 problems/python/permutations-ii.py mode change 100644 => 100755 problems/python/permutations.py mode change 100644 => 100755 problems/python/populating-next-right-pointers-in-each-node-ii.py mode change 100644 => 100755 problems/python/populating-next-right-pointers-in-each-node.py mode change 100644 => 100755 problems/python/powx-n.py mode change 100644 => 100755 problems/python/product-of-array-except-self.py mode change 100644 => 100755 problems/python/profitable-schemes.py mode change 100644 => 100755 problems/python/queue-reconstruction-by-height.py mode change 100644 => 100755 problems/python/random-pick-with-weight.py mode change 100644 => 100755 problems/python/range-addition.py mode change 100644 => 100755 problems/python/range-sum-of-bst.py mode change 100644 => 100755 problems/python/range-sum-query-immutable.py mode change 100644 => 100755 problems/python/range-sum-query-mutable.py mode change 100644 => 100755 problems/python/rearrange-string-k-distance-apart.py mode change 100644 => 100755 problems/python/reconstruct-itinerary.py mode change 100644 => 100755 problems/python/recover-binary-search-tree.py mode change 100644 => 100755 problems/python/redundant-connection.py mode change 100644 => 100755 problems/python/remove-all-adjacent-duplicates-in-string.py mode change 100644 => 100755 problems/python/remove-all-ones-with-row-and-column-flips.py mode change 100644 => 100755 problems/python/remove-duplicates-from-sorted-array-ii.py mode change 100644 => 100755 problems/python/remove-duplicates-from-sorted-array.py mode change 100644 => 100755 problems/python/remove-duplicates-from-sorted-list.py mode change 100644 => 100755 problems/python/remove-element.py mode change 100644 => 100755 problems/python/remove-invalid-parentheses.py mode change 100644 => 100755 problems/python/remove-linked-list-elements.py mode change 100644 => 100755 problems/python/remove-nth-node-from-end-of-list.py mode change 100644 => 100755 problems/python/reorder-list.py mode change 100644 => 100755 problems/python/repeated-string-match.py mode change 100644 => 100755 problems/python/replace-the-substring-for-balanced-string.py mode change 100644 => 100755 problems/python/restore-ip-addresses.py mode change 100644 => 100755 problems/python/reverse-integer.py mode change 100644 => 100755 problems/python/reverse-linked-list.py mode change 100644 => 100755 problems/python/reverse-string.py mode change 100644 => 100755 problems/python/reverse-vowels-of-a-string.py mode change 100644 => 100755 problems/python/reverse-words-in-a-string.py mode change 100644 => 100755 problems/python/robot-bounded-in-circle.py mode change 100644 => 100755 problems/python/roman-to-integer.py mode change 100644 => 100755 problems/python/rotate-array.py mode change 100644 => 100755 problems/python/rotate-image.py mode change 100644 => 100755 problems/python/russian-doll-envelopes.py mode change 100644 => 100755 problems/python/same-tree.py mode change 100644 => 100755 problems/python/satisfiability-of-equality-equations.py mode change 100644 => 100755 problems/python/score-of-parentheses.py mode change 100644 => 100755 problems/python/search-a-2d-matrix.py mode change 100644 => 100755 problems/python/search-in-a-binary-search-tree.py mode change 100644 => 100755 problems/python/search-in-rotated-sorted-array-ii.py mode change 100644 => 100755 problems/python/search-in-rotated-sorted-array.py mode change 100644 => 100755 problems/python/search-insert-position.py mode change 100644 => 100755 problems/python/search-suggestions-system.py mode change 100644 => 100755 problems/python/second-highest-salary.sql mode change 100644 => 100755 problems/python/sell-diminishing-valued-colored-balls.py mode change 100644 => 100755 problems/python/serialize-and-deserialize-binary-tree.py mode change 100644 => 100755 problems/python/serialize-and-deserialize-bst.py mode change 100644 => 100755 problems/python/set-matrix-zeroes.py mode change 100644 => 100755 problems/python/shortest-bridge.py mode change 100644 => 100755 problems/python/shortest-common-supersequence.py mode change 100644 => 100755 problems/python/shortest-distance-from-all-buildings.py mode change 100644 => 100755 problems/python/shortest-path-in-a-grid-with-obstacles-elimination.py mode change 100644 => 100755 problems/python/shortest-path-in-binary-matrix.py mode change 100644 => 100755 problems/python/shortest-path-to-get-food.py mode change 100644 => 100755 problems/python/shuffle-an-array.py mode change 100644 => 100755 problems/python/simplify-path.py mode change 100644 => 100755 problems/python/single-threaded-cpu.py mode change 100644 => 100755 problems/python/sliding-window-maximum.py mode change 100644 => 100755 problems/python/snapshot-array.py mode change 100644 => 100755 problems/python/sort-colors.py mode change 100644 => 100755 problems/python/sort-list.py mode change 100644 => 100755 problems/python/spiral-matrix.py mode change 100644 => 100755 problems/python/split-array-into-fibonacci-sequence.py mode change 100644 => 100755 problems/python/split-array-largest-sum.py mode change 100644 => 100755 problems/python/sqrtx.py mode change 100644 => 100755 problems/python/squares-of-a-sorted-array.py mode change 100644 => 100755 problems/python/step-by-step-directions-from-a-binary-tree-node-to-another.py mode change 100644 => 100755 problems/python/stock-price-fluctuation.py mode change 100644 => 100755 problems/python/stone-game-ii.py mode change 100644 => 100755 problems/python/student-attendance-record-ii.py mode change 100644 => 100755 problems/python/subarray-sum-equals-k.py mode change 100644 => 100755 problems/python/subarrays-with-k-different-integers.py mode change 100644 => 100755 problems/python/subdomain-visit-count.py mode change 100644 => 100755 problems/python/subsets-ii.py mode change 100644 => 100755 problems/python/subsets.py mode change 100644 => 100755 problems/python/substring-with-concatenation-of-all-words.py mode change 100644 => 100755 problems/python/subtree-of-another-tree.py mode change 100644 => 100755 problems/python/sum-of-subarray-minimums.py mode change 100644 => 100755 problems/python/sum-root-to-leaf-numbers.py mode change 100644 => 100755 problems/python/summary-ranges.py mode change 100644 => 100755 problems/python/super-ugly-number.py mode change 100644 => 100755 problems/python/swap-adjacent-in-lr-string.py mode change 100644 => 100755 problems/python/swap-nodes-in-pairs.py mode change 100644 => 100755 problems/python/swim-in-rising-water.py mode change 100644 => 100755 problems/python/symmetric-tree.py mode change 100644 => 100755 problems/python/tallest-billboard.py mode change 100644 => 100755 problems/python/target-sum.py mode change 100644 => 100755 problems/python/task-scheduler.py mode change 100644 => 100755 problems/python/text-justification.py mode change 100644 => 100755 problems/python/the-kth-factor-of-n.py mode change 100644 => 100755 problems/python/the-maze-ii.py mode change 100644 => 100755 problems/python/time-based-key-value-store.py mode change 100644 => 100755 problems/python/to-lower-case.py mode change 100644 => 100755 problems/python/toeplitz-matrix.py mode change 100644 => 100755 problems/python/top-k-frequent-elements.py mode change 100644 => 100755 problems/python/trapping-rain-water-ii.py mode change 100644 => 100755 problems/python/trapping-rain-water.py mode change 100644 => 100755 problems/python/trim-a-binary-search-tree.py mode change 100644 => 100755 problems/python/two-out-of-three.py mode change 100644 => 100755 problems/python/two-sum-ii-input-array-is-sorted.py mode change 100644 => 100755 problems/python/two-sum.py mode change 100644 => 100755 problems/python/ugly-number-ii.py mode change 100644 => 100755 problems/python/ugly-number.py mode change 100644 => 100755 problems/python/umber-of-islands-ii.py mode change 100644 => 100755 problems/python/unique-binary-search-trees-ii,py mode change 100644 => 100755 problems/python/unique-binary-search-trees.py mode change 100644 => 100755 problems/python/unique-email-addres.py mode change 100644 => 100755 problems/python/unique-paths.py mode change 100644 => 100755 problems/python/univalued-binary-tree.py mode change 100644 => 100755 problems/python/valid-anagram.py mode change 100644 => 100755 problems/python/valid-number.py mode change 100644 => 100755 problems/python/valid-palindrome-ii.py mode change 100644 => 100755 problems/python/valid-palindrome.py mode change 100644 => 100755 problems/python/valid-parentheses.py mode change 100644 => 100755 problems/python/valid-word-abbreviation.py mode change 100644 => 100755 problems/python/validate-binary-search-tree.py mode change 100644 => 100755 problems/python/verify-preorder-serialization-of-a-binary-tree.py mode change 100644 => 100755 problems/python/vertical-order-traversal-of-a-binary-tree.py mode change 100644 => 100755 problems/python/wiggle-subsequence.py mode change 100644 => 100755 problems/python/word-break.py mode change 100644 => 100755 problems/python/word-ladder-ii.py mode change 100644 => 100755 problems/python/word-ladder.py mode change 100644 => 100755 problems/python/word-search-ii.py mode change 100644 => 100755 problems/python/word-search.py mode change 100644 => 100755 problems/python3/3sum-closest.py mode change 100644 => 100755 problems/python3/3sum-smaller.py mode change 100644 => 100755 problems/python3/3sum.py mode change 100644 => 100755 problems/python3/4sum.py mode change 100644 => 100755 problems/python3/balanced-binary-tree.py mode change 100644 => 100755 problems/python3/binary-tree-level-order-traversal.py create mode 100644 problems/python3/binary-tree-maximum-path-sum.py mode change 100644 => 100755 problems/python3/binary-tree-right-side-view.py create mode 100644 problems/python3/construct-binary-tree-from-preorder-and-inorder-traversal.py mode change 100644 => 100755 problems/python3/container-with-most-water.py mode change 100644 => 100755 problems/python3/count-good-nodes-in-binary-tree.py mode change 100644 => 100755 problems/python3/diameter-of-binary-tree.py mode change 100644 => 100755 problems/python3/invert-binary-tree.py create mode 100755 problems/python3/kth-smallest-element-in-a-bst.py mode change 100644 => 100755 problems/python3/lowest-common-ancestor-of-a-binary-search-tree.py mode change 100644 => 100755 problems/python3/maximum-depth-of-binary-tree.py mode change 100644 => 100755 problems/python3/same-tree.py create mode 100644 problems/python3/serialize-and-deserialize-binary-tree.py create mode 100644 problems/python3/subsets.py mode change 100644 => 100755 problems/python3/substring-with-concatenation-of-all-words.py mode change 100644 => 100755 problems/python3/subtree-of-another-tree.py create mode 100644 problems/python3/trapping-rain-water.py create mode 100644 problems/python3/two-sum-ii-input-array-is-sorted.py create mode 100644 problems/python3/valid-palindrome.py mode change 100644 => 100755 problems/python3/validate-binary-search-tree.py diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git "a/common/bellman\342\200\223ford.py" "b/common/bellman\342\200\223ford.py" old mode 100644 new mode 100755 diff --git a/common/binary-search-tree.py b/common/binary-search-tree.py old mode 100644 new mode 100755 diff --git a/common/bst-in-order.py b/common/bst-in-order.py old mode 100644 new mode 100755 diff --git a/common/dijkstra.py b/common/dijkstra.py old mode 100644 new mode 100755 diff --git a/common/heap-sort.py b/common/heap-sort.py old mode 100644 new mode 100755 diff --git a/common/insertion-sort.py b/common/insertion-sort.py old mode 100644 new mode 100755 diff --git a/common/knapsack.py b/common/knapsack.py old mode 100644 new mode 100755 diff --git a/common/merge-sort-in-place.py b/common/merge-sort-in-place.py old mode 100644 new mode 100755 diff --git a/common/merge-sort.py b/common/merge-sort.py old mode 100644 new mode 100755 diff --git a/common/min-heap.py b/common/min-heap.py old mode 100644 new mode 100755 diff --git a/common/quick-sort.py b/common/quick-sort.py old mode 100644 new mode 100755 diff --git a/common/radix-sort.py b/common/radix-sort.py old mode 100644 new mode 100755 diff --git a/common/trie.py b/common/trie.py old mode 100644 new mode 100755 diff --git a/problems/python/01-matrix.py b/problems/python/01-matrix.py old mode 100644 new mode 100755 diff --git a/problems/python/3sum-closest.py b/problems/python/3sum-closest.py old mode 100644 new mode 100755 diff --git a/problems/python/3sum.py b/problems/python/3sum.py old mode 100644 new mode 100755 diff --git a/problems/python/4sum.py b/problems/python/4sum.py old mode 100644 new mode 100755 diff --git a/problems/python/accounts-merge.py b/problems/python/accounts-merge.py old mode 100644 new mode 100755 diff --git a/problems/python/add-binary.py b/problems/python/add-binary.py old mode 100644 new mode 100755 diff --git a/problems/python/add-digits.py b/problems/python/add-digits.py old mode 100644 new mode 100755 diff --git a/problems/python/add-strings.py b/problems/python/add-strings.py old mode 100644 new mode 100755 diff --git a/problems/python/add-two-numbers-ii.py b/problems/python/add-two-numbers-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/add-two-numbers.py b/problems/python/add-two-numbers.py old mode 100644 new mode 100755 diff --git a/problems/python/alien-dictionary.py b/problems/python/alien-dictionary.py old mode 100644 new mode 100755 diff --git a/problems/python/all-nodes-distance-k-in-binary-tree.py b/problems/python/all-nodes-distance-k-in-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/amount-of-new-area-painted-each-day.py b/problems/python/amount-of-new-area-painted-each-day.py old mode 100644 new mode 100755 diff --git a/problems/python/analyze-user-website-visit-pattern.py b/problems/python/analyze-user-website-visit-pattern.py old mode 100644 new mode 100755 diff --git a/problems/python/backspace-string-compare.py b/problems/python/backspace-string-compare.py old mode 100644 new mode 100755 diff --git a/problems/python/balance-a-binary-search-tree.py b/problems/python/balance-a-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/balanced-binary-tree.py b/problems/python/balanced-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/basic-calculator-ii.py b/problems/python/basic-calculator-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/best-time-to-buy-an-stock.py b/problems/python/best-time-to-buy-an-stock.py old mode 100644 new mode 100755 diff --git a/problems/python/best-time-to-buy-and-sell-stock-iii.py b/problems/python/best-time-to-buy-and-sell-stock-iii.py old mode 100644 new mode 100755 diff --git a/problems/python/best-time-to-buy-and-sell-stock-with-cooldown.py b/problems/python/best-time-to-buy-and-sell-stock-with-cooldown.py old mode 100644 new mode 100755 diff --git a/problems/python/best-time-to-buy-and-sell-stock.py b/problems/python/best-time-to-buy-and-sell-stock.py old mode 100644 new mode 100755 diff --git a/problems/python/big-countries.sql b/problems/python/big-countries.sql old mode 100644 new mode 100755 diff --git a/problems/python/binary-search-tree-iterator.py b/problems/python/binary-search-tree-iterator.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-search.py b/problems/python/binary-search.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-subarrays-with-sum.py b/problems/python/binary-subarrays-with-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-tree-inorder-traversal.py b/problems/python/binary-tree-inorder-traversal.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-tree-level-order-traversal-ii.py b/problems/python/binary-tree-level-order-traversal-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-tree-level-order-traversal.py b/problems/python/binary-tree-level-order-traversal.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-tree-longest-consecutive-sequence.py b/problems/python/binary-tree-longest-consecutive-sequence.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-tree-maximum-path-sum.py b/problems/python/binary-tree-maximum-path-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-tree-paths.py b/problems/python/binary-tree-paths.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-tree-pruning.py b/problems/python/binary-tree-pruning.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-tree-right-side-view.py b/problems/python/binary-tree-right-side-view.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-tree-vertical-order-traversal.py b/problems/python/binary-tree-vertical-order-traversal.py old mode 100644 new mode 100755 diff --git a/problems/python/binary-watch.py b/problems/python/binary-watch.py old mode 100644 new mode 100755 diff --git a/problems/python/buildings-with-an-ocean-view.py b/problems/python/buildings-with-an-ocean-view.py old mode 100644 new mode 100755 diff --git a/problems/python/burst-balloons.py b/problems/python/burst-balloons.py old mode 100644 new mode 100755 diff --git a/problems/python/campus-bikes-ii.py b/problems/python/campus-bikes-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/candy.py b/problems/python/candy.py old mode 100644 new mode 100755 diff --git a/problems/python/capacity-to-ship-packages-within-d-days.py b/problems/python/capacity-to-ship-packages-within-d-days.py old mode 100644 new mode 100755 diff --git a/problems/python/cheapest-flights-within-k-stops.py b/problems/python/cheapest-flights-within-k-stops.py old mode 100644 new mode 100755 diff --git a/problems/python/climbing-stairs.py b/problems/python/climbing-stairs.py old mode 100644 new mode 100755 diff --git a/problems/python/clone-graph.py b/problems/python/clone-graph.py old mode 100644 new mode 100755 diff --git a/problems/python/closest-binary-search-tree-value.py b/problems/python/closest-binary-search-tree-value.py old mode 100644 new mode 100755 diff --git a/problems/python/coin-change.py b/problems/python/coin-change.py old mode 100644 new mode 100755 diff --git a/problems/python/coloring-a-border.py b/problems/python/coloring-a-border.py old mode 100644 new mode 100755 diff --git a/problems/python/combination-sum-ii.py b/problems/python/combination-sum-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/combination-sum-iii.py b/problems/python/combination-sum-iii.py old mode 100644 new mode 100755 diff --git a/problems/python/combination-sum-iv.py b/problems/python/combination-sum-iv.py old mode 100644 new mode 100755 diff --git a/problems/python/combination-sum.py b/problems/python/combination-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/combinations.py b/problems/python/combinations.py old mode 100644 new mode 100755 diff --git a/problems/python/combine-two-tables.sql b/problems/python/combine-two-tables.sql old mode 100644 new mode 100755 diff --git a/problems/python/compare-version-numbers.py b/problems/python/compare-version-numbers.py old mode 100644 new mode 100755 diff --git a/problems/python/connecting-cities-with-minimum-cost.py b/problems/python/connecting-cities-with-minimum-cost.py old mode 100644 new mode 100755 diff --git a/problems/python/consecutive-numbers-sum.py b/problems/python/consecutive-numbers-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/construct-binary-tree-from-inorder-and-postorder-traversal.py b/problems/python/construct-binary-tree-from-inorder-and-postorder-traversal.py old mode 100644 new mode 100755 diff --git a/problems/python/construct-binary-tree-from-preorder-and-inorder-traversal.py b/problems/python/construct-binary-tree-from-preorder-and-inorder-traversal.py old mode 100644 new mode 100755 diff --git a/problems/python/container-with-most-water.py b/problems/python/container-with-most-water.py old mode 100644 new mode 100755 diff --git a/problems/python/contains-duplicate-ii.py b/problems/python/contains-duplicate-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/contains-duplicate-iii.py b/problems/python/contains-duplicate-iii.py old mode 100644 new mode 100755 diff --git a/problems/python/contains-duplicate.py b/problems/python/contains-duplicate.py old mode 100644 new mode 100755 diff --git a/problems/python/continuous-subarray-sum.py b/problems/python/continuous-subarray-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/convert-binary-search-tree-to-sorted-doubly-linked-list.py b/problems/python/convert-binary-search-tree-to-sorted-doubly-linked-list.py old mode 100644 new mode 100755 diff --git a/problems/python/convert-sorted-array-to-binary-search-tree.py b/problems/python/convert-sorted-array-to-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/convert-sorted-list-to-binary-search-tree.py b/problems/python/convert-sorted-list-to-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/copy-list-with-random-pointer.py b/problems/python/copy-list-with-random-pointer.py old mode 100644 new mode 100755 diff --git a/problems/python/count-all-valid-pickup-and-delivery-opti.py b/problems/python/count-all-valid-pickup-and-delivery-opti.py old mode 100644 new mode 100755 diff --git a/problems/python/count-binary-substrings.py b/problems/python/count-binary-substrings.py old mode 100644 new mode 100755 diff --git a/problems/python/count-complete-tree-nodes.py b/problems/python/count-complete-tree-nodes.py old mode 100644 new mode 100755 diff --git a/problems/python/count-number-of-nice-subarrays.py b/problems/python/count-number-of-nice-subarrays.py old mode 100644 new mode 100755 diff --git a/problems/python/count-unique-characters-of-all-substrings-of-a-given-string.py b/problems/python/count-unique-characters-of-all-substrings-of-a-given-string.py old mode 100644 new mode 100755 diff --git a/problems/python/course-schedule-ii.py b/problems/python/course-schedule-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/course-schedule.py b/problems/python/course-schedule.py old mode 100644 new mode 100755 diff --git a/problems/python/custom-sort-string.py b/problems/python/custom-sort-string.py old mode 100644 new mode 100755 diff --git a/problems/python/cutting-ribbons.py b/problems/python/cutting-ribbons.py old mode 100644 new mode 100755 diff --git a/problems/python/data-stream-as-disjoint-intervals.py b/problems/python/data-stream-as-disjoint-intervals.py old mode 100644 new mode 100755 diff --git a/problems/python/decode-string.py b/problems/python/decode-string.py old mode 100644 new mode 100755 diff --git a/problems/python/decode-ways.py b/problems/python/decode-ways.py old mode 100644 new mode 100755 diff --git a/problems/python/delete-and-earn.py b/problems/python/delete-and-earn.py old mode 100644 new mode 100755 diff --git a/problems/python/delete-duplicate-folders-in-system.py b/problems/python/delete-duplicate-folders-in-system.py old mode 100644 new mode 100755 diff --git a/problems/python/delete-node-in-a-bst.py b/problems/python/delete-node-in-a-bst.py old mode 100644 new mode 100755 diff --git a/problems/python/delete-operation-for-two-strings.py b/problems/python/delete-operation-for-two-strings.py old mode 100644 new mode 100755 diff --git a/problems/python/design-add-and-search-words-data-structure.py b/problems/python/design-add-and-search-words-data-structure.py old mode 100644 new mode 100755 diff --git a/problems/python/design-in-memory-file-system.py b/problems/python/design-in-memory-file-system.py old mode 100644 new mode 100755 diff --git a/problems/python/design-linked-list.py b/problems/python/design-linked-list.py old mode 100644 new mode 100755 diff --git a/problems/python/design-tic-tac-toe.py b/problems/python/design-tic-tac-toe.py old mode 100644 new mode 100755 diff --git a/problems/python/diagonal-traverse.py b/problems/python/diagonal-traverse.py old mode 100644 new mode 100755 diff --git a/problems/python/diameter-of-binary-tree.py b/problems/python/diameter-of-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/different-ways-to-add-parentheses.py b/problems/python/different-ways-to-add-parentheses.py old mode 100644 new mode 100755 diff --git a/problems/python/distinct-subsequences.py b/problems/python/distinct-subsequences.py old mode 100644 new mode 100755 diff --git a/problems/python/distribute-coins-in-binary-tree.py b/problems/python/distribute-coins-in-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/domino-and-tromino-tiling.py b/problems/python/domino-and-tromino-tiling.py old mode 100644 new mode 100755 diff --git a/problems/python/dot-product-of-two-sparse-vectors.py b/problems/python/dot-product-of-two-sparse-vectors.py old mode 100644 new mode 100755 diff --git a/problems/python/dungeon-game.py b/problems/python/dungeon-game.py old mode 100644 new mode 100755 diff --git a/problems/python/edit-distance.py b/problems/python/edit-distance.py old mode 100644 new mode 100755 diff --git a/problems/python/egions-cut-by-slashes.py b/problems/python/egions-cut-by-slashes.py old mode 100644 new mode 100755 diff --git a/problems/python/evaluate-division.py b/problems/python/evaluate-division.py old mode 100644 new mode 100755 diff --git a/problems/python/evaluate-reverse-polish-notation.py b/problems/python/evaluate-reverse-polish-notation.py old mode 100644 new mode 100755 diff --git a/problems/python/exclusive-time-of-functions.py b/problems/python/exclusive-time-of-functions.py old mode 100644 new mode 100755 diff --git a/problems/python/expression-add-operators.py b/problems/python/expression-add-operators.py old mode 100644 new mode 100755 diff --git a/problems/python/filling-bookcase-shelves.py b/problems/python/filling-bookcase-shelves.py old mode 100644 new mode 100755 diff --git a/problems/python/find-all-possible-recipes-from-given-supplies.py b/problems/python/find-all-possible-recipes-from-given-supplies.py old mode 100644 new mode 100755 diff --git a/problems/python/find-and-replace-in-string.py b/problems/python/find-and-replace-in-string.py old mode 100644 new mode 100755 diff --git a/problems/python/find-distance-in-a-binary-tree.py b/problems/python/find-distance-in-a-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/find-duplicate-subtrees.py b/problems/python/find-duplicate-subtrees.py old mode 100644 new mode 100755 diff --git a/problems/python/find-eventual-safe-states.py b/problems/python/find-eventual-safe-states.py old mode 100644 new mode 100755 diff --git a/problems/python/find-first-and-last-position-of-element-in-sorted-array.py b/problems/python/find-first-and-last-position-of-element-in-sorted-array.py old mode 100644 new mode 100755 diff --git a/problems/python/find-k-closest-elements.py b/problems/python/find-k-closest-elements.py old mode 100644 new mode 100755 diff --git a/problems/python/find-k-pairs-with-smallest-sums.py b/problems/python/find-k-pairs-with-smallest-sums.py old mode 100644 new mode 100755 diff --git a/problems/python/find-leaves-of-binary-tree.py b/problems/python/find-leaves-of-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/find-median-from-data-stream.py b/problems/python/find-median-from-data-stream.py old mode 100644 new mode 100755 diff --git a/problems/python/find-minimum-in-rotated-sorted-array-ii.py b/problems/python/find-minimum-in-rotated-sorted-array-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/find-minimum-in-rotated-sorted-array.py b/problems/python/find-minimum-in-rotated-sorted-array.py old mode 100644 new mode 100755 diff --git a/problems/python/find-mode-in-binary-search-tree.py b/problems/python/find-mode-in-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/find-original-array-from-doubled-array,py b/problems/python/find-original-array-from-doubled-array,py old mode 100644 new mode 100755 diff --git a/problems/python/find-peak-element.py b/problems/python/find-peak-element.py old mode 100644 new mode 100755 diff --git a/problems/python/find-the-duplicate-number.py b/problems/python/find-the-duplicate-number.py old mode 100644 new mode 100755 diff --git a/problems/python/first-bad-version.py b/problems/python/first-bad-version.py old mode 100644 new mode 100755 diff --git a/problems/python/first-missing-positive.py b/problems/python/first-missing-positive.py old mode 100644 new mode 100755 diff --git a/problems/python/first-unique-character-in-a-string.py b/problems/python/first-unique-character-in-a-string.py old mode 100644 new mode 100755 diff --git a/problems/python/fizz-buzz.py b/problems/python/fizz-buzz.py old mode 100644 new mode 100755 diff --git a/problems/python/flatten-binary-tree-to-linked-list.py b/problems/python/flatten-binary-tree-to-linked-list.py old mode 100644 new mode 100755 diff --git a/problems/python/flip-binary-tree-to-match-preorder-traversal.py b/problems/python/flip-binary-tree-to-match-preorder-traversal.py old mode 100644 new mode 100755 diff --git a/problems/python/flip-string-to-monotone-increasing.py b/problems/python/flip-string-to-monotone-increasing.py old mode 100644 new mode 100755 diff --git a/problems/python/flood-fill.py b/problems/python/flood-fill.py old mode 100644 new mode 100755 diff --git a/problems/python/friend-circles.py b/problems/python/friend-circles.py old mode 100644 new mode 100755 diff --git a/problems/python/fruit-into-baskets.py b/problems/python/fruit-into-baskets.py old mode 100644 new mode 100755 diff --git a/problems/python/game-of-life.py b/problems/python/game-of-life.py old mode 100644 new mode 100755 diff --git a/problems/python/generate-parentheses.py b/problems/python/generate-parentheses.py old mode 100644 new mode 100755 diff --git a/problems/python/graph-valid-tree.py b/problems/python/graph-valid-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/greatest-sum-divisible-by-three.py b/problems/python/greatest-sum-divisible-by-three.py old mode 100644 new mode 100755 diff --git a/problems/python/group-anagrams.py b/problems/python/group-anagrams.py old mode 100644 new mode 100755 diff --git a/problems/python/group-shifted-strings.py b/problems/python/group-shifted-strings.py old mode 100644 new mode 100755 diff --git a/problems/python/guess-number-higher-or-lower-ii.py b/problems/python/guess-number-higher-or-lower-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/guess-number-higher-or-lower.py b/problems/python/guess-number-higher-or-lower.py old mode 100644 new mode 100755 diff --git a/problems/python/guess-the-word.py b/problems/python/guess-the-word.py old mode 100644 new mode 100755 diff --git a/problems/python/h-index-ii.py b/problems/python/h-index-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/h-index.py b/problems/python/h-index.py old mode 100644 new mode 100755 diff --git a/problems/python/hamming-distance.py b/problems/python/hamming-distance.py old mode 100644 new mode 100755 diff --git a/problems/python/house-robber-ii.py b/problems/python/house-robber-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/house-robber-iii.py b/problems/python/house-robber-iii.py old mode 100644 new mode 100755 diff --git a/problems/python/house-robber.py b/problems/python/house-robber.py old mode 100644 new mode 100755 diff --git a/problems/python/implement-trie-prefix-tree.py b/problems/python/implement-trie-prefix-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/increasing-triplet-subsequence.py b/problems/python/increasing-triplet-subsequence.py old mode 100644 new mode 100755 diff --git a/problems/python/inorder-successor-in-bst-ii.py b/problems/python/inorder-successor-in-bst-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/inorder-successor-in-bst.py b/problems/python/inorder-successor-in-bst.py old mode 100644 new mode 100755 diff --git a/problems/python/insert-interval.py b/problems/python/insert-interval.py old mode 100644 new mode 100755 diff --git a/problems/python/insert-into-a-binary-search-tree.py b/problems/python/insert-into-a-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/insert-into-a-sorted-circular-linked-list.py b/problems/python/insert-into-a-sorted-circular-linked-list.py old mode 100644 new mode 100755 diff --git a/problems/python/insertion-sort-list.py b/problems/python/insertion-sort-list.py old mode 100644 new mode 100755 diff --git a/problems/python/integer-to-english-words.py b/problems/python/integer-to-english-words.py old mode 100644 new mode 100755 diff --git a/problems/python/interleaving-string.py b/problems/python/interleaving-string.py old mode 100644 new mode 100755 diff --git a/problems/python/intersection-of-two-arrays-ii.py b/problems/python/intersection-of-two-arrays-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/intersection-of-two-arrays.py b/problems/python/intersection-of-two-arrays.py old mode 100644 new mode 100755 diff --git a/problems/python/invert-binary-tree.py b/problems/python/invert-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/is-graph-bipartite.py b/problems/python/is-graph-bipartite.py old mode 100644 new mode 100755 diff --git a/problems/python/is-subsequence.py b/problems/python/is-subsequence.py old mode 100644 new mode 100755 diff --git a/problems/python/isomorphic-strings.py b/problems/python/isomorphic-strings.py old mode 100644 new mode 100755 diff --git a/problems/python/jewels-and-stones.py b/problems/python/jewels-and-stones.py old mode 100644 new mode 100755 diff --git a/problems/python/jump-game.py b/problems/python/jump-game.py old mode 100644 new mode 100755 diff --git a/problems/python/k-closest-points-to-origin.py b/problems/python/k-closest-points-to-origin.py old mode 100644 new mode 100755 diff --git a/problems/python/k-empty-slots.py b/problems/python/k-empty-slots.py old mode 100644 new mode 100755 diff --git a/problems/python/keys-and-rooms.py b/problems/python/keys-and-rooms.py old mode 100644 new mode 100755 diff --git a/problems/python/knight-dialer.py b/problems/python/knight-dialer.py old mode 100644 new mode 100755 diff --git a/problems/python/knight-probability-in-chessboard.py b/problems/python/knight-probability-in-chessboard.py old mode 100644 new mode 100755 diff --git a/problems/python/koko-eating-bananas.py b/problems/python/koko-eating-bananas.py old mode 100644 new mode 100755 diff --git a/problems/python/kth-largest-element-in-an-array.py b/problems/python/kth-largest-element-in-an-array.py old mode 100644 new mode 100755 diff --git a/problems/python/kth-smallest-element-in-a-bst.py b/problems/python/kth-smallest-element-in-a-bst.py old mode 100644 new mode 100755 diff --git a/problems/python/kth-smallest-element-in-a-sorted-matrix.py b/problems/python/kth-smallest-element-in-a-sorted-matrix.py old mode 100644 new mode 100755 diff --git a/problems/python/largest-1-bordered-square.py b/problems/python/largest-1-bordered-square.py old mode 100644 new mode 100755 diff --git a/problems/python/largest-bst-subtree.py b/problems/python/largest-bst-subtree.py old mode 100644 new mode 100755 diff --git a/problems/python/largest-sum-of-averages.py b/problems/python/largest-sum-of-averages.py old mode 100644 new mode 100755 diff --git a/problems/python/last-stone-weight-ii.py b/problems/python/last-stone-weight-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/last-stone-weight.py b/problems/python/last-stone-weight.py old mode 100644 new mode 100755 diff --git a/problems/python/least-number-of-unique-integers-after-k-removals.py b/problems/python/least-number-of-unique-integers-after-k-removals.py old mode 100644 new mode 100755 diff --git a/problems/python/letter-case-permutation.py b/problems/python/letter-case-permutation.py old mode 100644 new mode 100755 diff --git a/problems/python/letter-combinations-of-a-phone-number.py b/problems/python/letter-combinations-of-a-phone-number.py old mode 100644 new mode 100755 diff --git a/problems/python/license-key-formatting.py b/problems/python/license-key-formatting.py old mode 100644 new mode 100755 diff --git a/problems/python/linked-list-cycle-ii.py b/problems/python/linked-list-cycle-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/linked-list-cycle.py b/problems/python/linked-list-cycle.py old mode 100644 new mode 100755 diff --git a/problems/python/linked-list-random-node.py b/problems/python/linked-list-random-node.py old mode 100644 new mode 100755 diff --git a/problems/python/logger-rate-limiter.py b/problems/python/logger-rate-limiter.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-common-prefix.py b/problems/python/longest-common-prefix.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-common-subsequence.py b/problems/python/longest-common-subsequence.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-consecutive-sequence.py b/problems/python/longest-consecutive-sequence.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-increasing-path-in-a-matrix.py b/problems/python/longest-increasing-path-in-a-matrix.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-increasing-subsequence.py b/problems/python/longest-increasing-subsequence.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-palindromic-subsequence.py b/problems/python/longest-palindromic-subsequence.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-palindromic-substring.py b/problems/python/longest-palindromic-substring.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-repeating-character-replacement.py b/problems/python/longest-repeating-character-replacement.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-string-chain.py b/problems/python/longest-string-chain.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-substring-with-at-least-k-repeating-characters.py b/problems/python/longest-substring-with-at-least-k-repeating-characters.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-substring-without-repeating-characters.py b/problems/python/longest-substring-without-repeating-characters.py old mode 100644 new mode 100755 diff --git a/problems/python/longest-univalue-path.py b/problems/python/longest-univalue-path.py old mode 100644 new mode 100755 diff --git a/problems/python/lowest-common-ancestor-of-a-binary-search-tree.py b/problems/python/lowest-common-ancestor-of-a-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/lowest-common-ancestor-of-a-binary-search.py b/problems/python/lowest-common-ancestor-of-a-binary-search.py old mode 100644 new mode 100755 diff --git a/problems/python/lowest-common-ancestor-of-a-binary-tree-ii.py b/problems/python/lowest-common-ancestor-of-a-binary-tree-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/lowest-common-ancestor-of-a-binary-tree-iii.py b/problems/python/lowest-common-ancestor-of-a-binary-tree-iii.py old mode 100644 new mode 100755 diff --git a/problems/python/lowest-common-ancestor-of-a-binary-tree-iv.py b/problems/python/lowest-common-ancestor-of-a-binary-tree-iv.py old mode 100644 new mode 100755 diff --git a/problems/python/lowest-common-ancestor-of-a-binary-tree.py b/problems/python/lowest-common-ancestor-of-a-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/lowest-common-ancestor-of-deepest-leaves.py b/problems/python/lowest-common-ancestor-of-deepest-leaves.py old mode 100644 new mode 100755 diff --git a/problems/python/lru-cache.py b/problems/python/lru-cache.py old mode 100644 new mode 100755 diff --git a/problems/python/majority-element-ii.py b/problems/python/majority-element-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/majority-element.py b/problems/python/majority-element.py old mode 100644 new mode 100755 diff --git a/problems/python/making-a-large-island.py b/problems/python/making-a-large-island.py old mode 100644 new mode 100755 diff --git a/problems/python/max-area-of-island.py b/problems/python/max-area-of-island.py old mode 100644 new mode 100755 diff --git a/problems/python/max-consecutive-ones-iii.py b/problems/python/max-consecutive-ones-iii.py old mode 100644 new mode 100755 diff --git a/problems/python/max-stack.py b/problems/python/max-stack.py old mode 100644 new mode 100755 diff --git a/problems/python/max-sum-of-rectangle-no-larger-than-k.py b/problems/python/max-sum-of-rectangle-no-larger-than-k.py old mode 100644 new mode 100755 diff --git a/problems/python/maximal-square.py b/problems/python/maximal-square.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-average-subtree.py b/problems/python/maximum-average-subtree.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-compatibility-score-sum.py b/problems/python/maximum-compatibility-score-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-depth-of-binary-tree.py b/problems/python/maximum-depth-of-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-gap.py b/problems/python/maximum-gap.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-length-of-repeated-subarray.py b/problems/python/maximum-length-of-repeated-subarray.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-number-of-events-that-can-be-attended.py b/problems/python/maximum-number-of-events-that-can-be-attended.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-number-of-points-with-cost.py b/problems/python/maximum-number-of-points-with-cost.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-number-of-visible-points.py b/problems/python/maximum-number-of-visible-points.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-product-of-three-numbers.py b/problems/python/maximum-product-of-three-numbers.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-product-subarray.py b/problems/python/maximum-product-subarray.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-subarray-sum-with-one-deletion.py b/problems/python/maximum-subarray-sum-with-one-deletion.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-subarray.py b/problems/python/maximum-subarray.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-swap.py b/problems/python/maximum-swap.py old mode 100644 new mode 100755 diff --git a/problems/python/maximum-units-on-a-truck.py b/problems/python/maximum-units-on-a-truck.py old mode 100644 new mode 100755 diff --git a/problems/python/median-of-two-sorted-arrays.py b/problems/python/median-of-two-sorted-arrays.py old mode 100644 new mode 100755 diff --git a/problems/python/meeting-rooms-ii.py b/problems/python/meeting-rooms-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/meeting-rooms.py b/problems/python/meeting-rooms.py old mode 100644 new mode 100755 diff --git a/problems/python/merge-intervals.py b/problems/python/merge-intervals.py old mode 100644 new mode 100755 diff --git a/problems/python/merge-k-sorted-lists.py b/problems/python/merge-k-sorted-lists.py old mode 100644 new mode 100755 diff --git a/problems/python/merge-sorted-array.py b/problems/python/merge-sorted-array.py old mode 100644 new mode 100755 diff --git a/problems/python/merge-two-sorted-lists.py b/problems/python/merge-two-sorted-lists.py old mode 100644 new mode 100755 diff --git a/problems/python/min-cost-climbing-stairs.py b/problems/python/min-cost-climbing-stairs.py old mode 100644 new mode 100755 diff --git a/problems/python/min-stack.py b/problems/python/min-stack.py old mode 100644 new mode 100755 diff --git a/problems/python/minimize-malware-spread.py b/problems/python/minimize-malware-spread.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-absolute-difference-in-bst.py b/problems/python/minimum-absolute-difference-in-bst.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-ascii-delete-sum-for-two-strings.py b/problems/python/minimum-ascii-delete-sum-for-two-strings.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-cost-to-connect-sticks.py b/problems/python/minimum-cost-to-connect-sticks.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-cost-to-hire-k-workers.py b/problems/python/minimum-cost-to-hire-k-workers.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py b/problems/python/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-cost-to-reach-city-with-discounts.py b/problems/python/minimum-cost-to-reach-city-with-discounts.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-depth-of-binary-tree.py b/problems/python/minimum-depth-of-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-difficulty-of-a-job-schedule.py b/problems/python/minimum-difficulty-of-a-job-schedule.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-falling-path-sum-ii.py b/problems/python/minimum-falling-path-sum-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-knight-moves.py b/problems/python/minimum-knight-moves.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py b/problems/python/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-path-sum.py b/problems/python/minimum-path-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-score-triangulation-of-polygon.py b/problems/python/minimum-score-triangulation-of-polygon.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-size-subarray-sum.py b/problems/python/minimum-size-subarray-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-swaps-to-group-all-1s-together.py b/problems/python/minimum-swaps-to-group-all-1s-together.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-swaps-to-make-sequences-increasing.py b/problems/python/minimum-swaps-to-make-sequences-increasing.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-time-difference.py b/problems/python/minimum-time-difference.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-window-substring.py b/problems/python/minimum-window-substring.py old mode 100644 new mode 100755 diff --git a/problems/python/minimum-xor-sum-of-two-arrays.py b/problems/python/minimum-xor-sum-of-two-arrays.py old mode 100644 new mode 100755 diff --git a/problems/python/missing-number.py b/problems/python/missing-number.py old mode 100644 new mode 100755 diff --git a/problems/python/most-frequent-subtree-sum.py b/problems/python/most-frequent-subtree-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/most-stones-removed-with-same-row-or-column.py b/problems/python/most-stones-removed-with-same-row-or-column.py old mode 100644 new mode 100755 diff --git a/problems/python/move-zeroes.py b/problems/python/move-zeroes.py old mode 100644 new mode 100755 diff --git a/problems/python/moving-average-from-data-stream.py b/problems/python/moving-average-from-data-stream.py old mode 100644 new mode 100755 diff --git a/problems/python/my-calendar-ii.py b/problems/python/my-calendar-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/n-ary-tree-level-order-traversal.py b/problems/python/n-ary-tree-level-order-traversal.py old mode 100644 new mode 100755 diff --git a/problems/python/n-ary-tree-postorder-traversal.py b/problems/python/n-ary-tree-postorder-traversal.py old mode 100644 new mode 100755 diff --git a/problems/python/n-ary-tree-preorder-traversal.py b/problems/python/n-ary-tree-preorder-traversal.py old mode 100644 new mode 100755 diff --git a/problems/python/nested-list-weight-sum.py b/problems/python/nested-list-weight-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/network-delay-time.py b/problems/python/network-delay-time.py old mode 100644 new mode 100755 diff --git a/problems/python/next-closest-time.py b/problems/python/next-closest-time.py old mode 100644 new mode 100755 diff --git a/problems/python/next-permutation.py b/problems/python/next-permutation.py old mode 100644 new mode 100755 diff --git a/problems/python/number-complement.py b/problems/python/number-complement.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-connected-components-in-an-undirected-graph.py b/problems/python/number-of-connected-components-in-an-undirected-graph.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-islands-ii.py b/problems/python/number-of-islands-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-islands.py b/problems/python/number-of-islands.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-longest-increasing-subsequence.py b/problems/python/number-of-longest-increasing-subsequence.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-matching-subsequences.py b/problems/python/number-of-matching-subsequences.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-provinces.py b/problems/python/number-of-provinces.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-recent-calls.py b/problems/python/number-of-recent-calls.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-squareful-arrays.py b/problems/python/number-of-squareful-arrays.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-substrings-containing-all-thre.py b/problems/python/number-of-substrings-containing-all-thre.py old mode 100644 new mode 100755 diff --git a/problems/python/number-of-ways-to-arrive-at-destination.py b/problems/python/number-of-ways-to-arrive-at-destination.py old mode 100644 new mode 100755 diff --git a/problems/python/odd-even-jump.py b/problems/python/odd-even-jump.py old mode 100644 new mode 100755 diff --git a/problems/python/ones-and-zeroes.py b/problems/python/ones-and-zeroes.py old mode 100644 new mode 100755 diff --git a/problems/python/open-the-lock.py b/problems/python/open-the-lock.py old mode 100644 new mode 100755 diff --git a/problems/python/out-of-boundary-paths.py b/problems/python/out-of-boundary-paths.py old mode 100644 new mode 100755 diff --git a/problems/python/pacific-atlantic-water-flow.py b/problems/python/pacific-atlantic-water-flow.py old mode 100644 new mode 100755 diff --git a/problems/python/pairs-of-songs-with-total-durations-divisible-by-60.py b/problems/python/pairs-of-songs-with-total-durations-divisible-by-60.py old mode 100644 new mode 100755 diff --git a/problems/python/palindrome-number.py b/problems/python/palindrome-number.py old mode 100644 new mode 100755 diff --git a/problems/python/palindrome-pairs.py b/problems/python/palindrome-pairs.py old mode 100644 new mode 100755 diff --git a/problems/python/palindrome-partitioning-iii.py b/problems/python/palindrome-partitioning-iii.py old mode 100644 new mode 100755 diff --git a/problems/python/palindrome-partitioning.py b/problems/python/palindrome-partitioning.py old mode 100644 new mode 100755 diff --git a/problems/python/palindromic-substrings.py b/problems/python/palindromic-substrings.py old mode 100644 new mode 100755 diff --git a/problems/python/partition-array-for-maximum-sum.py b/problems/python/partition-array-for-maximum-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/partition-labels.py b/problems/python/partition-labels.py old mode 100644 new mode 100755 diff --git a/problems/python/partition-to-k-equal-sum-subsets.py b/problems/python/partition-to-k-equal-sum-subsets.py old mode 100644 new mode 100755 diff --git a/problems/python/path-sum-ii.py b/problems/python/path-sum-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/path-sum-iii.py b/problems/python/path-sum-iii.py old mode 100644 new mode 100755 diff --git a/problems/python/path-sum.py b/problems/python/path-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/path-with-maximum-probability.py b/problems/python/path-with-maximum-probability.py old mode 100644 new mode 100755 diff --git a/problems/python/peak-index-in-a-mountain-array.py b/problems/python/peak-index-in-a-mountain-array.py old mode 100644 new mode 100755 diff --git a/problems/python/perfect-squares.py b/problems/python/perfect-squares.py old mode 100644 new mode 100755 diff --git a/problems/python/permutation-in-string.py b/problems/python/permutation-in-string.py old mode 100644 new mode 100755 diff --git a/problems/python/permutation-sequence.py b/problems/python/permutation-sequence.py old mode 100644 new mode 100755 diff --git a/problems/python/permutations-ii.py b/problems/python/permutations-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/permutations.py b/problems/python/permutations.py old mode 100644 new mode 100755 diff --git a/problems/python/populating-next-right-pointers-in-each-node-ii.py b/problems/python/populating-next-right-pointers-in-each-node-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/populating-next-right-pointers-in-each-node.py b/problems/python/populating-next-right-pointers-in-each-node.py old mode 100644 new mode 100755 diff --git a/problems/python/powx-n.py b/problems/python/powx-n.py old mode 100644 new mode 100755 diff --git a/problems/python/product-of-array-except-self.py b/problems/python/product-of-array-except-self.py old mode 100644 new mode 100755 diff --git a/problems/python/profitable-schemes.py b/problems/python/profitable-schemes.py old mode 100644 new mode 100755 diff --git a/problems/python/queue-reconstruction-by-height.py b/problems/python/queue-reconstruction-by-height.py old mode 100644 new mode 100755 diff --git a/problems/python/random-pick-with-weight.py b/problems/python/random-pick-with-weight.py old mode 100644 new mode 100755 diff --git a/problems/python/range-addition.py b/problems/python/range-addition.py old mode 100644 new mode 100755 diff --git a/problems/python/range-sum-of-bst.py b/problems/python/range-sum-of-bst.py old mode 100644 new mode 100755 diff --git a/problems/python/range-sum-query-immutable.py b/problems/python/range-sum-query-immutable.py old mode 100644 new mode 100755 diff --git a/problems/python/range-sum-query-mutable.py b/problems/python/range-sum-query-mutable.py old mode 100644 new mode 100755 diff --git a/problems/python/rearrange-string-k-distance-apart.py b/problems/python/rearrange-string-k-distance-apart.py old mode 100644 new mode 100755 diff --git a/problems/python/reconstruct-itinerary.py b/problems/python/reconstruct-itinerary.py old mode 100644 new mode 100755 diff --git a/problems/python/recover-binary-search-tree.py b/problems/python/recover-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/redundant-connection.py b/problems/python/redundant-connection.py old mode 100644 new mode 100755 diff --git a/problems/python/remove-all-adjacent-duplicates-in-string.py b/problems/python/remove-all-adjacent-duplicates-in-string.py old mode 100644 new mode 100755 diff --git a/problems/python/remove-all-ones-with-row-and-column-flips.py b/problems/python/remove-all-ones-with-row-and-column-flips.py old mode 100644 new mode 100755 diff --git a/problems/python/remove-duplicates-from-sorted-array-ii.py b/problems/python/remove-duplicates-from-sorted-array-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/remove-duplicates-from-sorted-array.py b/problems/python/remove-duplicates-from-sorted-array.py old mode 100644 new mode 100755 diff --git a/problems/python/remove-duplicates-from-sorted-list.py b/problems/python/remove-duplicates-from-sorted-list.py old mode 100644 new mode 100755 diff --git a/problems/python/remove-element.py b/problems/python/remove-element.py old mode 100644 new mode 100755 diff --git a/problems/python/remove-invalid-parentheses.py b/problems/python/remove-invalid-parentheses.py old mode 100644 new mode 100755 diff --git a/problems/python/remove-linked-list-elements.py b/problems/python/remove-linked-list-elements.py old mode 100644 new mode 100755 diff --git a/problems/python/remove-nth-node-from-end-of-list.py b/problems/python/remove-nth-node-from-end-of-list.py old mode 100644 new mode 100755 diff --git a/problems/python/reorder-list.py b/problems/python/reorder-list.py old mode 100644 new mode 100755 diff --git a/problems/python/repeated-string-match.py b/problems/python/repeated-string-match.py old mode 100644 new mode 100755 diff --git a/problems/python/replace-the-substring-for-balanced-string.py b/problems/python/replace-the-substring-for-balanced-string.py old mode 100644 new mode 100755 diff --git a/problems/python/restore-ip-addresses.py b/problems/python/restore-ip-addresses.py old mode 100644 new mode 100755 diff --git a/problems/python/reverse-integer.py b/problems/python/reverse-integer.py old mode 100644 new mode 100755 diff --git a/problems/python/reverse-linked-list.py b/problems/python/reverse-linked-list.py old mode 100644 new mode 100755 diff --git a/problems/python/reverse-string.py b/problems/python/reverse-string.py old mode 100644 new mode 100755 diff --git a/problems/python/reverse-vowels-of-a-string.py b/problems/python/reverse-vowels-of-a-string.py old mode 100644 new mode 100755 diff --git a/problems/python/reverse-words-in-a-string.py b/problems/python/reverse-words-in-a-string.py old mode 100644 new mode 100755 diff --git a/problems/python/robot-bounded-in-circle.py b/problems/python/robot-bounded-in-circle.py old mode 100644 new mode 100755 diff --git a/problems/python/roman-to-integer.py b/problems/python/roman-to-integer.py old mode 100644 new mode 100755 diff --git a/problems/python/rotate-array.py b/problems/python/rotate-array.py old mode 100644 new mode 100755 diff --git a/problems/python/rotate-image.py b/problems/python/rotate-image.py old mode 100644 new mode 100755 diff --git a/problems/python/russian-doll-envelopes.py b/problems/python/russian-doll-envelopes.py old mode 100644 new mode 100755 diff --git a/problems/python/same-tree.py b/problems/python/same-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/satisfiability-of-equality-equations.py b/problems/python/satisfiability-of-equality-equations.py old mode 100644 new mode 100755 diff --git a/problems/python/score-of-parentheses.py b/problems/python/score-of-parentheses.py old mode 100644 new mode 100755 diff --git a/problems/python/search-a-2d-matrix.py b/problems/python/search-a-2d-matrix.py old mode 100644 new mode 100755 diff --git a/problems/python/search-in-a-binary-search-tree.py b/problems/python/search-in-a-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/search-in-rotated-sorted-array-ii.py b/problems/python/search-in-rotated-sorted-array-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/search-in-rotated-sorted-array.py b/problems/python/search-in-rotated-sorted-array.py old mode 100644 new mode 100755 diff --git a/problems/python/search-insert-position.py b/problems/python/search-insert-position.py old mode 100644 new mode 100755 diff --git a/problems/python/search-suggestions-system.py b/problems/python/search-suggestions-system.py old mode 100644 new mode 100755 diff --git a/problems/python/second-highest-salary.sql b/problems/python/second-highest-salary.sql old mode 100644 new mode 100755 diff --git a/problems/python/sell-diminishing-valued-colored-balls.py b/problems/python/sell-diminishing-valued-colored-balls.py old mode 100644 new mode 100755 diff --git a/problems/python/serialize-and-deserialize-binary-tree.py b/problems/python/serialize-and-deserialize-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/serialize-and-deserialize-bst.py b/problems/python/serialize-and-deserialize-bst.py old mode 100644 new mode 100755 diff --git a/problems/python/set-matrix-zeroes.py b/problems/python/set-matrix-zeroes.py old mode 100644 new mode 100755 diff --git a/problems/python/shortest-bridge.py b/problems/python/shortest-bridge.py old mode 100644 new mode 100755 diff --git a/problems/python/shortest-common-supersequence.py b/problems/python/shortest-common-supersequence.py old mode 100644 new mode 100755 diff --git a/problems/python/shortest-distance-from-all-buildings.py b/problems/python/shortest-distance-from-all-buildings.py old mode 100644 new mode 100755 diff --git a/problems/python/shortest-path-in-a-grid-with-obstacles-elimination.py b/problems/python/shortest-path-in-a-grid-with-obstacles-elimination.py old mode 100644 new mode 100755 diff --git a/problems/python/shortest-path-in-binary-matrix.py b/problems/python/shortest-path-in-binary-matrix.py old mode 100644 new mode 100755 diff --git a/problems/python/shortest-path-to-get-food.py b/problems/python/shortest-path-to-get-food.py old mode 100644 new mode 100755 diff --git a/problems/python/shuffle-an-array.py b/problems/python/shuffle-an-array.py old mode 100644 new mode 100755 diff --git a/problems/python/simplify-path.py b/problems/python/simplify-path.py old mode 100644 new mode 100755 diff --git a/problems/python/single-threaded-cpu.py b/problems/python/single-threaded-cpu.py old mode 100644 new mode 100755 diff --git a/problems/python/sliding-window-maximum.py b/problems/python/sliding-window-maximum.py old mode 100644 new mode 100755 diff --git a/problems/python/snapshot-array.py b/problems/python/snapshot-array.py old mode 100644 new mode 100755 diff --git a/problems/python/sort-colors.py b/problems/python/sort-colors.py old mode 100644 new mode 100755 diff --git a/problems/python/sort-list.py b/problems/python/sort-list.py old mode 100644 new mode 100755 diff --git a/problems/python/spiral-matrix.py b/problems/python/spiral-matrix.py old mode 100644 new mode 100755 diff --git a/problems/python/split-array-into-fibonacci-sequence.py b/problems/python/split-array-into-fibonacci-sequence.py old mode 100644 new mode 100755 diff --git a/problems/python/split-array-largest-sum.py b/problems/python/split-array-largest-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/sqrtx.py b/problems/python/sqrtx.py old mode 100644 new mode 100755 diff --git a/problems/python/squares-of-a-sorted-array.py b/problems/python/squares-of-a-sorted-array.py old mode 100644 new mode 100755 diff --git a/problems/python/step-by-step-directions-from-a-binary-tree-node-to-another.py b/problems/python/step-by-step-directions-from-a-binary-tree-node-to-another.py old mode 100644 new mode 100755 diff --git a/problems/python/stock-price-fluctuation.py b/problems/python/stock-price-fluctuation.py old mode 100644 new mode 100755 diff --git a/problems/python/stone-game-ii.py b/problems/python/stone-game-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/student-attendance-record-ii.py b/problems/python/student-attendance-record-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/subarray-sum-equals-k.py b/problems/python/subarray-sum-equals-k.py old mode 100644 new mode 100755 diff --git a/problems/python/subarrays-with-k-different-integers.py b/problems/python/subarrays-with-k-different-integers.py old mode 100644 new mode 100755 diff --git a/problems/python/subdomain-visit-count.py b/problems/python/subdomain-visit-count.py old mode 100644 new mode 100755 diff --git a/problems/python/subsets-ii.py b/problems/python/subsets-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/subsets.py b/problems/python/subsets.py old mode 100644 new mode 100755 diff --git a/problems/python/substring-with-concatenation-of-all-words.py b/problems/python/substring-with-concatenation-of-all-words.py old mode 100644 new mode 100755 diff --git a/problems/python/subtree-of-another-tree.py b/problems/python/subtree-of-another-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/sum-of-subarray-minimums.py b/problems/python/sum-of-subarray-minimums.py old mode 100644 new mode 100755 diff --git a/problems/python/sum-root-to-leaf-numbers.py b/problems/python/sum-root-to-leaf-numbers.py old mode 100644 new mode 100755 diff --git a/problems/python/summary-ranges.py b/problems/python/summary-ranges.py old mode 100644 new mode 100755 diff --git a/problems/python/super-ugly-number.py b/problems/python/super-ugly-number.py old mode 100644 new mode 100755 diff --git a/problems/python/swap-adjacent-in-lr-string.py b/problems/python/swap-adjacent-in-lr-string.py old mode 100644 new mode 100755 diff --git a/problems/python/swap-nodes-in-pairs.py b/problems/python/swap-nodes-in-pairs.py old mode 100644 new mode 100755 diff --git a/problems/python/swim-in-rising-water.py b/problems/python/swim-in-rising-water.py old mode 100644 new mode 100755 diff --git a/problems/python/symmetric-tree.py b/problems/python/symmetric-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/tallest-billboard.py b/problems/python/tallest-billboard.py old mode 100644 new mode 100755 diff --git a/problems/python/target-sum.py b/problems/python/target-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/task-scheduler.py b/problems/python/task-scheduler.py old mode 100644 new mode 100755 diff --git a/problems/python/text-justification.py b/problems/python/text-justification.py old mode 100644 new mode 100755 diff --git a/problems/python/the-kth-factor-of-n.py b/problems/python/the-kth-factor-of-n.py old mode 100644 new mode 100755 diff --git a/problems/python/the-maze-ii.py b/problems/python/the-maze-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/time-based-key-value-store.py b/problems/python/time-based-key-value-store.py old mode 100644 new mode 100755 diff --git a/problems/python/to-lower-case.py b/problems/python/to-lower-case.py old mode 100644 new mode 100755 diff --git a/problems/python/toeplitz-matrix.py b/problems/python/toeplitz-matrix.py old mode 100644 new mode 100755 diff --git a/problems/python/top-k-frequent-elements.py b/problems/python/top-k-frequent-elements.py old mode 100644 new mode 100755 diff --git a/problems/python/trapping-rain-water-ii.py b/problems/python/trapping-rain-water-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/trapping-rain-water.py b/problems/python/trapping-rain-water.py old mode 100644 new mode 100755 diff --git a/problems/python/trim-a-binary-search-tree.py b/problems/python/trim-a-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/two-out-of-three.py b/problems/python/two-out-of-three.py old mode 100644 new mode 100755 diff --git a/problems/python/two-sum-ii-input-array-is-sorted.py b/problems/python/two-sum-ii-input-array-is-sorted.py old mode 100644 new mode 100755 diff --git a/problems/python/two-sum.py b/problems/python/two-sum.py old mode 100644 new mode 100755 diff --git a/problems/python/ugly-number-ii.py b/problems/python/ugly-number-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/ugly-number.py b/problems/python/ugly-number.py old mode 100644 new mode 100755 diff --git a/problems/python/umber-of-islands-ii.py b/problems/python/umber-of-islands-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/unique-binary-search-trees-ii,py b/problems/python/unique-binary-search-trees-ii,py old mode 100644 new mode 100755 diff --git a/problems/python/unique-binary-search-trees.py b/problems/python/unique-binary-search-trees.py old mode 100644 new mode 100755 diff --git a/problems/python/unique-email-addres.py b/problems/python/unique-email-addres.py old mode 100644 new mode 100755 diff --git a/problems/python/unique-paths.py b/problems/python/unique-paths.py old mode 100644 new mode 100755 diff --git a/problems/python/univalued-binary-tree.py b/problems/python/univalued-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/valid-anagram.py b/problems/python/valid-anagram.py old mode 100644 new mode 100755 diff --git a/problems/python/valid-number.py b/problems/python/valid-number.py old mode 100644 new mode 100755 diff --git a/problems/python/valid-palindrome-ii.py b/problems/python/valid-palindrome-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/valid-palindrome.py b/problems/python/valid-palindrome.py old mode 100644 new mode 100755 diff --git a/problems/python/valid-parentheses.py b/problems/python/valid-parentheses.py old mode 100644 new mode 100755 diff --git a/problems/python/valid-word-abbreviation.py b/problems/python/valid-word-abbreviation.py old mode 100644 new mode 100755 diff --git a/problems/python/validate-binary-search-tree.py b/problems/python/validate-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/verify-preorder-serialization-of-a-binary-tree.py b/problems/python/verify-preorder-serialization-of-a-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/vertical-order-traversal-of-a-binary-tree.py b/problems/python/vertical-order-traversal-of-a-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python/wiggle-subsequence.py b/problems/python/wiggle-subsequence.py old mode 100644 new mode 100755 diff --git a/problems/python/word-break.py b/problems/python/word-break.py old mode 100644 new mode 100755 diff --git a/problems/python/word-ladder-ii.py b/problems/python/word-ladder-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/word-ladder.py b/problems/python/word-ladder.py old mode 100644 new mode 100755 diff --git a/problems/python/word-search-ii.py b/problems/python/word-search-ii.py old mode 100644 new mode 100755 diff --git a/problems/python/word-search.py b/problems/python/word-search.py old mode 100644 new mode 100755 diff --git a/problems/python3/3sum-closest.py b/problems/python3/3sum-closest.py old mode 100644 new mode 100755 diff --git a/problems/python3/3sum-smaller.py b/problems/python3/3sum-smaller.py old mode 100644 new mode 100755 diff --git a/problems/python3/3sum.py b/problems/python3/3sum.py old mode 100644 new mode 100755 index 0a92eb9..97f3388 --- a/problems/python3/3sum.py +++ b/problems/python3/3sum.py @@ -61,4 +61,32 @@ def threeSum(self, nums: List[int]) -> List[List[int]]: if v2 in needed: ans.add(tuple(sorted((v1, v2, -v1-v2)))) needed.add(-v1-v2) + return ans + + + +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + ans = [] + + nums.sort() + + for i in range(len(nums)): + if nums[i]>0: break + if i>0 and nums[i]==nums[i-1]: continue + + j = i+1 + k = len(nums)-1 + while j0: + k -= 1 + elif nums[j]+nums[k]+nums[i]<0: + j += 1 + else: + ans.append((nums[i], nums[j], nums[k])) + + while j int: + def helper(node): + nonlocal ans + + if not node: return 0 + left = max(helper(node.left), 0) #[3] + right = max(helper(node.right), 0) #[3] + ans = max(ans, node.val+left+right) #[1] + return node.val+max(left, right) #[0] + + ans = float('-inf') + helper(root) + return ans \ No newline at end of file diff --git a/problems/python3/binary-tree-right-side-view.py b/problems/python3/binary-tree-right-side-view.py old mode 100644 new mode 100755 diff --git a/problems/python3/construct-binary-tree-from-preorder-and-inorder-traversal.py b/problems/python3/construct-binary-tree-from-preorder-and-inorder-traversal.py new file mode 100644 index 0000000..eb7f19c --- /dev/null +++ b/problems/python3/construct-binary-tree-from-preorder-and-inorder-traversal.py @@ -0,0 +1,34 @@ +""" +preorder: [root][left][right] +inorder: [left][root][right] + +[0] +As you can see, the root is always located at the first index of the preorder list. + +[2] +Using the same logic, we can recursively get the left and right node +Inorder to do that, we need to define left and right nodes' range. +And we can get the length of the left subtree by locating the index of the root in the in order list. [1] +i and j is the startIndex and the (endIndex+1) of the preorder list. +k and l is the startIndex and the (endIndex+1) of the inorder list. + +Time: O(N) +Space: O(N) +""" +class Solution: + def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: + def helper(i, j, k, l): + if i==j or k==l: return None + + root = TreeNode(preorder[i]) #[0] + + rootInorderIndex = getInorderIndex[root.val] #[1] + leftLen = rootInorderIndex-k + + root.left = helper(i+1, i+1+leftLen, k, k+leftLen) #[2] + root.right = helper(i+1+leftLen, j, rootInorderIndex+1, l) + return root + + getInorderIndex = {} + for i, v in enumerate(inorder): getInorderIndex[v] = i + return helper(0, len(preorder), 0, len(inorder)) \ No newline at end of file diff --git a/problems/python3/container-with-most-water.py b/problems/python3/container-with-most-water.py old mode 100644 new mode 100755 index c24f0c9..a560441 --- a/problems/python3/container-with-most-water.py +++ b/problems/python3/container-with-most-water.py @@ -18,6 +18,23 @@ def maxArea(self, height: List[int]) -> int: while iheight[j]: + j -= 1 + else: + i += 1 + return ans + + + +class Solution: + def maxArea(self, height: List[int]) -> int: + i = 0 + j = len(height)-1 + ans = 0 + + while iheight[j]: j -= 1 else: diff --git a/problems/python3/count-good-nodes-in-binary-tree.py b/problems/python3/count-good-nodes-in-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python3/diameter-of-binary-tree.py b/problems/python3/diameter-of-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python3/invert-binary-tree.py b/problems/python3/invert-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python3/kth-smallest-element-in-a-bst.py b/problems/python3/kth-smallest-element-in-a-bst.py new file mode 100755 index 0000000..c8a1555 --- /dev/null +++ b/problems/python3/kth-smallest-element-in-a-bst.py @@ -0,0 +1,21 @@ +""" +Time: O(N) for the inorder traversal +Space: O(LogN) if the tree is balanced. +""" +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + count = 0 + stack = [] + node = root + + while stack or node: + while node: + stack.append(node) + node = node.left + node = stack.pop() + + count += 1 + if count==k: return node.val + + node = node.right + return 0 \ No newline at end of file diff --git a/problems/python3/lowest-common-ancestor-of-a-binary-search-tree.py b/problems/python3/lowest-common-ancestor-of-a-binary-search-tree.py old mode 100644 new mode 100755 diff --git a/problems/python3/maximum-depth-of-binary-tree.py b/problems/python3/maximum-depth-of-binary-tree.py old mode 100644 new mode 100755 diff --git a/problems/python3/same-tree.py b/problems/python3/same-tree.py old mode 100644 new mode 100755 diff --git a/problems/python3/serialize-and-deserialize-binary-tree.py b/problems/python3/serialize-and-deserialize-binary-tree.py new file mode 100644 index 0000000..1b057d0 --- /dev/null +++ b/problems/python3/serialize-and-deserialize-binary-tree.py @@ -0,0 +1,22 @@ +class Codec: + + def serialize(self, root): + if not root: return '#' + return str(root.val)+','+self.serialize(root.left)+','+self.serialize(root.right) + + + def deserialize(self, data): + def helper(): + if data[self.i]=='#': + self.i += 1 + return None + + node = TreeNode(int(data[self.i])) + self.i += 1 + node.left = helper() + node.right = helper() + return node + + data = data.split(",") + self.i = 0 + return helper() \ No newline at end of file diff --git a/problems/python3/subsets.py b/problems/python3/subsets.py new file mode 100644 index 0000000..9cfcc00 --- /dev/null +++ b/problems/python3/subsets.py @@ -0,0 +1,22 @@ +""" +Time: O(N * 2^N) +Space: O(N) for "subset". +""" +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + def helper(i): + if not i int: + ans = 0 + l = 0 + r = len(height)-1 + + leftMax = float('-inf') + rightMax = float('-inf') + + while l<=r: + if leftMax=leftMax: + leftMax = height[l] + else: + ans += leftMax-height[l] + l += 1 + else: + if height[r]>=rightMax: + rightMax = height[r] + else: + ans += rightMax-height[r] + r -= 1 + return ans \ No newline at end of file diff --git a/problems/python3/two-sum-ii-input-array-is-sorted.py b/problems/python3/two-sum-ii-input-array-is-sorted.py new file mode 100644 index 0000000..2890404 --- /dev/null +++ b/problems/python3/two-sum-ii-input-array-is-sorted.py @@ -0,0 +1,11 @@ +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + i = 0 + j = len(numbers)-1 + + while numbers[i]+numbers[j] != target: + if numbers[i]+numbers[j] > target: + j -= 1 + else: + i += 1 + return (i+1, j+1) \ No newline at end of file diff --git a/problems/python3/valid-palindrome.py b/problems/python3/valid-palindrome.py new file mode 100644 index 0000000..0069c83 --- /dev/null +++ b/problems/python3/valid-palindrome.py @@ -0,0 +1,15 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + i = 0 + j = len(s)-1 + + while i<=j: + while i Date: Tue, 31 May 2022 09:02:47 +0800 Subject: [PATCH 25/52] combination-sum --- problems/python3/combination-sum.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 problems/python3/combination-sum.py diff --git a/problems/python3/combination-sum.py b/problems/python3/combination-sum.py new file mode 100644 index 0000000..256cefa --- /dev/null +++ b/problems/python3/combination-sum.py @@ -0,0 +1,29 @@ +""" +Time: O(N^K), assuming the number of element in the combination that sums up to "target" is K. +For each element, there is N choices. +Which means the number of combination is N*N*N... for K times. +~= O(N^K) + +Space: O(K) + +K is approximate to target/min(candidates). +""" +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + def helper(i, currSum, target): + if currSum>target: + return + + if currSum==target: + ans.append(combination.copy()) + return + + for j in range(i, len(candidates)): + combination.append(candidates[j]) + helper(j, currSum+candidates[j], target) + combination.pop() + + ans = [] + combination = [] + helper(0, 0, target) + return ans \ No newline at end of file From ec99f026ffa60f6fe8a9710dddd1ab195d5476a3 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Wed, 1 Jun 2022 09:10:09 +0800 Subject: [PATCH 26/52] permutation --- problems/python3/permutations.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 problems/python3/permutations.py diff --git a/problems/python3/permutations.py b/problems/python3/permutations.py new file mode 100644 index 0000000..98d536d --- /dev/null +++ b/problems/python3/permutations.py @@ -0,0 +1,28 @@ +""" +Time: O(N!), since we call helper() N! times. +Space: O(N) for recursion stacks. + +Whenever we call `helper()`, we pick a num that is not "used" and add it to the `permutation`. +Recursively call the `helper()` until we filled the `permutation`. +Resotre `permutation` and `used` and try another `num`. +""" +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + def helper(): + if len(permutation)==len(nums): + ans.append(permutation.copy()) + return + + for num in nums: + if num in used: continue + used.add(num) + permutation.append(num) + helper() + used.remove(num) + permutation.pop() + + ans = [] + permutation = [] + used = set() + helper() + return ans \ No newline at end of file From 06dd433f726e47c155d77dd3524fc57316a67676 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Thu, 2 Jun 2022 14:13:23 +0800 Subject: [PATCH 27/52] subsets-ii --- problems/python3/subsets-ii.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 problems/python3/subsets-ii.py diff --git a/problems/python3/subsets-ii.py b/problems/python3/subsets-ii.py new file mode 100644 index 0000000..8d6771c --- /dev/null +++ b/problems/python3/subsets-ii.py @@ -0,0 +1,19 @@ +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + def helper(i): + if i==len(nums): + ans.append(subset.copy()) + return + + subset.append(nums[i]) + helper(i+1) + subset.pop() + + while i+1 Date: Fri, 3 Jun 2022 09:10:29 +0800 Subject: [PATCH 28/52] combination-sum-ii --- problems/python3/combination-sum-ii.py | 22 ++++++++++++++++++++++ problems/python3/subsets-ii.py | 4 ++++ 2 files changed, 26 insertions(+) create mode 100644 problems/python3/combination-sum-ii.py diff --git a/problems/python3/combination-sum-ii.py b/problems/python3/combination-sum-ii.py new file mode 100644 index 0000000..c9f8957 --- /dev/null +++ b/problems/python3/combination-sum-ii.py @@ -0,0 +1,22 @@ +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + def helper(i, target): + if target==0: + ans.append(combination.copy()) + return + + if i==len(candidates) or candidates[i]>target: + return + + combination.append(candidates[i]) + helper(i+1, target-candidates[i]) + combination.pop() + + while i+1 List[List[int]]: def helper(i): From 66f6f8d6c5801228688efc0eb6073a7703572774 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 7 Jun 2022 08:14:41 +0800 Subject: [PATCH 29/52] update --- .../letter-combinations-of-a-phone-number.py | 25 ++++++++ problems/python3/palindrome-partitioning.py | 64 +++++++++++++++++++ problems/python3/word-search.py | 27 ++++++++ 3 files changed, 116 insertions(+) create mode 100644 problems/python3/letter-combinations-of-a-phone-number.py create mode 100644 problems/python3/palindrome-partitioning.py create mode 100644 problems/python3/word-search.py diff --git a/problems/python3/letter-combinations-of-a-phone-number.py b/problems/python3/letter-combinations-of-a-phone-number.py new file mode 100644 index 0000000..582106c --- /dev/null +++ b/problems/python3/letter-combinations-of-a-phone-number.py @@ -0,0 +1,25 @@ +""" +Time: O(4^N * N), there are around 4^N of combination. Each taking O(N) to form. +Space: O(N). O(N) for recursion stack. O(N). O(N) for `combination`. O(N+N) ~= O(N). +""" +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + def helper(i): + if i==len(digits): + ans.append(''.join(combination)) + return + + for c in mapping[digits[i]]: + combination.append(c) + helper(i+1) + combination.pop() + + mapping = {'2': ('a', 'b', 'c'), '3': ('d', 'e', 'f'), + '4': ('g', 'h', 'i'), '5': ('j', 'k', 'l'), '6': ('m', 'n', 'o'), + '7': ('p', 'q', 'r', 's'), '8': ('t', 'u', 'v'), '9': ('w', 'x', 'y', 'z')} + + if not digits: return [] + ans = [] + combination = [] + helper(0) + return ans \ No newline at end of file diff --git a/problems/python3/palindrome-partitioning.py b/problems/python3/palindrome-partitioning.py new file mode 100644 index 0000000..d02ef17 --- /dev/null +++ b/problems/python3/palindrome-partitioning.py @@ -0,0 +1,64 @@ +""" +`helper(i)` finds all the palindrome substring from i to j see if we can get an answer by recursively calling `helper(j+1)`. + +Time: O(2^N * N), for a string length S, there will be 2^N combination of substrings. For each substring, it will take O(N) to test if they are all palindrome. +Space: O(N). `partition` will takes O(N) and recursion stack will also take O(N). O(N + N) ~= O(N) +""" +class Solution: + def partition(self, s: str) -> List[List[str]]: + def helper(i): + if i>=len(s): + ans.append(partition.copy()) + return + + for j in range(i, len(s)): + if isPalindrome(i, j): + partition.append(s[i:j+1]) + helper(j+1) + partition.pop() + + def isPalindrome(i, j): + while i<=j: + if s[i]!=s[j]: return False + i += 1 + j -= 1 + return True + + ans = [] + partition = [] + helper(0) + return ans + +""" +If you look closely you can see that we execute `isPalindrome` on many repeated substrings. +We can optimize this by storing the result in `dp` and reuse it. +Since all the less difference i and j (shorter substring s[i:j+1]) will be process first in the `isPalindrome`. +When checking if s[i:j+1] is a palindrome or not, we can simply check the if s[i]==s[j] and the previous result (dp[i+1][j-1]) + +Time: O(2^N * N), The overall time complexity is the same, but isPalindrome is actually a lot faster. +Space: O(N^2) for `dp`. +""" +class Solution: + def partition(self, s: str) -> List[List[str]]: + def helper(i): + if i>=N: + ans.append(partition.copy()) + return + + for j in range(i, N): + if isPalindrome(i, j): + partition.append(s[i:j+1]) + helper(j+1) + partition.pop() + + def isPalindrome(i, j): + dp[i][j] = i==j or (j-i==1 and s[i]==s[j]) or (s[i]==s[j] and dp[i+1][j-1]) #len==1 palindrome or len==2 palindrome or len>=3 palindrome + return dp[i][j] + + N = len(s) + ans = [] + partition = [] + dp = [[False]*N for _ in range(N)] + + helper(0) + return ans \ No newline at end of file diff --git a/problems/python3/word-search.py b/problems/python3/word-search.py new file mode 100644 index 0000000..b7ebb09 --- /dev/null +++ b/problems/python3/word-search.py @@ -0,0 +1,27 @@ +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + def helper(x, i, j): + if i<0 or i>=N or j<0 or j>=M: return False + if (i, j) in usedWords: return False + usedWords.add((i, j)) + + if word[x]==board[i][j]: + if x==len(word)-1: + return True + else: + if helper(x+1, i+1, j): return True + if helper(x+1, i, j+1): return True + if helper(x+1, i-1, j): return True + if helper(x+1, i, j-1): return True + + + usedWords.remove((i, j)) + return False + + usedWords = set() + N = len(board) + M = len(board[0]) + for i in range(N): + for j in range(M): + if helper(0, i, j): return True + return False \ No newline at end of file From 777337b4fa073c7946eb05933875435b86335d73 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Fri, 10 Jun 2022 08:22:21 +0800 Subject: [PATCH 30/52] updates --- problems/python3/binary-search.py | 16 +++++++++ problems/python3/n-queens.py | 45 ++++++++++++++++++++++++++ problems/python3/search-a-2d-matrix.py | 22 +++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 problems/python3/binary-search.py create mode 100644 problems/python3/n-queens.py create mode 100644 problems/python3/search-a-2d-matrix.py diff --git a/problems/python3/binary-search.py b/problems/python3/binary-search.py new file mode 100644 index 0000000..2e65a63 --- /dev/null +++ b/problems/python3/binary-search.py @@ -0,0 +1,16 @@ +class Solution: + def search(self, nums: List[int], target: int) -> int: + l = 0 + r = len(nums)-1 + + while l<=r: + m = l + int((r-l)/2) + + if nums[m]>target: + r = m-1 + elif nums[m] List[List[str]]: + def helper(row: int): + if row==n: + ans.append(convertFormat(queenCols)) + return + + for col in range(n): + posDiag = row+col + negDiag = row-col + + if col in colUsed or posDiag in posDiagUsed or negDiag in negDiagUsed: continue + + queenCols.append(col) + colUsed.add(col) + posDiagUsed.add(posDiag) + negDiagUsed.add(negDiag) + + helper(row+1) + + queenCols.pop() + colUsed.remove(col) + posDiagUsed.remove(posDiag) + negDiagUsed.remove(negDiag) + + def convertFormat(queenCols: List[int]) -> List[str]: + output = [] + for col in queenCols: + row = '' + for i in range(n): + if i==col: + row += 'Q' + else: + row += '.' + output.append(row) + return output + + ans = [] + queenCols = [] + colUsed = set() + posDiagUsed = set() + negDiagUsed = set() + + helper(0) + return ans \ No newline at end of file diff --git a/problems/python3/search-a-2d-matrix.py b/problems/python3/search-a-2d-matrix.py new file mode 100644 index 0000000..2afe301 --- /dev/null +++ b/problems/python3/search-a-2d-matrix.py @@ -0,0 +1,22 @@ +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + N = len(matrix) + M = len(matrix[0]) + + l = 0 + r = N*M-1 + + while l<=r: + m = l + int((r-l)/2) + + i = int(m/M) + j = m%M + + if matrix[i][j]target: + r = m-1 + else: + return True + + return False \ No newline at end of file From 756886863aaffd597dafada0668da0ae7316ea30 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Thu, 16 Jun 2022 10:19:12 +0800 Subject: [PATCH 31/52] updates --- .../find-minimum-in-rotated-sorted-array.py | 22 +++++++++++++++ problems/python3/koko-eating-bananas.py | 21 ++++++++++++++ .../python3/median-of-two-sorted-arrays.py | 27 ++++++++++++++++++ .../python3/time-based-key-value-store.py | 28 +++++++++++++++++++ 4 files changed, 98 insertions(+) create mode 100644 problems/python3/find-minimum-in-rotated-sorted-array.py create mode 100644 problems/python3/koko-eating-bananas.py create mode 100644 problems/python3/median-of-two-sorted-arrays.py create mode 100644 problems/python3/time-based-key-value-store.py diff --git a/problems/python3/find-minimum-in-rotated-sorted-array.py b/problems/python3/find-minimum-in-rotated-sorted-array.py new file mode 100644 index 0000000..c9af305 --- /dev/null +++ b/problems/python3/find-minimum-in-rotated-sorted-array.py @@ -0,0 +1,22 @@ +""" +Usually the binary search problem, the hard part is to clear all the edge cases. +What will be the edge case? It will be when the recursive function executed at the deepest level. Usually the list with only one or two element. +So I will suggest before submit, try out the case like [0,1] or [1,0] to make sure it will not run unstop. +""" +class Solution: + def findMin(self, nums: List[int]) -> int: + def helper(l, r): + nonlocal ans + if l>r: return + + m = l + int((r-l)/2) + if nums[l]<=nums[m]: + ans = min(ans, nums[l]) + helper(m+1, r) + else: + ans = min(ans, nums[m+1]) + helper(l, m) + + ans = float('inf') + helper(0, len(nums)-1) + return ans \ No newline at end of file diff --git a/problems/python3/koko-eating-bananas.py b/problems/python3/koko-eating-bananas.py new file mode 100644 index 0000000..fe03197 --- /dev/null +++ b/problems/python3/koko-eating-bananas.py @@ -0,0 +1,21 @@ +class Solution: + def minEatingSpeed(self, piles: List[int], h: int) -> int: + def canFinish(k): + timeNeeded = 0 + for pile in piles: + timeNeeded += math.ceil(pile/k) + return timeNeeded<=h + + kMin = 1 + kMax = max(piles) + ans = kMax + + while kMin<=kMax: + k = kMin + int((kMax-kMin)/2) + if canFinish(k): + ans = min(ans, k) + kMax = k-1 + else: + kMin = k+1 + + return ans \ No newline at end of file diff --git a/problems/python3/median-of-two-sorted-arrays.py b/problems/python3/median-of-two-sorted-arrays.py new file mode 100644 index 0000000..e38e5ee --- /dev/null +++ b/problems/python3/median-of-two-sorted-arrays.py @@ -0,0 +1,27 @@ +class Solution: + def findMedianSortedArrays(self, A: List[int], B: List[int]) -> float: + if len(A)>len(B): A, B = B, A + + total = len(A)+len(B) + half = total//2 + l = 0 + r = len(A)-1 + + while True: + i = l + (r-l)//2 + j = half-(i+1)-1 + + Aleft = A[i] if i>=0 else float('-inf') + Aright = A[i+1] if i+1=0 else float('-inf') + Bright = B[j+1] if j+1Bright: + r = i-1 + else: + l = i+1 \ No newline at end of file diff --git a/problems/python3/time-based-key-value-store.py b/problems/python3/time-based-key-value-store.py new file mode 100644 index 0000000..f43facf --- /dev/null +++ b/problems/python3/time-based-key-value-store.py @@ -0,0 +1,28 @@ +class TimeMap: + + def __init__(self): + self.data = collections.defaultdict(list) + + def set(self, key: str, value: str, timestamp: int) -> None: + self.data[key].append((timestamp, value)) + + def get(self, key: str, timestamp: int) -> str: + dataList = self.data[key] + l = 0 + r = len(dataList)-1 + ans = '' + + while l<=r: + m = l + int((r-l)/2) + t = dataList[m][0] + + if ttimestamp: + r = m-1 + else: + ans = dataList[m][1] + break + + return ans \ No newline at end of file From b17819091e771eec5ad9ef71d963e535503adf84 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 21 Jun 2022 09:15:56 +0800 Subject: [PATCH 32/52] updates --- problems/python3/gas-station.py | 23 +++++++++++++++++++ problems/python3/jump-game-ii.py | 22 ++++++++++++++++++ problems/python3/jump-game.py | 10 ++++++++ problems/python3/maximum-subarray.py | 17 ++++++++++++++ .../python3/median-of-two-sorted-arrays.py | 13 +++++++++++ 5 files changed, 85 insertions(+) create mode 100644 problems/python3/gas-station.py create mode 100644 problems/python3/jump-game-ii.py create mode 100644 problems/python3/jump-game.py create mode 100644 problems/python3/maximum-subarray.py diff --git a/problems/python3/gas-station.py b/problems/python3/gas-station.py new file mode 100644 index 0000000..017eaa6 --- /dev/null +++ b/problems/python3/gas-station.py @@ -0,0 +1,23 @@ +""" +First thing, you must understand that if sum(gas)>=sum(cost) there must be an answer. Guaranteed. +If we know there is an answer, we can simply test all the index. +If the currGas ever drops to below 0, it means that we need to switch a "start". + +Time: O(N) +Space: O(1) +""" +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + if sum(gas) int: + l = r = 0 + steps = 0 + + while r bool: + maxIndex = 0 + + for i, num in enumerate(nums): + if maxIndex int: + ans = float('-inf') + currSum = 0 + + for num in nums: + if currSum<0: currSum = 0 + currSum += num + ans = max(ans, currSum) + return ans \ No newline at end of file diff --git a/problems/python3/median-of-two-sorted-arrays.py b/problems/python3/median-of-two-sorted-arrays.py index e38e5ee..0fa31da 100644 --- a/problems/python3/median-of-two-sorted-arrays.py +++ b/problems/python3/median-of-two-sorted-arrays.py @@ -1,3 +1,16 @@ +""" +Try to find a i on array A and corespoding j on array B. + +Aleft = A[i] +Aright = A[i+1] +Bleft = B[j] +Bright = B[j+1] + +Such that Aleft<=Bright and Bleft<=Aright + +This means that A[:i+1] and B[:j+1] holds all the elements that is less than the median. +Aright A[i+1:] and B[j+1:] holds all the elements that is larger or equal to the median. +""" class Solution: def findMedianSortedArrays(self, A: List[int], B: List[int]) -> float: if len(A)>len(B): A, B = B, A From ab00993db54f12ce78a71b3e072637c5ab63b66b Mon Sep 17 00:00:00 2001 From: wuduhren Date: Wed, 6 Jul 2022 08:07:03 +0200 Subject: [PATCH 33/52] updates --- problems/python3/contains-duplicate.py | 7 +++++ problems/python3/hand-of-straights.py | 18 +++++++++++++ .../merge-triplets-to-form-target-triplet.py | 15 +++++++++++ problems/python3/partition-labels.py | 26 +++++++++++++++++++ problems/python3/two-sum.py | 8 ++++++ problems/python3/valid-anagram.py | 17 ++++++++++++ problems/python3/valid-parenthesis-string.py | 23 ++++++++++++++++ 7 files changed, 114 insertions(+) create mode 100644 problems/python3/contains-duplicate.py create mode 100644 problems/python3/hand-of-straights.py create mode 100644 problems/python3/merge-triplets-to-form-target-triplet.py create mode 100644 problems/python3/partition-labels.py create mode 100644 problems/python3/two-sum.py create mode 100644 problems/python3/valid-anagram.py create mode 100644 problems/python3/valid-parenthesis-string.py diff --git a/problems/python3/contains-duplicate.py b/problems/python3/contains-duplicate.py new file mode 100644 index 0000000..7849e84 --- /dev/null +++ b/problems/python3/contains-duplicate.py @@ -0,0 +1,7 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + seen = set() + for num in nums: + if num in seen: return True + seen.add(num) + return False \ No newline at end of file diff --git a/problems/python3/hand-of-straights.py b/problems/python3/hand-of-straights.py new file mode 100644 index 0000000..f20c32d --- /dev/null +++ b/problems/python3/hand-of-straights.py @@ -0,0 +1,18 @@ +class Solution: + def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: + if len(hand)%groupSize!=0: return False + + counter = collections.Counter(hand) + h = list(counter.keys()) + heapq.heapify(h) + + while h: + minNum = h[0] + for n in range(minNum, minNum+groupSize): + if counter[n]<=0: return False + counter[n] -= 1 + if counter[n]==0: + if h[0]!=n: return False + heapq.heappop(h) + + return True \ No newline at end of file diff --git a/problems/python3/merge-triplets-to-form-target-triplet.py b/problems/python3/merge-triplets-to-form-target-triplet.py new file mode 100644 index 0000000..4708e4f --- /dev/null +++ b/problems/python3/merge-triplets-to-form-target-triplet.py @@ -0,0 +1,15 @@ +""" +If any element in the triplets is larger than the element in target, it cannot be used. +Check if we have all 3 index found the same value. +""" +class Solution: + def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: + okIndex = set() + + for a, b, c in triplets: + if a>target[0] or b>target[1] or c>target[2]: continue + if a==target[0]: okIndex.add(0) + if b==target[1]: okIndex.add(1) + if c==target[2]: okIndex.add(2) + + return len(okIndex)==3 \ No newline at end of file diff --git a/problems/python3/partition-labels.py b/problems/python3/partition-labels.py new file mode 100644 index 0000000..0c12d00 --- /dev/null +++ b/problems/python3/partition-labels.py @@ -0,0 +1,26 @@ +""" +Time: O(N) +Space: O(N) + +For each char, store its max index in maxIndex. +Iterate through the string, update the "currMax" along the way. +currMax is the place we can partition unless it get updated again. +If the current index is the currMax, update "ans". +""" +class Solution: + def partitionLabels(self, s: str) -> List[int]: + ans = [] + maxIndex = {} + + for i, c in enumerate(s): + maxIndex[c] = i + + currMax = 0 + processedLength = 0 + for i, c in enumerate(s): + currMax = max(currMax, maxIndex[c]) + if i==currMax: + ans.append(i+1 - processedLength) + processedLength += ans[-1] + + return ans \ No newline at end of file diff --git a/problems/python3/two-sum.py b/problems/python3/two-sum.py new file mode 100644 index 0000000..aa90d66 --- /dev/null +++ b/problems/python3/two-sum.py @@ -0,0 +1,8 @@ +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + #needed: {number required : counter part index} + needed = {} + for i, num in enumerate(nums): + if num in needed: + return (needed[num], i) + needed[target-num] = i \ No newline at end of file diff --git a/problems/python3/valid-anagram.py b/problems/python3/valid-anagram.py new file mode 100644 index 0000000..6c37cb0 --- /dev/null +++ b/problems/python3/valid-anagram.py @@ -0,0 +1,17 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + counter = collections.Counter() + + for c in s: + counter[c] += 1 + + for c in t: + if c not in counter: + return False + counter[c] -= 1 + + for c in counter: + if counter[c]>0: + return False + + return True \ No newline at end of file diff --git a/problems/python3/valid-parenthesis-string.py b/problems/python3/valid-parenthesis-string.py new file mode 100644 index 0000000..52ea446 --- /dev/null +++ b/problems/python3/valid-parenthesis-string.py @@ -0,0 +1,23 @@ +class Solution: + def checkValidString(self, s: str) -> bool: + leftMin = 0 + leftMax = 0 + + for c in s: + if c=='(': + leftMin += 1 + leftMax += 1 + elif c==')': + leftMin -= 1 + leftMax -= 1 + else: + leftMin -= 1 + leftMax += 1 + + if leftMax<0: + return False + + if leftMin<0: + leftMin = 0 + + return leftMin == 0 \ No newline at end of file From 881c58db2e6c7027d287ac0072444253850c51d7 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sun, 17 Jul 2022 09:24:20 +0200 Subject: [PATCH 34/52] updates --- problems/python3/encode-and-decode-strings.py | 23 ++++++++ problems/python3/group-anagrams.py | 23 ++++++++ .../python3/product-of-array-except-self.py | 45 ++++++++++++++++ problems/python3/top-k-frequent-elements.py | 53 +++++++++++++++++++ problems/python3/valid-sudoku.py | 37 +++++++++++++ 5 files changed, 181 insertions(+) create mode 100644 problems/python3/encode-and-decode-strings.py create mode 100644 problems/python3/group-anagrams.py create mode 100644 problems/python3/product-of-array-except-self.py create mode 100644 problems/python3/top-k-frequent-elements.py create mode 100644 problems/python3/valid-sudoku.py diff --git a/problems/python3/encode-and-decode-strings.py b/problems/python3/encode-and-decode-strings.py new file mode 100644 index 0000000..f38c4e4 --- /dev/null +++ b/problems/python3/encode-and-decode-strings.py @@ -0,0 +1,23 @@ +class Codec: + def encode(self, strs: List[str]) -> str: + output = '' + for string in strs: + output += str(len(string))+'#'+string + return output + + + def decode(self, s: str) -> List[str]: + output = [] + i = 0 + + while i List[List[str]]: + def normalize(string: str) -> str: + counter = collections.Counter() + ans = '' + + for c in string: + counter[c] += 1 + + for c in 'abcdefghijklmnopqrstuvwxyz': + if counter[c]>0: + ans += c+str(counter[c]) + return ans + + group = collections.defaultdict(list) + ans = [] + + for string in strs: + group[normalize(string)].append(string) + + for normalizedString in group: + ans.append(group[normalizedString]) + return ans \ No newline at end of file diff --git a/problems/python3/product-of-array-except-self.py b/problems/python3/product-of-array-except-self.py new file mode 100644 index 0000000..2309896 --- /dev/null +++ b/problems/python3/product-of-array-except-self.py @@ -0,0 +1,45 @@ +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + #left[i] := product of all nums left of nums[i] (not include nums[i]) + left = [1] + temp = 1 + for num in nums: + temp *= num + left.append(temp) + + #right[i] := product of all nums right of nums[i] (not include nums[i]) + right = [] + temp = 1 + for num in reversed(nums): + temp *= num + right.append(temp) + right.reverse() + right.append(1) + right = right[1:] + + ans = [] + for i in range(len(nums)): + ans.append(left[i]*right[i]) + return ans + +#In Place +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + N = len(nums) + ans = [0]*N + + #generate "left" + ans[0] = 1 + for i in range(1, N): + ans[i] = ans[i-1]*nums[i-1] + + #generate "right" + temp = 1 + for i in range(N-2, -1, -1): + temp *= nums[i+1] + ans[i] *= temp + + return ans + + + \ No newline at end of file diff --git a/problems/python3/top-k-frequent-elements.py b/problems/python3/top-k-frequent-elements.py new file mode 100644 index 0000000..7d728cb --- /dev/null +++ b/problems/python3/top-k-frequent-elements.py @@ -0,0 +1,53 @@ +#Bucket Sort +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + bucket = collections.defaultdict(list) + counter = collections.Counter(nums) + ans = [] + + for num in counter: + bucket[counter[num]].append(num) + + tempCount = len(nums) + while len(ans) List[int]: + def quickSelect(freqs, s, e, K): + i = s + t = s + j = e + pivot = freqs[(s+e)//2][1] + + while t<=j: + if freqs[t][1]pivot: + freqs[j], freqs[t] = freqs[t], freqs[j] + j -= 1 + else: + t += 1 + if e-j>=K: + return quickSelect(freqs, j+1, e, K) + elif e-(i-1)>=K: + return pivot + else: + return quickSelect(freqs, s, i-1, K-(e-i+1)) + + counts = collections.Counter(nums) + freqs = [(num, counts[num]) for num in counts] + ans = [] + + KthLargestFreq = quickSelect(freqs, 0, len(freqs)-1, K) + + for num, freq in freqs: + if freq>=KthLargestFreq: + ans.append(num) + return ans \ No newline at end of file diff --git a/problems/python3/valid-sudoku.py b/problems/python3/valid-sudoku.py new file mode 100644 index 0000000..b2e6fa7 --- /dev/null +++ b/problems/python3/valid-sudoku.py @@ -0,0 +1,37 @@ +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + def rowIsValid(i): + used = set() + for j in range(N): + if board[i][j]=='.': continue + if board[i][j] in used: return False + used.add(board[i][j]) + return True + + def columnIsValid(i): + used = set() + for j in range(N): + if board[j][i]=='.': continue + if board[j][i] in used: return False + used.add(board[j][i]) + return True + + def isBoxValid(i1, i2, j1, j2): + used = set() + for i in range(i1, i2+1): + for j in range(j1, j2+1): + if board[i][j]=='.': continue + if board[i][j] in used: return False + used.add(board[i][j]) + return True + + N = 9 + for i in range(N): + if not rowIsValid(i): return False + if not columnIsValid(i): return False + + for i in range(0, N, 3): + for j in range(0, N, 3): + if not isBoxValid(i, i+2, j, j+2): return False + + return True \ No newline at end of file From 53d11bc54af366f05292b39cc100faceda21b716 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sat, 23 Jul 2022 09:02:24 +0200 Subject: [PATCH 35/52] updates --- .../best-time-to-buy-and-sell-stock.py | 10 +++++++ .../python3/longest-consecutive-sequence.py | 15 ++++++++++ ...longest-repeating-character-replacement.py | 13 +++++++++ ...ongest-substring-without-repeating-char.py | 14 ++++++++++ problems/python3/permutation-in-string.py | 28 +++++++++++++++++++ 5 files changed, 80 insertions(+) create mode 100644 problems/python3/best-time-to-buy-and-sell-stock.py create mode 100644 problems/python3/longest-consecutive-sequence.py create mode 100644 problems/python3/longest-repeating-character-replacement.py create mode 100644 problems/python3/longest-substring-without-repeating-char.py create mode 100644 problems/python3/permutation-in-string.py diff --git a/problems/python3/best-time-to-buy-and-sell-stock.py b/problems/python3/best-time-to-buy-and-sell-stock.py new file mode 100644 index 0000000..f04ad91 --- /dev/null +++ b/problems/python3/best-time-to-buy-and-sell-stock.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + minPrice = prices[0] + ans = 0 + + for i in range(1, len(prices)): + ans = max(ans, prices[i]-minPrice) + minPrice = min(prices[i], minPrice) + + return ans \ No newline at end of file diff --git a/problems/python3/longest-consecutive-sequence.py b/problems/python3/longest-consecutive-sequence.py new file mode 100644 index 0000000..dec2cfa --- /dev/null +++ b/problems/python3/longest-consecutive-sequence.py @@ -0,0 +1,15 @@ +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + numSet = set(nums) + ans = 0 + + for num in nums: + isStart = num-1 not in numSet + if isStart: + count = 0 + temp = num + while temp in numSet: + count += 1 + temp += 1 + ans = max(count, ans) + return ans \ No newline at end of file diff --git a/problems/python3/longest-repeating-character-replacement.py b/problems/python3/longest-repeating-character-replacement.py new file mode 100644 index 0000000..714d8f1 --- /dev/null +++ b/problems/python3/longest-repeating-character-replacement.py @@ -0,0 +1,13 @@ +class Solution: + def characterReplacement(self, s: str, k: int) -> int: + counter = collections.Counter() + l = 0 + ans = 0 + + for r in range(len(s)): + counter[s[r]] += 1 + while (r-l+1)-max(counter.values()) > k: + counter[s[l]] -= 1 + l += 1 + ans = max(ans, r-l+1) + return ans \ No newline at end of file diff --git a/problems/python3/longest-substring-without-repeating-char.py b/problems/python3/longest-substring-without-repeating-char.py new file mode 100644 index 0000000..9902bb5 --- /dev/null +++ b/problems/python3/longest-substring-without-repeating-char.py @@ -0,0 +1,14 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + ans = 0 + l = 0 + seen = set() + + for r in range(len(s)): + while s[r] in seen: + seen.remove(s[l]) + l += 1 + seen.add(s[r]) + ans = max(ans, r-l+1) + + return ans \ No newline at end of file diff --git a/problems/python3/permutation-in-string.py b/problems/python3/permutation-in-string.py new file mode 100644 index 0000000..cd22781 --- /dev/null +++ b/problems/python3/permutation-in-string.py @@ -0,0 +1,28 @@ +class Solution: + def checkInclusion(self, s1: str, s2: str) -> bool: + if len(s1)>len(s2): return False + + counter1 = collections.Counter(s1) + counter2 = collections.Counter(s2[:len(s1)]) + matches = 0 + for c in 'abcdefghijklmnopqrstuvwxyz': + if counter1[c]==counter2[c]: matches += 1 + if matches==26: return True + + l = 0 + for r in range(len(s1), len(s2)): + counter2[s2[r]] += 1 + if counter1[s2[r]]==counter2[s2[r]]: + matches += 1 + elif counter1[s2[r]]+1==counter2[s2[r]]: + matches -= 1 + + counter2[s2[l]] -= 1 + if counter1[s2[l]]==counter2[s2[l]]: + matches += 1 + elif counter1[s2[l]]-1==counter2[s2[l]]: + matches -= 1 + l += 1 + + if matches==26: return True + return False \ No newline at end of file From b68839f9141a93ad4e002480b308651ab4c35565 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Mon, 1 Aug 2022 08:06:03 +0200 Subject: [PATCH 36/52] update --- problems/python3/minimum-window-substring.py | 25 ++++++++++++++++++++ problems/python3/sliding-window-maximum.py | 18 ++++++++++++++ problems/python3/valid-parentheses.py | 17 +++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 problems/python3/minimum-window-substring.py create mode 100644 problems/python3/sliding-window-maximum.py create mode 100644 problems/python3/valid-parentheses.py diff --git a/problems/python3/minimum-window-substring.py b/problems/python3/minimum-window-substring.py new file mode 100644 index 0000000..1a23a82 --- /dev/null +++ b/problems/python3/minimum-window-substring.py @@ -0,0 +1,25 @@ +class Solution: + def minWindow(self, s: str, t: str) -> str: + if len(t)>len(s): return "" + + ans = "" + counter1 = collections.Counter(t) + charSet = set(t) + counter2 = collections.Counter() #sliding window in string s, index between l and r + charSet2 = set(s) + matchCount = 0 #count of char in the sliding window that counts are larger than the char count in t. + + l = 0 + for r in range(len(s)): + counter2[s[r]] += 1 + + if s[r] in charSet and counter1[s[r]]==counter2[s[r]]: matchCount += 1 + + while lcounter1[s[l]]): + counter2[s[l]] -= 1 + l += 1 + + if matchCount==len(charSet) and (ans=="" or r-l+1 List[int]: + ans = [] + q = collections.deque() + l = r = 0 + + while r bool: + mapping = {')': '(', ']': '[', '}':'{'} + stack = [] + + for c in s: + if c not in mapping: + #open parentheses + stack.append(c) + else: + #close parentheses + if stack and stack[-1]==mapping[c]: + stack.pop() + else: + return False + + return not stack \ No newline at end of file From 612e17e73b2f8f3df6158cfd68f837f7a942eed3 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 9 Aug 2022 07:17:56 +0200 Subject: [PATCH 37/52] update --- problems/python3/car-fleet.py | 16 +++++++++++++ problems/python3/daily-temperatures.py | 12 ++++++++++ .../evaluate-reverse-polish-notation.py | 22 ++++++++++++++++++ problems/python3/generate-parentheses.py | 20 ++++++++++++++++ problems/python3/min-stack.py | 23 +++++++++++++++++++ 5 files changed, 93 insertions(+) create mode 100644 problems/python3/car-fleet.py create mode 100644 problems/python3/daily-temperatures.py create mode 100644 problems/python3/evaluate-reverse-polish-notation.py create mode 100644 problems/python3/generate-parentheses.py create mode 100644 problems/python3/min-stack.py diff --git a/problems/python3/car-fleet.py b/problems/python3/car-fleet.py new file mode 100644 index 0000000..24ccba8 --- /dev/null +++ b/problems/python3/car-fleet.py @@ -0,0 +1,16 @@ +class Solution: + def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: + N = len(position) + + timeInfo = [] + for i in range(N): + timeInfo.append((position[i], (target-position[i])/speed[i])) + timeInfo.sort(reverse=True) + + stack = [] + for _, time in timeInfo: + stack.append(time) + if len(stack)>=2 and stack[-2]>=stack[-1]: + stack.pop() + + return len(stack) \ No newline at end of file diff --git a/problems/python3/daily-temperatures.py b/problems/python3/daily-temperatures.py new file mode 100644 index 0000000..d6e4c98 --- /dev/null +++ b/problems/python3/daily-temperatures.py @@ -0,0 +1,12 @@ +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: + ans = [0]*len(temperatures) + stack = [] + + for i, temp in enumerate(temperatures): + while stack and stack[-1][0] int: + operators = set(['+', '-', '*', '/']) + stack = [] + + for c in tokens: + if c in operators: + n2 = stack.pop() + n1 = stack.pop() + + if c=='+': + stack.append(n1+n2) + elif c=='-': + stack.append(n1-n2) + elif c=='*': + stack.append(n1*n2) + elif c=='/': + stack.append(int(n1/n2)) + else: + stack.append(int(c)) + + return stack.pop() \ No newline at end of file diff --git a/problems/python3/generate-parentheses.py b/problems/python3/generate-parentheses.py new file mode 100644 index 0000000..9b96ef9 --- /dev/null +++ b/problems/python3/generate-parentheses.py @@ -0,0 +1,20 @@ +class Solution: + def generateParenthesis(self, n: int) -> List[str]: + def helper(parentheses, left, right): + if len(parentheses)==n*2: + ans.append("".join(parentheses)) + return + + if leftright: + parentheses.append(')') + helper(parentheses, left, right+1) + parentheses.pop() + + ans = [] + helper([], 0, 0) + return ans \ No newline at end of file diff --git a/problems/python3/min-stack.py b/problems/python3/min-stack.py new file mode 100644 index 0000000..8fe03de --- /dev/null +++ b/problems/python3/min-stack.py @@ -0,0 +1,23 @@ +#"stack" is just a normal stack. +#"minStack" stores the min of the stack element in the same position. +#i.e. At the time stack[x] put in to the stack. minStack[x] is the min. + +class MinStack: + + def __init__(self): + self.stack = [] + self.minStack = [] + + def push(self, val: int) -> None: + self.stack.append(val) + self.minStack.append(val if (not self.minStack or val None: + self.minStack.pop() + return self.stack.pop() + + def top(self) -> int: + return self.stack[-1] + + def getMin(self) -> int: + return self.minStack[-1] \ No newline at end of file From 102969667a38c53844cfa5b2b94353e4ad547d4e Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sun, 14 Aug 2022 14:52:03 +0200 Subject: [PATCH 38/52] Updates --- .../python3/copy-list-with-random-pointer.py | 34 ++++++++++++++ .../python3/largest-rectangle-in-histogram.py | 21 +++++++++ problems/python3/merge-two-sorted-lists.py | 15 ++++++ .../remove-nth-node-from-end-of-list.py | 47 +++++++++++++++++++ problems/python3/reorder-list.py | 37 +++++++++++++++ problems/python3/reverse-linked-list.py | 21 +++++++++ 6 files changed, 175 insertions(+) create mode 100644 problems/python3/copy-list-with-random-pointer.py create mode 100644 problems/python3/largest-rectangle-in-histogram.py create mode 100644 problems/python3/merge-two-sorted-lists.py create mode 100644 problems/python3/remove-nth-node-from-end-of-list.py create mode 100644 problems/python3/reorder-list.py create mode 100644 problems/python3/reverse-linked-list.py diff --git a/problems/python3/copy-list-with-random-pointer.py b/problems/python3/copy-list-with-random-pointer.py new file mode 100644 index 0000000..4436b78 --- /dev/null +++ b/problems/python3/copy-list-with-random-pointer.py @@ -0,0 +1,34 @@ +""" +Time: O(N) +Space: O(1) + +The easiest way would be maintaining a hash map for original node to the copy and the other way around. Then the rest is easy. +But this will take us O(N) of extra space. + +Two pass solution with constant space. +First pass. +Create a copy of the original and store it inside "random". +The copy points to original's next and original's random. + +Second pass. +Iterate through the nodes again. +This time we adjust the copy to point to the other copies. +""" +class Solution: + def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': + if not head: return head + + node = head + while node: + copy = Node(node.val, node.next, node.random) + node.random = copy + node = node.next + + node = head + while node: + newNode = node.random + if node.next: newNode.next = node.next.random + if newNode.random: newNode.random = newNode.random.random + node = node.next + + return head.random \ No newline at end of file diff --git a/problems/python3/largest-rectangle-in-histogram.py b/problems/python3/largest-rectangle-in-histogram.py new file mode 100644 index 0000000..1cf8508 --- /dev/null +++ b/problems/python3/largest-rectangle-in-histogram.py @@ -0,0 +1,21 @@ +""" +[0] For each height, if the it is lower than the previous one, it means that the previous are not able to extend anymore. So we calculate its area. + +[1] If the previous area, is larger than the current one, it means that the current one are able to extand backward. +""" +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + maxArea = 0 + stack = [] + + heights.append(0) #dummy for the ending + + for i, h in enumerate(heights): + start = i + while stack and h Optional[ListNode]: + head = ListNode() #dummy + node = head + while list1 and list2: + if list1.val Optional[ListNode]: + #count the length of the linked list + node = head + count = 0 + while node: + count += 1 + node = node.next + + + node = head + steps = count-n-1 + + #steps==-1 means that we need to remove the first node + if steps==-1: return head.next + + #traverse to the node before the node we wanted to remove + while steps>0: + node = node.next + steps -= 1 + + #remove "node.next" + node.next = node.next.next + + return head + + +#One pass. Fast pointer is ahead of slow pointer by n+1 +#So slow pointer will stop at the node before the node we wanted to remove +class Solution: + def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: + dummy = ListNode() + dummy.next = head + + ahead = n+1 + fast = dummy + slow = dummy + + while fast: + fast = fast.next + ahead -= 1 + if ahead<0: slow = slow.next + + slow.next = slow.next.next + + return dummy.next \ No newline at end of file diff --git a/problems/python3/reorder-list.py b/problems/python3/reorder-list.py new file mode 100644 index 0000000..89c6ba2 --- /dev/null +++ b/problems/python3/reorder-list.py @@ -0,0 +1,37 @@ +class Solution: + def reorderList(self, head: Optional[ListNode]) -> None: + #find the middle point + slow = head + fast = head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + middle = slow.next + + #reverse the linked list after the middle point + middle = self.reverseList(middle) + + #separate the linked list before the middle + slow.next = None + + #merge two linked list + node = head + while middle and node: + nextNode = node.next + node.next = middle + middle = middle.next + node.next.next = nextNode + node = nextNode + return head + + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + pre = None + node = head + + while node: + nextNode = node.next + node.next = pre + if not nextNode: return node + pre = node + node = nextNode + \ No newline at end of file diff --git a/problems/python3/reverse-linked-list.py b/problems/python3/reverse-linked-list.py new file mode 100644 index 0000000..c9c0655 --- /dev/null +++ b/problems/python3/reverse-linked-list.py @@ -0,0 +1,21 @@ +#Recursive +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + if not head or not head.next: return head + temp = self.reverseList(head.next) + head.next.next = head + head.next = None + return temp + +#Iterative +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + pre = None + node = head + + while node: + nextNode = node.next + node.next = pre + if not nextNode: return node + pre = node + node = nextNode \ No newline at end of file From 543e1f893e54b6bb47139db24531ea84ddd92534 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sat, 20 Aug 2022 09:32:32 +0200 Subject: [PATCH 39/52] updates --- problems/python3/add-two-numbers.py | 19 ++++++++ problems/python3/find-the-duplicate-number.py | 16 +++++++ .../kth-largest-element-in-a-stream.py | 14 ++++++ problems/python3/last-stone-weight.py | 12 +++++ problems/python3/linked-list-cycle.py | 16 +++++++ problems/python3/lru-cache.py | 47 +++++++++++++++++++ 6 files changed, 124 insertions(+) create mode 100644 problems/python3/add-two-numbers.py create mode 100644 problems/python3/find-the-duplicate-number.py create mode 100644 problems/python3/kth-largest-element-in-a-stream.py create mode 100644 problems/python3/last-stone-weight.py create mode 100644 problems/python3/linked-list-cycle.py create mode 100644 problems/python3/lru-cache.py diff --git a/problems/python3/add-two-numbers.py b/problems/python3/add-two-numbers.py new file mode 100644 index 0000000..ed9dee4 --- /dev/null +++ b/problems/python3/add-two-numbers.py @@ -0,0 +1,19 @@ +class Solution: + def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: + carry = 0 + dummy = ListNode() + curr = dummy + + while l1 or l2 or carry: + n = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry + if n>=10: + curr.next = ListNode(n-10) + carry = 1 + else: + curr.next = ListNode(n) + carry = 0 + curr = curr.next + if l1: l1 = l1.next + if l2: l2 = l2.next + + return dummy.next \ No newline at end of file diff --git a/problems/python3/find-the-duplicate-number.py b/problems/python3/find-the-duplicate-number.py new file mode 100644 index 0000000..41636df --- /dev/null +++ b/problems/python3/find-the-duplicate-number.py @@ -0,0 +1,16 @@ +class Solution: + def findDuplicate(self, nums: List[int]) -> int: + head = nums[0] + slow = head + fast = head + + while True: + slow = nums[slow] + fast = nums[nums[fast]] + if slow==fast: break + + slow = head + while slow!=fast: + slow = nums[slow] + fast = nums[fast] + return slow \ No newline at end of file diff --git a/problems/python3/kth-largest-element-in-a-stream.py b/problems/python3/kth-largest-element-in-a-stream.py new file mode 100644 index 0000000..1eb9095 --- /dev/null +++ b/problems/python3/kth-largest-element-in-a-stream.py @@ -0,0 +1,14 @@ +class KthLargest: + + def __init__(self, k: int, nums: List[int]): + self.k = k + self.nums = nums + + heapq.heapify(self.nums) + while len(self.nums)>self.k: heapq.heappop(self.nums) + + + def add(self, val: int) -> int: + heapq.heappush(self.nums, val) + if len(self.nums)>self.k: heapq.heappop(self.nums) + return self.nums[0] \ No newline at end of file diff --git a/problems/python3/last-stone-weight.py b/problems/python3/last-stone-weight.py new file mode 100644 index 0000000..9b30665 --- /dev/null +++ b/problems/python3/last-stone-weight.py @@ -0,0 +1,12 @@ +class Solution: + def lastStoneWeight(self, stones: List[int]) -> int: + stones = [-stone for stone in stones] + heapq.heapify(stones) + + while len(stones)>=2: + w1 = -heapq.heappop(stones) + w2 = -heapq.heappop(stones) + + if w1-w2>0: heapq.heappush(stones, -(w1-w2)) + + return -stones[0] if stones else 0 \ No newline at end of file diff --git a/problems/python3/linked-list-cycle.py b/problems/python3/linked-list-cycle.py new file mode 100644 index 0000000..d2e5395 --- /dev/null +++ b/problems/python3/linked-list-cycle.py @@ -0,0 +1,16 @@ +class Solution: + def hasCycle(self, head: Optional[ListNode]) -> bool: + if not head: return False + + slow = head + fast = head + + while fast: + slow = slow.next + + if not fast.next: return False + fast = fast.next.next + + if slow==fast: return True + + return False \ No newline at end of file diff --git a/problems/python3/lru-cache.py b/problems/python3/lru-cache.py new file mode 100644 index 0000000..7cb1822 --- /dev/null +++ b/problems/python3/lru-cache.py @@ -0,0 +1,47 @@ +class Node: + def __init__(self, key: int, val: int): + self.key = key + self.val = val + self.next = None + self.prev = None + +class LRUCache: + + def __init__(self, capacity: int): + self.capacity = capacity + self.dic = {} #[0] + self.head = Node(0, 0) #[3] + self.tail = Node(0, 0) #[3] + self.head.next = self.tail + self.tail.prev = self.head + + def remove(self, node): + node.prev.next = node.next + node.next.prev = node.prev + + def promote(self, node): #[1] + #set the node next to head + temp = self.head.next + node.next = temp + temp.prev = node + self.head.next = node + node.prev = self.head + + def get(self, key: int) -> int: + if key in self.dic: + node = self.dic[key] + self.remove(node) + self.promote(node) + return node.val + return -1 + + def put(self, key: int, value: int) -> None: + if key in self.dic: + self.remove(self.dic[key]) + node = Node(key, value) + self.promote(node) + self.dic[key] = node + + if len(self.dic)>self.capacity: #[2] + del self.dic[self.tail.prev.key] + self.remove(self.tail.prev) From 758ba68d95d77c4fe7e73a3caec7f79331c73fd0 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Thu, 25 Aug 2022 08:36:37 +0200 Subject: [PATCH 40/52] Updates --- problems/python3/design-twitter.py | 49 +++++++++++++++++++ .../python3/find-median-from-data-stream.py | 32 ++++++++++++ .../python3/k-closest-points-to-origin.py | 10 ++++ problems/python3/task-scheduler.py | 23 +++++++++ 4 files changed, 114 insertions(+) create mode 100644 problems/python3/design-twitter.py create mode 100644 problems/python3/find-median-from-data-stream.py create mode 100644 problems/python3/k-closest-points-to-origin.py create mode 100644 problems/python3/task-scheduler.py diff --git a/problems/python3/design-twitter.py b/problems/python3/design-twitter.py new file mode 100644 index 0000000..a2781ae --- /dev/null +++ b/problems/python3/design-twitter.py @@ -0,0 +1,49 @@ +class Twitter: + + def __init__(self): + self.followData = collections.defaultdict(set) + self.tweetData = collections.defaultdict(list) + self.count = 0 + + + def postTweet(self, userId: int, tweetId: int) -> None: + self.tweetData[userId].append((self.count, tweetId)) + self.count -= 1 + + + def getNewsFeed(self, userId: int) -> List[int]: + newsFeed = [] + h = [] + + self.followData[userId].add(userId) + for followeeId in self.followData[userId]: + if followeeId not in self.tweetData: continue + index = len(self.tweetData[followeeId])-1 + count, tweetId = self.tweetData[followeeId][index] + h.append((count, tweetId, followeeId, index-1)) + heapq.heapify(h) + + while h and len(newsFeed)<10: + _, tweetId, userId, index = heapq.heappop(h) + newsFeed.append(tweetId) + if index>=0: + count, tweetId2 = self.tweetData[userId][index] + heapq.heappush(h, (count, tweetId2, userId, index-1)) + return newsFeed + + + + def follow(self, followerId: int, followeeId: int) -> None: + self.followData[followerId].add(followeeId) + + def unfollow(self, followerId: int, followeeId: int) -> None: + if followerId not in self.followData: return + self.followData[followerId].remove(followeeId) + + +# Your Twitter object will be instantiated and called as such: +# obj = Twitter() +# obj.postTweet(userId,tweetId) +# param_2 = obj.getNewsFeed(userId) +# obj.follow(followerId,followeeId) +# obj.unfollow(followerId,followeeId) \ No newline at end of file diff --git a/problems/python3/find-median-from-data-stream.py b/problems/python3/find-median-from-data-stream.py new file mode 100644 index 0000000..f83ee40 --- /dev/null +++ b/problems/python3/find-median-from-data-stream.py @@ -0,0 +1,32 @@ +class MedianFinder: + + def __init__(self): + self.large = [] #store nums larger or equal to the median + self.small = [] #store nums samaller to the median + + def addNum(self, num: int) -> None: + if not self.large and not self.small: + heapq.heappush(self.large, num) + elif num>=self.findMedian(): + heapq.heappush(self.large, num) + self.balance() + else: + heapq.heappush(self.small, -num) + self.balance() + + def balance(self) -> None: + #make the length of two heaps as even as posible + if len(self.large)>len(self.small)+1: + num = heapq.heappop(self.large) + heapq.heappush(self.small, -num) + + if len(self.small)>len(self.large): + num = -heapq.heappop(self.small) + heapq.heappush(self.large, num) + + + def findMedian(self) -> float: + if (len(self.large)+len(self.small))%2==0: + return (self.large[0]-self.small[0])/2 + else: + return self.large[0] \ No newline at end of file diff --git a/problems/python3/k-closest-points-to-origin.py b/problems/python3/k-closest-points-to-origin.py new file mode 100644 index 0000000..8f08e89 --- /dev/null +++ b/problems/python3/k-closest-points-to-origin.py @@ -0,0 +1,10 @@ +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + h = [] + + for x, y in points: + dis = (x**2+y**2)**0.5 + heapq.heappush(h, (-dis, x, y)) + if len(h)>k: heapq.heappop(h) + + return [(x, y) for dis, x, y in h] \ No newline at end of file diff --git a/problems/python3/task-scheduler.py b/problems/python3/task-scheduler.py new file mode 100644 index 0000000..ddc4625 --- /dev/null +++ b/problems/python3/task-scheduler.py @@ -0,0 +1,23 @@ +class Solution: + def leastInterval(self, tasks: List[str], n: int) -> int: + q = collections.deque() + h = [] + time = 0 + + counter = collections.Counter(tasks) + for task in counter: + heapq.heappush(h, (-counter[task], task)) + + while h or q: + if q and q[0][0]<=time: + _, count, task = q.popleft() + heapq.heappush(h, (-count, task)) + + if h: + count, task = heapq.heappop(h) + count*=-1 + count -= 1 + if count>0: q.append((time+n+1, count, task)) + time += 1 + + return time \ No newline at end of file From 91179a34bf0c718a86696aebf151f5e3e1f45101 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Fri, 2 Sep 2022 11:09:53 +0200 Subject: [PATCH 41/52] updates --- problems/python3/merge-intervals.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 problems/python3/merge-intervals.py diff --git a/problems/python3/merge-intervals.py b/problems/python3/merge-intervals.py new file mode 100644 index 0000000..c8a4678 --- /dev/null +++ b/problems/python3/merge-intervals.py @@ -0,0 +1,17 @@ +""" +Time: O(NLogN) for sorting +Space: O(1) excluding the output. +""" +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + ans = [] + intervals.sort() + + for s, e in intervals: + if not ans: + ans.append([s, e]) + elif ans[-1][1]>=s: + ans[-1][1] = max(ans[-1][1], e) + else: + ans.append([s, e]) + return ans \ No newline at end of file From dddf785deb5d9faae06e29b008d7a11aea93e6f5 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Fri, 2 Sep 2022 11:10:23 +0200 Subject: [PATCH 42/52] updates --- problems/python3/insert-interval.py | 23 +++++++++++++++++++ problems/python3/meeting-rooms-ii.py | 12 ++++++++++ problems/python3/meeting-rooms.py | 10 ++++++++ .../minimum-interval-to-include-each-query.py | 23 +++++++++++++++++++ problems/python3/non-overlapping-intervals.py | 17 ++++++++++++++ 5 files changed, 85 insertions(+) create mode 100644 problems/python3/insert-interval.py create mode 100644 problems/python3/meeting-rooms-ii.py create mode 100644 problems/python3/meeting-rooms.py create mode 100644 problems/python3/minimum-interval-to-include-each-query.py create mode 100644 problems/python3/non-overlapping-intervals.py diff --git a/problems/python3/insert-interval.py b/problems/python3/insert-interval.py new file mode 100644 index 0000000..667ba04 --- /dev/null +++ b/problems/python3/insert-interval.py @@ -0,0 +1,23 @@ +class Solution: + def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: + ans = [] + i = 0 + + #add intervals before newInterval + while i int: + intervals.sort() + h = [] + ans = 0 + + for s, e in intervals: + while h and s>=h[0][0]: + heapq.heappop(h) + heapq.heappush(h, (e, s)) + ans = max(ans, len(h)) + return ans \ No newline at end of file diff --git a/problems/python3/meeting-rooms.py b/problems/python3/meeting-rooms.py new file mode 100644 index 0000000..60cf429 --- /dev/null +++ b/problems/python3/meeting-rooms.py @@ -0,0 +1,10 @@ +class Solution: + def canAttendMeetings(self, intervals: List[List[int]]) -> bool: + intervals.sort() + lastEnd = float('-inf') + for s, e in intervals: + if lastEnd>s: + return False + else: + lastEnd = e + return True \ No newline at end of file diff --git a/problems/python3/minimum-interval-to-include-each-query.py b/problems/python3/minimum-interval-to-include-each-query.py new file mode 100644 index 0000000..ca43de3 --- /dev/null +++ b/problems/python3/minimum-interval-to-include-each-query.py @@ -0,0 +1,23 @@ +class Solution: + def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: + ans = [-1]*len(queries) + queries = sorted([(query, i) for i, query in enumerate(queries)]) + intervals.sort() + h = [] + + itervalIndex = 0 + for query, queryIndex in queries: + #push all intervals that include 'query' to the min heap + while itervalIndex int: + intervals.sort() + + ans = 0 + prevEnd = intervals[0][1] + + for s, e in intervals[1:]: + if s>=prevEnd: + prevEnd = e + else: + ans += 1 + prevEnd = min(prevEnd, e) + return ans \ No newline at end of file From 5a67c5f093445a44278d7a1e9eeb02c2a5a858fd Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 20 Sep 2022 07:46:21 +0200 Subject: [PATCH 43/52] updates --- problems/python3/clone-graph.py | 16 ++++++ problems/python3/course-schedule-ii.py | 30 +++++++++++ problems/python3/course-schedule.py | 23 ++++++++ ...ign-add-and-search-words-data-structure.py | 33 ++++++++++++ .../python3/implement-trie-prefix-tree.py | 26 +++++++++ problems/python3/max-area-of-island.py | 23 ++++++++ problems/python3/number-of-islands.py | 22 ++++++++ .../python3/pacific-atlantic-water-flow.py | 30 +++++++++++ problems/python3/rotting-oranges.py | 35 ++++++++++++ problems/python3/surrounded-regions.py | 34 ++++++++++++ problems/python3/walls-and-gates.py | 29 ++++++++++ problems/python3/word-search-ii.py | 54 +++++++++++++++++++ 12 files changed, 355 insertions(+) create mode 100644 problems/python3/clone-graph.py create mode 100644 problems/python3/course-schedule-ii.py create mode 100644 problems/python3/course-schedule.py create mode 100644 problems/python3/design-add-and-search-words-data-structure.py create mode 100644 problems/python3/implement-trie-prefix-tree.py create mode 100644 problems/python3/max-area-of-island.py create mode 100644 problems/python3/number-of-islands.py create mode 100644 problems/python3/pacific-atlantic-water-flow.py create mode 100644 problems/python3/rotting-oranges.py create mode 100644 problems/python3/surrounded-regions.py create mode 100644 problems/python3/walls-and-gates.py create mode 100644 problems/python3/word-search-ii.py diff --git a/problems/python3/clone-graph.py b/problems/python3/clone-graph.py new file mode 100644 index 0000000..9a6765f --- /dev/null +++ b/problems/python3/clone-graph.py @@ -0,0 +1,16 @@ +class Solution: + def cloneGraph(self, start: 'Node') -> 'Node': + def dfs(node): + if node in clones: return clones[node] + + copy = Node(node.val) + clones[node] = copy + + for neighbor in node.neighbors: + copy.neighbors.append(dfs(neighbor)) + + return clones[node] + if not start: return start + clones = {} + dfs(start) + return clones[start] \ No newline at end of file diff --git a/problems/python3/course-schedule-ii.py b/problems/python3/course-schedule-ii.py new file mode 100644 index 0000000..00725b4 --- /dev/null +++ b/problems/python3/course-schedule-ii.py @@ -0,0 +1,30 @@ +#Topological Sort +class Solution: + def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: + sortedCourse = [] + G = collections.defaultdict(list) #graph + inbounds = collections.Counter() + q = collections.deque() + + #build graph + for c1, c2 in prerequisites: + G[c2].append(c1) + inbounds[c1] += 1 + + #add the starting point to the q. (the ones that have 0 inbounds) + for course in range(numCourses): + if inbounds[course]==0: q.append(course) + + #add the course that have 0 inbounds to the sortedCourse. + #after that, imagine we remove it from the graph, so nextCourse inbound will -1 + #add to q if nextCourse have 0 inbounds + while q: + course = q.popleft() + + sortedCourse.append(course) + + for nextCourse in G[course]: + inbounds[nextCourse] -= 1 + if inbounds[nextCourse]==0: q.append(nextCourse) + + return sortedCourse if len(sortedCourse)==numCourses else [] \ No newline at end of file diff --git a/problems/python3/course-schedule.py b/problems/python3/course-schedule.py new file mode 100644 index 0000000..f52d07d --- /dev/null +++ b/problems/python3/course-schedule.py @@ -0,0 +1,23 @@ +class Solution: + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: + sortedCourse = [] + inbounds = collections.Counter() + G = collections.defaultdict(list) + q = collections.deque() + + for c1, c2 in prerequisites: + G[c2].append(c1) + inbounds[c1] += 1 + + for c in range(numCourses): + if inbounds[c]==0: q.append(c) + + while q: + c = q.popleft() + + for c2 in G[c]: + inbounds[c2] -= 1 + if inbounds[c2]==0: q.append(c2) + sortedCourse.append(c) + + return len(sortedCourse)==numCourses \ No newline at end of file diff --git a/problems/python3/design-add-and-search-words-data-structure.py b/problems/python3/design-add-and-search-words-data-structure.py new file mode 100644 index 0000000..52effc8 --- /dev/null +++ b/problems/python3/design-add-and-search-words-data-structure.py @@ -0,0 +1,33 @@ +class WordDictionary: + + def __init__(self): + self.root = {} + + def addWord(self, word: str) -> None: + node = self.root + for c in word: + if c not in node: node[c] = {} + node = node[c] + node['$'] = {} #'.' means the end of the word + + def search(self, word: str) -> bool: + def helper(node, i): + if i==len(word): return '$' in node + + if word[i]=='.': + for c in node: + if helper(node[c], i+1): return True + return False + else: + if word[i] not in node: return False + return helper(node[word[i]], i+1) + return helper(self.root, 0) + + + + + + + + + \ No newline at end of file diff --git a/problems/python3/implement-trie-prefix-tree.py b/problems/python3/implement-trie-prefix-tree.py new file mode 100644 index 0000000..1118e97 --- /dev/null +++ b/problems/python3/implement-trie-prefix-tree.py @@ -0,0 +1,26 @@ +class Trie: + + def __init__(self): + self.root = {} + + def insert(self, word: str) -> None: + node = self.root + for c in word: + if c not in node: node[c] = {} + node = node[c] + node['.'] = {} #'.' means the end of the word + + + def search(self, word: str) -> bool: + node = self.root + for c in word: + if c not in node: return False + node = node[c] + return '.' in node + + def startsWith(self, prefix: str) -> bool: + node = self.root + for c in prefix: + if c not in node: return False + node = node[c] + return True diff --git a/problems/python3/max-area-of-island.py b/problems/python3/max-area-of-island.py new file mode 100644 index 0000000..fd55a94 --- /dev/null +++ b/problems/python3/max-area-of-island.py @@ -0,0 +1,23 @@ +class Solution: + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: + def dfs(i, j) -> int: + if i<0 or j<0 or i>=MAX_ROW or j>=MAX_COL: return 0 + if grid[i][j]==0 or grid[i][j]==2: return 0 + + grid[i][j] = 2 #mark as visited + + area = 1 + area += dfs(i+1, j) + area += dfs(i-1, j) + area += dfs(i, j+1) + area += dfs(i, j-1) + return area + + ans = 0 + MAX_ROW = len(grid) + MAX_COL = len(grid[0]) + + for i in range(MAX_ROW): + for j in range(MAX_COL): + ans = max(ans, dfs(i, j)) + return ans \ No newline at end of file diff --git a/problems/python3/number-of-islands.py b/problems/python3/number-of-islands.py new file mode 100644 index 0000000..6cc325e --- /dev/null +++ b/problems/python3/number-of-islands.py @@ -0,0 +1,22 @@ +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + def dfs(i, j): + if i<0 or j<0 or i>=MAX_ROWS or j>=MAX_COLS: return + if grid[i][j]!='1': return + + grid[i][j] = '2' + dfs(i+1, j) + dfs(i-1, j) + dfs(i, j+1) + dfs(i, j-1) + + count = 0 + MAX_ROWS = len(grid) + MAX_COLS = len(grid[0]) + + for i in range(MAX_ROWS): + for j in range(MAX_COLS): + if grid[i][j]=='1': + dfs(i, j) + count += 1 + return count \ No newline at end of file diff --git a/problems/python3/pacific-atlantic-water-flow.py b/problems/python3/pacific-atlantic-water-flow.py new file mode 100644 index 0000000..05032b0 --- /dev/null +++ b/problems/python3/pacific-atlantic-water-flow.py @@ -0,0 +1,30 @@ +class Solution: + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: + def bfs(q, ocian): + while q: + i0, j0 = q.popleft() + if (i0, j0) in ocian: continue + ocian.add((i0, j0)) + + for i, j in ((i0+1, j0), (i0-1, j0), (i0, j0+1), (i0, j0-1)): + if i<0 or j<0 or i>=MAX_ROW or j>=MAX_COL: continue + if heights[i][j]>=heights[i0][j0]: q.append((i, j)) + + MAX_ROW = len(heights) + MAX_COL = len(heights[0]) + + #add the top and left to q1 + pacific = set() + q1 = collections.deque() + for j in range(MAX_COL): q1.append((0, j)) + for i in range(MAX_ROW): q1.append((i, 0)) + + #add botton and right to q2 + atlantic = set() + q2 = collections.deque() + for j in range(MAX_COL): q2.append((MAX_ROW-1, j)) + for i in range(MAX_ROW): q2.append((i, MAX_COL-1)) + + bfs(q1, pacific) + bfs(q2, atlantic) + return pacific.intersection(atlantic) \ No newline at end of file diff --git a/problems/python3/rotting-oranges.py b/problems/python3/rotting-oranges.py new file mode 100644 index 0000000..2e1216a --- /dev/null +++ b/problems/python3/rotting-oranges.py @@ -0,0 +1,35 @@ +class Solution: + def orangesRotting(self, grid: List[List[int]]) -> int: + time = 0 + rotten = set() + aboutToRot = set() + fresh = set() + + for i in range(len(grid)): + for j in range((len(grid[0]))): + if grid[i][j]==2: + rotten.add((i, j)) + elif grid[i][j]==1: + fresh.add((i, j)) + + while rotten: + i0, j0 = rotten.pop() #randomly get one + grid[i0][j0] = 2 + + for i, j in ((i0+1, j0), (i0-1, j0), (i0, j0+1), (i0, j0-1)): + if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]): continue + if (i, j) in rotten or (i, j) in aboutToRot: continue + if (i, j) in fresh: + fresh.remove((i, j)) + aboutToRot.add((i, j)) + + if not rotten and not aboutToRot: break + + if not rotten: + time += 1 + rotten = aboutToRot + aboutToRot = set() + + if fresh: return -1 + + return time \ No newline at end of file diff --git a/problems/python3/surrounded-regions.py b/problems/python3/surrounded-regions.py new file mode 100644 index 0000000..42aa4c0 --- /dev/null +++ b/problems/python3/surrounded-regions.py @@ -0,0 +1,34 @@ +""" +Time: O(N) +Space: O(N) +""" +class Solution: + def solve(self, board: List[List[str]]) -> None: + def dfs(i0, j0): + if i0<0 or j0<0 or i0>=MAX_ROW or j0>=MAX_COL: return + if board[i0][j0]!='O': return + if (i0, j0) in survived: return + + survived.add((i0, j0)) + dfs(i0+1, j0) + dfs(i0-1, j0) + dfs(i0, j0+1) + dfs(i0, j0-1) + + + MAX_ROW = len(board) + MAX_COL = len(board[0]) + survived = set() + + for i in range(MAX_ROW): + dfs(i, 0) + dfs(i, MAX_COL-1) + + for j in range(MAX_COL): + dfs(0, j) + dfs(MAX_ROW-1, j) + + for i in range(MAX_ROW): + for j in range(MAX_COL): + board[i][j] = 'O' if (i, j) in survived else 'X' + return board \ No newline at end of file diff --git a/problems/python3/walls-and-gates.py b/problems/python3/walls-and-gates.py new file mode 100644 index 0000000..5f27f9a --- /dev/null +++ b/problems/python3/walls-and-gates.py @@ -0,0 +1,29 @@ +class Solution: + def wallsAndGates(self, rooms: List[List[int]]) -> None: + def bfs(i0, j0) -> None: + q = collections.deque([(i0+1, j0, 1), (i0-1, j0, 1), (i0, j0+1, 1), (i0, j0-1, 1)]) + visited = set() + + while q: + i, j, dis = q.popleft() + + if i<0 or j<0 or i>=MAX_ROW or j>=MAX_COL: continue + if rooms[i][j]==0 or rooms[i][j]==-1: continue + if (i, j, dis) in visited: continue + visited.add((i, j, dis)) + + if dis List[str]: + def dfs(r, c, node, word): + if c<0 or r<0 or c==COLS or r==ROWS: return + if board[r][c] not in node.children: return + if (r, c) in visited: return + + visited.add((r, c)) + node = node.children[board[r][c]] + word += board[r][c] + if node.isEnd: + ans.add(word) + node.isEnd = False + + dfs(r+1, c, node, word) + dfs(r-1, c, node, word) + dfs(r, c+1, node, word) + dfs(r, c-1, node, word) + + visited.remove((r, c)) + + + root = TrieNode() + for word in words: + root.addWord(word) + + ROWS = len(board) + COLS = len(board[0]) + + visited = set() + ans = set() + node = root + for r in range(ROWS): + for c in range(COLS): + dfs(r, c, root, '') + return ans \ No newline at end of file From 02d6d3b63e5ffcbb88eb4b893b94499411f7d60b Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sun, 25 Sep 2022 10:46:21 +0200 Subject: [PATCH 44/52] update --- problems/python3/graph-valid-tree.py | 33 ++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 problems/python3/graph-valid-tree.py diff --git a/problems/python3/graph-valid-tree.py b/problems/python3/graph-valid-tree.py new file mode 100644 index 0000000..2168e9a --- /dev/null +++ b/problems/python3/graph-valid-tree.py @@ -0,0 +1,33 @@ +class Solution: + def validTree(self, N: int, edges: List[List[int]]) -> bool: + def union(n1, n2) -> bool: + p1 = find(n1) + p2 = find(n2) + + if p1==p2: + return False + elif p1 int: + p = parents[n] + while p!=parents[p]: p = find(p) + parents[n] = p + return p + + parents = [n for n in range(N)] + + for n1, n2 in edges: + if not union(n1, n2): return False + + #check if all node trace back to the same root + root = find(0) + for n in range(1, N): + if root!=find(n): return False + + return True \ No newline at end of file From 3af72365974096fdff631de776b4a26384012e91 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sun, 25 Sep 2022 10:46:41 +0200 Subject: [PATCH 45/52] updates --- ...ected-components-in-an-undirected-graph.py | 25 +++++++++++++++ problems/python3/redundant-connection.py | 32 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 problems/python3/number-of-connected-components-in-an-undirected-graph.py create mode 100644 problems/python3/redundant-connection.py diff --git a/problems/python3/number-of-connected-components-in-an-undirected-graph.py b/problems/python3/number-of-connected-components-in-an-undirected-graph.py new file mode 100644 index 0000000..28571ea --- /dev/null +++ b/problems/python3/number-of-connected-components-in-an-undirected-graph.py @@ -0,0 +1,25 @@ +class Solution: + def countComponents(self, N: int, edges: List[List[int]]) -> int: + def union(n1, n2): + p1 = find(n1) + p2 = find(n2) + if p1==p2: + return + elif p1 List[int]: + def union(n1, n2): + p1 = find(n1) + p2 = find(n2) + + if p1==p2: + return False #union failed, already united. + elif p1 Date: Sat, 8 Oct 2022 10:26:40 +0200 Subject: [PATCH 46/52] updates --- problems/python3/alien-dictionary.py | 36 +++++++++++++++++ .../cheapest-flights-within-k-stops.py | 17 ++++++++ problems/python3/climbing-stairs.py | 10 +++++ problems/python3/min-cost-climbing-stairs.py | 16 ++++++++ .../python3/min-cost-to-connect-all-points.py | 28 +++++++++++++ problems/python3/network-delay-time.py | 23 +++++++++++ problems/python3/reconstruct-itinerary.py | 27 +++++++++++++ problems/python3/swim-in-rising-water.py | 23 +++++++++++ problems/python3/word-ladder.py | 40 +++++++++++++++++++ 9 files changed, 220 insertions(+) create mode 100644 problems/python3/alien-dictionary.py create mode 100644 problems/python3/cheapest-flights-within-k-stops.py create mode 100644 problems/python3/climbing-stairs.py create mode 100644 problems/python3/min-cost-climbing-stairs.py create mode 100644 problems/python3/min-cost-to-connect-all-points.py create mode 100644 problems/python3/network-delay-time.py create mode 100644 problems/python3/reconstruct-itinerary.py create mode 100644 problems/python3/swim-in-rising-water.py create mode 100644 problems/python3/word-ladder.py diff --git a/problems/python3/alien-dictionary.py b/problems/python3/alien-dictionary.py new file mode 100644 index 0000000..23ca1ee --- /dev/null +++ b/problems/python3/alien-dictionary.py @@ -0,0 +1,36 @@ +class Solution: + def alienOrder(self, words: List[str]) -> str: + adj = collections.defaultdict(list) + inbounds = collections.Counter() + q = collections.deque() + ans = '' + + adj = {c: set() for word in words for c in word} + for i in range(len(words)-1): + w1, w2 = words[i], words[i+1] + minLen = min(len(w1), len(w2)) + if w1[:minLen]==w2[:minLen] and len(w1)>len(w2): return "" + + for j in range(minLen): + if w1[j]!=w2[j]: + adj[w1[j]].add(w2[j]) + break + + for c in adj: + for nc in list(adj[c]): + inbounds[nc] += 1 + + for c in adj: + if inbounds[c]==0: q.append(c) + + while q: + c = q.popleft() + + ans += c + + for nc in adj[c]: + inbounds[nc] -= 1 + if inbounds[nc]==0: q.append(nc) + + return ans if len(ans)==len(adj) else '' + diff --git a/problems/python3/cheapest-flights-within-k-stops.py b/problems/python3/cheapest-flights-within-k-stops.py new file mode 100644 index 0000000..4595802 --- /dev/null +++ b/problems/python3/cheapest-flights-within-k-stops.py @@ -0,0 +1,17 @@ +""" +Bellman-Ford. +Time: O(KE) +""" +class Solution: + def findCheapestPrice(self, N: int, flights: List[List[int]], src: int, dst: int, K: int) -> int: + prices = {n:float('inf') for n in range(N)} + prices[src] = 0 + + for k in range(K+1): + temp = prices.copy() + for source, destination, price in flights: + if prices[source]==float('inf'): continue + if prices[source]+price int: + dp = [0]*(N+1) + dp[0] = 1 + for i in range(len(dp)): + if i-1>=0: + dp[i] += dp[i-1] + if i-2>=0: + dp[i] += dp[i-2] + return dp[-1] \ No newline at end of file diff --git a/problems/python3/min-cost-climbing-stairs.py b/problems/python3/min-cost-climbing-stairs.py new file mode 100644 index 0000000..c59c446 --- /dev/null +++ b/problems/python3/min-cost-climbing-stairs.py @@ -0,0 +1,16 @@ +""" +Time: O(N) +Space: O(N), can further reduce to using only 2 variables -> O(1). + +dp[i] := the cost to get to index i. +""" +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + N = len(cost) + dp = [float('inf')]*(N+1) + dp[0] = 0 + dp[1] = 0 + + for i in range(2, len(dp)): + dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]) + return dp[-1] \ No newline at end of file diff --git a/problems/python3/min-cost-to-connect-all-points.py b/problems/python3/min-cost-to-connect-all-points.py new file mode 100644 index 0000000..4cd6ada --- /dev/null +++ b/problems/python3/min-cost-to-connect-all-points.py @@ -0,0 +1,28 @@ +class Solution: + def minCostConnectPoints(self, points: List[List[int]]) -> int: + ans = 0 + visited = set() + adj = collections.defaultdict(list) + N = len(points) + + #build adjacency list + for i in range(N): + x0, y0 = points[i] + for j in range(i+1, N): + x1, y1 = points[j] + dis = abs(x0-x1)+abs(y0-y1) + adj[(x0, y0)].append((dis, x1, y1)) + adj[(x1, y1)].append((dis, x0, y0)) + + h = [(0, points[0][0], points[0][1])] #min heap + while len(visited) int: + ans = 0 + adj = collections.defaultdict(list) + h = [] + visited = set() + + for u, v, w in times: + adj[u].append((v, w)) + + heapq.heappush(h, (0, k)) + while h: + timeNeededToGetHere, node = heapq.heappop(h) + + if node in visited: continue + visited.add(node) + ans = max(ans, timeNeededToGetHere) + + for nei, time in adj[node]: + if nei in visited: continue + heapq.heappush(h, (time+timeNeededToGetHere, nei)) + + return ans if len(visited)==n else -1 \ No newline at end of file diff --git a/problems/python3/reconstruct-itinerary.py b/problems/python3/reconstruct-itinerary.py new file mode 100644 index 0000000..14c928f --- /dev/null +++ b/problems/python3/reconstruct-itinerary.py @@ -0,0 +1,27 @@ +""" +DFS with backtracking. +""" +class Solution: + def findItinerary(self, tickets: List[List[str]]) -> List[str]: + def dfs(start) -> bool: + if len(ans)==len(tickets)+1: return True + if start not in adj: return False + + temp = list(adj[start]) + for i, arr in enumerate(temp): + adj[start].pop(i) + ans.append(arr) + if dfs(arr): return True + adj[start].insert(i, arr) + ans.pop() + return False + + ans = ['JFK'] + adj = collections.defaultdict(list) + + tickets.sort() + for des, arr in tickets: + adj[des].append(arr) + + dfs('JFK') + return ans \ No newline at end of file diff --git a/problems/python3/swim-in-rising-water.py b/problems/python3/swim-in-rising-water.py new file mode 100644 index 0000000..dd5dbef --- /dev/null +++ b/problems/python3/swim-in-rising-water.py @@ -0,0 +1,23 @@ +""" +Time: O(N^2 * LogN^2) = O(N^2 * 2LogN) = O(N^2LogN), N is the number of elements in a row or column. +Space: O(N^2) +""" +class Solution: + def swimInWater(self, grid: List[List[int]]) -> int: + ROWS = len(grid) + COLS = len(grid[0]) + + visited = set() + h = [(grid[0][0], 0, 0)] + + while h: + t, r0, c0 = heapq.heappop(h) + + if (r0, c0) in visited: continue + visited.add((r0, c0)) + if r0==ROWS-1 and c0==COLS-1: return t + + for r, c in ((r0+1, c0), (r0-1, c0), (r0, c0+1), (r0, c0-1)): + if r<0 or c<0 or r>=ROWS or c>=COLS: continue + if (r, c) in visited: continue + heapq.heappush(h, (max(t, grid[r][c]), r, c)) \ No newline at end of file diff --git a/problems/python3/word-ladder.py b/problems/python3/word-ladder.py new file mode 100644 index 0000000..453fb4a --- /dev/null +++ b/problems/python3/word-ladder.py @@ -0,0 +1,40 @@ +""" +Time: O(NxM^2). N is the number of words. M is the length of the word. +Note that, getPatterns() takes O(M^2) since creating new string will also takes O(M) and for each word we do that O(M) times. + +Space: O(NxM^2) +""" +class Solution: + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: + def getPatterns(word) -> List[str]: + patterns = [] + for i in range(len(word)): + pattern = word[:i]+'*'+word[i+1:] + patterns.append(pattern) + return patterns + + + if endWord not in wordList: return 0 + wordList.append(beginWord) + + #build adjacency list + nei = collections.defaultdict(list) + for word in wordList: + for pattern in getPatterns(word): + nei[pattern].append(word) + + #BFS + q = collections.deque([(beginWord, 1)]) + visited = set() + while q: + word, steps = q.popleft() + + if word in visited: continue + visited.add(word) + if word==endWord: return steps + + for pattern in getPatterns(word): + for nextWord in nei[pattern]: + if nextWord in visited: continue + q.append((nextWord, steps+1)) + return 0 \ No newline at end of file From 82ca4d9a5ff1a4e3efce92cfaa0bc067394e16dc Mon Sep 17 00:00:00 2001 From: wuduhren Date: Tue, 1 Nov 2022 08:24:43 +0100 Subject: [PATCH 47/52] updates --- problems/python3/coin-change.py | 14 ++++++ problems/python3/decode-ways.py | 14 ++++++ problems/python3/house-robber-ii.py | 18 ++++++++ problems/python3/house-robber.py | 17 +++++++ .../python3/longest-common-subsequence.py | 16 +++++++ .../python3/longest-palindromic-substring.py | 45 +++++++++++++++++++ problems/python3/maximum-product-subarray.py | 25 +++++++++++ problems/python3/palindromic-substrings.py | 16 +++++++ .../python3/partition-equal-subset-sum.py | 20 +++++++++ problems/python3/unique-paths.py | 11 +++++ problems/python3/word-break.py | 23 ++++++++++ 11 files changed, 219 insertions(+) create mode 100644 problems/python3/coin-change.py create mode 100644 problems/python3/decode-ways.py create mode 100644 problems/python3/house-robber-ii.py create mode 100644 problems/python3/house-robber.py create mode 100644 problems/python3/longest-common-subsequence.py create mode 100644 problems/python3/longest-palindromic-substring.py create mode 100644 problems/python3/maximum-product-subarray.py create mode 100644 problems/python3/palindromic-substrings.py create mode 100644 problems/python3/partition-equal-subset-sum.py create mode 100644 problems/python3/unique-paths.py create mode 100644 problems/python3/word-break.py diff --git a/problems/python3/coin-change.py b/problems/python3/coin-change.py new file mode 100644 index 0000000..19571e4 --- /dev/null +++ b/problems/python3/coin-change.py @@ -0,0 +1,14 @@ +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + dp = [float('inf')]*(amount+1) + dp[0] = 0 + for coin in coins: + if coin int: + mapping = set([str(n) for n in range(1, 27)]) + N = len(s) + dp = [0]*(N+1) + dp[0] = 1 + + for i in range(1, N+1): + if i-1>=0 and s[i-1] in mapping: dp[i] += dp[i-1] + if i-2>=0 and s[i-2:i] in mapping: dp[i] += dp[i-2] + return dp[-1] \ No newline at end of file diff --git a/problems/python3/house-robber-ii.py b/problems/python3/house-robber-ii.py new file mode 100644 index 0000000..1ed9b82 --- /dev/null +++ b/problems/python3/house-robber-ii.py @@ -0,0 +1,18 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + if len(nums)<=1: return max(nums) + + N = len(nums) + dp = [[0, 0] for _ in range(N)] + dp[0][0] = nums[0] + + for i in range(1, N): + dp[i][0] = nums[i]+dp[i-1][1] + dp[i][1] = max(dp[i-1]) + + dp2 = [[0, 0] for _ in range(N)] + for i in range(1, N): + dp2[i][0] = nums[i]+dp2[i-1][1] + dp2[i][1] = max(dp2[i-1]) + + return max(dp[-1][1], dp2[-1][0]) \ No newline at end of file diff --git a/problems/python3/house-robber.py b/problems/python3/house-robber.py new file mode 100644 index 0000000..fbd86a5 --- /dev/null +++ b/problems/python3/house-robber.py @@ -0,0 +1,17 @@ +""" +Time: O(N) +Space: O(N), can reduece to O(1). + +dp[i][0] := max revenue if house i robbed +dp[i][1] := max revenue if house i not robbed +""" +class Solution: + def rob(self, nums: List[int]) -> int: + N = len(nums) + dp = [[0, 0] for _ in range(N)] + dp[0][0] = nums[0] + + for i in range(1, N): + dp[i][0] = nums[i]+dp[i-1][1] + dp[i][1] = max(dp[i-1]) + return max(dp[-1]) \ No newline at end of file diff --git a/problems/python3/longest-common-subsequence.py b/problems/python3/longest-common-subsequence.py new file mode 100644 index 0000000..5ba3a68 --- /dev/null +++ b/problems/python3/longest-common-subsequence.py @@ -0,0 +1,16 @@ +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + #dp[i][j] := number of longest Common Subsequence with text2[:i] and text2[:j] + + N = len(text1) + M = len(text2) + + dp = [[0]*(M+1) for _ in range(N+1)] + + for i in range(1, N+1): + for j in range(1, M+1): + if text1[i-1]==text2[j-1]: + dp[i][j] = dp[i-1][j-1]+1 + else: + dp[i][j] = max(dp[i][j-1], dp[i-1][j]) + return dp[-1][-1] \ No newline at end of file diff --git a/problems/python3/longest-palindromic-substring.py b/problems/python3/longest-palindromic-substring.py new file mode 100644 index 0000000..9edb477 --- /dev/null +++ b/problems/python3/longest-palindromic-substring.py @@ -0,0 +1,45 @@ +""" +Time: O(N^2) +Space: O(N^2) + +DP, TLE +""" +class Solution: + def longestPalindrome(self, s: str) -> str: + ans = s[0] + N = len(s) + dp = [[False]*N for _ in range(N)] + + for i in range(N): dp[i][i] = True + + for l in range(2, N+1): + for i in range(N): + j = i+l-1 + if j>=N: continue + dp[i][j] = s[i]==s[j] and (dp[i+1][j-1] or j-1 str: + N = len(s) + ans = s[0] + + for i in range(N): + l, r = i, i + while l>=0 and rlen(ans): ans = s[l:r+1] + l -= 1 + r += 1 + + l, r = i, i+1 + while l>=0 and rlen(ans): ans = s[l:r+1] + l -= 1 + r += 1 + return ans \ No newline at end of file diff --git a/problems/python3/maximum-product-subarray.py b/problems/python3/maximum-product-subarray.py new file mode 100644 index 0000000..243bf41 --- /dev/null +++ b/problems/python3/maximum-product-subarray.py @@ -0,0 +1,25 @@ +""" +Time: O(N) +Space: O(N), can be reduce to O(1) + +dp[i][0] := The max product from subarray that end with nums[i] +dp[i][1] := The min product from subarray that end with nums[i] +""" +class Solution: + def maxProduct(self, nums: List[int]) -> int: + N = len(nums) + dp = [[1, 1] for _ in range(N+1)] + ans = float('-inf') + + for i in range(1, N+1): + dp[i][0] = dp[i][1] = nums[i-1] + + if nums[i-1]>0: + dp[i][0] = max(dp[i][0], nums[i-1]*dp[i-1][0]) + dp[i][1] = min(dp[i][1], nums[i-1]*dp[i-1][1]) + else: + dp[i][0] = max(dp[i][0], nums[i-1]*dp[i-1][1]) + dp[i][1] = min(dp[i][1], nums[i-1]*dp[i-1][0]) + ans = max(ans, dp[i][0]) + + return ans \ No newline at end of file diff --git a/problems/python3/palindromic-substrings.py b/problems/python3/palindromic-substrings.py new file mode 100644 index 0000000..7ef7e96 --- /dev/null +++ b/problems/python3/palindromic-substrings.py @@ -0,0 +1,16 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + def countPalindrome(l, r) -> int: + count = 0 + while l>=0 and r bool: + total = sum(nums) + if total%2!=0: return False + + target = total/2 + possibleSum = set() + possibleSum.add(0) + for num in nums: + temp = set() + for p in possibleSum: + if p==target or p+num==target: return True + temp.add(p) + temp.add(p+num) + possibleSum = temp + return False \ No newline at end of file diff --git a/problems/python3/unique-paths.py b/problems/python3/unique-paths.py new file mode 100644 index 0000000..9c7ce40 --- /dev/null +++ b/problems/python3/unique-paths.py @@ -0,0 +1,11 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + m = m-1 #number of steps need to move down + n = n-1 #number of steps need to move right + + #the total combination of m and n to sort will be (m+n)! + #since all "move down" are consider the same, we need to remove the repeatition of it sorting: m!. + #since all "move right" are consider the same, we need to remove the repeatition of it sorting: n!. + #(m+n)!/m!n! + + return math.factorial(m+n)//(math.factorial(m)*math.factorial(n)) \ No newline at end of file diff --git a/problems/python3/word-break.py b/problems/python3/word-break.py new file mode 100644 index 0000000..8d2c817 --- /dev/null +++ b/problems/python3/word-break.py @@ -0,0 +1,23 @@ +""" +Time: O(N^2 * M). N is the length of the s. M is the number of word in wordDict. +Note that s[i:i+len(word)]==word takes O(N) time. + +Space: O(N) for the recursion memory stack size. + +dfs(i) := will return starting at index i, if i to the end the string can be separated. +""" +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + def dfs(i): + if i==len(s): return True + if i in history and not history[i]: return False + + for word in wordDict: + if i+len(word)<=len(s) and s[i:i+len(word)]==word: + history[i] = True + if dfs(i+len(word)): return True + history[i] = False + return False + + history = {} + return dfs(0) \ No newline at end of file From bcef8a4a0835589cc686a72614455ac723caef94 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Sun, 27 Nov 2022 10:41:31 +0100 Subject: [PATCH 48/52] updates --- ...ime-to-buy-and-sell-stock-with-cooldown.py | 16 ++++++++ problems/python3/burst-balloons.py | 28 ++++++++++++++ problems/python3/coin-change-ii.py | 12 ++++++ problems/python3/counting-bits.py | 9 +++++ problems/python3/distinct-subsequences.py | 17 +++++++++ problems/python3/edit-distance.py | 37 +++++++++++++++++++ problems/python3/interleaving-string.py | 13 +++++++ .../longest-increasing-path-in-a-matrix.py | 26 +++++++++++++ problems/python3/number-of-1-bits.py | 10 +++++ .../python3/regular-expression-matching.py | 24 ++++++++++++ problems/python3/reverse-bits.py | 7 ++++ problems/python3/single-number.py | 15 ++++++++ problems/python3/target-sum.py | 25 +++++++++++++ 13 files changed, 239 insertions(+) create mode 100644 problems/python3/best-time-to-buy-and-sell-stock-with-cooldown.py create mode 100644 problems/python3/burst-balloons.py create mode 100644 problems/python3/coin-change-ii.py create mode 100644 problems/python3/counting-bits.py create mode 100644 problems/python3/distinct-subsequences.py create mode 100644 problems/python3/edit-distance.py create mode 100644 problems/python3/interleaving-string.py create mode 100644 problems/python3/longest-increasing-path-in-a-matrix.py create mode 100644 problems/python3/number-of-1-bits.py create mode 100644 problems/python3/regular-expression-matching.py create mode 100644 problems/python3/reverse-bits.py create mode 100644 problems/python3/single-number.py create mode 100644 problems/python3/target-sum.py diff --git a/problems/python3/best-time-to-buy-and-sell-stock-with-cooldown.py b/problems/python3/best-time-to-buy-and-sell-stock-with-cooldown.py new file mode 100644 index 0000000..06644e3 --- /dev/null +++ b/problems/python3/best-time-to-buy-and-sell-stock-with-cooldown.py @@ -0,0 +1,16 @@ +#dp[i][0] := max profit when last action is buy +#dp[i][1] := max profit when last action is sell +class Solution: + def maxProfit(self, prices: List[int]) -> int: + if not prices or len(prices)<=1: return 0 + + N = len(prices) + dp = [[0, 0] for _ in range(N)] + dp[0] = [-prices[0], 0] + dp[1][0] = max(-prices[1], -prices[0]) + dp[1][1] = max(prices[1]+dp[0][0], dp[0][1]) + + for i in range(2, N): + dp[i][0] = max(dp[i-2][1]-prices[i], dp[i-1][0]) + dp[i][1] = max(prices[i]+dp[i-1][0], dp[i-1][1]) + return max(dp[-1][0], dp[-1][1], 0) \ No newline at end of file diff --git a/problems/python3/burst-balloons.py b/problems/python3/burst-balloons.py new file mode 100644 index 0000000..aae31be --- /dev/null +++ b/problems/python3/burst-balloons.py @@ -0,0 +1,28 @@ +""" +dfs(l, r) return the max coins that we can get at range l to r. + +``` +for i in range(l, r+1): + dp[(l, r)] = max(dp[(l, r)], nums[l-1]*nums[i]*nums[r+1] + dfs(l, i-1) + dfs(i+1, r)) +``` +Assuming i is the last one we extract, the max coins we can get. + +Start from the last becasue, we are not able to track the neighbor if we start from the first we extract. + +Time: O(N^3) +Space: O(N^2) +""" +class Solution: + def maxCoins(self, nums: List[int]) -> int: + def dfs(l, r)->int: + if l>r: return 0 + if (l, r) in dp: return dp[(l, r)] + + dp[(l, r)] = 0 + for i in range(l, r+1): + dp[(l, r)] = max(dp[(l, r)], nums[l-1]*nums[i]*nums[r+1] + dfs(l, i-1) + dfs(i+1, r)) + return dp[(l, r)] + + nums = [1]+nums+[1] + dp = {} + return dfs(1, len(nums)-2) \ No newline at end of file diff --git a/problems/python3/coin-change-ii.py b/problems/python3/coin-change-ii.py new file mode 100644 index 0000000..8b4ad26 --- /dev/null +++ b/problems/python3/coin-change-ii.py @@ -0,0 +1,12 @@ +class Solution: + def change(self, amount: int, coins: List[int]) -> int: + dp = [0]*(amount+1) + dp[0] = 1 + + coins.sort() + + for coin in coins: + for a in range(1, amount+1): + if a-coin<0: continue + dp[a] += dp[a-coin] + return dp[-1] \ No newline at end of file diff --git a/problems/python3/counting-bits.py b/problems/python3/counting-bits.py new file mode 100644 index 0000000..7325596 --- /dev/null +++ b/problems/python3/counting-bits.py @@ -0,0 +1,9 @@ +class Solution: + def countBits(self, n: int) -> List[int]: + ans = [0]*(n+1) + offset = 1 + + for i in range(1, n+1): + if offset*2==i: offset = offset*2 + ans[i] = 1+ans[i-offset] + return ans \ No newline at end of file diff --git a/problems/python3/distinct-subsequences.py b/problems/python3/distinct-subsequences.py new file mode 100644 index 0000000..d84fcf6 --- /dev/null +++ b/problems/python3/distinct-subsequences.py @@ -0,0 +1,17 @@ +class Solution: + def numDistinct(self, s: str, t: str) -> int: + def dfs(i, j): + if (i, j) in visited: return visited[(i, j)] + + if j>=len(t): return 1 + if i>=len(s): return 0 + + if s[i]==t[j]: + visited[(i, j)] = dfs(i+1, j+1)+dfs(i+1, j) + else: + visited[(i, j)] = dfs(i+1, j) + return visited[(i, j)] + + visited = {} + dfs(0, 0) + return dfs(0, 0) \ No newline at end of file diff --git a/problems/python3/edit-distance.py b/problems/python3/edit-distance.py new file mode 100644 index 0000000..c8fa8f4 --- /dev/null +++ b/problems/python3/edit-distance.py @@ -0,0 +1,37 @@ +""" +dfs(i, j) +i being the unprocessed index in word1. +j, word2. + +MAIN LOGIC: +if word1[i]==word2[j], no operation need, return dfs(i+1, j+1) +if not, need 1 operation, so +replace: dfs(i+1, j+1) +insert: dfs(i, j+1) +delete: dfs(i+1, j) + +BASE CASE: +If both string are empty (i==N and j==M), no operation needed. +If one string are empty, then the remain operation is the length of the non-empty one. +""" +class Solution: + def minDistance(self, word1: str, word2: str) -> int: + N = len(word1) + M = len(word2) + def dfs(i, j)->int: + if i==N and j==M: return 0 + if i==N: return M-j + if j==M: return N-i + + if (i, j) in history: + return history[(i, j)] + + if word1[i]==word2[j]: + history[(i, j)] = dfs(i+1, j+1) + else: + history[(i, j)] = 1+min(dfs(i+1, j+1), dfs(i+1, j), dfs(i, j+1)) + + return history[(i, j)] + + history = {} + return dfs(0, 0) \ No newline at end of file diff --git a/problems/python3/interleaving-string.py b/problems/python3/interleaving-string.py new file mode 100644 index 0000000..76f9837 --- /dev/null +++ b/problems/python3/interleaving-string.py @@ -0,0 +1,13 @@ +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + def dfs(i, j): + if (i, j) in history: return False + if i+j==len(s3): return True + if i int: + def dfs(i0, j0): + if (i0, j0) in memo: return memo[(i0, j0)] + ans = 1 + + for i, j in ((i0+1, j0), (i0-1, j0), (i0, j0+1),(i0, j0-1)): + if i<0 or i>=N or j<0 or j>=M: continue + if matrix[i][j]<=matrix[i0][j0]: continue + ans = max(ans, 1+dfs(i, j)) + + memo[(i0, j0)] = ans + return ans + + N = len(matrix) + M = len(matrix[0]) + memo = {} + ans = 0 + for i in range(N): + for j in range(M): + ans = max(ans, dfs(i, j)) + return ans \ No newline at end of file diff --git a/problems/python3/number-of-1-bits.py b/problems/python3/number-of-1-bits.py new file mode 100644 index 0000000..2273859 --- /dev/null +++ b/problems/python3/number-of-1-bits.py @@ -0,0 +1,10 @@ +""" +n = n&(n-1) will turn the right most 1 to 0. +""" +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + while n>0: + n = n&(n-1) + ans += 1 + return ans \ No newline at end of file diff --git a/problems/python3/regular-expression-matching.py b/problems/python3/regular-expression-matching.py new file mode 100644 index 0000000..93b44e6 --- /dev/null +++ b/problems/python3/regular-expression-matching.py @@ -0,0 +1,24 @@ +class Solution: + def isMatch(self, s: str, p: str) -> bool: + def dfs(i, j): + if (i, j) in cache: return cache[(i, j)] + if i>=M and j>=N: return True + if j>=N: return False + + match = i int: + res = 0 + for i in range(32): + bit = (n >> i) & 1 + res = res | (bit << (31 - i)) + return res \ No newline at end of file diff --git a/problems/python3/single-number.py b/problems/python3/single-number.py new file mode 100644 index 0000000..daa3268 --- /dev/null +++ b/problems/python3/single-number.py @@ -0,0 +1,15 @@ +""" +^ (XOR) +The same will be 0 +0^0 = 0 +1^1 = 0 + +Different will be 1 +1^0 = 1 +0^1 = 1 +""" +class Solution: + def singleNumber(self, nums: List[int]) -> int: + ans = 0 + for num in nums: ans ^= num + return ans \ No newline at end of file diff --git a/problems/python3/target-sum.py b/problems/python3/target-sum.py new file mode 100644 index 0000000..832fadd --- /dev/null +++ b/problems/python3/target-sum.py @@ -0,0 +1,25 @@ +""" +Time: O(NS), S is sum(nums), N is len(nums). This is the max possible number of element in "history". Which will be lesser than 2^N. +Space: O(NS) +""" +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + def dfs(i, curr): + #cache + if (i, curr) in history: + return history[(i, curr)] + + #ending condition + if i==len(nums): + if curr==target: + history[(i, curr)] = 1 + else: + history[(i, curr)] = 0 + return history[(i, curr)] + + history[(i, curr)] = dfs(i+1, curr+nums[i])+dfs(i+1, curr-nums[i]) + return history[(i, curr)] + + ans = 0 + history = {} + return dfs(0, 0) \ No newline at end of file From f14be0f429850344c738edc9f18e35e561c724d1 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Thu, 1 Dec 2022 08:00:24 +0100 Subject: [PATCH 49/52] updates --- README.md | 1 + problems/python3/missing-number.py | 12 ++++++++++++ problems/python3/reverse-integer.py | 16 ++++++++++++++++ problems/python3/sum-of-two-integers.py | 12 ++++++++++++ 4 files changed, 41 insertions(+) create mode 100644 problems/python3/missing-number.py create mode 100644 problems/python3/reverse-integer.py create mode 100644 problems/python3/sum-of-two-integers.py diff --git a/README.md b/README.md index 8e05de7..28486a9 100755 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Please [BUY ME A COFFEE](https://www.buymeacoffee.com/chriswu) if you want to sh # Leetcode Problem Lists I found it makes sense to solve similar problems together, so that we can recognize the problem faster when we encounter a new one. My suggestion is to skip the HARD problems when you first go through these list. +* https://neetcode.io/practice (150 problems with video explaination) * https://www.programcreek.com/2013/08/leetcode-problem-classification/ * https://github.com/wisdompeak/LeetCode * https://docs.google.com/spreadsheets/d/1SbpY-04Cz8EWw3A_LBUmDEXKUMO31DBjfeMoA0dlfIA/edit#gid=126913158 ([huahua](https://www.youtube.com/user/xxfflower/videos)). diff --git a/problems/python3/missing-number.py b/problems/python3/missing-number.py new file mode 100644 index 0000000..f0531f6 --- /dev/null +++ b/problems/python3/missing-number.py @@ -0,0 +1,12 @@ +class Solution: + def missingNumber(self, nums: List[int]) -> int: + N = len(nums) + ans = 0 + + for n in range(N+1): + ans ^= n + + for n in nums: + ans ^= n + + return ans \ No newline at end of file diff --git a/problems/python3/reverse-integer.py b/problems/python3/reverse-integer.py new file mode 100644 index 0000000..76137ab --- /dev/null +++ b/problems/python3/reverse-integer.py @@ -0,0 +1,16 @@ +class Solution: + def reverse(self, x: int) -> int: + MAX = 2**31-1 + MIN = -2**31 + ans = 0 + + while x: + digit = int(math.fmod(x, 10)) + x = int(x/10) + + if ans>MAX//10 or (ans==MAX//10 and digit>MAX%10): return 0 + if ans int: + ans = a^b + carry = (a&b)<<1 + + while carry!=0: + ans, carry = ans^carry, (ans&carry)<<1 + + return ans \ No newline at end of file From dbaa78d7677b5e6092997972188e2b5d1266e3d7 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Mon, 5 Dec 2022 08:15:04 +0100 Subject: [PATCH 50/52] updates --- problems/python3/rotate-image.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 problems/python3/rotate-image.py diff --git a/problems/python3/rotate-image.py b/problems/python3/rotate-image.py new file mode 100644 index 0000000..c8a872a --- /dev/null +++ b/problems/python3/rotate-image.py @@ -0,0 +1,16 @@ +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + l, r = 0, len(matrix[0])-1 + + while l Date: Mon, 5 Dec 2022 08:15:18 +0100 Subject: [PATCH 51/52] updates --- problems/python3/set-matrix-zeroes.py | 28 +++++++++ problems/python3/spiral-matrix.py | 90 +++++++++++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 problems/python3/set-matrix-zeroes.py create mode 100644 problems/python3/spiral-matrix.py diff --git a/problems/python3/set-matrix-zeroes.py b/problems/python3/set-matrix-zeroes.py new file mode 100644 index 0000000..dd836e5 --- /dev/null +++ b/problems/python3/set-matrix-zeroes.py @@ -0,0 +1,28 @@ +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + M = len(matrix) + N = len(matrix[0]) + firstRowZero = False + + for i in range(M): + for j in range(N): + if matrix[i][j]==0: + matrix[0][j] = 0 + if i==0: + firstRowZero = True + else: + matrix[i][0] = 0 + + for i in range(1, M): + if matrix[i][0]==0: + for j in range(N): + matrix[i][j] = 0 + + for j in range(N): + if matrix[0][j]==0: + for i in range(M): + matrix[i][j] = 0 + + if firstRowZero: + for j in range(N): + matrix[0][j] = 0 \ No newline at end of file diff --git a/problems/python3/spiral-matrix.py b/problems/python3/spiral-matrix.py new file mode 100644 index 0000000..ddce35c --- /dev/null +++ b/problems/python3/spiral-matrix.py @@ -0,0 +1,90 @@ +""" +Original's solution +Time: O(MN) +Space: O(1) +""" +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + ans = [] + x0 = 0 + y0 = 0 + dx = len(matrix[0])-1 + dy = len(matrix)-1 + direction = 'right' + isFirst = True + + ans.append(matrix[x0][y0]) + while True: + if direction=='right': + for x in range(x0+1, x0+dx+1): + ans.append(matrix[y0][x]) + x0 += dx + direction = 'down' + + if isFirst: + isFirst = False + else: + dx -= 1 + + if dy==0: break + + elif direction=='left': + for x in range(x0-1, x0-dx-1, -1): + ans.append(matrix[y0][x]) + x0 -= dx + direction = 'up' + dx -= 1 + if dy==0: break + + elif direction=='down': + for y in range(y0+1, y0+dy+1): + ans.append(matrix[y][x0]) + y0 += dy + direction = 'left' + dy -= 1 + if dx==0: break + + elif direction=='up': + for y in range(y0-1, y0-dy-1, -1): + ans.append(matrix[y][x0]) + y0 -= dy + direction = 'right' + dy -= 1 + if dx==0: break + return ans + + +""" +Answer from Neetcode, more elegant. +left, right, top, bottom is the border (index is exclusive on the border. +In other words, for matrix[i][j] +i: top List[int]: + res = [] + left, right = 0, len(matrix[0]) + top, bottom = 0, len(matrix) + + while left < right and top < bottom: + # get every i in the top row + for i in range(left, right): + res.append(matrix[top][i]) + top += 1 + # get every i in the right col + for i in range(top, bottom): + res.append(matrix[i][right - 1]) + right -= 1 + if not (left < right and top < bottom): + break + # get every i in the bottom row + for i in range(right - 1, left - 1, -1): + res.append(matrix[bottom - 1][i]) + bottom -= 1 + # get every i in the left col + for i in range(bottom - 1, top - 1, -1): + res.append(matrix[i][left]) + left += 1 + + return res \ No newline at end of file From 74a34466d44007399b6b67a051f0fcd800595ee8 Mon Sep 17 00:00:00 2001 From: wuduhren Date: Wed, 21 Dec 2022 08:11:55 +0100 Subject: [PATCH 52/52] update --- problems/python3/detect-squares.py | 22 ++++++++++++++++++++++ problems/python3/happy-number.py | 17 +++++++++++++++++ problems/python3/multiply-strings.py | 22 ++++++++++++++++++++++ problems/python3/plus-one.py | 16 ++++++++++++++++ problems/python3/powx-n.py | 14 ++++++++++++++ 5 files changed, 91 insertions(+) create mode 100644 problems/python3/detect-squares.py create mode 100644 problems/python3/happy-number.py create mode 100644 problems/python3/multiply-strings.py create mode 100644 problems/python3/plus-one.py create mode 100644 problems/python3/powx-n.py diff --git a/problems/python3/detect-squares.py b/problems/python3/detect-squares.py new file mode 100644 index 0000000..af86946 --- /dev/null +++ b/problems/python3/detect-squares.py @@ -0,0 +1,22 @@ +class DetectSquares: + + def __init__(self): + self.store = collections.Counter() + + def add(self, point: List[int]) -> None: + self.store[tuple(point)] += 1 + + def count(self, point: List[int]) -> int: + x, y = point + ans = 0 + + for dx, dy in self.store: + if abs(x-dx)!=abs(y-dy) or x==dx or y==dy: continue + ans += self.store[(dx, dy)]*self.store[(dx, y)]*self.store[(x, dy)] + return ans + + +# Your DetectSquares object will be instantiated and called as such: +# obj = DetectSquares() +# obj.add(point) +# param_2 = obj.count(point) \ No newline at end of file diff --git a/problems/python3/happy-number.py b/problems/python3/happy-number.py new file mode 100644 index 0000000..7756197 --- /dev/null +++ b/problems/python3/happy-number.py @@ -0,0 +1,17 @@ +class Solution: + def isHappy(self, n: int) -> bool: + def digitSquare(n) -> int: + ans = 0 + while n>0: + ans += (n%10)**2 + n = n//10 + return ans + + visited = set() + visited.add(1) + + while n not in visited: + visited.add(n) + n = digitSquare(n) + + return n==1 diff --git a/problems/python3/multiply-strings.py b/problems/python3/multiply-strings.py new file mode 100644 index 0000000..be9f675 --- /dev/null +++ b/problems/python3/multiply-strings.py @@ -0,0 +1,22 @@ +class Solution: + def multiply(self, num1: str, num2: str) -> str: + if num1=='0' or num2=='0': return '0' + M, N = len(num1), len(num2) + temp = [0]*(M+N+1) + + num1, num2 = num1[::-1], num2[::-1] + for i in range(M): + for j in range(N): + digits = int(num1[i])*int(num2[j]) + temp[i+j] += digits + temp[i+j+1] += temp[i+j]//10 + temp[i+j] = temp[i+j]%10 + + ans = '' + temp = temp[::-1] + isLeadingZero = True + for d in temp: + if d!=0 or not isLeadingZero: + isLeadingZero = False + ans += str(d) + return ans \ No newline at end of file diff --git a/problems/python3/plus-one.py b/problems/python3/plus-one.py new file mode 100644 index 0000000..8cfedb4 --- /dev/null +++ b/problems/python3/plus-one.py @@ -0,0 +1,16 @@ +class Solution: + def plusOne(self, digits: List[int]) -> List[int]: + i = len(digits)-1 + needAdditionDigit = True + + while i>=0 and needAdditionDigit: + if digits[i]==9: + digits[i] = 0 + i -= 1 + needAdditionDigit = True + else: + digits[i] += 1 + needAdditionDigit = False + if needAdditionDigit: digits.insert(0, 1) + return digits + \ No newline at end of file diff --git a/problems/python3/powx-n.py b/problems/python3/powx-n.py new file mode 100644 index 0000000..2b1b4fc --- /dev/null +++ b/problems/python3/powx-n.py @@ -0,0 +1,14 @@ +class Solution: + def myPow(self, x: float, k: int) -> float: + if k<0: return 1/self.myPow(x, -k) + + if k==0: + return 1 + elif k==1: + return x + elif k%2==0: + half = self.myPow(x, k//2) + return half * half + else: + half = self.myPow(x, (k-1)//2) + return half * half * x \ No newline at end of file