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 = s...
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] ...
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 i...
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 hea...
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) ...
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] = ' -> '.joi...
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)): ...
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(r...
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('.'))) ...
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 ...
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): ...
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: ...
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 m...
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: ...
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 ...
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 +=...
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 ...
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'...
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...
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...
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 ...
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...
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] +=...
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 ...
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_nu...
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)) ...
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 ...
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: r...
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 <...
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 ...
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...
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 ) de...
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((r...
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 = Tr...
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...
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 ...
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 = [[...
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...
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(mat...
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_co...
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...
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(tr...
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...
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): ...
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 = b...
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...
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 ...
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) * mi...
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 enum...
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(...
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): ...
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 ...
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] whi...
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, ma...
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: cur...
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 ...
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...
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: #...
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(nod...
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): ...
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((no...
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) ...
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...
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) ...
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: ...
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: ...
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...
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)...
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 - nod...
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...
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 ...
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: pa...
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': ...
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 retur...
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: r...
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() pr...
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...
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...
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,...
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 ...
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 =...
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...
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_...
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(...
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(...
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: ...
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...
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]) s...
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...
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...
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 elemen...
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(nei...
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[-...
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_count...
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 ...
Python
45
19
41
/linkedList/partition_list.py
0.538376
0.529477