- Notifications
You must be signed in to change notification settings - Fork2.4k
chore - move python solutions from root to /python#425
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
4 commits Select commitHold shift + click to select a range
e26371c
moving python solutions from root to /python
mitchellirvin93c6a9b
Merge branch 'main' of https://github.com/neetcode-gh/leetcode into m…
mitchellirvin1ba7c0f
keeping originals
mitchellirvin7639cc7
Merge branch 'main' of https://github.com/neetcode-gh/leetcode into m…
mitchellirvinFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
9 changes: 9 additions & 0 deletionspython/1-Two-Sum.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
class Solution: | ||
def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
prevMap = {} # val -> index | ||
for i, n in enumerate(nums): | ||
diff = target - n | ||
if diff in prevMap: | ||
return [prevMap[diff], i] | ||
prevMap[n] = i |
45 changes: 45 additions & 0 deletionspython/10-Regular-Expression-Matching.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# BOTTOM-UP Dynamic Programming | ||
class Solution: | ||
def isMatch(self, s: str, p: str) -> bool: | ||
cache = [[False] * (len(p) + 1) for i in range(len(s) + 1)] | ||
cache[len(s)][len(p)] = True | ||
for i in range(len(s), -1, -1): | ||
for j in range(len(p) - 1, -1 ,-1): | ||
match = i < len(s) and (s[i] == p[j] or p[j] == ".") | ||
if (j + 1) < len(p) and p[j + 1] == "*": | ||
cache[i][j] = cache[i][j + 2] | ||
if match: | ||
cache[i][j] = cache[i + 1][j] or cache[i][j] | ||
elif match: | ||
cache[i][j] = cache[i+1][j+1] | ||
return cache[0][0] | ||
# TOP DOWN MEMOIZATION | ||
class Solution: | ||
def isMatch(self, s: str, p: str) -> bool: | ||
cache = {} | ||
def dfs(i, j): | ||
if (i, j) in cache: | ||
return cache[(i, j)] | ||
if i >= len(s) and j >= len(p): | ||
return True | ||
if j >= len(p): | ||
return False | ||
match = i < len(s) and (s[i] == p[j] or p[j] == ".") | ||
if (j + 1) < len(p) and p[j + 1] == "*": | ||
cache[(i, j)] = (dfs(i, j + 2) or # dont use * | ||
(match and dfs(i + 1, j))) # use * | ||
return cache[(i, j)] | ||
if match: | ||
cache[(i,j)] = dfs(i + 1, j + 1) | ||
return cache[(i,j)] | ||
cache[(i,j)] = False | ||
return False | ||
return dfs(0, 0) |
13 changes: 13 additions & 0 deletionspython/100-Same-Tree.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
# Definition for a binary tree node. | ||
# class TreeNode: | ||
# def __init__(self, x): | ||
# self.val = x | ||
# self.left = None | ||
# self.right = None | ||
class Solution: | ||
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: | ||
if not p and not q: return True | ||
if p and q and p.val == q.val: | ||
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) | ||
else: return False |
23 changes: 23 additions & 0 deletionspython/102-Binary-Tree-Level-Order-Traversal.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# Definition for a binary tree node. | ||
# class TreeNode: | ||
# def __init__(self, x): | ||
# self.val = x | ||
# self.left = None | ||
# self.right = None | ||
class Solution: | ||
def levelOrder(self, root: TreeNode) -> List[List[int]]: | ||
res = [] | ||
q = collections.deque() | ||
if root: q.append(root) | ||
while q: | ||
val = [] | ||
for i in range(len(q)): | ||
node = q.popleft() | ||
val.append(node.val) | ||
if node.left: q.append(node.left) | ||
if node.right: q.append(node.right) | ||
res.append(val) | ||
return res |
41 changes: 41 additions & 0 deletionspython/104-Maximum-Depth-of-Binary-Tree.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
# RECURSIVE DFS | ||
class Solution: | ||
def maxDepth(self, root: TreeNode) -> int: | ||
if not root: | ||
return 0 | ||
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) | ||
# ITERATIVE DFS | ||
class Solution: | ||
def maxDepth(self, root: TreeNode) -> int: | ||
stack = [[root, 1]] | ||
res = 0 | ||
while stack: | ||
node, depth = stack.pop() | ||
if node: | ||
res = max(res, depth) | ||
stack.append([node.left, depth + 1]) | ||
stack.append([node.right, depth + 1]) | ||
return res | ||
# BFS | ||
class Solution: | ||
def maxDepth(self, root: TreeNode) -> int: | ||
if not root: | ||
return 0 | ||
level = 0 | ||
q = deque([root]) | ||
while q: | ||
for i in range(len(q)): | ||
node = q.popleft() | ||
if node.left: | ||
q.append(node.left) | ||
if node.right: | ||
q.append(node.right) | ||
level += 1 | ||
return level |
13 changes: 13 additions & 0 deletionspython/1046-Last-Stone-Weight.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
class Solution: | ||
def lastStoneWeight(self, stones: List[int]) -> int: | ||
stones = [-s for s in stones] | ||
heapq.heapify(stones) | ||
while len(stones) > 1: | ||
first = heapq.heappop(stones) | ||
second = heapq.heappop(stones) | ||
if second > first: | ||
heapq.heappush(stones, first - second) | ||
stones.append(0) | ||
return abs(stones[0]) |
10 changes: 10 additions & 0 deletionspython/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
class Solution: | ||
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: | ||
if not preorder or not inorder: | ||
return None | ||
root = TreeNode(preorder[0]) | ||
mid = inorder.index(preorder[0]) | ||
root.left = self.buildTree(preorder[1:mid + 1], inorder[:mid]) | ||
root.right = self.buildTree(preorder[mid + 1:], inorder[mid + 1:]) | ||
return root |
12 changes: 12 additions & 0 deletionspython/11-Container-With-Most-Water.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
class Solution: | ||
def maxArea(self, height: List[int]) -> int: | ||
l, r = 0, len(height) - 1 | ||
res = 0 | ||
while l < r: | ||
res = max(res, min(height[l], height[r]) * (r - l)) | ||
if height[l] < height[r]: | ||
l += 1 | ||
elif height[r] <= height[l]: | ||
r -= 1 | ||
return res |
17 changes: 17 additions & 0 deletionspython/110-Balanced-Binary-Tree.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
# Definition for a binary tree node. | ||
# class TreeNode: | ||
# def __init__(self, val=0, left=None, right=None): | ||
# self.val = val | ||
# self.left = left | ||
# self.right = right | ||
class Solution: | ||
def isBalanced(self, root: Optional[TreeNode]) -> bool: | ||
def dfs(root): | ||
if not root: return [True, 0] | ||
left, right = dfs(root.left), dfs(root.right) | ||
balanced = (left[0] and right[0] and | ||
abs(left[1] - right[1]) <= 1) | ||
return [balanced, 1 + max(left[1], right[1])] | ||
return dfs(root)[0] |
12 changes: 12 additions & 0 deletionspython/1143-Longest-Common-Subsequence.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
class Solution: | ||
def longestCommonSubsequence(self, text1: str, text2: str) -> int: | ||
dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)] | ||
for i in range(len(text1) - 1, -1, -1): | ||
for j in range(len(text2) - 1, -1, -1): | ||
if text1[i] == text2[j]: | ||
dp[i][j] = 1 + dp[i + 1][j + 1] | ||
else: | ||
dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]) | ||
return dp[0][0] |
16 changes: 16 additions & 0 deletionspython/115-Distinct-Subsequences.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
class Solution: | ||
def numDistinct(self, s: str, t: str) -> int: | ||
cache = {} | ||
for i in range(len(s) + 1): | ||
cache[(i, len(t))] = 1 | ||
for j in range(len(t)): | ||
cache[(len(s), j)] = 0 | ||
for i in range(len(s) - 1, -1, -1): | ||
for j in range(len(t) - 1, -1, -1): | ||
if s[i] == t[j]: | ||
cache[(i, j)] = cache[(i+1,j+1)] + cache[(i+1,j)] | ||
else: | ||
cache[(i,j)] = cache[(i+1,j)] | ||
return cache[(0,0)] |
13 changes: 13 additions & 0 deletionspython/12-Integer-To-Roman.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
class Solution: | ||
def intToRoman(self, num: int) -> str: | ||
symList = [["I", 1], ["IV" , 4], ["V" , 5], ["IX" , 9], | ||
["X" , 10], ["XL" , 40], ["L" , 50], ["XC" , 90], | ||
["C" , 100], ["CD", 400], ["D", 500], ["CM", 900], | ||
["M" , 1000]] | ||
res = "" | ||
for sym, val in reversed(symList): | ||
if num // val: | ||
count = num // val | ||
res += (sym * count) | ||
num = num % val | ||
return res |
10 changes: 10 additions & 0 deletionspython/121-Best-Time-To-Buy-and-Sell-Stock.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
class Solution: | ||
def maxProfit(self, prices: List[int]) -> int: | ||
res = 0 | ||
l = 0 | ||
for r in range(1, len(prices)): | ||
if prices[r] < prices[l]: | ||
l = r | ||
res = max(res, prices[r] - prices[l]) | ||
return res |
27 changes: 27 additions & 0 deletionspython/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
class Solution: | ||
def maxLength(self, arr: List[str]) -> int: | ||
charSet = set() | ||
def overlap(charSet, s): | ||
c = Counter(charSet) + Counter(s) | ||
return max(c.values()) > 1 | ||
# prev = set() | ||
# for c in s: | ||
# if c in charSet or c in prev: | ||
# return True | ||
# prev.add(c) | ||
# return False | ||
def backtrack(i): | ||
if i == len(arr): | ||
return len(charSet) | ||
res = 0 | ||
if not overlap(charSet, arr[i]): | ||
for c in arr[i]: | ||
charSet.add(c) | ||
res = backtrack(i + 1) | ||
for c in arr[i]: | ||
charSet.remove(c) | ||
return max(res, backtrack(i + 1)) # dont concatenate arr[i] | ||
return backtrack(0) |
26 changes: 26 additions & 0 deletionspython/124-Binary-Tree-Maximum-Path-Sum.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
# Definition for a binary tree node. | ||
# class TreeNode: | ||
# def __init__(self, val=0, left=None, right=None): | ||
# self.val = val | ||
# self.left = left | ||
# self.right = right | ||
class Solution: | ||
def maxPathSum(self, root: TreeNode) -> int: | ||
res = [root.val] | ||
# return max path sum without split | ||
def dfs(root): | ||
if not root: | ||
return 0 | ||
leftMax = dfs(root.left) | ||
rightMax = dfs(root.right) | ||
leftMax = max(leftMax, 0) | ||
rightMax = max(rightMax, 0) | ||
# compute max path sum WITH split | ||
res[0] = max(res[0], root.val + leftMax + rightMax) | ||
return root.val + max(leftMax, rightMax) | ||
dfs(root) | ||
return res[0] |
19 changes: 19 additions & 0 deletionspython/125-Valid-Palindrome.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
class Solution: | ||
def isPalindrome(self, s: str) -> bool: | ||
l, r = 0, len(s) - 1 | ||
while l < r: | ||
while l < r and not self.alphanum(s[l]): | ||
l += 1 | ||
while l < r and not self.alphanum(s[r]): | ||
r -= 1 | ||
if s[l].lower() != s[r].lower(): | ||
return False | ||
l += 1 | ||
r -= 1 | ||
return True | ||
# Could write own alpha-numeric function | ||
def alphanum(self, c): | ||
return (ord('A') <= ord(c) <= ord('Z') or | ||
ord('a') <= ord(c) <= ord('z') or | ||
ord('0') <= ord(c) <= ord('9')) |
28 changes: 28 additions & 0 deletionspython/127-Word-Ladder.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
class Solution: | ||
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: | ||
if endWord not in wordList: | ||
return 0 | ||
nei = collections.defaultdict(list) | ||
wordList.append(beginWord) | ||
for word in wordList: | ||
for j in range(len(word)): | ||
pattern = word[:j] + "*" + word[j + 1:] | ||
nei[pattern].append(word) | ||
visit = set([beginWord]) | ||
q = deque([beginWord]) | ||
res = 1 | ||
while q: | ||
for i in range(len(q)): | ||
word = q.popleft() | ||
if word == endWord: | ||
return res | ||
for j in range(len(word)): | ||
pattern = word[:j] + "*" + word[j + 1:] | ||
for neiWord in nei[pattern]: | ||
if neiWord not in visit: | ||
visit.add(neiWord) | ||
q.append(neiWord) | ||
res += 1 | ||
return 0 |
14 changes: 14 additions & 0 deletionspython/128-Longest-consecutive-sequence.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
classSolution: | ||
deflongestConsecutive(self,nums:List[int])->int: | ||
numSet=set(nums) | ||
longest=0 | ||
forninnums: | ||
# check if its the start of a sequence | ||
if (n-1)notinnumSet: | ||
length=1 | ||
while (n+length)innumSet: | ||
length+=1 | ||
longest=max(length,longest) | ||
returnlongest | ||
11 changes: 11 additions & 0 deletionspython/13-Roman-To-Integer.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
class Solution: | ||
def romanToInt(self, s: str) -> int: | ||
roman = { "I" : 1, "V" : 5, "X" : 10, | ||
"L" : 50, "C" : 100, "D" : 500, "M" : 1000 } | ||
res = 0 | ||
for i in range(len(s)): | ||
if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]: | ||
res -= roman[s[i]] | ||
else: | ||
res += roman[s[i]] | ||
return res |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.