repo_name stringclasses 400 values | branch_name stringclasses 4 values | file_content stringlengths 16 72.5k | language stringclasses 1 value | num_lines int64 1 1.66k | avg_line_length float64 6 85 | max_line_length int64 9 949 | path stringlengths 5 103 | alphanum_fraction float64 0.29 0.89 | alpha_fraction float64 0.27 0.89 |
|---|---|---|---|---|---|---|---|---|---|
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
#O(min(N1, N2)) time and space
def is_same_tree(self, node1, node2):
"""
type node1: TreeNode
type node2: TreeNode
rtype: bool
"""
if not node1 and not node2:
return True
if not node1 or not node2:
return False
if node1.value != node2.value:
return False
return self.is_same_tree(node1.left, node2.left) and self.is_same_tree(node1.right, node2.right)
| Python | 20 | 26.049999 | 104 | /trees/same_tree.py | 0.560886 | 0.531365 |
aymane081/python_algo | refs/heads/master | import unittest
class Solution:
def get_longest_common_sequence(self, str1, str2):
if not str1 or not str2:
return ''
max_length = float('-inf')
num_rows, num_cols = len(str2) + 1, len(str1) + 1
T = [[0 for _ in range(num_cols)] for _ in range(num_rows)]
for i in range(1, num_rows):
for j in range(1, num_cols):
if str2[i - 1] != str1[j - 1]:
# if the sequences do not need to be contigious
T[i][j] = max(T[i - 1][j], T[i][j - 1])
# if the sequence need to be contiguous
T[i][j] = 0
else:
T[i][j] = T[i - 1][j - 1] + 1
# to get the max length of the contiguous common sequence
max_length = max(max_length, T[i][j])
result = ''
i = num_rows - 1
j = num_cols - 1
while T[i][j]:
if T[i][j] == T[i - 1][j]:
i -= 1
elif T[i][j] == T[i][j - 1]:
j -= 1
elif T[i][j] == T[i - 1][j - 1] + 1:
result += str2[i - 1]
i -= 1
j -= 1
else:
raise Exception('Error constructing table')
return result[::-1]
class Test(unittest.TestCase):
def test_longest_common_subsequence(self):
solution = Solution()
str1 = 'ABCDEFGHIJ'
str2 = 'FOOBCDBCDEG'
expected = 'BCDEG'
actual = solution.get_longest_common_sequence(str1, str2)
self.assertEqual(expected, actual)
print('Success!')
def main():
test = Test()
test.test_longest_common_subsequence()
if __name__ == '__main__':
main() | Python | 59 | 29.864407 | 77 | /dynamicProgramming/longest_common_sequence.py | 0.438462 | 0.417033 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class TreeLinkNode(TreeNode):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.next = None
class Solution:
#O(N) time and space
def set_next_right_pointers(self, node):
if not node or not node.left:
return
# node has children
node.left.next = node.right
node.right.next = None if not node.next else node.next.left
self.set_next_right_pointers(node.right)
self.set_next_right_pointers(node.left)
#O(N) time and space
def set_next_right_pointers2(self, node):
level = [node]
while level and level[0]:
prev = None
next_level = []
for node in level:
if prev:
prev.next = node
prev = node
next_level.append(node.left)
next_level.append(node.right)
level = next_level
| Python | 40 | 23.975 | 67 | /trees/next_right_pointer.py | 0.525526 | 0.523524 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_max_words(self, words, zeroes_count, ones_count):
memo = [[0 for _ in range(ones_count + 1)] for _ in range(zeroes_count + 1)]
for word in words:
zeroes = sum([True for c in word if c == '0'])
ones = len(word) - zeroes
for i in range(zeroes_count + 1):
for j in range(ones_count + 1):
can_build = i >= zeroes and j >= ones
if can_build:
memo[i][j] = max(memo[i][j], 1 + memo[i - zeroes][j - ones])
return memo[-1][-1]
words = ["10", "0001", "111001", "1", "0"]
solution = Solution()
print(solution.get_max_words(words, 5, 3)) | Python | 19 | 36.157894 | 84 | /dynamicProgramming/ones_and_zeroes.py | 0.493617 | 0.458156 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
from collections import defaultdict
class Solution:
def get_paths_count(self, node, target):
if not node:
return 0
sum_mapping = defaultdict(int)
sum_mapping[0] = 1
return self.helper(node, 0, target, sum_mapping)
def helper(self, node, curr_sum, target, sum_mapping):
if not node:
return 0
curr_sum += node.value
result = sum_mapping[curr_sum - target]
sum_mapping[curr_sum] += 1
result += self.helper(node.left, curr_sum, target, sum_mapping)
result += self.helper(node.right, curr_sum, target, sum_mapping)
sum_mapping[curr_sum] -= 1
return result
node1 = TreeNode(10)
node2 = TreeNode(5)
node3 = TreeNode(-3)
node4 = TreeNode(3)
node5 = TreeNode(2)
node6 = TreeNode(6)
node7 = TreeNode(11)
node8 = TreeNode(3)
node9 = TreeNode(-2)
node10 = TreeNode(1)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node4.left = node8
node4.right = node9
node5.left = node10
node3.right = node7
# node6.left = node7
print(node1)
solution = Solution()
print(solution.get_paths_count(node1, 8)) | Python | 55 | 21.054546 | 72 | /trees/path_sum3.py | 0.636139 | 0.593234 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_combinations(self, k, target):
result = []
self.backtrack([], 1, target, k, result)
return result
def backtrack(self, prefix, current_num, remaining, k, result):
if len(prefix) > k or remaining < 0:
return
if remaining == 0 and len(prefix) == k:
result.append(prefix)
return
for i in range(10 - current_num):
self.backtrack(
prefix + [current_num + i],
current_num + i + 1,
remaining - current_num - i,
k,
result
)
solution = Solution()
print(solution.get_combinations(3, 9))
| Python | 26 | 26.73077 | 67 | /arrays/combimation_sum_3.py | 0.480218 | 0.469304 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_major(self, nums):
candidate1, candidate2 = None, None
count1, count2 = 0, 0
for num in nums:
if num == candidate1:
count1 += 1
elif num == candidate2:
count2 += 1
elif count1 == 0:
candidate1 = num
count1 = 1
elif count2 == 0:
candidate2 = num
count2 = 1
else:
count1 -= 1
count2 -= 1
return [candidate for candidate in [candidate1, candidate2] if nums.count(candidate) > len(nums) // 3]
solution = Solution()
nums = [1,2,3,2,2,1,3,1,2,1]
print(solution.get_major(nums)) | Python | 25 | 28.24 | 110 | /arrays/majority_element_2.py | 0.471233 | 0.417808 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def contains_duplicates(self, values, k):
hash_set = set()
for i, val in enumerate(values):
if i > k:
hash_set.remove(values[i - k - 1])
if val in hash_set:
return True
hash_set.add(val)
return False
solution = Solution()
values = [1, 2, 3, 4, 1, 7, 5]
print(solution.contains_duplicates(values, 3)) | Python | 15 | 27.666666 | 50 | /arrays/contains_duplicates2.py | 0.526807 | 0.505827 |
aymane081/python_algo | refs/heads/master | class Solution:
# O(N) time - O(1) space
def climb_stairs(self, n):
if n < 0:
return 0
if n <= 2:
return n
curr, prev = 2, 1
for _ in range(2, n):
curr, prev = curr + prev, curr
return curr
def climbStairs3(self, n):
"""
:type n: int
:rtype: int
"""
if n < 0:
return 0
if n <= 2:
return n
curr, prev = 1, 1
for i in range(2, n + 1):
curr, prev = curr + prev, curr
return curr
# O(N) time - O(N) space
def climb_stairs2(self, n):
memo = [0] + [-1 for _ in range(n)]
return self.stairs(n, memo)
def stairs(self, n, memo):
if n < 0:
return 0
if n <= 2:
return n
if memo[n] != -1:
return memo[n]
result = self.stairs(n - 1, memo) + self.stairs(n - 2, memo)
memo[n] = result
return result
solution = Solution()
for i in range(7):
print("climb_stairs({}) = {}".format(i, solution.climb_stairs2(i))) | Python | 57 | 20.350878 | 71 | /dynamicProgramming/climbing_stairs.py | 0.40625 | 0.384868 |
aymane081/python_algo | refs/heads/master | class Solution:
def is_valid_bst(self, node):
return self.helper(node, float('-inf'), float('inf'))
def helper(self, node, min_value, max_value):
if not node:
return True
if node.value < min_value or node.value > max_value:
return False
return (
self.helper(node.left, min_value, node.value)
and self.helper(node.right, node.value, max_value)
)
def is_valid_bst2(self, node):
self.is_valid = True
self.prev_value = float('-inf')
self.in_order(node)
return self.is_valid
def in_order(self, node):
if not node or not self.is_valid:
return
self.in_order(node.left)
if node.value <= self.prev_value:
self.is_valid = False
return
self.prev_value = node.value
self.in_order(node.right)
| Python | 34 | 27 | 62 | /trees/validate_bst.py | 0.522059 | 0.521008 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
#O(N) time and space
def is_balanced(self, root):
return self.absHeight(root) != -1
def absHeight(self, root):
if not root:
return 0
left_height = self.absHeight(root.left)
right_height = self.absHeight(root.right)
if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1:
return -1
return 1 + max(left_height, right_height)
| Python | 18 | 27.388889 | 90 | /trees/is_balanced.py | 0.566219 | 0.552783 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
def get_unique_bst(self, n):
result = []
if n <= 0:
return result
return self.get_unique_bst_helper(1, n)
def get_unique_bst_helper(self, start, end):
result = []
if start > end:
return [None] # return [None] so that I can get in the for lefts and rights loops below
for i in range(start, end + 1):
lefts = self.get_unique_bst_helper(start, i - 1)
rights = self.get_unique_bst_helper(i + 1, end)
for left in lefts:
for right in rights:
root = TreeNode(i, left, right)
result.append(root)
return result
solution = Solution()
print(solution.get_unique_bst(3)) | Python | 29 | 27.482759 | 99 | /trees/unique_bst2.py | 0.532121 | 0.524848 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
def get_level_order_traversal(self, root):
"""
type root: TreeNode
rtype: List[List[Int]]
"""
result = []
if not root:
return result
level_nodes = [root]
while level_nodes:
result.append([])
new_level_nodes = []
for node in level_nodes:
result[-1].append(node.value)
if node.left:
new_level_nodes.append(node.left)
if node.right:
new_level_nodes.append(node.right)
level_nodes = new_level_nodes
return result[::-1]
def get_level_order_traversal2(self, root):
result = []
if not root:
return result
self.helper(root, 0, result)
return result[::-1]
def helper(self, root, level, result):
if not root:
return
if len(result) == level:
# create a new array for this level
result.append([])
result[level].append(root.value)
self.helper(root.left, level + 1, result)
self.helper(root.right, level + 1, result)
node5 = TreeNode(5)
node4 = TreeNode(4)
node3 = TreeNode(3, node4, node5)
node2 = TreeNode(2)
node1 = TreeNode(1, node2, node3)
print(node1)
solution = Solution()
print(solution.get_level_order_traversal(node1))
| Python | 58 | 24.586206 | 54 | /trees/binary_tree_level_order_traversal.py | 0.524933 | 0.509434 |
aymane081/python_algo | refs/heads/master | # 309
class Solution:
def get_max_profit(self, prices):
buy, sell, prev_sell = float('-inf'), 0, 0
for price in prices:
sell, prev_sell = max(prev_sell, buy + price), sell
buy = max(buy, prev_sell - price)
return sell
| Python | 11 | 24.545454 | 63 | /dynamicProgramming/buy_sell_stock_cooldown.py | 0.530249 | 0.512456 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_max_break(self, n):
memo = [0, 1]
for i in range(2, n + 1):
max_product = 0
for j in range(1, (i // 2) + 1):
max_product = max(max_product, max(j, memo[j]) * max(i - j, memo[i - j]))
memo.append(max_product)
return memo[-1]
def get_max_break2(self, n):
memo = [0 for _ in range(n + 1)]
memo[1] = 1
for i in range(2, n+1):
memo[i] = max(max(j, memo[j]) * max(i - j, memo[i - j]) for j in range(1, (i//2) + 1))
return memo[-1]
solution = Solution()
for i in range(2, 10):
print('get_max_break({}) = {}'.format(i, solution.get_max_break2(i))) | Python | 24 | 28.416666 | 98 | /dynamicProgramming/integer_break.py | 0.478014 | 0.443972 |
aymane081/python_algo | refs/heads/master | # iterate over the list, and keep track of where the next 0 and 1 should be placed
# because 2 will always be last, replace the current element with 2
# TAKEAWAY: when sorting in place, have a counter to keep track of where an element should placed next
class Solution:
def sort_colors(self, colors):
next_red, next_white = 0, 0
for i, c in enumerate(colors):
if c < 2:
colors[i] = 2
colors[next_white] = 1
next_white += 1
if c == 0:
colors[next_red] = 0
next_red += 1
solution = Solution()
colors = [2, 1, 2, 2, 1, 0, 0]
print(colors)
solution.sort_colors(colors)
print(colors)
| Python | 20 | 34.799999 | 102 | /arrays/sort_colors.py | 0.575419 | 0.547486 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def move_zeroes(self, numbers):
if not numbers:
return None
insert_pos = 0
for i, num in enumerate(numbers):
if num != 0:
numbers[insert_pos] = num
insert_pos += 1
for i in range(insert_pos, len(numbers)):
numbers[i] = 0
solution = Solution()
numbers = [0, 0, 3, 0, 12, 5, 6, 0, 0, 0]
solution.move_zeroes(numbers)
print(numbers) | Python | 19 | 24.157894 | 49 | /arrays/move_zeroes.py | 0.512552 | 0.481172 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_first_bad_version(self, n):
left, right = 1, n
while left < right:
mid = (left + right) // 2
if not self.is_bad(mid):
left = mid + 1 # this will avoid an infinite loop, because left <= mid < right
else:
right = mid
return left
def get_first_bad_version2(self, n):
left, right = 1, n
while left <= right:
mid = (left + right) // 2
if self.is_bad(mid):
right = mid - 1
else:
left = mid + 1
return left
def is_bad(self, n):
return n >= 4
solution = Solution()
print(solution.get_first_bad_version2(8)) | Python | 28 | 25.857143 | 94 | /binarySearch/first_bad_version.py | 0.466045 | 0.451398 |
aymane081/python_algo | refs/heads/master | import unittest
class Solution(object):
def three_sum(self, numbers):
"""
:type numbers: List[int]
:rtype : List[List[int]]
"""
result = []
if not numbers:
return result
numbers.sort()
i = 0
while i < len(numbers) - 2:
left = i + 1
right = len(numbers) - 1
while left < right:
triple_sum = numbers[i] + numbers[left] + numbers[right]
if triple_sum == 0:
result.append([numbers[i], numbers[left], numbers[right]])
# move left to the next possible value
left += 1
while left < right and numbers[left] == numbers[left - 1]:
left += 1
# move right to the next possible value
right -= 1
while left < right and numbers[right] == numbers[right + 1]:
right -= 1
elif triple_sum < 0:
# move left to the next possible value
left += 1
while left < right and numbers[left] == numbers[left - 1]:
left += 1
else:
# move right to the next possible value
right -= 1
while left < right and numbers[right - 1] == numbers[right]:
right -= 1
# move i to the next possible value
i += 1
while i < len(numbers) - 2 and numbers[i] == numbers[i - 1]:
i += 1
return result
class Test(unittest.TestCase):
test_data = [([-1, 0, 1, 2, -1, 4], [[-1, -1, 2], [-1, 0, 1]])]
def test_three_way(self):
solution = Solution()
for data in self.test_data:
self.assertEqual(solution.three_sum(data[0]), data[1])
if __name__ == '__main__':
unittest.main()
| Python | 57 | 33.877193 | 80 | /arrays/three_sum.py | 0.438632 | 0.420523 |
aymane081/python_algo | refs/heads/master | #684
from collections import defaultdict
class Solution:
def find_redundant_connection(self, edges):
graph = defaultdict(set)
for u, v in edges:
visited = set()
if u in graph and v in graph and self.dfs(u, v, graph, visited):
return [u, v]
graph[u].add(v)
graph[v].add(u)
def dfs(self, source, target, graph, visited):
if source in visited:
return False
visited.add(source)
if source == target:
return True
return any(self.dfs(nbr, target, graph, visited) for nbr in graph[source])
solution = Solution()
edges = [[1,2], [1,3], [2,3]]
# edges = [[1,2], [2,3], [3,4], [1,4], [1,5]]
print(solution.find_redundant_connection(edges)) | Python | 31 | 25.258064 | 82 | /arrays/find_redundant_connection.py | 0.538745 | 0.515375 |
aymane081/python_algo | refs/heads/master | class Solution:
def can_construct(self, org, seqs):
extended = [None] + seqs
pairs = set((u, v) for u, v in zip(extended, org))
num_to_index = { num: i for i, num in enumerate(extended)}
for seq in seqs:
for u, v in zip([None]+seq, seq):
if v not in num_to_index or num_to_index[v] <= num_to_index[u]:
return False
pairs.discard((u,v))
return not pairs | Python | 13 | 35.23077 | 79 | /graphs/reconstruct_sequence.py | 0.508511 | 0.508511 |
aymane081/python_algo | refs/heads/master | class RangeSum:
def __init__(self, nums):
self.sums = [0 for _ in range(len(nums) + 1)]
for i, num in enumerate(nums):
self.sums[i + 1] = num + self.sums[i]
def get_range_sum(self, start, end):
return self.sums[end + 1] - self.sums[start]
nums = [1, 2, 3, 4, 5, 6, 7]
range_sum = RangeSum(nums)
print(range_sum.get_range_sum(1, 3)) | Python | 12 | 30.833334 | 53 | /dynamicProgramming/range_sum_query_immutable.py | 0.559055 | 0.524934 |
aymane081/python_algo | refs/heads/master | class Solution:
# time: O(log(min(m, n) * (m + n) * min(m, n)))
# space: O(m ** 2)
def get_max_length(self, A, B):
def mutual_subarray(length):
# generate all subarrays of A with length length
subarrays = set(tuple(A[i: i + length]) for i in range(len(A) - length + 1))
return any(tuple(B[j: j + length]) in subarrays for j in range(len(B) - length + 1))
left, right = 0, min(len(A), len(B)) - 1
while left <= right: # search for smallest length with no mutual subarray
mid = (right + left) // 2
if mutual_subarray(mid):
left = mid + 1
else:
right = mid - 1
return left - 1
#time: O(M * N)
#space: O(M * N)
def get_max_length2(self, A, B):
# rows = A, cols = B
memo = [[0 for _ in range(len(B) + 1)] for _ in range(len(A) + 1)]
result = 0
for row in range(1, len(A) + 1):
for col in range(1, len(B) + 1):
if A[row - 1] == B[col - 1]:
memo[row][col] = memo[row - 1][col - 1] + 1
result = max(result, memo[row][col])
return result
## this is the solution for the problem if the subarrays do not need to be continuous
## in this case, dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
def get_max_length3(self, A, B):
dp = [[0 for _ in range(len(B) + 1)] for _ in range(len(A) + 1)]
for i in range(1, len(A) + 1):
for j in range(1, len(B) + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1]
solution = Solution()
A = [3, 2, 1, 8, 6, 9]
B = [7, 6, 3, 2, 1, 9]
print(solution.get_max_length3(A, B)) | Python | 60 | 31.1 | 96 | /binarySearch/maximum_length_repeated_subarray.py | 0.447273 | 0.418701 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
# O(N) time and space
def get_minimum_depth(self, root):
if not root:
return 0
depth = 0
level_nodes = [root]
while level_nodes:
depth += 1
new_level_nodes = []
for node in level_nodes:
if not node.left and not node.right:
#leaf node. return depth
return depth
if node.left:
new_level_nodes.append(node.left)
if node.right:
new_level_nodes.append(node.right)
level_nodes = new_level_nodes
return depth
# O(N) time and space
def get_minimum_depth2(self, root):
if not root:
return 0
left_height, right_height = self.get_minimum_depth2(root.left), self.get_minimum_depth2(root.right)
if not left_height or not right_height:
return 1 + left_height + right_height
return 1 + min(left_height, right_height)
solution = Solution()
print(solution.get_minimum_depth(None))
| Python | 43 | 26.72093 | 107 | /trees/minimum_depth.py | 0.507858 | 0.500414 |
aymane081/python_algo | refs/heads/master | import unittest
# Time: O(N), Space: O(1)
def is_palyndrome(str):
if not str: return True
head = 0
tail = len(str) - 1
while head < tail:
# only compare digits and alphabetical values
if not str[head].isdigit() and not str[head].isalpha():
head += 1
elif not str[tail].isdigit() and not str[tail].isalpha():
tail -= 1
else:
if str[head].lower() != str[tail].lower():
return False
head += 1
tail -= 1
return True
class Test(unittest.TestCase):
data = [('A man, A plan, a canal: Panama', True), ('abab', False)]
def test_is_palindrome(self):
for test_data in self.data:
actual = is_palyndrome(test_data[0])
self.assertIs(actual, test_data[1])
if __name__ == '__main__':
unittest.main() | Python | 35 | 23.742857 | 70 | /strings/palindrome.py | 0.536416 | 0.526012 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
from utils.treeUtils import generate_tree
class Solution:
def get_root_to_leaves_sum(self, node):
leaves = [0]
self.get_sum_helper("", node, leaves)
return sum([int(num) for num in leaves])
def get_sum_helper(self, path, node, leaves):
if not node:
return
path += str(node.value)
if not node.left and not node.right:
leaves.append(path)
self.get_sum_helper(path, node.left, leaves)
self.get_sum_helper(path, node.right, leaves)
path = path[:-1]
def get_root_to_leaves_sum2(self, node):
return self.helper(0, node)
def helper(self, partial, node):
if not node:
return 0
partial = partial * 10 + node.value
if not node.left and not node.right:
return partial
return self.helper(partial, node.left) + self.helper(partial, node.right)
root = generate_tree()
print(root)
solution = Solution()
print(solution.get_root_to_leaves_sum2(root)) | Python | 41 | 26.170732 | 81 | /trees/sum_root_to_leaf_numbers.py | 0.58221 | 0.575022 |
aymane081/python_algo | refs/heads/master | class Solution:
def combination_sum_unlimited(self, nums, target):
'''
In this method, each number can be used an unlimited time
type nums: List[int]
type target: int
rtype: List[List[int]
'''
nums.sort()
results = []
# for i, num in enumerate(nums):
# self.helper(nums, num, [nums[i]], i, target, results)
self.backtrack_unlimited(nums, target, [], 0, results)
return results
def helper(self, nums, sum, partial, index, target, results):
if sum > target:
return
if sum == target: # found a solution
results.append(partial)
return
self.helper(nums, sum + nums[index], partial + [nums[index]], index, target, results) ## add the number to current sum
if index < len(nums) - 1:
self.helper(nums, sum + nums[index + 1], partial + [nums[index + 1]], index + 1, target, results) # move to the next number
def backtrack_unlimited(self, nums, remainder, partial, start, results):
if remainder < 0:
return
if remainder == 0:
results.append(partial)
return
for i in range(start, len(nums)):
self.backtrack_unlimited(nums, remainder - nums[i], partial + [nums[i]], i, results)
def combination_sum_once(self, nums, target):
nums.sort()
results = []
self.backtrack_once(nums, target, [], 0, results)
return results
def backtrack_once(self, nums, remainder, partial, start, results):
if remainder < 0:
return
if remainder == 0:
results.append(partial)
return
for i in range(start, len(nums)):
self.backtrack_once(nums, remainder - nums[i], partial + [nums[i]], i + 1, results)
solution = Solution()
nums = [2, 6, 5, 3, 7]
# print(solution.combination_sum_unlimited(nums, 7))
print(solution.combination_sum_once(nums, 7))
| Python | 61 | 32.360657 | 135 | /arrays/combination_sum.py | 0.558208 | 0.54944 |
aymane081/python_algo | refs/heads/master | import unittest
# O(N) time and O(1) space
# def lengthOfLastWord(string):
# list = string.split(' ')
# return len(list[-1]) if list else 0
# def length_of_last_word(string):
# current_length, prev_length = 0, 0
# for char in string:
# if char == ' ':
# if current_length != 0:
# prev_length = current_length
# current_length = 0
# else:
# current_length += 1
# return current_length if current_length != 0 else prev_length
# def length_of_last_word(string):
# result = 0
# i = len(string) - 1
# while string[i] == ' ' and i >= 0:
# i -= 1
# if i == -1:
# # Reached the beginning of the word, and did not find any words
# return 0
# # result = 1
# while string[i] != ' ' and i >= 0:
# result += 1
# i -= 1
# return result
def length_of_last_word(string):
i = len(string) - 1
end = -1
while i >= 0:
if string[i] == ' ' and end != -1:
# already found a word, and encoutered a space
return end - i
if string[i] != ' ' and end == -1:
# found a letter for the first time
end = i
i -= 1
return end + 1 if end != -1 else 0
class Test(unittest.TestCase):
dataTrue = [('Hello World', 5), ('qwerte', 6), (' ', 0)]
dataFalse = [('Hello World', 7), ('qwerte', 2), (' ', 3)]
def test_length_of_last_word(self):
# true check
for test_data in self.dataTrue:
actual = length_of_last_word(test_data[0])
self.assertEqual(actual, test_data[1])
# false check
for test_data in self.dataFalse:
actual = length_of_last_word(test_data[0])
self.assertNotEqual(actual, test_data[1])
if __name__ == '__main__':
unittest.main()
def length_of_last_word(word):
if not word:
return None
i = len(word) - 1
end = -1
while i >= 0:
if word[i] == ' ' and end != -1:
return end - i
if word[i] != ' ' and end == -1:
end = i
i -= 1
return end + 1 if end != -1 else 0 | Python | 91 | 23.406593 | 73 | /strings/lengthOfLastWord.py | 0.487838 | 0.466667 |
aymane081/python_algo | refs/heads/master | class Solution:
# O(N) time and space
def get_maximum_depth(self, root):
if not root:
return 0
return 1 + max(self.get_maximum_depth(root.left), self.get_maximum_depth(root.right)) | Python | 7 | 31.285715 | 93 | /trees/maximum_depth_binary_tree.py | 0.595556 | 0.586667 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def parenthesis_generator(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
self.generator_helper([], n, n, result)
return result
def generator_helper(self, curr, left, right, result):
if left == 0 and right == 0:
result.append(''.join(curr))
return
if left != 0:
curr.append('(')
self.generator_helper(curr, left - 1, right, result)
curr.pop()
if right > left:
curr.append(')')
self.generator_helper(curr, left, right - 1, result)
curr.pop()
solution = Solution()
print(solution.parenthesis_generator(3)) | Python | 27 | 26 | 64 | /strings/parenthesis_generator.py | 0.51511 | 0.506868 |
aymane081/python_algo | refs/heads/master | class Solution:
def rotate_image(self, image):
if not self.isValidImage(image):
raise Exception('Invalid image')
n = len(image)
for row in range(n//2):
start = row
end = n - 1 - row
for col in range(start, end): # end should not be included, because it is already taken care of in the first iteration
x = row
y = col
prev = image[x][y]
for _ in range(4):
new_row = y
new_col = n - x - 1
new_cell = image[new_row][new_col]
image[new_row][new_col] = prev
x = new_row
y = new_col
prev = new_cell
def isValidImage(self, image):
n = len(image)
return n > 0 and len(image[0]) == n
def print_image(self, image):
for row in image:
print(row)
image = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
solution = Solution()
solution.print_image(image)
solution.rotate_image(image)
print('===============')
solution.print_image(image) | Python | 37 | 30.459459 | 130 | /arrays/rotate_image.py | 0.473775 | 0.448839 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
from utils.treeUtils import generate_tree
class Solution:
def get_side_view(self, node):
result = []
if not node:
return result
level_nodes = [node]
while level_nodes:
result.append(level_nodes[-1].value)
new_level_nodes = []
for node in level_nodes:
if node.left:
new_level_nodes.append(node.left)
if node.right:
new_level_nodes.append(node.right)
level_nodes = new_level_nodes
return result
def get_side_view2(self, node):
result = []
self.helper(node, 0, result)
return result
def helper(self, node, level, result):
if not node:
return
if len(result) == level:
result.append(node.value)
else:
result[level] = node.value
self.helper(node.left, level + 1, result)
self.helper(node.right, level + 1, result)
root = generate_tree()
print(root)
solution = Solution()
print(solution.get_side_view2(root))
| Python | 47 | 24.148935 | 54 | /trees/binary_tree_side_view.py | 0.529163 | 0.524091 |
aymane081/python_algo | refs/heads/master | class Solution:
# Time: O(rows * cols) - space: O(1)
def fill_zeroes(self, matrix):
rows_count, col_count = len(matrix), len(matrix[0])
for row in range(rows_count):
for col in range(col_count):
if not matrix[row][col]:
matrix[row][col] = 'X'
self.fill_row(row, 'X', matrix)
self.fill_col(col, 'X', matrix)
for row in range(rows_count):
for col in range(col_count):
if matrix[row][col] == 'X':
matrix[row][col] = 0
def fill_row(self, row, val, matrix):
col_count = len(matrix[0])
for col in range(col_count):
matrix[row][col] = val
def fill_col(self, col, val, matrix):
row_count = len(matrix)
for row in range(row_count):
matrix[row][col] = val
def print_matrix(self, matrix):
for row in matrix:
print(row)
def fill_zeroes2(self, matrix):
should_fill_row, should_fill_col = False, False
rows_count, col_count = len(matrix), len(matrix[0])
for row in range(rows_count):
for col in range(col_count):
if not matrix[row][col]:
if row == 0:
should_fill_row = True
if col == 0:
should_fill_col = True
matrix[0][col] = 0
matrix[row][0] = 0
for row in range(1, rows_count):
for col in range(1, rows_count):
if not matrix[row][0] or not matrix[0][col]:
matrix[row][col] = 0
if should_fill_row:
self.fill_row(0, 0, matrix)
if should_fill_col:
self.fill_col(0, 0, matrix)
matrix = [[1,0,1,1,1],[1,1,1,1,1],[1,1,1,1,1], [1,1,1,0,1], [1,1,1,1,1]]
solution = Solution()
solution.print_matrix(matrix)
solution.fill_zeroes2(matrix)
print('===============')
solution.print_matrix(matrix)
| Python | 62 | 32.467743 | 72 | /arrays/fil_zeroes.py | 0.47736 | 0.454721 |
aymane081/python_algo | refs/heads/master | from utils.interval import Interval
class Solution:
def merge_intervals(self, intervals):
"""
type: intervals: List[Interval]
rtype: List[Interval]
"""
result = []
intervals.sort(key=lambda interval:interval.start)
for interval in intervals:
if not result or interval.start > result[-1].end:
result.append(interval)
else:
result[-1].end = max(result[-1].end, interval.end)
return result
interval1 = Interval(2, 5)
interval2 = Interval(7, 10)
interval3 = Interval(4, 6)
intervals = [interval1, interval3, interval2]
print(intervals)
solution = Solution()
print(solution.merge_intervals(intervals)) | Python | 26 | 27.192308 | 66 | /arrays/merge_intervals.py | 0.618852 | 0.596995 |
aymane081/python_algo | refs/heads/master | from utils.matrix import Matrix
class Solution:
def min_path_sum(self, matrix):
row_count, col_count = matrix.row_count, matrix.col_count
if not row_count or not col_count:
return 0
sum_row = [float('inf') for _ in range(col_count + 1)]
sum_row[1] = 0
for row in range(1, row_count + 1):
new_sum_row = [float('inf') for _ in range(col_count + 1)]
for col in range(1, col_count + 1):
new_sum_row[col] = matrix[row - 1][col - 1] + min(new_sum_row[col - 1], sum_row[col])
sum_row = new_sum_row
return sum_row[-1]
matrix = Matrix([[5,2,8],[6,1,0],[3,3,7]])
print(matrix)
solution = Solution()
print(solution.min_path_sum(matrix))
| Python | 24 | 30.833334 | 101 | /arrays/min_path_sum.py | 0.547712 | 0.518954 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
from utils.treeUtils import generate_tree
class Solution:
def in_order_traversal(self, node):
result = []
self.in_order_rec(node, result)
return result
def in_order_rec(self, node, result):
if not node:
return
self.in_order_rec(node.left, result)
result.append(node.value)
self.in_order_rec(node.right, result)
def in_order_traversal2(self, node):
result = []
if not node:
return result
stack = []
while node or stack:
if node:
stack.append(node)
node = node.left
continue
node = stack.pop()
result.append(node.value)
node = node.right
return result
def in_order_traversal3(self, node):
stack, result = [], []
while node:
stack.append(node)
node = node.left
while stack:
node = stack.pop()
result.append(node.value)
if node.right:
node = node.right
while node:
stack.append(node)
node = node.left
return result
root = generate_tree()
print(root)
solution = Solution()
print(solution.in_order_traversal3(root)) | Python | 61 | 22.180328 | 45 | /trees/binary_tree_inorder_traversal.py | 0.501769 | 0.499646 |
aymane081/python_algo | refs/heads/master | import unittest
def add_binary(str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
carry = 0
result = []
i = len(str1) - 1
j = len(str2) - 1
while carry or i >= 0 or j >= 0:
total = carry
if i >= 0:
total += int(str1[i])
i -= 1
if j >= 0:
total += int(str2[j])
j -= 1
result.append(str(total % 2))
carry = total // 2
return ''.join(result[::-1])
class Test(unittest.TestCase):
data = [('11', '1', '100')]
def test_add_binary(self):
for test_data in self.data:
actual = add_binary(test_data[0], test_data[1])
self.assertEqual(actual, test_data[2])
if __name__ == '__main__':
unittest.main() | Python | 39 | 19.307692 | 59 | /strings/addBinary.py | 0.467762 | 0.4311 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
from utils.treeUtils import generate_tree
class Solution:
def preorder_traversal(self, node):
result, rights = [], []
while node or rights:
if not node:
node = rights.pop()
result.append(node.value)
if node.right:
rights.append(node.right)
node = node.left
return result
def preorder_traversal2(self, root):
result = []
if not root:
return result
stack = [root]
while stack:
node = stack.pop()
result.append(node.value)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
def preorder_traversal3(self, node):
result = []
self.preorder_traversal_rec(node, result)
return result
def preorder_traversal_rec(self, node, result):
if not node:
return
result.append(node.value)
self.preorder_traversal_rec(node.left, result)
self.preorder_traversal_rec(node.right, result)
root = generate_tree()
print(root)
solution = Solution()
print(solution.preorder_traversal2(root)) | Python | 54 | 23.444445 | 55 | /trees/preorder_traversal.py | 0.548143 | 0.545868 |
aymane081/python_algo | refs/heads/master | class TreeNode:
def __init__(self, value = None, left = None, right = None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return self.trace(padding="")
def trace(self, padding=""):
string_representation = ''
if self.right:
string_representation += self.right.trace(padding + " ") + "\n"
string_representation += padding + str(self.value) + "\n"
if self.left:
string_representation += self.left.trace(padding + " ")
return string_representation
| Python | 20 | 30.299999 | 83 | /utils/treeNode.py | 0.528754 | 0.528754 |
aymane081/python_algo | refs/heads/master | from bisect import bisect
class Solution:
# n = len(houses), m = len(heathers)
# O(m log m + n log m) = O(max(mlogm, nlogm)) time - O(1) space
def get_heathers_radius(self, houses, heathers):
heathers = [float('-inf')] + sorted(heathers) + [float('inf')]
result = 0
for house in houses:
i = bisect(heathers, house)
min_distance = min(house - heathers[i-1], heathers[i] - house)
result = max(result, min_distance)
return result
houses = [1, 2, 3, 4]
heathers = [2]
solution = Solution()
print(solution.get_heathers_radius(houses, heathers)) | Python | 19 | 32.210526 | 74 | /binarySearch/heaters.py | 0.590476 | 0.577778 |
aymane081/python_algo | refs/heads/master | # 515
from utils.treeNode import TreeNode
# time: O(N)
# space: O(N)
class Solution:
def max_rows(self, root):
result = []
if not root:
return result
self.traverse(root, 0, result)
return result
def traverse(self, root, level, result):
if not root:
return
if len(result) == level:
result.append(root.value)
else:
result[level] = max(result[level], root.value)
self.traverse(root.left, level + 1, result)
self.traverse(root.right, level + 1, result)
# time: O(N)
# space: O(N)
class Solution2:
def max_rows(self, root):
result = []
if not root:
return result
level = [root]
while level:
new_level = []
max_value = max(map(lambda node: node.value, level))
result.append(max_value)
for node in level:
if node.left:
new_level.append(node.left)
if node.right:
new_level.append(node.right)
level = new_level
return result
one = TreeNode(1)
two = TreeNode(2)
three = TreeNode(3)
four = TreeNode(4)
five = TreeNode(5)
six = TreeNode(6)
seven = TreeNode(7)
one.left = five
five.left = three
five.right = four
one.right = two
two.right = six
six.right = seven
print(one)
print('===========')
solution = Solution2()
print(solution.max_rows(one)) | Python | 74 | 19.824324 | 64 | /trees/find_largest_value_in_each_tree_row.py | 0.520779 | 0.511039 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_kth_smallest(self, node, k):
count = self.count(node.left)
if k <= count:
return self.get_kth_smallest(node.left, k)
elif k > count + 1:
return self.get_kth_smallest(node.right, k - count - 1)
return node.value
def count(self, node):
if not node:
return 0
return 1 + self.count(node.left) + self.count(node.right)
def get_kth_smallest2(self, node, k):
stack = []
while node:
stack.append(node.value)
node = node.left
while stack:
node = stack.pop()
k -= 1
if k == 0:
return node.value
if node.right:
node = node.right
while node:
stack.append(node)
node = node.left
def get_kth_smallest3(self, node, k):
self.k = k
self.result = None
self.helper(node)
return self.result
def helper(self, node):
if not node:
return
self.helper(node.left)
self.k -= 1
if self.k == 0:
self.result = node.value
return
self.helper(node.right)
def get_kth_smallest(root, k):
left_count = get_count(root.left)
if left_count <= k:
return get_kth_smallest(root.left, k)
if left_count == k + 1:
return root.value
return get_kth_smallest(root.right, k - left_count - 1)
def get_count(root):
if not root:
return 0
return 1 + get_count(root.left) + get_count(root.right)
def get_kth_smallest4(root, k):
stack = []
while root:
stack.append(root)
root = root.left
while stack:
node = stack.pop()
k -= 1
if k == 0:
return node.value
if node.right:
node = node.right
while node:
stack.append(node)
node = node.left
| Python | 92 | 22.206522 | 67 | /trees/kth_smallest_element_in_bst.py | 0.465888 | 0.457944 |
aymane081/python_algo | refs/heads/master | # 561
class Solution:
def partition(self, nums):
result = 0
if not nums:
return result
nums.sort()
for i in range(0, len(nums), 2):
result += nums[i]
return result
class Solution2:
def partition(self, nums):
return sum(sorted(nums)[::2])
solution = Solution2()
nums = [1,4, 3, 2]
print(solution.partition(nums)) | Python | 23 | 17.043478 | 40 | /arrays/array_partition_1.py | 0.531401 | 0.5 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_ones(self, n):
if n < 0:
return 0
ones = [0 for _ in range(n + 1)]
for i in range(1, n + 1):
ones[i] = ones[i // 2] + i % 2
return ones
solution = Solution()
print(solution.get_ones(5)) | Python | 15 | 18.4 | 42 | /dynamicProgramming/couting_bits.py | 0.448276 | 0.417241 |
aymane081/python_algo | refs/heads/master | class Solution:
def spiral(self, matrix):
rows_count = len(matrix[0])
cols_count = len(matrix)
row, col = 0, -1
d_row, d_col = 0, 1
row_leg, col_leg = rows_count, cols_count - 1
leg_count = 0
spiral = []
for _ in range(rows_count * cols_count):
row += d_row
col += d_col
spiral.append(matrix[row][col])
leg_count += 1
if (d_row == 0 and leg_count == row_leg) or (d_col == 0 and leg_count == col_leg):
# change direction
# decrease the right leg (possible number of moves through the axis)
if d_row == 0:
row_leg -= 1
else:
col_leg -= 1
# get the new direction
d_row, d_col = d_col, - d_row
leg_count = 0
return spiral
def print_matrix(self, matrix):
for row in matrix:
print(row)
solution = Solution()
matrix = [[1,2,3],[5,6,7],[9,10,11],[13,14,15]]
solution.print_matrix(matrix)
print(solution.spiral(matrix))
| Python | 38 | 29.447369 | 94 | /arrays/spiral_matrix.py | 0.459574 | 0.433191 |
aymane081/python_algo | refs/heads/master | class Solution:
def can_jump(self, nums):
last = len(nums) - 1
for i in range(last - 1, -1, -1):
if i + nums[i] >= last:
last = i
return last == 0
def can_jump2(self, nums):
max_reached = 0
stack = [0]
while stack:
index = stack.pop()
if index + nums[index] > max_reached:
if index + nums[index] >= len(nums) - 1:
return True
for i in range(max_reached + 1, index + nums[index] + 1):
stack.append(i)
max_reached = index + nums[index]
return False
nums = [2,3,1,0,4]
# nums = [3, 2, 1, 0, 4]
solution = Solution()
print(solution.can_jump2(nums)) | Python | 29 | 26.689655 | 73 | /arrays/jump_game.py | 0.437656 | 0.410224 |
aymane081/python_algo | refs/heads/master | class Solution:
# time: O(rows_count * cols_count). space: O(cols_count)
def get_unique_paths_count(self, rows_count, cols_count):
row_paths = [1 for _ in range(cols_count)]
for _ in range(1, rows_count):
new_row_paths = [1]
for col in range(1, cols_count):
new_row_paths.append(new_row_paths[-1] + row_paths[col])
row_paths = new_row_paths
return row_paths[-1]
def get_unique_paths_count2(self, rows_count, cols_count):
if rows_count == 0 or cols_count == 0:
return 0
if rows_count == 1 or cols_count == 1:
return 1
res = 1
for i in range(1, cols_count):
res *= (cols_count + rows_count - 1 - i) / i
return int(res)
solution = Solution()
print(solution.get_unique_paths_count2(6, 3)) | Python | 27 | 31.555555 | 72 | /arrays/unique_paths.py | 0.536446 | 0.514806 |
aymane081/python_algo | refs/heads/master | # 565
class Solution:
def array_nesting(self, nums):
result = 0
if not nums:
return result
for i in range(len(nums)):
if nums[i] == float('inf'):
continue
start, count = i, 0
while nums[start] != float('inf'):
temp = start
start = nums[start]
nums[temp] = float('inf')
count += 1
result = max(result, count)
return result
| Python | 22 | 23.681818 | 46 | /arrays/array_nesting.py | 0.403315 | 0.392265 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
class Solution:
def get_min_height_trees(self, n, edges):
graph = defaultdict(set)
for edge in edges:
graph[edge[0]].add(edge[1])
graph[edge[1]].add(edge[0])
height_to_nodes = defaultdict(set)
for node in graph:
self.bfs(node, graph, set(), height_to_nodes)
min_height = min(height_to_nodes.keys())
return list(height_to_nodes[min_height])
def bfs(self, node, graph, visited, height_to_nodes):
height = -1
queue = [node]
visited.add(node)
while queue:
height += 1
new_queue = []
for curr in queue:
for nbr in graph[curr]:
if nbr in visited:
continue
visited.add(nbr)
new_queue.append(nbr)
queue = new_queue
height_to_nodes[height].add(node)
def get_min_height_trees2(self, n, edges):
graph = defaultdict(set)
for edge in edges:
graph[edge[0]].add(edge[1])
graph[edge[1]].add(edge[0])
leaves = [i for i in graph if len(graph[i]) == 1]
while len(graph) > 2:
new_leaves = []
for leaf in leaves:
nbr = graph[leaf].pop()
del graph[leaf]
graph[nbr].remove(leaf)
if len(graph[nbr]) == 1:
new_leaves.append(nbr)
leaves = new_leaves
return list(graph.keys())
solution = Solution()
# edges = [[1, 0], [1, 2], [1, 3]]
# print(solution.get_min_height_trees2(4, edges))
edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
print(solution.get_min_height_trees2(6, edges))
| Python | 68 | 26.617647 | 57 | /graphs/minumum_height_trees.py | 0.473376 | 0.455272 |
aymane081/python_algo | refs/heads/master | from utils.graph import Vertex, Graph
class Solution:
# DFS
def search(self, graph, start, end):
if not end:
return
if start == end:
return True
visited = set()
set.add(start)
for nbr in graph[start]:
if nbr not in visited:
if self.search(graph, nbr, end):
return True
return False
def search_BFS(self, graph, start, end):
if start == end:
return True
start.visited = True
queue = [start]
while queue:
new_queue = []
for node in queue:
for nbr in graph[node]:
if nbr == end:
return True
if not nbr.visited:
nbr.visited = True
new_queue.append(nbr)
queue = new_queue
return False
| Python | 43 | 22.697674 | 48 | /graphs/dfs.py | 0.400957 | 0.400957 |
aymane081/python_algo | refs/heads/master | # 368
class Solution:
#O(N ** 2) time, O(N) space
def get_largest_divisible_subset(self, nums):
if not nums:
return []
max_to_set = dict()
nums.sort()
for num in nums:
new_set = set()
for max_in_s, s in max_to_set.items():
if num % max_in_s == 0 and len(s) > len(new_set):
new_set = s
max_to_set[num] = new_set | { num }
return list(max(max_to_set.values(), key=len))
def get_max_divisible_subset_length(self, nums):
"""
returns the length of the longest divisible subset
"""
if not nums:
return 0
max_lengths = [1]
max_length = 1
for i in range(1, len(nums)):
max_length_here = 1
for j in range(i - 1, -1, -1):
if nums[i] % nums[j] == 0:
max_length_here = max(max_length_here, 1 + max_lengths[j])
max_lengths.append(max_length_here)
max_length = max(max_length, max_length_here)
return max_length
solution = Solution()
nums = [1,2,3]
print(solution.get_largest_divisible_subset(nums))
| Python | 44 | 26.727272 | 78 | /dynamicProgramming/largest_divisible_subset.py | 0.490164 | 0.47541 |
aymane081/python_algo | refs/heads/master | # 849
class Solution:
def max_distance_to_closest(self, seats):
if not seats:
return 0
n = len(seats)
lefts, rights = [n] * n, [n] * n
for i in range(len(seats)):
if seats[i] == 1:
lefts[i] = 0
elif i > 0:
lefts[i] = 1 + lefts[i - 1]
for i in range(n - 1, -1, -1):
if seats[i] == 1:
rights[i] = 0
elif i < n - 1:
rights[i] = 1 + rights[i + 1]
return max(min(lefts[i], rights[i]) for i in range(n))
class Solution2:
def max_distance_to_closest(self, seats):
if not seats:
return 0
n = len(seats)
lefts, rights = [n] * n, [n] * n
for i in range(n):
if seats[i] == 1:
lefts[i] = 0
elif i > 0:
lefts[i] = lefts[i - 1] + 1
for i in range(n - 1, -1, -1):
if seats[i] == 1:
rights[i] = 0
elif i < n - 1:
rights[i] = rights[i + 1] + 1
return max(min(lefts[i], rights[i]) for i in range(n))
seats = [1,0,0,0,1,0,1]
solution = Solution()
print(solution.max_distance_to_closest(seats))
[0, 1, 2, 1, 0, 1, 0]
| Python | 54 | 23.314816 | 62 | /arrays/maximize_distance_to_closest_person.py | 0.408225 | 0.373191 |
aymane081/python_algo | refs/heads/master | import random
class Solution:
def __init__(self, nums):
self.original = nums
# def shuffle(self):
# shuffled = []
# copy = list(self.original)
# for i in range(len(copy) - 1, -1, -1):
# index = random.randint(0, i)
# shuffled.append(copy[index])
# copy[index] = copy[-1]
# copy.pop()
# return shuffled
def shuffle(self):
shuffled = list(self.original)
for i in range(len(shuffled)):
swap = random.randint(i, len(shuffled) - 1)
shuffled[i], shuffled[swap] = shuffled[swap], shuffled[i]
return shuffled
def restore(self):
return self.original
nums = [1,2,3,4]
solution = Solution(nums)
print(solution.shuffle())
print(solution.shuffle())
print(solution.restore()) | Python | 31 | 25.935484 | 69 | /arrays/shuffle_array.py | 0.555156 | 0.543165 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def add_one(self, arr):
"""
:type arr: list[int]
:rtype: list[int]
"""
sum = 0
carry = 1
arr.reverse()
for i, c in enumerate(arr):
sum = c + carry
arr[i] = sum % 10
carry = sum // 10
if carry == 1:
arr.append(1)
arr.reverse()
return arr
def add_one2(self, digits):
"""
:type digits: list[int]
:rtype: list[int]
"""
i = len(digits) - 1
while i >= 0 and digits[i] == 9:
digits[i] = 0
i -= 1
if i == -1:
return [1] + digits
return digits[:i] + [digits[i] + 1] + digits[i + 1 :]
solution = Solution()
print(solution.add_one2([9, 8, 9])) | Python | 38 | 20.894737 | 61 | /arrays/add_1.py | 0.406739 | 0.380265 |
aymane081/python_algo | refs/heads/master | class Solution:
def pow(self, x, n):
if n == 0:
return 1
if n < 0:
n *= -1
x = 1/x
# return x * pow(x, n - 1)
return pow(x*x, n // 2) if n % 2 == 0 else x * pow(x * x, n // 2)
solution = Solution()
print(solution.pow(2, 3)) | Python | 12 | 23.75 | 73 | /binarySearch/pow.py | 0.412162 | 0.371622 |
aymane081/python_algo | refs/heads/master | #Gotcha: because int are immutable in python, changing it in a function does not update its value outside of this method
# therefore, we have to return its value from the function that changes it
class Solution(object):
def decode_ways(self, nums):
"""
:type nums: str
:rtype: int
"""
if not nums:
return 0
result = 0
result = self.decode_ways_count(nums, 0, result)
return result
def decode_ways_count(self, nums, index, result):
# went through all the digits in the string, increment the result count
if index == len(nums):
result += 1
elif nums[index] != '0':
# The digit at index is not 0, I can use it to get a character
result = self.decode_ways_count(nums, index + 1, result)
# Check if we can build a character using 2 digits
if index < len(nums) - 1 and 10 <= int(nums[index: index + 2]) <= 26:
result = self.decode_ways_count(nums, index + 2, result)
return result
def get_decode_ways(self, code):
"""
type code: str
rtype: int
"""
if not code:
return 0
ways = [0 for _ in range(len(code) + 1)]
ways[0] = 1
if code[0] != '0':
ways[1] = 1
for i in range(1, len(code)):
if code[i] != '0':
ways[i + 1] += ways[i]
if 10 <= int(code[i-1: i+1]) <= 26:
ways[i + 1] += ways[i - 1]
return ways[-1]
solution = Solution()
print(solution.decode_ways('12123'))
print(solution.get_decode_ways('12123'))
| Python | 58 | 28.465517 | 120 | /strings/decode_ways.py | 0.519602 | 0.492686 |
aymane081/python_algo | refs/heads/master | #669
from utils.treeNode import TreeNode
class Solution:
def trim(self, root, l, r):
if not root:
return root
if root.value < l:
return self.trim(root.right, l, r)
if root.value > r:
return self.trim(root.left, l, r)
root.left, root.right = self.trim(root.left, l, r), self.trim(root.right, l, r)
return root
class Solution2:
def trim(self, root, l, r):
if not root:
return root
root.left, root.right = self.trim(root.left, l, r), self.trim(root.right, l, r)
if root.value < l:
return root.right
if root.value > r:
return root.left
return root
# one = TreeNode(1)
# zero = TreeNode(0)
# two = TreeNode(2)
# one.left = zero
# one.right = two
one = TreeNode(1)
zero = TreeNode(0)
two = TreeNode(2)
three = TreeNode(3)
four = TreeNode(4)
three.left = zero
zero.right = two
two.left = one
three.right = four
print(three)
print('=============')
solution = Solution()
print(solution.trim(three, 1, 3)) | Python | 56 | 19 | 87 | /trees/trim_binary_search_tree.py | 0.548704 | 0.536193 |
aymane081/python_algo | refs/heads/master | #162
class Solution:
def get_peak(self, nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
mid2 = mid + 1 # will not exceed len(nums) - 1 because left < right
if nums[mid] < nums[mid2]: #mid2 is potential peak
left = mid2 #notice how it is mid2 and not mid2+1
else: #mid is potential peak
right = mid #notice how it is mid and not mid - 1
return nums[left]
nums = [1, 2, 3, 1]
solution = Solution()
print(solution.get_peak(nums)) | Python | 17 | 32.705883 | 79 | /arrays/find_peak_element.py | 0.548951 | 0.513986 |
aymane081/python_algo | refs/heads/master | #82
from utils.listNode import ListNode
class Solution:
def remove_duplicates(self, head):
if not head:
return head
curr, runner = head, head.next
while runner:
if curr.value != runner.value:
curr.next = runner
curr = curr.next
runner = runner.next
curr.next = None
return head
one = ListNode(1)
two = ListNode(1)
three = ListNode(3)
four = ListNode(3)
five = ListNode(4)
six = ListNode(4)
seven = ListNode(5)
one.next = two
two.next = three
three.next = four
four.next = five
five.next = six
six.next = seven
print(one)
solution = Solution()
print(solution.remove_duplicates(one)) | Python | 40 | 17.4 | 42 | /linkedList/remove_duplicates2.py | 0.580952 | 0.568707 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def merge_sorted_arrays(self, nums1, nums2):
m = len(nums1)
n = len(nums2)
nums1 += [0] * n
i = m - 1
j = n - 1
k = i + j + 1
while i >= 0 and j >= 0:
nums1[k] = max(nums1[i], nums2[j])
k -= 1
if nums1[i] < nums2[j]:
j -= 1
else:
i -= 1
# nothing to move if only nums1 digits are left, move the rest of digits2 if any
if j >= 0:
nums1[:k+ 1] = nums2[:j + 1]
return nums1
arr1 = [5, 7, 12, 20]
arr2 = [2, 6, 9, 40, 80]
solution = Solution()
print(solution.merge_sorted_arrays(arr1, arr2)) | Python | 29 | 23.724138 | 96 | /arrays/merge_sorted_arrays.py | 0.434358 | 0.372905 |
aymane081/python_algo | refs/heads/master | from utils.matrix import Matrix
class Solution:
def traverse(self, matrix):
"""
:type matrix: Matrix
:rtype: List[int]
"""
if not matrix.row_count or not matrix.col_count:
return
row, col = 0, 0
d_row, d_col = -1, 1
result = []
for _ in range(matrix.row_count * matrix.col_count):
result.append(matrix[row][col])
row += d_row
col += d_col
if not self.is_valid_cell(row, col, matrix):
if col == matrix.col_count:
col -= 1
row += 2
elif row < 0:
row = 0
elif row == matrix.row_count:
row -= 1
col += 2
elif col < 0:
col = 0
d_row, d_col = d_col, d_row
return result
def is_valid_cell(self, row, col, matrix):
return (
row >= 0 and row < matrix.row_count and
col >= 0 and col < matrix.col_count
)
# matrix = Matrix([[1,2,3],[4,5,6]])
matrix = Matrix([[1,2,3],[4,5,6], [7,8,9]])
print(matrix)
solution = Solution()
print(solution.traverse(matrix)) | Python | 43 | 27.744186 | 60 | /arrays/diagonal_traverse.py | 0.447773 | 0.424291 |
aymane081/python_algo | refs/heads/master | import unittest
# Time: O(N) - Space: O(N)
class Solution(object):
def super_reduced_string(self, str):
res = []
for c in str:
if res and res[-1] == c:
res.pop()
else:
res.append(c)
return ''.join(res)
class Test(unittest.TestCase):
test_data = [('aaabccbddd', 'ad')]
def test_super_reduced_string(self):
solution = Solution()
for data in self.test_data:
actual = solution.super_reduced_string(data[0])
self.assertEqual(actual, data[1])
if __name__ == '__main__':
unittest.main() | Python | 26 | 23.23077 | 59 | /strings/super_reduced_string.py | 0.521463 | 0.516693 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
# O(N) time and space
def is_symetric(self, root):
"""
type root: TreeNode
rtype: bool
"""
if not root:
return True
return self.is_mirror(root.left, root.right)
def is_mirror(self, node1, node2):
if not node1 and not node2:
return True
if not node1 or not node2:
return False
if node1.value != node2.value:
return False
return self.is_mirror(node1.left, node2.right) and self.is_mirror(node1.right, node2.left) | Python | 25 | 24.799999 | 98 | /trees/symetric_tree.py | 0.541925 | 0.523292 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
class Solution:
WHITE, GRAY, BLACK = 0, 1, 2
def eventually_safe_nodes(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[int]
"""
colors = defaultdict(int)
result_set = set()
for node in range(len(graph)):
self.dfs(node, graph, colors, result_set)
return sorted(list(result_set))
def dfs(self, node, graph, colors, result_set):
if colors[node] != self.WHITE:
return colors[node] == self.BLACK
colors[node] = self.GRAY
for nbr in graph[node]:
if colors[nbr] == self.BLACK:
continue
if colors[nbr] == self.GRAY or not self.dfs(nbr, graph, colors, result_set):
return False
colors[node] = self.BLACK
result_set.add(node)
return True
def eventually_safe_nodes2(self, graph):
n = len(graph)
out_degree = [0] * n
in_nodes = defaultdict(list)
terminales = []
for i in range(n):
out_degree[i] = len(graph[i])
if out_degree[i] == 0:
terminales.append(i)
for j in graph[i]:
in_nodes[j].append(i)
for term in terminales:
for in_node in in_nodes[term]:
out_degree[in_node] -= 1
if out_degree[in_node] == 0:
terminales.append(in_node)
return sorted(terminales)
solution = Solution()
graph = [[1,2],[2,3],[5],[0],[5],[],[]]
print(solution.eventually_safe_nodes2(graph)) | Python | 65 | 25.200001 | 88 | /graphs/eventually_safe.py | 0.496475 | 0.487074 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
def generate_tree():
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
node7 = TreeNode(7)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node6.left = node7
return node1 | Python | 21 | 17.428572 | 35 | /utils/treeUtils.py | 0.624352 | 0.554404 |
aymane081/python_algo | refs/heads/master | # 203
from utils.listNode import ListNode
class Solution:
def remove_element(self, head, target):
if not head:
return
dummy, prev = ListNode(None), ListNode(None)
dummy.next = head
prev = dummy
while head:
if head.value == target:
prev.next = head.next
else:
prev = head
head = head.next
return dummy.next
one = ListNode(6)
two = ListNode(2)
three = ListNode(6)
four = ListNode(3)
five = ListNode(4)
six = ListNode(5)
seven = ListNode(6)
one.next = two
two.next = three
three.next = four
four.next = five
five.next = six
six.next = seven
print(one)
# solution = Solution()
# print(solution.remove_element(one, 6)) | Python | 42 | 17.190475 | 52 | /linkedList/remove_linked_list_elements.py | 0.576271 | 0.56193 |
aymane081/python_algo | refs/heads/master | #687
class Solution:
def longest_univalue_path(self, root):
if not root:
return 0
return max(self.longest_univalue_path(root.left),
self.longest_univalue_path(root.right),
self.straight_univalue_path(root.left, root.value) + self.straight_univalue_path(root.right, root.value))
def straight_univalue_path(self, root, value):
if not root or root.value != value:
return 0
return max(self.straight_univalue_path(root.left, value), self.straight_univalue_path(root.right, value)) + 1
| Python | 16 | 36.5 | 121 | /trees/longest_univalue_path.py | 0.587302 | 0.577778 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def get_third_max(self, numbers):
if not numbers:
return None
max1, max2, max3 = None, None, None
for num in numbers:
if num in (max1, max2, max3):
continue
elif not max1 or max1 < num:
max3 = max2
max2 = max1
max1 = num
elif not max2 or max2 < num:
max3 = max2
max2 = num
elif not max3 or max3 < num:
max3 = num
return max3 if max3 else max1
solution = Solution()
numbers = [3, 5, 8, 5, 5, 2, 5]
print(solution.get_third_max(numbers))
| Python | 25 | 26.719999 | 43 | /arrays/third_max.py | 0.463977 | 0.419308 |
aymane081/python_algo | refs/heads/master | class Solution(object):
# time: O(N), space: O(N)
def maximum_subarray(self, arr):
if not arr:
return 0
result = arr[0]
dp = [arr[0]]
for i in range(1, len(arr)):
dp.append(arr[i] + max(dp[i - 1], 0)) # longest subarray until index i
result = max(result, dp[i])
return result
# time: O(N), space: O(1)
def maximum_subarray2(self, arr):
if not arr:
return 0
result = arr[0]
max_ending_here = arr[0]
for i in range(1, len(arr)):
max_ending_here = arr[i] + max(max_ending_here, 0)
result = max(result, max_ending_here)
return result
test_arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
solution = Solution()
print(solution.maximum_subarray2(test_arr))
| Python | 33 | 24.333334 | 82 | /arrays/maximum_subarray.py | 0.505376 | 0.477897 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_max_profit(self, prices):
if not prices:
return 0
max_profit, max_here = 0, 0
for i in range(1, len(prices)):
max_here = max(max_here + prices[i] - prices[i - 1], 0)
max_profit = max(max_profit, max_here)
return max_profit
def get_max_profit2(self, prices):
if not prices:
return 0
buy, sell = float('-inf'), 0
for price in prices:
buy = max(buy, - price)
sell = max(sell, price + buy)
return sell | Python | 22 | 24.227272 | 67 | /dynamicProgramming/buy_sell_stock1.py | 0.523466 | 0.50722 |
aymane081/python_algo | refs/heads/master | #671
from utils.treeNode import TreeNode
class Solution:
def second_minimum(self, root):
if not root:
return -1
level = [root]
curr_min = root.value
while level:
next_level = []
for node in level:
if node.left:
next_level.append(node.left)
next_level.append(node.right)
candidates = [node.value for node in next_level if node.value > curr_min]
if candidates:
return min(candidates)
level = next_level
return -1
# one = TreeNode(2)
# two = TreeNode(2)
# three = TreeNode(5)
# four = TreeNode(5)
# five = TreeNode(7)
# one.left = two
# one.right = three
# three.left = four
# three.right = five
one = TreeNode(2)
two = TreeNode(2)
three = TreeNode(2)
one.left = two
one.right = three
print(one)
print('=========')
solution = Solution()
print(solution.second_minimum(one))
| Python | 51 | 18.843138 | 85 | /trees/second_minimum_binary_tree.py | 0.529297 | 0.516602 |
aymane081/python_algo | refs/heads/master | class Solution:
def can_partition(self, nums):
sum_nums = sum(nums)
if sum_nums % 2:
return False
target = sum_nums // 2
nums.sort(reverse = True) #Try the largest numbers first, since less operations to reach the target
subset_sum = [True] + [False for _ in range(target)]
for num in nums:
for i in range(target - 1, -1, -1): # Try the largest sums first
if num + i <= target and subset_sum[i]:
if i + num == target:
return True
subset_sum[num + i] = True
return False
| Python | 18 | 35.277779 | 107 | /dynamicProgramming/partition_equal_subset_sum.py | 0.500766 | 0.493109 |
aymane081/python_algo | refs/heads/master | class Solution:
def count_nodes(self, node):
if not node:
return 0
left_depth, right_depth = self.get_depth(node.left), self.get_depth(node.right)
if left_depth == right_depth:
#left side is complete
return 2 ** (left_depth) + self.count_nodes(node.right)
else:
# right side is complete
return 2 ** (right_depth) + self.count_nodes(node.left)
def get_depth(self, node):
depth = 0
while node:
depth += 1
node = node.left
return depth
| Python | 21 | 27.809525 | 87 | /trees/complete_tree_nodes_count.py | 0.512275 | 0.504092 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
class Vertex:
def __init__(self, key):
self.id =key
self.connectedTo = {}
def add_neighbor(self, nbr, weight = 0):
self.connectedTo[nbr] = weight
def __str__(self):
return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])
def get_connections(self):
return self.connectedTo.keys()
def get_id(self):
return self.id
def get_weight(self, nbr):
return self.connectedTo[nbr]
class Graph:
def __init__(self):
self.vert_list = defaultdict(set)
def add(self, node1, node2):
self.vert_list[node1].add(node2)
self.vert_list[node2].add(node1)
def get_vertices(self):
return self.vert_list.keys()
def __iter__(self):
return iter(self.vert_list.keys())
def is_connected(self, node1, node2):
return node2 in self.vert_list[node1] and node1 in self.vert_list[node2]
| Python | 38 | 25.289474 | 86 | /utils/graph.py | 0.585657 | 0.572709 |
aymane081/python_algo | refs/heads/master | from utils.matrix import Matrix
class Solution:
def pacific_atlantic(self, matrix):
if not matrix or not matrix[0]:
return []
rows, cols = len(matrix), len(matrix[0])
pacific, atlantic = set(), set()
for row in range(rows):
atlantic.add((row, cols - 1))
pacific.add((row, 0))
for col in range(cols):
atlantic.add((rows - 1, col))
pacific.add((0, col))
for ocean in [atlantic, pacific]:
frontier = set(ocean)
while frontier:
new_frontier = set()
for row, col in frontier:
for dir_r, dir_c in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
new_row, new_col = row + dir_r, col + dir_c
if new_row < 0 or new_row >= rows or new_col < 0 or new_col >= cols or (new_row, new_col) in ocean:
continue
if matrix[new_row][new_col] >= matrix[row][col]:
new_frontier.add((new_row, new_col))
frontier = new_frontier
ocean |= frontier
return list(atlantic & pacific)
def pacific_atlantic2(self, matrix):
"""
type matrix: Matrix
rtype: List([int, int])
"""
if not matrix or not matrix.rows_count or matrix.cols_count:
raise Exception('Invalid Matrix')
reached_cells = [[0 for _ in range(matrix.rows_count)] for _ in range(matrix.cols_count)]
pacific_queue = []
atlantic_queue = []
for row in range(matrix.rows_count):
pacific_queue.append((row, 0))
atlantic_queue.append((row, matrix.rows_count - 1))
reached_cells[row][0] += 1
reached_cells[row][matrix.rows_count - 1] += 1
for col in range(matrix.cols_count):
pacific_queue.append((0, col))
atlantic_queue.append((col, matrix.rows_cols - 1))
reached_cells[0][col] += 1
reached_cells[row][matrix.rows_cols - 1] += 1
self.bfs(pacific_queue, matrix, pacific_queue[:], reached_cells)
self.bfs(atlantic_queue, matrix, atlantic_queue[:], reached_cells)
return [[row, col] for row in range(matrix.rows_count) for col in range(matrix.cols_count) if reached_cells[row][col] == 2]
def bfs(self, queue, matrix, visited, reached_cells):
while queue:
new_queue = []
for (row, col) in queue:
for dir_r, dir_c in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
new_row, new_col = row + dir_r, col + dir_c
if not matrix.is_valid_cell(new_row, new_col) or (new_row, new_col) in visited or matrix[row][col] > matrix[new_row][new_col]:
continue
new_queue.append((new_row, new_col))
matrix[new_row][new_col] += 1
queue = new_queue
| Python | 81 | 37.65432 | 146 | /graphs/pacific_atlantic.py | 0.487065 | 0.474289 |
aymane081/python_algo | refs/heads/master | class Solution:
def connect(self, node):
if not node:
return
level = [node]
while level:
prev = None
next_level = []
for node in level:
if prev:
prev.next = node
prev = node
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
level = next_level
| Python | 23 | 22.782608 | 49 | /next_right_pointer2.py | 0.367568 | 0.367568 |
aymane081/python_algo | refs/heads/master | class Solution:
def coin_change(self, coins, amount):
if amount < 1:
return -1
memo = [0 for _ in range(amount)]
return self.helper(coins, amount, memo)
def helper(self, coins, amount, memo):
if amount < 0:
return -1
if amount == 0:
return 0
if memo[amount - 1]:
return memo[amount - 1]
min_count = float('inf')
for coin in coins:
res = self.helper(coins, amount - coin, memo)
if res >= 0 and res < min_count:
min_count = res
memo[amount - 1] = -1 if min_count == float('inf') else 1 + min_count
return memo[amount - 1] | Python | 26 | 27.692308 | 77 | /dynamicProgramming/coin_change.py | 0.472483 | 0.453691 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
from utils.treeUtils import generate_tree
class Solution:
def get_zigzag_level_order(self, node):
result = []
if not node:
return result
should_reverse = False
level_nodes = [node]
while level_nodes:
result.append([])
new_level_nodes = []
for node in level_nodes:
result[-1].append(node.value)
if node.left:
new_level_nodes.append(node.left)
if node.right:
new_level_nodes.append(node.right)
level_nodes = new_level_nodes
if should_reverse:
result[-1] = result[-1][::-1]
should_reverse = not should_reverse
return result
root = generate_tree()
print(root)
solution = Solution()
print(solution.get_zigzag_level_order(root)) | Python | 35 | 26.4 | 54 | /trees/binary_tree_zigzag_level_order.py | 0.518789 | 0.514614 |
aymane081/python_algo | refs/heads/master | #24
from utils.listNode import ListNode
class Solution:
def swap_pairs(self, head):
if not head:
return None
dummy = prev = ListNode(None)
while head and head.next:
next_head = head.next.next
prev.next = head.next
head.next.next = head
prev = head
head = next_head
prev.next = head
return dummy.next
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
one.next = two
two.next = three
three.next = four
print(one)
solution = Solution()
print(solution.swap_pairs(one)) | Python | 35 | 16.714285 | 38 | /linkedList/swap_nodes_in_pair.py | 0.581583 | 0.57189 |
aymane081/python_algo | refs/heads/master | # 623
from utils.treeNode import TreeNode
# time: O(N)
# space: O(N) or the max number of node at each level
class Solution:
def add_row(self, root, v, d):
if d == 1:
new_root = TreeNode(v)
new_root.left = root
return new_root
current_level = [root]
while d > 2:
d -= 1
new_level = []
for node in current_level:
if node.left:
new_level.append(node.left)
if node.right:
new_level.append(node.right)
current_level = new_level
# current_level is at d - 1
for node in current_level:
node.left, node.left.left = TreeNode(v), node.left
node.right, node.right.right = TreeNode(v), node.right
return root
# one = TreeNode(1)
# two = TreeNode(2)
# three = TreeNode(3)
# four = TreeNode(4)
# five = TreeNode(5)
# six = TreeNode(6)
# four.left = two
# four.right = six
# two.left = three
# two.right = one
# six.left = five
one = TreeNode(1)
two = TreeNode(2)
three = TreeNode(3)
four = TreeNode(4)
five = TreeNode(5)
six = TreeNode(6)
four.left = two
# four.right = six
two.left = three
two.right = one
# six.left = five
print(four)
print('==============')
solution = Solution()
print(solution.add_row(four, 1, 3))
| Python | 66 | 20.333334 | 66 | /trees/add_one_row_to_tree.py | 0.52983 | 0.514915 |
aymane081/python_algo | refs/heads/master | from utils.treeUtils import TreeNode
class Solution:
def build_tree(self, pre_order, in_order):
if not pre_order:
return None
return self.helper(0, 0, len(in_order) - 1, pre_order, in_order)
def helper(self, pre_start, in_start, in_end, pre_order, in_order):
if pre_start > len(pre_order) - 1 or in_start > in_end:
return None
value = pre_order[pre_start]
in_order_index = in_order.index(value)
root = TreeNode(value)
root.left = self.helper(pre_start + 1, in_start, in_order_index - 1, pre_order, in_order)
root.right = self.helper(pre_start + 1 + in_order_index - in_start, in_order_index + 1, in_end, pre_order, in_order)
return root
in_order = [4, 2, 5, 1, 3, 6, 7]
pre_order = [1, 2, 4, 5, 3, 6, 7]
solution = Solution()
print(solution.build_tree(pre_order, in_order))
| Python | 27 | 32.555557 | 124 | /trees/tree_from_preorder_inorder.py | 0.593164 | 0.568909 |
aymane081/python_algo | refs/heads/master | class Solution(object):
# O(n) time and space
def basic_calculator(self, expression):
if not expression:
return
stack = []
num = 0
operation = '+'
for i, c in enumerate(expression):
if c.isdigit():
num = num * 10 + int(c)
if i == len(expression) - 1 or (not c.isdigit() and c != ' '): # c is operator or end of string
if operation == '+':
stack.append(num)
elif operation == '-':
stack.append(-num)
elif operation == '*':
stack.append(stack.pop() * num)
elif operation == '/':
left = stack.pop()
stack.append(left // num)
if left // num < 0 and left % num != 0:
stack[-1] += 1 # negative integer division result with remainder rounds down by default
num = 0 # num has been used, so reset
operation = c
return sum(stack)
solution = Solution()
print(solution.basic_calculator('1 + 2 * 3 - 4')) | Python | 34 | 33.882355 | 111 | /strings/basic_calculator.py | 0.443882 | 0.432911 |
aymane081/python_algo | refs/heads/master | # 445
from utils.listNode import ListNode
class Solution:
def add(self, head1, head2):
num1 = self.listToInt(head1)
num2 = self.listToInt(head2)
return self.intToList(num1 + num2)
def listToInt(self, head):
result = 0
if not head:
return result
while head:
result = (result * 10) + head.value
head = head.next
return result
def intToList(self, num):
dummy = prev = ListNode(None)
for c in str(num):
prev.next = ListNode(int(c))
prev = prev.next
return dummy.next
class Solution2:
def add(self, head1, head2):
rev1, rev2 = self.reverse(head1), self.reverse(head2)
carry = 0
total_head = total_tail = ListNode(None)
while rev1 or rev2:
total = carry
if rev1:
total += rev1.value
rev1 = rev1.next
if rev2:
total += rev2.value
rev2 = rev2.next
total_tail.next = ListNode(total % 10)
carry = total // 10
total_tail = total_tail.next
if carry:
total_tail.next = ListNode(carry)
return self.reverse(total_head.next)
def reverse(self, head):
if not head:
return head
rev = None
while head:
rev, rev.next, head = head, rev, head.next
return rev
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
five = ListNode(5)
six = ListNode(6)
seven = ListNode(7)
one.next = two
two.next = three
three.next = four
five.next = six
six.next = seven
print(one)
print(five)
solution = Solution2()
print(solution.add(one, five))
| Python | 91 | 19.43956 | 61 | /linkedList/add_two_numbers.py | 0.516389 | 0.492746 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class BSTIterator:
# O(n) worst case for time and space
def __init__(self, root):
self.stack = []
while root:
self.stack.append(root)
root = root.left
# O(1) time and space
def has_next(self):
return len(self.stack) > 0
#time: O(n) worst case, O(1) average
# space: O(n) worst case, O(log n) if balanced
def next(self):
if not self.has_next():
return None
node = self.stack.pop()
result = node.value
if node.right:
node = node.right
while node:
self.stack.append(node)
node = node.left
return result
| Python | 31 | 23.354839 | 50 | /trees/bst_iterator.py | 0.501966 | 0.498034 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_insert_position(self, nums, value):
left, right = 0, len(nums) - 1
# left <= right because we want the first occurrence of left > right, aka, left is bigger than value
while left <= right:
mid = (left + right) // 2
if mid == value:
return mid
if mid < value:
left = mid + 1
else:
right = mid - 1
return left
def get_insert_position2(self, nums, value):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] > value:
right = mid - 1
else:
left = mid + 1
return left
nums = [1, 2, 3, 3, 5, 8]
solution = Solution()
print(solution.get_insert_position2(nums, 8))
| Python | 30 | 28.533333 | 108 | /binarySearch/search_insert_position.py | 0.465011 | 0.443567 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
def get_paths_sum(self, node, target):
result = []
if not node:
return result
self.get_paths_helper([], target, node, result)
return result
def get_paths_helper(self, path, target, node, result):
if not node:
return
target -= node.value
path.append(node.value)
if target == 0 and not node.left and not node.right:
result.append(path[:]) # import to add a new copy of path, because path will change
self.get_paths_helper(path, target, node.left, result)
self.get_paths_helper(path, target, node.right, result)
path.pop()
| Python | 26 | 27.461538 | 95 | /trees/path_sum2.py | 0.567819 | 0.566489 |
aymane081/python_algo | refs/heads/master | class Solution:
# Time: O(2 ** n), space(n * 2**n)
def generate_subsets_from_unique(self, nums):
result = []
self.backtrack(nums, [], 0, result)
return result
def generate_subsets_from_duplicates(self, nums):
result = []
nums.sort()
self.backtrack(nums, [], 0, result)
return result
def backtrack(self, nums, prefix, start, result):
result.append(prefix)
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i-1]:
continue
self.backtrack(nums, prefix + [nums[i]], i + 1, result)
solution = Solution()
nums = [1,2,3]
# nums = [1,2,2]
print(solution.generate_subsets_from_unique(nums)) | Python | 24 | 29.708334 | 67 | /arrays/subsets.py | 0.559783 | 0.543478 |
aymane081/python_algo | refs/heads/master | # time: O(n ** 3)
class Solution:
ELEMENTS_COUNT = 4
def four_way(self, nums, target):
results = []
self.n_way(sorted(nums), target, [], self.ELEMENTS_COUNT, results)
return results
def n_way(self, nums, target, partial, n, results):
if len(nums) < n or nums[0] * n > target or nums[-1] * n < target:
return
if n == 2:
left, right = 0, len(nums)
while left < right:
if nums[left] + nums[right] == target:
results.append(partial + [nums[left], nums[right]])
left += 1
right -= 1
while nums[right] == nums[right + 1] and right > left:
right -= 1
while nums[left] == nums[left - 1] and left < right:
left += 1
elif nums[left] + nums[right] < target:
left += 1
else:
right -= 1
else:
# add the next element in the list to partial, in order to get to 2-sum
for i in range(len(nums) - n + 1):
if i == 0 or nums[i] != nums[i - 1]: # avoid dups if possible
self.n_way(nums[i + 1 :], target - nums[i], partial + [nums[i]], n - 1, results) | Python | 34 | 38.35294 | 100 | /arrays/four_way.py | 0.445774 | 0.430815 |
aymane081/python_algo | refs/heads/master | # 147
from utils.listNode import ListNode
# time: O(N ** 2)
# space: O(1)
class Solution:
def insert_sort_list(self, head):
sorted_tail = dummy = ListNode(float('-inf'))
dummy.next = head
while sorted_tail.next:
node = sorted_tail.next
if node.value >= sorted_tail.value:
sorted_tail = sorted_tail.next
continue
sorted_tail.next = node.next
insertion = dummy
while insertion.next.value <= node.value:
insertion = insertion.next
node.next = insertion.next
insertion.next = node
return dummy.next
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
one.next = two
two.next = three
three.next = four
print(one)
solution = Solution()
print(solution.insert_sort_list(one)) | Python | 42 | 20.404762 | 53 | /linkedList/insertion_sort_list.py | 0.565702 | 0.555679 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_duplicate(self, nums):
if not nums:
return
slow = nums[0]
fast = nums[slow] # which is nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
fast = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return fast
nums = [1, 3, 2, 4, 3]
solution = Solution()
print(solution.get_duplicate(nums)) | Python | 21 | 22.476191 | 50 | /arrays/find_duplicate.py | 0.477642 | 0.461382 |
aymane081/python_algo | refs/heads/master | # 746
class Solution:
def min_cost(self, costs):
one_before, two_before = costs[1], costs[0]
for i in range(2, len(costs)):
one_before, two_before = min(one_before, two_before) + costs[i], one_before
return min(one_before, two_before)
solution = Solution()
costs = [10, 15, 20]
# costs = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
print(solution.min_cost(costs)) | Python | 16 | 24.625 | 87 | /arrays/min_cost_climbing_stairs.py | 0.584352 | 0.515892 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def two_sum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: Tuple(int)
"""
left, right = 0, len(numbers) - 1
while left < right:
pair_sum = numbers[left] + numbers[right]
if pair_sum == target:
return (left + 1, right + 1)
elif pair_sum < target:
left += 1
else:
right -= 1
solution = Solution()
numbers = [1, 4, 8, 10, 18]
print(solution.two_sum(numbers, 12)) | Python | 21 | 26.333334 | 53 | /arrays/two_sum_sorted_array.py | 0.481675 | 0.455497 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
from utils.treeUtils import generate_tree
class Solution:
def __init__(self):
self.prev = None
def flatten(self, node):
if not node:
return None
self.prev = node
self.flatten(node.left)
temp = node.right
node.right = node.left
node.left = None
self.prev.right = temp
self.flatten(self.prev.right)
root = generate_tree()
print(root)
print('==============')
solution = Solution()
solution.flatten(root)
print(root) | Python | 27 | 19.25926 | 41 | /trees/flatten_binary_tree.py | 0.600733 | 0.600733 |
aymane081/python_algo | refs/heads/master | # 513
from utils.treeNode import TreeNode
# time: O(N)
# space: O(N)
class Solution:
def find_bottom_left_value(self, root):
level = [root]
most_left = None
while level:
most_left = level[0].value
new_level = []
for node in level:
if node.left:
new_level.append(node.left)
if node.right:
new_level.append(node.right)
level = new_level
return most_left
one = TreeNode(1)
two = TreeNode(2)
three = TreeNode(3)
four = TreeNode(4)
five = TreeNode(5)
six = TreeNode(6)
seven = TreeNode(7)
one.left = five
five.left = three
five.right = four
one.right = two
two.right = six
# six.right = seven
print(one)
print('===========')
solution = Solution()
print(solution.find_bottom_left_value(one)) | Python | 45 | 18.733334 | 48 | /trees/find_bottom_left_value.py | 0.542277 | 0.529876 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def remove_element(self, arr, val):
if not arr:
return 0
j = 0
for i in range(len(arr)):
if arr[i] != val:
arr[j] = arr[i]
j += 1
for i in range(len(arr) - j):
arr.pop()
return j
solution = Solution()
arr = [1, 2, 3, 2, 4, 5]
print(solution.remove_element(arr, 2))
print(arr)
| Python | 20 | 20.6 | 39 | /arrays/remove_element.py | 0.444444 | 0.421296 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_ugly_number(self, n, primes):
if n <= 0:
return 0
if n == 1:
return 1
uglys = [1]
indices = [0 for _ in range(len(primes))]
candidates = primes[:]
while len(uglys) < n:
ugly = min(candidates)
uglys.append(ugly)
# increment the correct indexes to avoid duplicates, and set the new candidates
for i in range(len(indices)):
if candidates[i] == ugly:
indices[i] += 1
candidates[i] = uglys[indices[i]] * primes[i]
return uglys[-1]
solution = Solution()
primes = [2, 3, 5]
print(solution.get_ugly_number(11, primes))
| Python | 27 | 26 | 91 | /dynamicProgramming/ugly_number.py | 0.507524 | 0.48974 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_unique_bst_count(self, n):
if n <= 0:
return 0
return self.get_unique_bst_count_rec(1, n)
def get_unique_bst_count_rec(self, start, end):
if start >= end:
return 1
result = 0
for i in range(start, end + 1):
left_count = self.get_unique_bst_count_rec(start, i - 1)
right_count = self.get_unique_bst_count_rec(i + 1, end)
result += left_count * right_count
return result
def get_unique_bst_count2(self, n):
memo = [-1 for _ in range(n + 1)]
memo[0], memo[1] = 1, 1
return self.helper(n, memo)
def helper(self, n, memo):
if memo[n] != -1:
return memo[n]
count = 0
for i in range(n):
# how many ways can i distribute n - 1 nodes between left and right
count += self.helper(i, memo) * self.helper(n - 1 - i, memo)
return count
solution = Solution()
print(solution.get_unique_bst_count2(3)) | Python | 39 | 26.897436 | 79 | /trees/unique_bst.py | 0.50966 | 0.49034 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
class Solution:
def networkDelayTime(self, times, K):
graph = self.build_graph(times)
dist = { node: int('float') for node in graph }
def dfs(node, elapsed):
if elapsed >= dist[node]:
return
dist[node] = elapsed
for time, nbr in sorted(graph[node]): # start with the node with the smallest travel time, as it has more chances of reaching all the nodes quicker
dfs(nbr, elapsed + time)
dfs(K, 0)
ans = max(dist.values())
return ans if ans != float('inf') else -1
def build_graph(self, times):
graph = defaultdict(list)
for u, v, w in times:
graph[u].append((w, v))
return graph | Python | 26 | 30.23077 | 159 | /graphs/network_delay_time.py | 0.545006 | 0.54254 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
def build_tree(self, in_order, post_order):
if not in_order:
return None
return self.build(len(post_order) - 1, 0, len(in_order) - 1, in_order, post_order)
def build(self, post_end, in_start, in_end, in_order, post_order):
if post_end < 0 or in_start > in_end:
return None
value = post_order[post_end]
in_index = in_order.index(value)
root = TreeNode(value)
root.right = self.build(post_end - 1, in_index + 1, in_end, in_order, post_order)
root.left = self.build(post_end - 1 - in_end + in_index, in_start, in_index - 1, in_order, post_order)
return root
in_order = [4, 2, 5, 1, 3, 6, 7]
post_order = [4, 5, 2, 7, 6, 3, 1]
solution = Solution()
print(solution.build_tree(in_order, post_order))
| Python | 28 | 30.392857 | 110 | /trees/tree_from_postorder_inorder.py | 0.584755 | 0.559727 |
aymane081/python_algo | refs/heads/master | import unittest
class Solution:
def get_unique_paths_count(self, matrix):
row_count, col_count = len(matrix), len(matrix[0])
if row_count == 0 or col_count == 0:
raise Exception('Unvalid Matrix')
if matrix[0][0] or matrix[-1][-1]:
return 0
row_paths = [0 for _ in range(col_count)]
path_count = 0
for row in range(row_count):
new_row_paths = []
for col in range(col_count):
if row == 0 and col == 0:
path_count = 1
elif matrix[row][col] == 1:
path_count = 0
else:
path_count = row_paths[col]
path_count += new_row_paths[-1] if col > 0 else 0
new_row_paths.append(path_count)
row_paths = new_row_paths
return row_paths[-1]
def uniquePathsWithObstacles(self, grid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if grid[0][0] or grid[-1][-1]:
return 0
m, n = len(grid), len(grid[0])
ways = [0] * (n + 1)
ways[1] = 1
for row in range(1, m + 1):
new_ways = [0]
for col in range(1, n + 1):
if grid[row - 1][col - 1] == 1:
new_ways.append(0)
else:
new_ways.append(new_ways[-1] + ways[col])
ways = new_ways
return ways[-1]
class Test(unittest.TestCase):
test_data = [([[0,0,0], [0,1,0], [0,0,0]], 2), ([[0,0,0], [1,0,1], [0,0,0]], 1)]
def test_get_unique_paths_count(self):
solution = Solution()
for data in self.test_data:
actual = solution.uniquePathsWithObstacles(data[0])
self.assertEqual(actual, data[1])
if __name__ == '__main__':
unittest.main() | Python | 66 | 28.757576 | 84 | /arrays/unique_paths2.py | 0.449822 | 0.418237 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.