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.listNode import ListNode
class Solution:
def has_cycle(self, head):
if not head or not head.next:
return False
slow, fast = head.next, head.next.next
while fast and fast.next:
if fast == slow:
return True
slow = slow.next
fast = fast.next.next
return False
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
four.next = five
five.next = six
six.next = three
solution = Solution()
print(solution.has_cycle(one)) | Python | 36 | 17.944445 | 46 | /linkedList/linked_list_cycle.py | 0.591777 | 0.581498 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
class Solution:
def target_sum(self, nums, target):
if not nums:
return 0
sums = defaultdict(int)
sums[0] = 1
running = nums[:]
for i in range(len(running) - 2, -1, -1):
running[i] += running[i + 1]
for i, num in enumerate(nums):
new_sums = defaultdict(int)
for old_sum in sums:
if target <= old_sum + running[i]: # if I can reach the target from this sum
new_sums[num + old_sum] += sums[old_sum]
if target >= old_sum - running[i]:
new_sums[old_sum - num] += sums[old_sum]
sums = new_sums
return sums[target]
nums = [1, 1, 1, 1, 1]
target = 3
solution = Solution()
print(solution.target_sum(nums, target))
| Python | 31 | 26.67742 | 92 | /dynamicProgramming/target_sum.py | 0.506344 | 0.491349 |
aymane081/python_algo | refs/heads/master | class Solution:
def surrond(self, matrix):
if not matrix or not matrix.rows_count or not matrix.cols_count:
return matrix
for row in range(matrix.rows_count):
self.dfs(row, 0, matrix)
self.dfs(row, matrix.cols_count - 1, matrix)
for col in range(matrix.cols_count):
self.dfs(0, col, matrix)
self.dfs(matrix.rows_count - 1, col, matrix)
for row in range(matrix.rows_count):
for col in range(matrix.cols_count):
if matrix[row][col] == 'O':
matrix[row][col] = 'X'
elif matrix[row][col] == '*':
matrix[row][col] = 'O'
def dfs(self, row, col, matrix):
if not matrix.is_valid_cell(row, col):
return
if matrix[row][col] != 'O':
return
matrix[row][col] = '*'
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dr, dc in directions:
self.dfs(row + dr, col + dc, matrix)
| Python | 33 | 31.545454 | 72 | /graphs/surronded_regions.py | 0.476723 | 0.465549 |
aymane081/python_algo | refs/heads/master | from utils.listNode import ListNode
class Solution:
def reverse(self, head):
rev = None
while head:
rev, rev.next, head = head, rev, head.next
return rev
def reverse2(self, head):
rev = None
while head:
next = head.next
head.next = rev
rev = head
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
four.next = five
five.next = six
six.next = seven
print(one)
solution = Solution()
print(solution.reverse2(one))
| Python | 47 | 14.765958 | 54 | /linkedList/reverse_linked_list.py | 0.547908 | 0.535762 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_maximum_product(self, nums):
max_so_far = float('-inf')
max_here, min_here = 1, 1
for num in nums:
max_here, min_here = max(max_here * num, min_here * num, num), min(min_here * num, max_here * num, num)
max_so_far = max(max_so_far, max_here)
return max_so_far
solution = Solution()
nums = [2, 3, -2, -4]
print(solution.get_maximum_product(nums))
| Python | 12 | 34.916668 | 115 | /arrays/maximum_product_subarray.py | 0.577726 | 0.563805 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_summary_ranges(self, nums):
result = []
for i, num in enumerate(nums):
if not result or nums[i] > nums[i - 1] + 1:
result.append(str(num))
else:
start = result[-1].split(' -> ')[0]
result[-1] = ' -> '.join([start, str(num)])
return result
solution = Solution()
nums = [0, 1, 2, 4, 5, 7]
print(solution.get_summary_ranges(nums)) | Python | 14 | 31.357143 | 59 | /arrays/summary_ranges.py | 0.5 | 0.475664 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
result = [0] * (len(num1) + len(num2))
num1, num2 = num1[::-1], num2[::-1]
for i in range(len(num1)):
for j in range(len(num2)):
product = int(num1[i]) * int(num2[j])
units = product % 10
tens = product // 10
result[i + j] += units
if result[i + j] > 9:
tens += result[i + j] // 10
result[i + j] %= 10
result[i + j + 1] += tens
if result[i + j + 1] > 9:
result[i + j + 2] += result[i + j + 1] // 10
result[i + j + 1] %= 10
# remove the trailing zeros from result
while len(result) > 0 and result[-1] == 0:
result.pop()
return ''.join(map(str, result[::-1])) | Python | 31 | 31.612904 | 64 | /strings/multiply_strings.py | 0.387129 | 0.347525 |
aymane081/python_algo | refs/heads/master | # 213
class Solution:
def rob(self, houses):
if not houses:
return 0
# last house is not robbed
rob_first = self.helper(houses, 0, len(houses) - 2)
# first house is not robbed
skip_first = self.helper(houses, 1, len(houses) - 1)
return max(rob_first, skip_first)
def helper(self, houses, start, end):
if end == start:
return houses[start]
curr, prev = 0, 0
for i in range(start, end + 1):
curr, prev = max(curr, houses[i] + prev), curr
return curr | Python | 24 | 24.791666 | 60 | /dynamicProgramming/house_robber2.py | 0.504854 | 0.487055 |
aymane081/python_algo | refs/heads/master | import unittest
class Solution(object):
def compare_versions(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
if not version1 or not version2:
return None
digits1 = list(map(int, version1.split('.')))
digits2 = list(map(int, version2.split('.')))
for i in range(max(len(digits1), len(digits2))):
v1 = digits1[i] if i < len(digits1) else 0
v2 = digits2[i] if i < len(digits2) else 0
if v1 < v2:
return -1
if v1 > v2:
return 1
return 0
class Test(unittest.TestCase):
data = [('1.2.3', '1.2.1', 1), ('1.2', '1.2.4', -1), ('1', '1.0.0', 0)]
def test_compare_versions(self):
solution = Solution()
for test_data in self.data:
actual = solution.compare_versions(test_data[0], test_data[1])
self.assertEqual(actual, test_data[2])
if __name__ == '__main__':
unittest.main() | Python | 38 | 26.578947 | 75 | /strings/compare_versions.py | 0.512894 | 0.467049 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def max_consecutive_ones(self, numbers):
if not numbers:
return 0
longest, count = 0, 0
for num in numbers:
if num > 0:
count += 1
longest = max(longest, count)
else:
count = 0
return longest
solution = Solution()
numbers = [1, 1, 0, 1, 1, 1]
print(solution.max_consecutive_ones(numbers)) | Python | 18 | 23.666666 | 45 | /arrays/max_consecutive_ones.py | 0.503386 | 0.476298 |
aymane081/python_algo | refs/heads/master | from utils.matrix import Matrix
class RangeSumQuery:
def __init__(self, matrix):
"""
:type matrix: Matrix
:rtype: None
"""
matrix_sum = [[0 for _ in range(matrix.col_count + 1)] for _ in range(matrix.row_count + 1)]
for row in range(1, matrix.row_count + 1):
for col in range(1, matrix.col_count + 1):
matrix_sum[row][col] = (
matrix[row - 1][col - 1]
+ matrix_sum[row][col - 1]
+ matrix_sum[row - 1][col]
- matrix_sum[row - 1][col - 1]
)
self.matrix_sum = Matrix(matrix_sum)
print(self.matrix_sum)
def get_range_sum(self, row1, col1, row2, col2):
return (
self.matrix_sum[row2 + 1][col2 + 1]
- self.matrix_sum[row1][col2 + 1]
+ self.matrix_sum[row1][col1]
- self.matrix_sum[row2 + 1][col1]
)
matrix = Matrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]])
print("Matrix = {}".format(matrix))
rangeSumQuery = RangeSumQuery(matrix)
print(rangeSumQuery.get_range_sum(2, 1, 4, 3))
print(rangeSumQuery.get_range_sum(1, 1, 2, 2))
print(rangeSumQuery.get_range_sum(1, 2, 2, 4))
| Python | 35 | 35.771427 | 102 | /dynamicProgramming/range_sum_query2.py | 0.503497 | 0.452214 |
aymane081/python_algo | refs/heads/master | #83
from utils.listNode import ListNode
class Solution:
def remove_duplicates(self, head):
if not head:
return
curr = head
while curr and curr.next:
if curr.value == curr.next.value:
curr.next = curr.next.next
else:
curr = curr.next
return head
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(1)
one.next = four
four.next = two
two.next = three
print(one)
solution = Solution()
print(solution.remove_duplicates(one))
| Python | 32 | 16.5625 | 45 | /linkedList/remove_duplicates.py | 0.578761 | 0.568142 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_min(self, nums):
if not nums:
return None
left, right = 0, len(nums) - 1
while left < right:
if nums[left] <= nums[right]: # not rotated
break
mid = (left + right) // 2
if nums[mid] < nums[left]: # min must be on the left of mid or mid
right = mid
else: # min must be on the right of mid
left = mid + 1
return nums[left]
solution = Solution()
nums = [7,0,1,2,3,4,5,6]
# nums = [4,5,6, 7, 8, 1, 2, 3]
print(solution.get_min(nums))
| Python | 21 | 28 | 78 | /binarySearch/min_circular_sorted_array.py | 0.482759 | 0.449918 |
aymane081/python_algo | refs/heads/master | #19
from utils.listNode import ListNode
class Solution:
def delete_from_end(self, head, n):
if not head:
return
front, back = head, head
dummy = prev = ListNode(None)
while n > 0:
back = back.next
n -= 1
while back:
back = back.next
prev.next = front
prev = front
front = front.next
# front is the node I need to delete, and prev is right behind it
prev.next = prev.next.next
return dummy.next
class Solution2:
def delete_from_end(self, head, n):
first, second = head, head
for _ in range(n):
first = first.next
if not first: # n is the length of the linked list. the first element needs to be removed
return head.next
while first.next:
first = first.next
second = second.next
# second is right before the nth element from the end
second.next = second.next.next
return head
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
five = ListNode(5)
one.next = two
two.next = three
three.next = four
four.next = five
print(one)
solution = Solution()
print(solution.delete_from_end(one, 2)) | Python | 63 | 20.190475 | 97 | /linkedList/delete_nth_node_from_end.py | 0.551724 | 0.543478 |
aymane081/python_algo | refs/heads/master | # 328
from utils.listNode import ListNode
class Solution:
def odd_even_list(self, head):
if not head:
return None
odd = head
even_head, even = head.next, head.next
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = even_head
return head
class Solution2:
def odd_even_list(self, head):
if not head:
return None
odd_head = odd_tail = ListNode(None)
even_head = even_tail = ListNode(None)
node = head
count = 1
while node:
if count == 1:
odd_tail.next = node
odd_tail = odd_tail.next
else:
even_tail.next = node
even_tail = even_tail.next
count = 1 - count
node = node.next
even_tail.next = None
odd_tail.next = even_head.next
return odd_head.next
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
five = ListNode(5)
one.next = two
two.next = three
three.next = four
four.next = five
print(one)
solution = Solution()
print(solution.odd_even_list(one)) | Python | 65 | 19.123077 | 46 | /linkedList/odd_even_linked_list.py | 0.515685 | 0.506503 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def remove_duplicate(self, arr):
"""
type arr: list
rtype: int
"""
if not arr:
return 0
j = 0
for i in range(1, len(arr)):
if arr[i] != arr[j]:
j += 1
arr[j] = arr[i]
j += 1
for i in range(len(arr) - j):
arr.pop()
return j
solution = Solution()
arr = [1, 1, 2, 3, 4, 4]
print(solution.remove_duplicate(arr))
print(arr) | Python | 25 | 19.6 | 37 | /arrays/remove_duplicate_sorted_array.py | 0.418288 | 0.396887 |
aymane081/python_algo | refs/heads/master | #442
class Solution:
def get_duplicates(self, nums):
if not nums:
return None
result = []
for num in nums:
index = abs(num) - 1
if nums[index] < 0:
result.append(abs(num))
else:
nums[index] *= -1
return result
solution = Solution()
nums = [4, 3, 2, 7, 8, 2, 4, 1]
print(solution.get_duplicates(nums)) | Python | 18 | 22.277779 | 39 | /arrays/find_all_duplicates.py | 0.485646 | 0.452153 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
import unittest
class Solution:
def reconstruct_itinerary(self, flights):
graph = self.build_graph(flights)
path = []
self.dfs('JFK', graph, path, len(flights))
return path
def dfs(self, node, graph, path, remaining):
if node == 'X':
return
print('current node: {} - current path: {}'.format(node, path))
path.append(node)
if remaining == 0:
return True
for i, nbr in enumerate(graph[node]):
# remove nbr from the graph
graph[node][i] = 'X'
if self.dfs(nbr, graph, path, remaining - 1):
return True
graph[node][i] = nbr
path.pop()
return False
def build_graph(self, flights):
graph = defaultdict(list)
for source, dest in flights:
graph[source].append(dest)
for nbrs in graph.values():
nbrs.sort()
return graph
class Solution3:
def reconstruct_itinerary(self, flights):
graph = self.build_graph(flights)
path = []
def dfs(airport):
path.append(airport)
while graph[airport]:
nbr = graph[airport].pop()
dfs(nbr)
dfs('JFK')
return path
def build_graph(self, flights):
graph = defaultdict(list)
for start, end in flights:
graph[start].append(end)
for node in graph:
graph[node].sort(reverse=True)
return graph
class Test(unittest.TestCase):
test_data = [[["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]], [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]]
expected_results = [["JFK", "MUC", "LHR", "SFO", "SJC"], ["JFK","ATL","JFK","SFO","ATL","SFO"]]
def test_reconstruct_itinerary(self):
solution = Solution3()
for i, data in enumerate(self.test_data):
self.assertEqual(solution.reconstruct_itinerary(data), self.expected_results[i])
if __name__ == '__main__':
unittest.main()
| Python | 79 | 26.531645 | 155 | /graphs/reconstruct_itenirary.py | 0.524598 | 0.522759 |
aymane081/python_algo | refs/heads/master | #814
from utils.treeNode import TreeNode
class Solution:
def prune(self, root):
if not root:
return root
root.left, root.right = self.prune(root.left), self.prune(root.right)
return root if root.value == 1 or root.left or root.right else None
| Python | 12 | 23.583334 | 77 | /trees/binary_tree_pruning.py | 0.608553 | 0.595395 |
aymane081/python_algo | refs/heads/master | # 817
from utils.listNode import ListNode
class Solution:
# time: O(len of linked list)
# space: O(len of G)
def get_connected_count(self, head, G):
count = 0
if not head:
return count
values_set = set(G)
prev = ListNode(None)
prev.next = head
while prev.next:
if prev.value not in values_set and prev.next.value in values_set:
count += 1
prev = prev.next
return count
zero = ListNode(0)
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
five = ListNode(5)
zero.next = one
one.next = two
two.next = three
three.next = four
four.next = five
print(zero)
G = [0, 3, 1, 4]
print(G)
solution = Solution()
print(solution.get_connected_count(zero, G))
| Python | 46 | 17.065218 | 78 | /linkedList/linked_list_components.py | 0.56213 | 0.544379 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
def has_path_sum(self, node, sum):
if not node:
return False
sum -= node.value
if not sum and not node.left and not node.right:
return True
return self.has_path_sum(node.left, sum) or self.has_path_sum(node.right, sum) | Python | 13 | 26 | 86 | /trees/path_sum.py | 0.588571 | 0.588571 |
aymane081/python_algo | refs/heads/master | class Solution:
def generate_spiral(self, n):
if n <= 0:
raise Exception('n should be bigger than 0')
# matrix = [[0] * n] * n # for some reason this does not work
matrix = [[0 for _ in range(n)] for _ in range(n)]
row, col = 0, 0
d_row, d_col = 0, 1
for i in range(n ** 2):
matrix[row][col] = i + 1
next_row, next_col = row + d_row, col + d_col
if self.is_out_of_border(next_row, next_col, n) or matrix[next_row][next_col] != 0:
# the next cell is either out of border, or already processed. Change direction
d_row, d_col = d_col, - d_row
# move to the next cell
row += d_row
col += d_col
return matrix
def is_out_of_border(self, row, col, n):
return row < 0 or row == n or col < 0 or col == n
def print_matrix(self, matrix):
for row in matrix:
print(row)
solution = Solution()
solution.print_matrix(solution.generate_spiral(3)) | Python | 31 | 33.322582 | 95 | /arrays/matrix_spiral2.py | 0.517404 | 0.504233 |
aymane081/python_algo | refs/heads/master | import unittest
class Solution(object):
def time_conversion(self, time_str):
if not time_str:
return None
time_list = list(time_str)
is_pm = time_list[-2].lower() == 'p'
# handle the 12 AM case. It should be converted to 00
if not is_pm and time_str[:2] == '12':
time_list[:2] = ['0', '0']
elif is_pm:
hour = str(int(time_str[:2]) + 12)
time_list[:2] = list(hour)
return ''.join(map(str, time_list[:-2]))
class Test(unittest.TestCase):
test_data = [('03:22:22PM', '15:22:22'), ('12:22:22AM', '00:22:22')]
def test_time_conversion(self):
solution = Solution()
for data in self.test_data:
actual = solution.time_conversion(data[0])
self.assertEqual(actual, data[1])
if __name__ == '__main__':
unittest.main() | Python | 30 | 28.700001 | 72 | /strings/time_conversion.py | 0.525843 | 0.478652 |
aymane081/python_algo | refs/heads/master | import collections
import unittest
# time: O(M + N) - space: O(N)
# def can_construct(ransom, magazine):
# if not magazine:
# return False
# ransom_dict = dict()
# for s in ransom:
# if s not in ransom_dict:
# ransom_dict[s] = 1
# else:
# ransom_dict[s] += 1
# for char in magazine:
# if char in ransom_dict:
# if ransom_dict[char] > 1:
# ransom_dict[char] -= 1
# else:
# del ransom_dict[char]
# return not ransom_dict
# def can_construct(ransom, magazine):
# return all(ransom.count(x) <= magazine.count(x) for x in set(ransom))
#time: O(M+N) - space: O(M+N)
# each time a Counter is produced through an operation, any items with zero or negative counts are discarded
class Solution(object):
def can_construct(self, ransom, magazine):
return not collections.Counter(ransom) - collections.Counter(magazine)
class Test(unittest.TestCase):
test_data = [('ab', 'aab', True), ('abb', 'aab', False)]
def test_can_construct(self):
solution = Solution()
for data in self.test_data:
actual = solution.can_construct(data[0], data[1])
self.assertIs(actual, data[2])
if __name__ == '__main__':
unittest.main() | Python | 45 | 28.200001 | 108 | /strings/ransom_note.py | 0.581874 | 0.576542 |
aymane081/python_algo | refs/heads/master | from utils.interval import Interval
class Solution:
def get_right_intervals(self, intervals):
intervals = [(intervals[i], i) for i in range(len(intervals))]
# In order to do binary search, the array needs to be sorted
# We need to sort by the start because the intervals with a bigger start represent the pool of possibilities
intervals.sort(key= lambda x: x[0].start)
result = [-1 for _ in range(len(intervals))]
for index, (interval, i) in enumerate(intervals):
left, right = index + 1, len(intervals) # right = len(intervals) means that it is possible to get no right interval
while left < right:
mid = (left + right) // 2
midInterval = intervals[mid][0]
if midInterval.start < interval.end:
left = mid + 1
else:
right = mid
# left is the index of the right interval
if left < len(intervals):
result[i] = intervals[left][1]
return result
solution = Solution()
interval1 = Interval(1, 4)
interval2 = Interval(2, 3)
interval3 = Interval(3, 4)
intervals = [interval1, interval3, interval2]
print("intervals = {}".format(intervals))
print(solution.get_right_intervals(intervals)) | Python | 32 | 40.21875 | 127 | /binarySearch/find_right_interval.py | 0.603187 | 0.588771 |
aymane081/python_algo | refs/heads/master | #654
from utils.treeNode import TreeNode
class Solution:
def build_maximum_tree(self, nums):
if not nums:
return None
return self.helper(nums, 0, len(nums) - 1)
def helper(self, nums, start, end):
if start > end:
return None
max_num, index = float('-inf'), -1
for i, num in enumerate(nums[start: end + 1]):
if num > max_num:
max_num, index = num, i + start
root = TreeNode(max_num)
root.left = self.helper(nums, start, index - 1)
root.right = self.helper(nums, index + 1, end)
return root
nums = [3,2,1,6,0,5]
solution = Solution()
print(solution.build_maximum_tree(nums)) | Python | 29 | 24.551723 | 55 | /trees/maximum_binary_tree.py | 0.537534 | 0.517426 |
aymane081/python_algo | refs/heads/master | class ListNode:
def __init__(self, value):
self.value = value
self.next = None
# def __repr__(self):
# return '(value = {}, next: {})'.format(self.value, self.next)
def __repr__(self):
nodes = []
while self:
nodes.append(str(self.value))
self = self.next
return ' -> '.join(nodes) | Python | 14 | 25.5 | 71 | /utils/listNode.py | 0.483784 | 0.483784 |
aymane081/python_algo | refs/heads/master | # 543
from utils.treeNode import TreeNode
# time: O(N)
# space: O(N)
class Solution:
def dimater(self, root):
self.result = 0
if not root:
return self.result
def depth(root):
left_depth = 1 + depth(root.left) if root.left else 0
right_depth = 1 + depth(root.right) if root.right else 0
self.result = max(self.result, left_depth + right_depth)
return max(left_depth, right_depth)
depth(root)
return self.result
# time = O(N)
# space = O(N)
class Solution2:
heights_map = dict()
def dimater(self, root):
if not root:
return 0
return max(
self.height(root.left) + self.height(root.right),
self.dimater(root.left),
self.dimater(root.right)
)
def height(self, root):
if not root:
return 0
if root in self.heights_map:
return self.heights_map[root]
height = 1 + max(self.height(root.left), self.height(root.right))
self.heights_map[root] = height
return height
one = TreeNode(1)
two = TreeNode(2)
three = TreeNode(3)
four = TreeNode(4)
five = TreeNode(5)
six = TreeNode(6)
seven = TreeNode(7)
one.left = two
two.left = three
three.left = four
two.right = five
five.right = six
six.right = seven
print(one)
print('===============')
solution = Solution()
print(solution.dimater(one))
class SOlution:
def get_diameter(self, root):
depth_map = dict()
if not root:
return 0
def depth(root):
if not root:
return 0
if root in depth_map:
return depth_map[root]
result = 1 + max(depth(root.left), depth(root.right))
depth_map[root] = result
return result
return max(
1 + depth(root.left) + depth(root.right),
self.get_diameter(root.left),
self.get_diameter(root.right)
)
| Python | 95 | 21.273684 | 73 | /trees/diameter_binary_tree.py | 0.52552 | 0.51465 |
aymane081/python_algo | refs/heads/master | # 795
class Solution:
def subarray_count(self, nums, L, R):
# dp is the number of subarrays ending with nums[i]
result, dp = 0, 0
prev_invalid_index = -1
if not nums:
return result
for i, num in enumerate(nums):
if num < L:
result += dp
elif num > R:
dp = 0
prev_invalid_index = i
else:
dp = i - prev_invalid_index
result += dp
return result
class Solution2:
def subarray_count(self, nums, L, R):
prev_invalid_index = -1
res = count = 0
for i, num in enumerate(nums):
if num < L:
res += count
elif num > R:
count = 0
prev_invalid_index = i
else:
count = i - prev_invalid_index
res += count
return res
| Python | 43 | 22.069767 | 59 | /arrays/number_of_subarrays_bounded_maximum.py | 0.415323 | 0.404234 |
aymane081/python_algo | refs/heads/master | class Solution:
# time: O(N) worst case, O(height) average
# space: O(N) worst case, O(height) average
def delete_node(self, root, value):
if not root:
return None
if root.value > value:
root.left = self.delete_node(root.left, value)
elif root.value < value:
root.right = self.delete_node(root.right, value)
else:
if not root.left or not root.right:
# one or no children
root = root.left or root.right
else:
# has both children
next_biggest = root.right
while next_biggest.left:
next_biggest = next_biggest.left
root.value = next_biggest.value
root.right = self.delete_node(root.right, root.value)
return root
| Python | 24 | 35.333332 | 69 | /trees/delete_note_bst.py | 0.5189 | 0.5189 |
aymane081/python_algo | refs/heads/master | #143
from utils.listNode import ListNode
class Solution:
def reorder(self, head):
if not head:
return head
fast, slow = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
rev, node = None, slow
while node:
rev, rev.next, node = node, rev, node.next
first, second = head, rev
while second.next:
first.next, first = second, first.next
second.next, second = first, second.next
return head
class Solution2:
def reorder(self, head):
list_map = dict()
curr, i = head, 1
while curr:
list_map[i] = curr
curr = curr.next
i += 1
left, right = 1, i - 1
node = head
while left <= right:
node.next = list_map[right]
left += 1
if left <= right:
node = node.next
node.next = list_map[left]
right -= 1
node = node.next
node.next = None
return head
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
five = ListNode(5)
one.next = two
two.next = three
three.next = four
four.next = five
print(one)
solution = Solution()
print(solution.reorder(one))
def reorder(head):
if not head:
return None
slow = fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
rev = ListNode(None)
while slow:
rev, rev.next, slow = slow, rev, slow.next
first, second = head, rev
while second.next:
first.next, first = second, first.next
second.next, second = first, second.next
| Python | 87 | 19.827587 | 54 | /linkedList/reorder_list.py | 0.513245 | 0.504967 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
# time: O(N) - space: O(N)
def build_binary_tree(self, nums):
if not nums:
return None
return self.convert(nums, 0, len(nums) - 1)
def convert(self, nums, left, right):
if left > right:
return None
mid = (left + right) // 2
left = self.convert(nums, left, mid - 1)
right = self.convert(nums, mid + 1, right)
root = TreeNode(nums[mid], left, right)
return root
nums = [1,2,3,4,5,6,7,8,9]
solution = Solution()
print(solution.build_binary_tree(nums)) | Python | 24 | 24.958334 | 51 | /trees/binary_tree_from_sorted_array.py | 0.559486 | 0.536977 |
aymane081/python_algo | refs/heads/master | class Matrix:
def __init__(self, rows):
self.rows = rows
self.row_count = len(rows)
self.col_count = len(rows[0])
def is_valid_cell(self, row, col):
return (
row >= 0 and row < self.row_count and
col >= 0 and col < self.col_count
)
def __repr__(self):
result = ''
for row in self.rows:
result += str(row) + '\n'
return result
def __getitem__(self, index):
return self.rows[index]
def __setitem__(self, index, value):
self.rows[index] = value | Python | 23 | 24.826086 | 49 | /utils/matrix.py | 0.492411 | 0.487352 |
aymane081/python_algo | refs/heads/master | class Solution:
def sum_target(self, collection1, collection2, target):
result = []
sum_dict = dict()
for nums in [collection1, collection2]:
for num in nums:
remaining = target - num
if remaining in sum_dict:
result.append((remaining, num))
if sum_dict[remaining] == 1:
del sum_dict[remaining]
else:
sum_dict[remaining] -= 1
else:
sum_dict[num] = 1 if num not in sum_dict else sum_dict[num] + 1
return result
collection1 = [4, 5, 2, 1, 1, 8]
collection2 = [7, 1, 8, 8]
solution = Solution()
print(solution.sum_target(collection1, collection2, 9)) | Python | 24 | 31.708334 | 83 | /arrays/target_sum_amazon.py | 0.496815 | 0.467516 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
def invert(self, node):
if not node:
return
self.invert(node.left)
self.invert(node.right)
node.left, node.right = node.right, node.left
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
print(node1)
print('=================')
solution = Solution()
solution.invert(node1)
print(node1)
| Python | 37 | 15.486486 | 53 | /trees/invert_binary_tree.py | 0.640984 | 0.593443 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def simplify_path(self, path):
"""
:type path: str
:rtype: str
"""
directories = path.split('/') # get the directories from the path
result = [] # stack to hold the result
for dir in directories:
if dir == '..' and result: # go up one level if possible
result.pop()
elif dir and dir != '.': # add the dir to the stack
result.append(dir)
# else ignore '' and '.'
return '/' + result[-1] if result else '/'
solution = Solution()
print(solution.simplify_path('/a/b/c/./../')) | Python | 22 | 28.545454 | 73 | /strings/simplify_path.py | 0.505393 | 0.503852 |
aymane081/python_algo | refs/heads/master | import random
class RandomizedSet:
def __init(self):
self.mapping = {}
self.items = []
def insert(self, value):
if value not in self.mapping:
self.items.append(value)
self.mapping[value] = len(self.items) - 1
return True
return False
def remove(self, value):
if value not in self.mapping:
return False
index = self.mapping[value]
self.items[index] = self.items[-1]
self.mapping[self.items[index]] = index
self.items.pop()
del self.mapping[value]
return True
def get_random(self):
index = random.randint(0, len(self.items) - 1)
return self.items[index]
class RandomizedSet2:
def __init__(self):
self.mapping = {}
self.items = []
def insert(self, value):
if value not in self.mapping:
self.items.append(value)
self.mapping[value] = len(self.items) - 1
return True
return False
def remove(self, value):
if value in self.mapping:
index = self.mapping[value]
self.items[index] = self.items[-1]
self.mapping[self.items[-1]] = index
self.items.pop()
del self.mapping[value]
return True
return False
def get_random(self):
index = random.randint(0, len(self.items) - 1)
return self.items[index] | Python | 55 | 25.981817 | 54 | /arrays/insert_delete_get_random.py | 0.538098 | 0.531355 |
aymane081/python_algo | refs/heads/master | # 655
#time: O(H * 2**H - 1) need to fill the result array
# space: O(H * 2**H - 1) the number of elements in the result array
from utils.treeNode import TreeNode
class Solution:
def print(self, root):
if not root:
return []
height = self.get_height(root)
result = [["" for _ in range((2 ** height - 1))] for _ in range(height)]
self.traverse(root, 0, (2 ** height) - 2, 0, result)
return result
# DFS traverse
def traverse(self, root, start, end, level, result):
if not root:
return
mid = (start + end) // 2
result[level][mid] = root.value
self.traverse(root.left, start, mid - 1, level + 1, result)
self.traverse(root.right, mid + 1, end, level + 1, result)
def get_height(self, root):
if not root:
return 0
return 1 + max(self.get_height(root.left), self.get_height(root.right))
one = TreeNode(1)
two = TreeNode(2)
three = TreeNode(3)
four = TreeNode(4)
five = TreeNode(5)
one.left = two
two.left = three
three.left = four
one.right = five
print(one)
print('==============')
solution = Solution()
print(solution.print(one)) | Python | 56 | 20.821428 | 80 | /trees/print_binary_tree.py | 0.567568 | 0.547093 |
aymane081/python_algo | refs/heads/master | class Solution(object):
# this algorithm is called the Boyer-Moore majority voting algorithm
# https://stackoverflow.com/questions/4325200/find-the-majority-element-in-array
# the majority element appears more than all the other elements combined. Therefore, if we keep a
# counter and change the major every time the counter is 0, eventually, major will be the major element
def majority_element(self, numbers):
counter, major = 0, None
for num in numbers:
if counter == 0:
counter = 1
major = num
elif num == major:
counter += 1
else:
counter -= 1
# major is guaranteed to be the major element if it exists.
# otherwise, iterate over the array, and count the occurrences of major
#return major
counter = 0
for num in numbers:
if num == major:
counter += 1
if counter > len(numbers) / 2:
return major
return None
numbers = [2, 3, 5, 3, 5, 6, 5, 5, 5]
solution = Solution()
print(solution.majority_element(numbers)) | Python | 32 | 35.78125 | 107 | /arrays/majority_element.py | 0.581633 | 0.560374 |
aymane081/python_algo | refs/heads/master | # 832
class Solution:
def flip(self, matrix):
for row in matrix:
for i in range((len(row) + 1) // 2):
row[i], row[-1 -i] = 1 - row[-1 -i], 1 - row[i]
return matrix
solution = Solution()
matrix = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
print(solution.flip(matrix)) | Python | 14 | 22.285715 | 63 | /arrays/flipping_image.py | 0.489231 | 0.412308 |
aymane081/python_algo | refs/heads/master | from utils.listNode import ListNode
#237
class Solution:
def delete_node(self, node):
# node is not the tail => node.next exists
node.value = node.next.value
node.next = node.next.next | Python | 9 | 22.888889 | 50 | /linkedList/delete_node_linked_list.py | 0.654206 | 0.640187 |
aymane081/python_algo | refs/heads/master | from utils.matrix import Matrix
class Solution:
# O(m * n * min(m, n)) time and O(1) space
def get_max_square(self, matrix):
"""
:type matrix: Matrix
:rtype: int
"""
max_area = 0
for row in range(1, matrix.row_count):
for col in range(1, matrix.col_count):
if matrix[row][col] == 0:
continue
max_length = matrix[row - 1][col - 1]
length = 1
while length <= max_length:
if matrix[row - length][col] == 0 or matrix[row][col - 1] == 0 or matrix[row - 1][col - 1] == 0:
break
length += 1
matrix[row][col] = length ** 2
max_area = max(max_area, matrix[row][col])
return max_area
# dynamic programming: changing the matrix itself
def get_max_square2(self, matrix):
"""
:type matrix: Matrix
:rtype: int
"""
max_side = 0
if not matrix or not matrix.row_count or not matrix.col_count:
return max_side
for row in range(1, matrix.row_count):
for col in range(1, matrix.col_count):
if matrix[row][col] == 0:
continue
matrix[row][col] = 1 + min(matrix[row - 1][col], matrix[row][col - 1], matrix[row - 1][col - 1])
max_side = max(max_side, matrix[row][col])
return max_side ** 2
# dynamic programming: keeping an array of longest square sides
def get_max_square3(self, matrix):
"""
:type matrix: Matrix
:rtype: int
"""
max_side = 0
if not matrix or not matrix.row_count or not matrix.col_count:
return max_side
max_sides = [0 for _ in range(matrix.col_count)]
for row in range(matrix.row_count):
new_max_sides = [matrix[row][0]] + [0 for _ in range(1, matrix.col_count)]
max_side = max(max_side, matrix[row][0])
for col in range(1, matrix.col_count):
if matrix[row][col] == 0:
continue
new_max_sides[col] = 1 + min(new_max_sides[col - 1], max_sides[col], max_sides[col - 1])
max_side = max(max_side, new_max_sides[col])
max_sides = new_max_sides
return max_side ** 2
matrix = Matrix([[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]])
print(matrix)
print('===============')
solution = Solution()
print(solution.get_max_square3(matrix)) | Python | 79 | 33.13924 | 116 | /dynamicProgramming/maximum_square.py | 0.477374 | 0.454748 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
def get_paths(self, node):
result = []
if not node:
return result
self.helper([], node, result)
return [" -> ".join(path) for path in result]
def helper(self, prefix, node, result):
if not node.left and not node.right:
#reached a leaf
result.append(prefix + [str(node.value)])
return
if node.left:
self.helper(prefix + [str(node.value)], node.left, result)
if node.right:
self.helper(prefix + [str(node.value)], node.right, result)
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
print(node1)
solution = Solution()
print(solution.get_paths(node1))
| Python | 44 | 21.15909 | 71 | /trees/binary_tree_paths.py | 0.590726 | 0.5625 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_min_path(self, triangle):
"""
type triangle: List[List[int]]
rtype: int
"""
if not triangle:
return 0
for row in range(len(triangle) - 2, -1, -1):
for col in range(row + 1):
triangle[row][col] += min(triangle[row + 1][col], triangle[row + 1][col + 1])
return triangle[0][0]
triangle = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]]
solution = Solution()
print(solution.get_min_path(triangle)) | Python | 19 | 26.421053 | 93 | /dynamicProgramming/triangle.py | 0.503846 | 0.465385 |
aymane081/python_algo | refs/heads/master |
# Time: O(N) - Space: O(1): the length of the set/map is bounded by the number of the alphabet
# set.clear() is O(1)
class Solution(object):
def longest_unique_substring(self, str):
if not str:
return 0
str_set = set()
result = 0
for char in str:
if char not in str_set:
# Non repeated character
str_set.add(char)
result = max(result, len(str_set))
else:
# Repeated character
str_set.clear()
str_set.add(char)
# result = max(result, len(str_set))
return result
# Sliding window technique
# Maitain a sliding window, updating the start whenever we see a character repeated
def longest_unique_substring2(self, s):
"""
:type str: str
:rtype: int
"""
if not s:
return 0
start = 0 # start index of the current window(substring)
longest = 0
last_seen = {} # mapping from character to its last seen index
for i, char in enumerate(s):
if char in last_seen and last_seen[char] >= start: # start a new substring after the previous c
start = last_seen[char] + 1
else:
longest = max(longest, i - start + 1)
last_seen[char] = i # update the last sightning index
return longest
| Python | 44 | 32.25 | 107 | /strings/substring_without_repeating_characters.py | 0.420648 | 0.415157 |
aymane081/python_algo | refs/heads/master | from utils.matrix import Matrix
class Solution:
def exist(self, matrix, word):
"""
:type matrix: Matrix
:type word: Str
:rtype: boolean
"""
if not matrix.row_count or not matrix.col_count:
return False
for row in range(matrix.row_count):
for col in range(matrix.col_count):
if self.can_find(matrix, row, col, 0, word):
return True
return False
def can_find(self, matrix, row, col, index, word):
"""
:type matrix: Matrix
:type row: int
:type col: int
:type index: int
:type word: str
:rtype: boolean
"""
if index == len(word):
return True
if not matrix.is_valid_cell(row, col):
return False
if matrix[row][col] != word[index]:
return False
# in order to avoid using the same cell twice, we should mark it
matrix[row][col]= '*'
found = (
self.can_find(matrix, row + 1, col, index + 1, word) or
self.can_find(matrix, row - 1, col, index + 1, word) or
self.can_find(matrix, row, col + 1, index + 1, word) or
self.can_find(matrix, row, col - 1, index + 1, word)
)
if found:
return True
matrix[row][col] = word[index]
return False
matrix = Matrix([['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']])
solution = Solution()
print(matrix)
print(solution.exist(matrix, 'ABCCED')) | Python | 57 | 27.649122 | 83 | /arrays/word_search.py | 0.487745 | 0.48223 |
aymane081/python_algo | refs/heads/master | from bisect import bisect
class Solution:
# Time: O(n log n) - Space: O(n)
def get_longest_increasing_sequence(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = []
for num in nums:
index = bisect(dp, num)
if index == len(dp):
dp.append(num)
else:
# num is smaller than the current value at dp[index], therefore, num can be used to build a
# longer increasing sequence
dp[index] = num
return len(dp)
solution = Solution()
nums = [5, 2, 3, 8, 1, 19, 7]
print(solution.get_longest_increasing_sequence(nums)) | Python | 27 | 26.444445 | 107 | /dynamicProgramming/longest_increasing_sequence.py | 0.505405 | 0.493243 |
aymane081/python_algo | refs/heads/master | class Solution:
def remove_duplicates(self, nums):
if len(nums) <= 2:
return len(nums)
j = 1
for i in range(2, len(nums)):
if nums[i] > nums[j - 1]:
j += 1
nums[j] = nums[i]
j += 1
for _ in range(j, len(nums)):
nums.pop()
return j
solution = Solution()
nums = [1,1,1,2,2,3]
print(solution.remove_duplicates(nums))
print(nums) | Python | 21 | 21.571428 | 39 | /arrays/remove_duplicate_sorted_array2.py | 0.446089 | 0.420719 |
aymane081/python_algo | refs/heads/master | class Solution:
def topological_sort(self, graph):
result = []
discovered = set()
path = []
for node in graph:
self.helper(node, result, discovered, path)
return result.reverse()
def helper(self, node, result, discovered, path):
if node in discovered:
return
path.append(node)
discovered.add(node)
for nbr in node.neighbors:
if nbr in path:
raise Exception('Cyclic graph')
self.helper(nbr, result, discovered, path)
path.pop()
result.append(node.key) | Python | 27 | 23.407408 | 55 | /graphs/topological_sort.py | 0.513678 | 0.513678 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_interesection(self, nums1, nums2):
set1 = set(nums1)
intersection = set()
for num in nums2:
if num in set1:
intersection.add(num)
return list(intersection)
| Python | 8 | 29.5 | 46 | /binarySearch/intersection_of_two_arrays.py | 0.550201 | 0.526104 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def max_area(self, heights):
"""
:type heights: List(int)
:rtype: int
"""
if not heights:
return 0
left = 0
right = len(heights) - 1
# calculate the area of the outer container
max_area = (right - left) * min(heights[left], heights[right])
# start moving in-ward.
# In order to get a bigger area, the min of both left and right borders need to be higher
while left < right:
if heights[left] < heights[right]: # increment left for the possibility of finding a larger area
left += 1
else:
right -= 1
max_area = max(max_area, (right - left) * min(heights[left], heights[right]))
return max_area
| Python | 24 | 33 | 108 | /arrays/container_with_most_water.py | 0.535539 | 0.529412 |
aymane081/python_algo | refs/heads/master | import random
from collections import defaultdict
class Solution:
# O(1) space and time in initialization. O(n) time and O(1) space when getting the rand index
def __init__(self, nums):
self.nums = nums
def get_random_index(self, target):
result, count = None, 0
for i, num in enumerate(self.nums):
if num == target:
if random.randint(0, count) == 0:
result = i
count += 1
return result
#Solution 2:
# O(N) space and time in initilization. O(1) space and time when picking random index
# def __init__(self, nums):
# self.nums = nums
# self.mapping = defaultdict(list)
# for i, num in enumerate(nums):
# self.mapping[num].append(i)
# def get_random_index(self, target):
# return random.choice(self.mapping[target])
nums = [1, 3, 2, 2, 3, 3, 3, 4]
solution = Solution(nums)
print(solution.get_random_index(2))
| Python | 31 | 30.806452 | 98 | /arrays/random_pick_index.py | 0.580122 | 0.56288 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_longest_common_prefix(self, words):
if not words:
return ''
min_word_length = min(words, key=len)
start, end = 0, len(min_word_length) - 1
while start <= end:
mid = (start + end) // 2
if not self.is_common_prefix(mid, words):
end = mid - 1
else:
start = mid + 1
return words[0][:end + 1]
def is_common_prefix(self, length, words):
prefix = words[0][:length + 1]
for word in words:
if not word.startswith(prefix):
return False
return True
list_strings = ['abu', 'abcd', 'abce', 'abcee']
solution = Solution()
print(solution.get_longest_common_prefix(list_strings)) | Python | 30 | 25.933332 | 55 | /strings/longestCommonPrefix.py | 0.505576 | 0.494424 |
aymane081/python_algo | refs/heads/master | class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return "[{0}, {1}]".format(self.start, self.end) | Python | 7 | 25.857143 | 56 | /utils/interval.py | 0.518717 | 0.508021 |
aymane081/python_algo | refs/heads/master | class Solution:
def word_break(self, s, wordDict):
if not wordDict:
return False
if not s:
return True
can_make = [True] + [False for _ in range(len(s))]
for i in range(1, len(s) + 1):
for j in range(i - 1, -1, -1):
if can_make[j] and s[j:i] in wordDict:
can_make[i] = True
break
return can_make[-1] | Python | 17 | 26.294117 | 58 | /dynamicProgramming/word_break.py | 0.425486 | 0.412527 |
aymane081/python_algo | refs/heads/master | from utils.listNode import ListNode
class Solution:
def merge(self, l1, l2):
if not l1 or not l2:
return l1 or l2
node1, node2 = l1, l2
head = None
curr = None
while node1 and node2:
min_value = min(node1.value, node2.value)
if min_value == node1.value:
node1 = node1.next
else:
node2 = node2.next
if not head:
head = ListNode(min_value)
curr = head
else:
curr.next = ListNode(min_value)
curr = curr.next
if node1:
curr.next = node1
elif node2:
curr.next = node2
return head
# time: O(m + n)
# space: O(1)
class Solution2:
def merge(self, l1, l2):
prev = dummy = ListNode(None)
while l1 and l2:
if l1.value < l2.value:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
prev.next = l1 or l2
return dummy.next
one = ListNode(1)
two = ListNode(2)
four = ListNode(4)
one.next = two
two.next = four
one_ = ListNode(1)
three_ = ListNode(3)
four_ = ListNode(4)
one_.next = three_
three_.next = four_
print(one)
print(one_)
solution = Solution2()
print(solution.merge(one, one_)) | Python | 72 | 19.430555 | 53 | /linkedList/merge_two_sorted_lists.py | 0.47551 | 0.444218 |
aymane081/python_algo | refs/heads/master | class Node:
def __init__(self, label):
self.label = label
self.neighbors = []
class Solution:
def clone_graph(self, node):
if not node:
return None
cloned_start = Node(node.key)
node_mapping = { node: cloned_start}
queue = [node]
while queue:
node = queue.pop()
cloned_node = node_mapping[node]
for nbr in node.neighbors:
if nbr not in node_mapping:
cloned_nbr = Node(nbr.key)
node_mapping[nbr] = cloned_nbr
queue.append(nbr)
else:
cloned_nbr = node_mapping[nbr]
cloned_node.neighbors.append(cloned_nbr)
return cloned_start
def clone_graph2(self, node):
mapping = dict()
return self.helper(node, mapping)
def helper(self, node, mapping):
if node in mapping:
return mapping[node]
cloned_node = Node(node.key)
for nbr in node.neighbors:
cloned_nbr = self.helper(nbr, mapping)
cloned_node.neighbors.append(cloned_nbr)
mapping[node] = cloned_node
return cloned_node | Python | 47 | 25.765957 | 56 | /graphs/clone_graph.py | 0.511535 | 0.51074 |
aymane081/python_algo | refs/heads/master | from utils.matrix import Matrix
import unittest
class Solution:
def search(self, matrix, value):
if value < matrix[0][0] or value > matrix[-1][-1]:
return False
row = self.get_row(matrix, value)
return self.binary_search_row(matrix[row], value)
def get_row(self, matrix, value):
left, right = 0, matrix.row_count - 1
while left <= right:
mid = (left + right) // 2
if value < matrix[mid][0]:
right = mid - 1
elif value > matrix[mid][-1]:
left = mid + 1
else:
return mid
return left
def binary_search_row(self, nums, value):
left, right = 0, len(nums) - 1
while left <= right:
mid = (right + left) // 2
if value == nums[mid]:
return True
if value > nums[mid]:
left = mid + 1
else:
right = mid - 1
return False
#time: O(col_count + row_count) - space: O(1)
def search2(self, matrix, value):
row, col = matrix.row_count - 1, 0
while row >= 0 and col < matrix.col_count:
if matrix[row][col] == value:
return True
elif value < matrix[row][col]:
row -= 1
else:
col += 1
return False
class Test(unittest.TestCase):
matrix = Matrix([[1,3,5,7],[10,11,16,20],[23,30,34,50]])
test_data = [(3, True), (9, False), (0, False), (56, False), (30, True)]
def test_search(self):
solution = Solution()
for data in self.test_data:
actual = solution.search2(self.matrix, data[0])
self.assertEqual(actual, data[1])
if __name__ == '__main__':
unittest.main()
| Python | 59 | 29.830509 | 76 | /arrays/search_matrix.py | 0.48928 | 0.460143 |
aymane081/python_algo | refs/heads/master | # 560
from collections import defaultdict
# time: O(N)
# space: O(N)
class Solution:
def subarray_sum(self, nums, k):
result = 0
if not nums:
return result
sum_map = defaultdict(int)
sum_map[0] = 1
curr_sum = 0
for num in nums:
curr_sum += num
result += sum_map[curr_sum - k]
sum_map[curr_sum] += 1
return result
nums = [1, 1, 1]
solution = Solution()
print(solution.subarray_sum(nums, 2))
| Python | 29 | 17.862068 | 43 | /arrays/subarray_sum_equals_k.py | 0.489945 | 0.468007 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
class Solution:
def solve_queries(self, equations, values, queries):
graph = self.build_graph(equations, values)
result = []
for query in queries:
result.append(self.dfs(query[0], query[1], 1, graph, set()))
return result
def dfs(self, start, target, temp_result, graph, visited):
if not start in graph or start in visited:
return -1
if start == target:
return temp_result
visited.add(start)
for nbr, division in graph[start].items():
result = self.dfs(nbr, target, temp_result * division, graph, visited)
if result != -1: # found the target
return result
return -1
def build_graph(self, equations, values):
graph = defaultdict(dict)
for i, eq in enumerate(equations):
graph[eq[0]][eq[1]] = values[i]
graph[eq[1]][eq[0]] = 1 / values[i]
return graph
equations = [ ["a", "b"], ["b", "c"] ]
values = [2.0, 3.0]
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]
solution = Solution()
print(solution.solve_queries(equations, values, queries)) | Python | 45 | 27.111111 | 82 | /graphs/evaluate_division.py | 0.53481 | 0.522943 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def contains_duplicates(self, numbers):
number_set = set(numbers)
return len(numbers) != len(number_set)
def contains_duplicates2(self, numbers):
"""
:type numbers: list
:rtype : Boolean
"""
numbers.sort()
for i in range(1, len(numbers)):
if numbers[i] == numbers[i - 1]:
return True
return False
numbers = [1, 2, 1, 4]
solution = Solution()
print(solution.contains_duplicates(numbers))
| Python | 21 | 24.285715 | 46 | /arrays/contains_duplicates.py | 0.557439 | 0.544256 |
aymane081/python_algo | refs/heads/master | class Solution:
def sqrt(self, n):
if n == 0:
return 0
left, right = 1, n
# while True:
# mid = (left + right) // 2
# if mid * mid > n:
# right = mid - 1
# else:
# if (mid + 1) * (mid + 1) > n:
# return mid
# left = mid + 1
# use the while left <= right and return left - 1 when looking for the max value that satisfies a condition. because we do left = mid + 1, the last value of left will be our result + 1
while left <= right:
mid = (left + right) // 2
if mid * mid > n:
right = mid - 1
else:
left = mid + 1
return left - 1
solution = Solution()
print(solution.sqrt(24)) | Python | 27 | 29.74074 | 192 | /binarySearch/sqrt.py | 0.430639 | 0.410133 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
class Solution:
def course_schedule(self, classes):
if not classes:
return[]
graph = self.build_graph(classes)
result = []
path = []
discovered = set()
for node in graph:
self.topological_sort(node, graph, path, discovered, result)
return result.reverse()
def build_graph(self, classes):
graph = defaultdict(set)
for dep in classes:
graph[dep[1]].add(dep[0])
return graph
def topological_sort(self, node, graph, path, discovered, result):
if node in discovered:
return
discovered.add(node)
path.append(node)
for nbr in graph[node]:
if nbr in path:
raise Exception('Cyclic dependency. Cannot finish all the courses')
self.topological_sort(nbr, graph, path, discovered, result)
result.append(result)
path.pop()
def can_finish(self, courses_count, prerequisites):
" Returns True if can finish all the courses "
nb_prerequisites = defaultdict(int) # mapping between each course and the number of its pre-requisites
preq_map = defaultdict(list) # mapping between each course and the courses depending on it
for after, before in prerequisites:
nb_prerequisites[after] += 1
preq_map[before].append(after)
# get the list of courses with no dependencies
can_take = set(range(courses_count)) - set(nb_prerequisites.keys())
while can_take:
course = can_take.pop()
courses_count -= 1
for dep in preq_map[course]:
nb_prerequisites[dep] -= 1
if nb_prerequisites[dep] == 0:
can_take.add(dep)
return courses_count == 0
def get_order(self, num_courses, prerequisites):
nb_prerequisites = defaultdict(int)
preq_list = defaultdict(list)
result = []
for (after, before) in prerequisites:
nb_prerequisites[after] += 1
preq_list[before].append(after)
can_take = set(i for i in range(num_courses)) - set(nb_prerequisites.keys())
while can_take:
course = can_take.pop()
result.append(course)
for dep in preq_list[course]:
nb_prerequisites[dep] -= 1
if nb_prerequisites[dep] == 0:
can_take.append(dep)
return result if len(result) == num_courses else []
| Python | 86 | 30.093023 | 110 | /graphs/course_schedule.py | 0.55273 | 0.54899 |
aymane081/python_algo | refs/heads/master | # 566
# time: O(N * M)
# space: O(N * M)
class Solution:
def reshape(self, nums, r, c):
if not nums or len(nums) * len(nums[0]) != r * c:
return nums
rows, cols = len(nums), len(nums[0])
queue = []
for row in range(rows):
for col in range(cols):
queue.append(nums[row][col])
res, count =[], 0
for row in range(r):
res.append([])
for col in range(c):
res[-1].append(queue[count])
count += 1
return res
# time: O(N * M)
# space: O(N * M)
class Solution2:
def reshape(self, nums, r, c):
if not nums or len(nums) * len(nums[0]) != r * c:
return nums
res = [[] * r]
rows = cols = 0
for i in range(len(nums)):
for j in range(len(nums[0])):
res[rows].append(nums[i][j])
cols += 1
if cols == c:
rows += 1
cols = 0
return res
nums = [[1,2], [3,4]]
solution = Solution2()
print(solution.reshape(nums, 1, 4)) | Python | 52 | 21.384615 | 57 | /arrays/reshape_matrix.py | 0.422184 | 0.403267 |
aymane081/python_algo | refs/heads/master | #662
from utils.treeNode import TreeNode
class Solution2:
def max_width(self, root):
queue = [(root, 0, 0)]
curr_level, left, result = 0, 0, 0
for node, pos, level in queue:
if node:
queue.append((node.left, 2 * pos, level + 1))
queue.append((node.right, (2 * pos) + 1, level + 1))
if curr_level != level:
curr_level = level
left = pos
result = max(result, pos - left + 1)
return result
class Solution:
def max_width(self, root):
if not root:
return 0
level = [(root, 0)]
left, right, result = float('inf'), 0, 1
while level:
new_level = []
for node, pos in level:
if node:
new_level.append((node.left, 2 * pos))
new_level.append((node.right, (2 * pos) + 1))
left = min(left, pos)
right = max(right, pos)
result = max(result, right - left + 1)
left, right = float('inf'), 0
level = new_level
return result
one = TreeNode(1)
two = TreeNode(1)
three = TreeNode(1)
four = TreeNode(1)
five = TreeNode(1)
six = TreeNode(1)
seven = TreeNode(1)
one.left = two
two.left = three
three.left = four
one.right = five
five.right = six
six.right = seven
print(one)
print('============')
solution = Solution2()
print(solution.max_width(one))
| Python | 68 | 21.955883 | 68 | /trees/maximum_width_binary_tree.py | 0.481742 | 0.461243 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def reverse_words(self, string):
if not string:
return ''
# words = string.split()
# return ' '.join(words[::-1])
word_lists = [[]]
for i, c in enumerate(string):
if c != ' ':
word_lists[-1].append(c)
elif string[i] == ' ' and i < len(string) - 1 and string[i + 1] != ' ':
word_lists.append([])
words = [''.join(word_list) for word_list in word_lists]
return ' '.join(words[::-1])
class Solution2(object):
# time: O(n)
# space: O(n) because we transform the str to list, otherwise it is O(1)
def reverse_words(self, s):
string_list = list(s)
self.reverse(string_list, 0, len(string_list) - 1)
string_list.append(' ')
start = 0
for i, c in enumerate(string_list):
if string_list[i] == ' ':
self.reverse(string_list, start, i - 1)
start = i + 1
string_list.pop()
return ''.join(string_list)
def reverse(self, s, left, right):
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
solution = Solution2()
print(solution.reverse_words('The sky is blue')) | Python | 44 | 29 | 83 | /strings/reverse_words_in_string.py | 0.495072 | 0.4837 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
# Gotcha 1: there is no sort for strings.
# You have to convert the word to a list, then sort it using list.sort(),
# then reconstruct the string using ''.join(sorted_list)
# Gotcha 2: defaultdict is part of the collections library
class Solution(object):
# Time: O(n * k * log k) where n is the number of words, and k is the length of the longest word
# Space: O(n * k) to hold the result - k * n is the total number of characters
def group_anagrams(self, words):
"""
:type words: List[str]
:rtype: List[List[str]]
"""
sorted_dict = defaultdict(list)
for word in words:
letter_list = list(word) # or [c for c in word]
letter_list.sort()
sorted_word = ''.join(letter_list)
sorted_dict[sorted_word].append(word)
return list(sorted_dict.values())
solution = Solution()
print(solution.group_anagrams(['bat', 'car', 'atb', 'rca', 'aaa'])) | Python | 29 | 33.551723 | 100 | /strings/anagram_groups.py | 0.62038 | 0.618382 |
aymane081/python_algo | refs/heads/master | from utils.listNode import ListNode
class Solution:
def get_intersection(self, head1, head2):
if not head1 or not head2:
return None
l1, l2 = self.get_length(head1), self.get_length(head2)
node1, node2 = self.move_ahead(head1, l1 - l2), self.move_ahead(head2, l2 - l1)
while node1 and node2:
if node1 == node2:
return node1
node1 = node1.next
node2 = node2.next
return None
def get_length(self, head):
count = 0
node = head
while node:
count += 1
node = node.next
return count
def move_ahead(self, head, l):
if l <= 0:
return head
curr = head
while l > 0:
curr = curr.next
l -= 1
return curr
class Solution2:
def get_intersection(self, head1, head2):
if not head1 or not head2:
return None
savedA, savedB = head1, head2
while head1 != head2:
head1 = savedB if not head1 else head1.next
head2 = savedA if not head2 else head2.next
return head1
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
four.next = five
six.next = seven
seven.next = two
print(one)
print(six)
solution = Solution()
print(solution.get_intersection(one, six))
| Python | 72 | 20.791666 | 87 | /linkedList/intersection_of_two_linked_list.py | 0.536213 | 0.502541 |
aymane081/python_algo | refs/heads/master | from math import floor, sqrt
class Solution:
def get_min_square_count(self, n):
if n == 0:
return 0
memo = [-1 for _ in range(n + 1)]
memo[0] = 0
return self.get_min_square_rec(memo, n)
def get_min_square_rec(self, memo, n):
if memo[n] < 0:
biggest_square = floor(sqrt(n)) ** 2
memo[n] = (n // biggest_square) + self.get_min_square_rec(memo, n % biggest_square)
return memo[n]
def get_min_squares(self, n):
memo = [0] + [float('inf') for _ in range(n)]
for i in range(1, n + 1):
min_count = float('inf')
j = 1
while i - j*j >= 0:
min_count = min(min_count, 1 + memo[i - j * j])
j += 1
memo[i] = min_count
return memo[-1]
solution = Solution()
for i in range(10):
print("n = {} : {}".format(i, solution.get_min_square_count(i)))
print("n = {} : {}".format(i, solution.get_min_squares(i))) | Python | 36 | 28.027779 | 95 | /dynamicProgramming/perfect_squares.py | 0.472222 | 0.454981 |
aymane081/python_algo | refs/heads/master | # 572
from utils.treeNode import TreeNode
class Solution:
def is_substree(self, s, t):
return self.traverse(s, t)
def traverse(self, s, t):
return s and (self.equal(s, t) or self.traverse(s.left, t) or self.traverse(s.right, t))
def equal(self, s, t):
if not s and not t:
return True
if not s or not t or s.value != t.value:
return False
return self.equal(s.left, t.left) and self.equal(s.right, t.right)
# time: O(m + n)
# space: O(m + n)
class Solution2:
def is_substree(self, s, t):
def serialize(root):
if not root:
serial.append('#')
return
serial.append(str(root.value))
serialize(root.left)
serialize(root.right)
serial = []
serialize(s)
s_serialized = ','.join(serial)
serial = []
serialize(t)
t_serialized = ','.join(serial)
return t_serialized in s_serialized | Python | 43 | 23.418604 | 96 | /trees/substree_of_another_tree.py | 0.516683 | 0.512869 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def countSegments(self, string):
count = 0
for i, char in enumerate(string):
if char != ' ' and (i == 0 or string[i - 1] == ' '):
count += 1
return count
# time: O(N)
# space: O(N) because we have to build the array of results first
def connt_segments2(self, s):
return sum([s[i] != ' ' and (i == 0 or s[i - 1] == ' ') for i in range(len(s))])
solution = Solution()
print(solution.connt_segments2('Hello, my name is Aymane')) | Python | 16 | 32.8125 | 88 | /strings/segments_in_a_string.py | 0.535185 | 0.52037 |
aymane081/python_algo | refs/heads/master | # 725
from utils.listNode import ListNode
class Solution:
def split(self, head, k):
if not head:
return []
nodes_count = self.get_count(head)
part_length, odd_parts = divmod(nodes_count, k)
result = []
prev, node = None, head
for _ in range(k):
required = part_length
if odd_parts:
required += 1
odd_parts -= 1
result.append(node)
for _ in range(required):
# we'll only get here if required > 0, i.e. node is not null
prev, node = node, node.next
if prev:
prev.next = None
return result
def get_count(self, head):
count = 0
while head:
head = head.next
count += 1
return count
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
four.next = five
five.next = six
six.next = seven
print(one)
solution = Solution()
print(solution.split(one, 10)) | Python | 60 | 18.883333 | 76 | /linkedList/split_linked_list_in_parts.py | 0.515101 | 0.500839 |
aymane081/python_algo | refs/heads/master | from utils.treeNode import TreeNode
class Solution:
#binary search tree
def get_lca_bst(self, root, node1, node2):
if not node1 or not node2 or not root:
return None
if not root or root == node1 or root == node2:
return root
if (root.value - node1.value) * (root.value - node2.value) < 0:
return root
if root.value > node1.value:
return self.get_lca(root.left, node1, node2)
return self.get_lca(root.right, node1, node2)
#O(N) time and space
def get_lca(self, root, node1, node2):
if not root or root == node1 or root == node2:
return root
left_lca = self.get_lca(root.left, node1, node2)
right_lca = self.get_lca(root.right, node1, node2)
if left_lca and right_lca:
return root
return left_lca or right_lca | Python | 31 | 28.838709 | 71 | /trees/lowest_common_ancestor.py | 0.560606 | 0.536797 |
aymane081/python_algo | refs/heads/master | #time: O(N**2) - space: O(N)
class Solution:
def is_bypartite(self, graph):
colors = dict()
for node in range(len(graph)):
if node not in colors[node]:
colors[node] = 0
if not self.dfs(node, graph, colors):
return False
return True
def dfs(self, node, graph, colors):
for nbr in graph[node]:
if nbr in colors:
if colors[nbr] == colors[node]:
return False
else:
colors[nbr] = 1 - colors[node]
if not self.dfs(nbr, graph, colors):
return False
return True
| Python | 25 | 26.799999 | 52 | /graphs/is_bypartite.py | 0.454545 | 0.450284 |
aymane081/python_algo | refs/heads/master | def countAndSay(n):
result = '1'
for _ in range(n - 1):
count, last = 0, None
newString = ''
for digit in result:
if last is None or digit == last:
count += 1
last = digit
else:
newString += str(count) + last
last = digit
count = 1
newString += str(count) + last
result = newString
return result
# Time: O(2 ^ n) because the sequence at worst double during each iteration
# Space: O(2 ^ n)
def countAndSay2 (n):
sequence = [1]
for _ in range(n - 1):
next = []
for digit in sequence:
if not next or next[-1] != digit:
next += [1, digit]
else:
next[-2] = next[-2] + 1
sequence = next
return ''.join(map(str, sequence))
| Python | 34 | 25.058823 | 75 | /strings/countAndSay.py | 0.457111 | 0.440181 |
aymane081/python_algo | refs/heads/master | # 532
from collections import Counter
# time: O(N)
# space: O(N)
class Solution:
def k_diff_pairs(self, nums, k):
if k < 0:
return 0
freq = Counter(nums)
pairs = 0
for num in freq:
if k == 0:
if freq[num] > 1:
pairs += 1
else:
if k + num in freq: # this will ensure we get unique pairs
pairs += 1
return pairs
# time: O(N log N + N)
# space: O(1)
class Solution2:
def k_diff_pairs(self, nums, k):
result = []
if not nums or len(nums) < 2:
return result
nums.sort()
left, right = 0, 1
while left < len(nums) and right < len(nums):
diff = nums[right] - nums[left]
if diff == k:
result.append((nums[left], nums[right]))
# move both left and right
right = self.move(right, nums)
left = self.move(left, nums)
elif diff < k:
# move right
right = self.move(right, nums)
else:
# move left
left = self.move(left, nums)
if left == right:
# move right
right = self.move(right, nums)
return result
def move(self, index, nums):
index += 1
while index < len(nums) and nums[index] == nums[index - 1]:
index += 1
return index
nums, k = [3, 1, 4, 1, 5], 2
# nums, k = [1, 2, 3, 4, 5], 1
# nums, k = [3, 1, 4, 1, 5], 0
solution = Solution()
print(solution.k_diff_pairs(nums, k)) | Python | 72 | 23.375 | 74 | /arrays/k_diif_pairs.py | 0.428164 | 0.40764 |
aymane081/python_algo | refs/heads/master | from utils.matrix import Matrix
class Solution:
def get_islands_count(self, grid):
if not grid or not len(grid) or not len(grid[0]):
return 0
count = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == '1':
self.dfs(row, col, grid)
count += 1
return count
def dfs(self, row, col, grid):
"""
type row: int
type col: int
type grid: Matrix
rtype: None
"""
if not grid.is_valid_cell(row, col):
return
if grid[row][col] != '1':
return
grid[row][col] = 'X'
self.dfs(row - 1, col, grid)
self.dfs(row + 1, col, grid)
self.dfs(row, col + 1, grid)
self.dfs(row, col - 1, grid) | Python | 36 | 23.638889 | 57 | /graphs/number_of_islands.py | 0.44921 | 0.436795 |
aymane081/python_algo | refs/heads/master | # 729
from bisect import bisect
class Node:
def __init__(self, start, end):
self.start = start
self.end = end
self.left = self.right = None
def insert(self, node):
if node.start >= self.end:
if not self.right:
self.right = node
return True
return self.right.insert(node)
if node.end <= self.start:
if not self.left:
self.left = node
return True
return self.left.insert(node)
return False
# time: O(N * log N) in average cases. time needed to insert N events in the tree. Worst case: O(N**2)
# space: O(N) for the tree structure
class MyCalendar:
def __init__(self):
self.root = None
def book(self, start, end):
node = Node(start, end)
if not self.root:
self.root = node
return True
return self.root.insert(node)
class MyCalendar2:
def __init__(self):
self.events = []
def book(self, start, end):
if start >= end:
raise ValueError('Start should be smaller than End')
if not self.events:
self.events.append((start, end))
return True
start_list = list(map(lambda event: event[0], self.events))
index = bisect(start_list, start)
if index == len(self.events) and self.events[-1][1] > start:
return False
if index == 0 and self.events[0][0] < end:
return False
if 0 < index < len(self.events) - 1:
prev, after = self.events[index - 1], self.events[index]
if prev[1] > start or after[0] < end:
return False
self.events.insert(index, (start, end))
return True
def print_events(self):
print(self.events)
calendar = MyCalendar()
print(calendar.book(10, 20))
print(calendar.book(15, 25))
print(calendar.book(20, 30))
print(calendar.book(30, 40))
# calendar.print_events()
| Python | 83 | 24.45783 | 106 | /arrays/my_calendar_1.py | 0.523518 | 0.508467 |
aymane081/python_algo | refs/heads/master | from collections import Counter
import unittest
class Solution(object):
### time: O(N**3), space: O(N)
def length_substring(self, string, k):
"""
:type string: str
:type k: int
:rtype: int
"""
if not string:
return 0
if k == 1:
return len(string) # return the length of the entire string
longest = 0
for i in range(1, len(string)): # iterate over the string
for j in range(0, i): # get all the possible susbstrings ending at i
substring = string[j: i + 1]
if self.is_valid_substring(substring, k): # check if the current substring meets the criteria
longest = max(longest, len(substring))
return longest
def is_valid_substring(self, substring, k):
"""
:type substring: str
:type k: int
:rtype : boolean
"""
frequencies = Counter(substring)
return all(frequencies[c] >= k for c in set(substring))
# time: O(N**3), space: O(N)
def length_substring2(self, string, k):
"""
:type string: str
:type k: int
:rtype: int
"""
if not string:
return 0
if k == 1:
return len(string) # return the length of the entire string
to_split = [string]
longest = 0
while to_split:
t = to_split.pop()
splitted = [t]
freq = Counter(t)
for c in freq:
if freq[c] < k:
new_splitted = []
for spl in splitted:
new_splitted += spl.split(c)
splitted = new_splitted
if len(splitted) == 1:
longest = max(longest, len(splitted[0]))
else:
to_split += [sub for sub in splitted if len(sub) > longest]
return longest
def length_substring4(self, s, k):
if not s or len(s) < k:
return 0
if k == 1:
return len(s)
longest = 0
to_split = [s]
while to_split:
t = to_split.pop()
frequencies = Counter(t)
new_splitted = []
for c in frequencies:
if frequencies[c] < k: # t is splittable
new_splitted += t.split(c)
if not new_splitted: # t is not splittable:
longest = max(longest, len(t))
else: # t was splittable, add the new splitted elements to to_split
to_split += [sp for sp in new_splitted if len(sp) > longest]
return longest
# recursive method
def length_substring3(self, string, k):
return self.helper(string, 0, len(string), k)
def helper(self, string, start, end, k):
if end - start < k:
return 0
substring = string[start : end]
freq = Counter(substring)
for i, c in enumerate(substring):
if freq[c] < k: # found an infrequent char, split by it
left = self.helper(string, start, i, k)
right = self.helper(string, i + 1, end, k)
return max(left, right)
return end - start # all chars are frequent
class Test(unittest.TestCase):
test_data = [('aaabb', 3, 3), ('ababbc', 2, 5), ('aabbccbcdeee', 3, 6)]
def test_length_substring(self):
solution = Solution()
for data in self.test_data:
actual = solution.length_substring4(data[0], data[1])
self.assertEqual(actual, data[2])
if __name__ == '__main__':
unittest.main()
| Python | 125 | 28.992001 | 109 | /strings/substring_with_at_least_k_repeating_characters.py | 0.496399 | 0.487863 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_unique_count(self, n):
if n == 0:
return 1
res = 10
available_numbers = 9
for digit in range(2, min(n, 10) + 1):
available_numbers *= 11 - digit
res += available_numbers
return res
solution = Solution()
print(solution.get_unique_count(3)) | Python | 15 | 22.6 | 46 | /dynamicProgramming/count_numbers_with_unique_digits.py | 0.526912 | 0.492918 |
aymane081/python_algo | refs/heads/master | # 508
from utils.treeNode import TreeNode
from collections import defaultdict
# time: O(N)
# space: O(N)
class Solution:
def most_frequent_substree_sum(self, root):
sum_mapping = defaultdict(int)
def helper(node):
if not node:
return 0
substree_sum = node.value + helper(node.left) + helper(node.right)
sum_mapping[substree_sum] += 1
return substree_sum
helper(root)
max_frequency = max(sum_mapping.values())
return [substree_sum for substree_sum in sum_mapping if sum_mapping[substree_sum] == max_frequency]
one = TreeNode(6)
two = TreeNode(2)
three = TreeNode(-5)
one.left = two
one.right = three
print(one)
print('===========')
solution = Solution()
print(solution.most_frequent_substree_sum(one))
| Python | 37 | 21.702703 | 107 | /trees/most_frequent_substree_sum.py | 0.60446 | 0.59507 |
aymane081/python_algo | refs/heads/master | class Solution:
def repeated_string_pattern(self, string):
if not string:
return False
length = len(string)
for i in range(2, (length // 2) + 1):
pattern_length = length // i
if length % i == 0 and all(string[j * pattern_length : (j + 1) * pattern_length] == string[:pattern_length] for j in range(i)):
return True
return False
def repeated_string_pattern2(self, string):
if not string:
return False
return string in (string * 2)[1 : -1]
solution = Solution()
print(solution.repeated_string_pattern2('ababab'))
| Python | 22 | 28.318182 | 139 | /strings/repeated_string_pattern.py | 0.564341 | 0.548837 |
aymane081/python_algo | refs/heads/master | # 581
#time: O(N log N)
# space: O(N)
class Solution:
def shortest_subarray(self, nums):
if not nums:
return []
s_nums = sorted(nums)
left, right = len(nums) - 1, 0
for i in range(len(nums)):
if nums[i] != s_nums[i]:
left = min(left, i)
right = max(right, i)
return right - left + 1 if right >= left else 0
nums = [2, 6, 4, 8, 10, 9, 15]
solution = Solution()
print(solution.shortest_subarray(nums)) | Python | 22 | 22.681818 | 55 | /arrays/shortest_unsorted_continuous_subarray.py | 0.498077 | 0.467308 |
aymane081/python_algo | refs/heads/master | class Solution(object):
# At most one transaction
def get_max_profit(self, prices):
max_profit = 0
if not prices:
return max_profit
buy = prices[0]
for i in range(1, len(prices)):
price = prices[i]
buy = min(price, buy)
max_profit = max(max_profit, price - buy)
return max_profit
# At most one transaction
def get_max_profit3(self, prices):
buy = float('inf')
profit = 0
for price in prices:
buy = min(price, buy)
profit = max(profit, price - buy)
return profit
# At most one transaction
def get_max_profit2(self, prices):
currMax = 0
maxSoFar = 0
for i in range(1, len(prices)):
currMax = max(0, currMax + prices[i] - prices[i - 1])
maxSoFar = max(currMax, maxSoFar)
return maxSoFar
# unlimited transactions
def get_max_profit4(self, prices):
return sum([max(prices[i] - prices[i - 1], 0) for i in range(1, len(prices))])
solution = Solution()
print(solution.get_max_profit([7, 1, 5, 3, 6, 4]))
print(solution.get_max_profit([7, 6, 5, 4, 3, 1])) | Python | 44 | 26.84091 | 86 | /arrays/stock_market.py | 0.540033 | 0.517974 |
aymane081/python_algo | refs/heads/master | class Solution:
def divide(self, dividend, divisor):
if divisor == 0:
raise ValueError('divisor should not be 0')
result, right = 0, abs(divisor)
while right <= abs(dividend):
result += 1
right += abs(divisor)
is_result_negative = (
(dividend > 0 and divisor < 0) or
(dividend < 0 and divisor > 0)
)
return int('-{}'.format(str(result))) if is_result_negative else result
def divide2(self, dividend, divisor):
if divisor == 0:
raise ValueError('divisor is 0')
is_result_negative = (
(dividend > 0 and divisor < 0) or
(dividend < 0 and divisor > 0)
)
dividend, divisor = abs(dividend), abs(divisor)
result = 1
right = divisor
while right <= dividend:
result += result
right += right
while right > dividend:
result -= 1
right -= divisor
return -result if is_result_negative else result
solution = Solution()
# print(solution.divide(-10, 2))
print(solution.divide2(-10, 3))
| Python | 43 | 27.069767 | 79 | /binarySearch/divide_two_integers.py | 0.509106 | 0.489238 |
aymane081/python_algo | refs/heads/master | from utils.listNode import ListNode
class Solution:
def rotate(self, head, k):
if not head:
return None
count, node = 1, head
while node.next:
node = node.next
count += 1
# link the end and the start of the list
node.next = head
to_move = count - (k % count)
while to_move > 0:
node = node.next
to_move -= 1
# next is the new last element of the list
head = node.next
node.next = None
return head
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
five = ListNode(5)
one.next = two
two.next = three
three.next = four
four.next = five
print(one)
solution = Solution()
print(solution.rotate(one, 6)) | Python | 42 | 18.476191 | 51 | /linkedList/rotate_list.py | 0.538556 | 0.526316 |
aymane081/python_algo | refs/heads/master | from utils.listNode import ListNode
class Solution:
def reverse(self, head, m, n):
if not head:
return head
dummy = prev = ListNode(None)
node = head
rev, rev_tail = None, None
count = 1
while node:
if count > n:
rev_tail.next = node
break
if count >= m:
if count == m: # set the rev tail
rev_tail = node
rev, rev.next, node = node, rev, node.next
prev.next = rev
else:
prev.next = node
prev = prev.next
node = node.next
count += 1
return dummy.next
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
five = ListNode(5)
one.next = two
two.next = three
three.next = four
four.next = five
print(one)
solution = Solution()
print(solution.reverse(one, 2, 4))
| Python | 47 | 20.319149 | 58 | /linkedList/reverse_linked_list2.py | 0.466535 | 0.457677 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def two_sum(self, arr, target):
if not arr:
return None
remainders = dict()
for i, num in enumerate(arr):
if target - num in remainders:
return (remainders[target - num], i)
remainders[num] = i
solution = Solution()
print(solution.two_sum([1, 3, 5, 9], 10)) | Python | 13 | 27 | 52 | /arrays/two_sums.py | 0.545455 | 0.528926 |
aymane081/python_algo | refs/heads/master | # 198
class Solution:
def rob(self, homes):
if not homes:
return 0
curr, prev = 0, 0
for home in homes:
curr, prev = max(curr, prev + home), curr
return curr
| Python | 12 | 18.75 | 53 | /dynamicProgramming/house_robber.py | 0.457983 | 0.432773 |
aymane081/python_algo | refs/heads/master | class Solution(object):
def pascal_triangle(self, numRows):
pascal = []
for k in range(numRows):
pascal.append([1] * (k + 1))
for i in range(1, k):
pascal[k][i] = pascal[k - 1][i - 1] + pascal[k - 1][i]
return pascal
def pascal_triangle2(self, numRows):
all_rows = []
row = []
for k in range(numRows):
row.append(1)
for i in range(k - 1, 0, -1):
row[i] = row[i] + row[i - 1]
all_rows.append(list(row))
return all_rows
def pascal_triangle_row(self, k):
row = []
for j in range(k + 1):
row.append(1)
for i in range(j - 1, 0, -1):
row[i] = row[i] + row[i - 1]
return row
solution = Solution()
print(solution.pascal_triangle_row(2)) | Python | 33 | 25.90909 | 70 | /arrays/pascal_triangle.py | 0.452086 | 0.430665 |
aymane081/python_algo | refs/heads/master | import unittest
class Solution(object):
def search_insert_position(self, arr, val):
if not arr:
return 0
for i, d in enumerate(arr):
if d >= val:
return i
return len(arr)
def search_insert_position2(self, arr, val):
if not arr:
return 0
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == val:
return mid
elif arr[mid] < val:
left = mid + 1
else:
right = mid - 1
return left
class Test(unittest.TestCase):
arr = [1, 3, 5, 6]
test_data = [(5, 2), (2, 1), (7, 4), (0, 0)]
def test_search_insert_positiion(self):
solution = Solution()
for data in self.test_data:
self.assertEqual(solution.search_insert_position2(self.arr, data[0]), data[1])
if __name__ == '__main__':
unittest.main()
| Python | 41 | 23.487804 | 90 | /arrays/search_insert_position.py | 0.48008 | 0.457171 |
aymane081/python_algo | refs/heads/master | # 731
# time: o(N**2)
# space: O(N)
class MyCalendar2:
def __inint__(self):
self.calendar = []
self.overlap = []
def book(self, start, end):
for s, e in self.overlap:
# conflict
if s < end and start < e:
return False
for s, e in self.calendar:
if s < end and start > e:
#conflict. The intersection becomes an overlap
self.overlap.append(max(start, s), min(end, e))
self.calendar.append((start, end))
return True | Python | 22 | 25.363636 | 63 | /arrays/my_calendar2.py | 0.48532 | 0.476684 |
aymane081/python_algo | refs/heads/master | # 830
class Solution:
def position_of_large_groups(self, chars):
result, start = [], 0
for i in range(len(chars)):
if i == len(chars) - 1 or chars[i] != chars[i + 1]:
if i - start + 1 >= 3:
result.append([start, i])
start = i + 1
return result
chars = "abcdddeeeeaabbbcd"
solution = Solution()
print(solution.position_of_large_groups(chars)) | Python | 20 | 22.25 | 63 | /arrays/position_of_large_groups.py | 0.497845 | 0.478448 |
aymane081/python_algo | refs/heads/master | import unittest
def reverse_vowels(str):
if not str: return str
vowels = ['a', 'e', 'i', 'o', 'u']
list_str = list(str)
head, tail = 0, len(list_str) - 1
while head < tail:
if list_str[head].lower() not in vowels:
head += 1
elif list_str[tail].lower() not in vowels:
tail -= 1
else:
list_str[head], list_str[tail] = list_str[tail], list_str[head]
head += 1
tail -= 1
return ''.join(list_str)
print(reverse_vowels('leEtcode'))
class Solution:
vowels = ['a', 'e', 'i', 'o', 'u']
def reverse_vowels(self, string):
if not string:
return string
string_list = list(string)
head, tail = 0, len(string) - 1
while head < tail:
if string_list[head] not in self.vowels:
head += 1
elif string_list[tail] not in self.vowels:
tail -= 1
else:
string_list[head], string_list[tail] = string_list[tail], string_list[head]
head += 1
tail -= 1
return ''.join(string_list)
| Python | 48 | 23.708334 | 91 | /strings/reverse_vowels.py | 0.475712 | 0.465662 |
aymane081/python_algo | refs/heads/master | # 769
class Solution:
# a new chunk is form only if the current element is the max so far,
# and it is where it is supposed to be
def max_chunks(self, nums):
result = max_so_far = 0
for i, num in enumerate(nums):
max_so_far = max(max_so_far, num)
if max_so_far == i:
result += 1
return result | Python | 14 | 26.214285 | 72 | /arrays/max_chunks_to_make_sorted.py | 0.536842 | 0.523684 |
aymane081/python_algo | refs/heads/master | class Solution:
# M = len(difficulties), N = len(workers)
# time = O(M log M + N log N + M + N), but can omit the M and N
# space = O(M)
def max_profit_assignment(self, difficulty, profits, workers):
jobs = list(zip(difficulty, profits))
jobs.sort() # will sort by the first tuple element
index, best_so_far, result = 0, 0, 0
for worker in sorted(workers):
while index < len(jobs) and worker >= jobs[index][0]:
best_so_far = max(best_so_far, jobs[index][1])
index += 1
result += best_so_far
return result
difficulty = [2,4,6,8,10]
profits = [10,20,30,40,50]
workers = [4,5,6,7]
solution = Solution()
print(solution.max_profit_assignment(difficulty, profits, workers)) | Python | 25 | 31.559999 | 67 | /dynamicProgramming/most_profit_assigning_work.py | 0.567036 | 0.535055 |
aymane081/python_algo | refs/heads/master | from collections import defaultdict
from string import ascii_lowercase
class Solution(object):
# Time: O(n * k * k) to build the graph. n = # of words. k = max number of character in a word
# O(b ^ (d/2)) to perform a bidrectional BFS search, where b is the branching factor ( the average number of children(neighbors) at each node),
# and d is the depth
# Space: O(n * k)
def word_ladder(self, start_word, end_word, word_list):
"""
:type start_word: str
:type end_word: str:
:type word_list: Set[str]
:rtye: int
"""
if not start_word or not end_word or not word_list:
return 0
word_list.add(end_word)
graph = self.build_graph(word_list)
visited = set()
length = 0
front, back = {start_word}, {end_word}
while front:
if front & back:
return length
new_front = set()
for word in front:
visited.add(word)
for i in range(len(word)):
wildcard = word[:i] + '-' + word[i + 1 :]
new_words = graph[wildcard]
new_words -= visited
new_front |= new_words
front = new_front
length += 1
if len(back) < len(front):
front, back = back, front
return 0
def build_graph(self, word_list):
"""
:type word_list: Set[str]
:rtype: defaultdict
"""
graph = defaultdict(set)
for word in word_list:
for i in range(len(word)):
wildcard = word[:i] + '-' + word[i + 1 :]
graph[wildcard].add(word)
return graph | Python | 62 | 27.82258 | 147 | /graphs/word_ladder.py | 0.494401 | 0.490482 |
aymane081/python_algo | refs/heads/master | # This bidirectional technique is useful when we want to get cumulutative information
# from the left and right of each index
class Solution:
def get_product_array(self, nums):
if not nums:
return None
result = [1]
for i in range(1, len(nums)):
result.append(result[-1] * nums[i - 1])
product_right = 1
for i in range(len(nums) - 1, -1, -1):
result[i] *= product_right
product_right *= nums[i]
return result
solution = Solution()
nums = [2, 3, 4, 5]
[60, 40, 30, 24]
60
print(solution.get_product_array(nums))
| Python | 22 | 27.272728 | 85 | /arrays/product_of_array_except_self.py | 0.57717 | 0.541801 |
aymane081/python_algo | refs/heads/master | class Solution:
def get_stack_count(self, n):
stack_count = 0
if n == 0:
return stack_count
remain = n
while remain >= stack_count + 1:
stack_count += 1
remain -= stack_count
return stack_count
def get_stack_count2(self, n):
if n == 0:
return 0
left, right = 1, n
while left <= right:
mid = (left + right) // 2
s = mid * (mid + 1) // 2
if s > n:
right = mid - 1
else:
left = mid + 1
return left - 1
solution = Solution()
print("n = {} : stack_count = {}".format(5, solution.get_stack_count2(5)))
print("n = {} : stack_count = {}".format(6, solution.get_stack_count2(6)))
print("n = {} : stack_count = {}".format(8, solution.get_stack_count2(8)))
print("n = {} : stack_count = {}".format(9, solution.get_stack_count2(9))) | Python | 33 | 28.424242 | 74 | /binarySearch/arranging_coins.py | 0.46701 | 0.440206 |
aymane081/python_algo | refs/heads/master | from utils.listNode import ListNode
class Solution:
# time: O(N)
# space: O(1)
def partition(self, head, pivot):
if not head:
return head
s_head = smaller = ListNode(None)
g_head = greater = ListNode(None)
node = head
while node:
if node.value < pivot:
smaller.next = node
smaller = node
else:
greater.next = node
greater = node
node = node.next
greater.next = None
smaller.next = g_head.next
return s_head.next
one = ListNode(1)
two = ListNode(4)
three = ListNode(3)
four = ListNode(2)
five = ListNode(5)
six = ListNode(2)
one.next = two
two.next = three
three.next = four
four.next = five
five.next = six
print(one)
solution = Solution()
print(solution.partition(one, 3)) | Python | 45 | 19 | 41 | /linkedList/partition_list.py | 0.538376 | 0.529477 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.