text
stringlengths
81
112k
Loading birth name dataset from a zip file in the repo def load_birth_names(): """Loading birth name dataset from a zip file in the repo""" data = get_example_data('birth_names.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='ms') pdf.to_sql( 'birth_names', d...
endpoint that refreshes druid datasources metadata def refresh_datasources(self, refreshAll=True): """endpoint that refreshes druid datasources metadata""" session = db.session() DruidCluster = ConnectorRegistry.sources['druid'].cluster_class for cluster in session.query(DruidCluster).a...
converts a positive integer into a (reversed) linked list. for example: give 112 result 2 -> 1 -> 1 def convert_to_list(number: int) -> Node: """ converts a positive integer into a (reversed) linked list. for example: give 112 result 2 -> 1 -> 1 """ if number >= 0: ...
converts the non-negative number list into a string. def convert_to_str(l: Node) -> str: """ converts the non-negative number list into a string. """ result = "" while l: result += str(l.val) l = l.next return result
:type root: TreeNode :rtype: int def longest_consecutive(root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 max_len = 0 dfs(root, 0, root.val, max_len) return max_len
:param array: List[int] :return: Set[ Tuple[int, int, int] ] def three_sum(array): """ :param array: List[int] :return: Set[ Tuple[int, int, int] ] """ res = set() array.sort() for i in range(len(array) - 2): if i > 0 and array[i] == array[i - 1]: continue l,...
Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) def top_sort_recursive(graph): """ Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) """ order, enter, state = [], set(graph), {} def dfs(node): state[node] = GRAY ...
Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) def top_sort(graph): """ Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) """ order, enter, state = [], set(graph), {} def is_ready(node): lst = graph.get(node, ()) ...
:type nums: List[int] :rtype: int def max_product(nums): """ :type nums: List[int] :rtype: int """ lmin = lmax = gmax = nums[0] for i in range(len(nums)): t1 = nums[i] * lmax t2 = nums[i] * lmin lmax = max(max(t1, t2), nums[i]) lmin = min(min(t1, t2), nums[i]...
arr is list of positive/negative numbers def subarray_with_max_product(arr): ''' arr is list of positive/negative numbers ''' l = len(arr) product_so_far = max_product_end = 1 max_start_i = 0 so_far_start_i = so_far_end_i = 0 all_negative_flag = True for i in range(l): max_product_...
:type words: list :type max_width: int :rtype: list def text_justification(words, max_width): ''' :type words: list :type max_width: int :rtype: list ''' ret = [] # return value row_len = 0 # current length of strs in a row row_words = [] # current words in a row index = ...
Insertion Sort Complexity: O(n^2) def insertion_sort(arr, simulation=False): """ Insertion Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): cursor = arr[i] pos = i ...
cycle_sort This is based on the idea that the permutations to be sorted can be decomposed into cycles, and the results can be individually sorted by cycling. reference: https://en.wikipedia.org/wiki/Cycle_sort Average time complexity : O(N^2) Worst case time complexity : O(N^2) def cy...
Cocktail_shaker_sort Sorting a given array mutation of bubble sort reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort Worst-case performance: O(N^2) def cocktail_shaker_sort(arr): """ Cocktail_shaker_sort Sorting a given array mutation of bubble sort reference: htt...
:type people: List[List[int]] :rtype: List[List[int]] def reconstruct_queue(people): """ :type people: List[List[int]] :rtype: List[List[int]] """ queue = [] people.sort(key=lambda x: (-x[0], x[1])) for h, k in people: queue.insert(k, [h, k]) return queue
:type root: TreeNode :rtype: int def min_depth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 if root.left is not None or root.right is not None: return max(self.minDepth(root.left), self.minDepth(root.right))+1 return min(self.minDepth(r...
:type s: str :type t: str :rtype: bool def is_one_edit(s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) > len(t): return is_one_edit(t, s) if len(t) - len(s) > 1 or t == s: return False for i in range(len(s)): if s[i] != t[i]: r...
Shell Sort Complexity: O(n^2) def shell_sort(arr): ''' Shell Sort Complexity: O(n^2) ''' n = len(arr) # Initialize size of the gap gap = n//2 while gap > 0: y_index = gap while y_index < len(arr): y = arr[y_index] x_index = y_index - ...
Return prefix common of 2 strings def common_prefix(s1, s2): "Return prefix common of 2 strings" if not s1 or not s2: return "" k = 0 while s1[k] == s2[k]: k = k + 1 if k >= len(s1) or k >= len(s2): return s1[0:k] return s1[0:k]
Euler's totient function or Phi function. Time Complexity: O(sqrt(n)). def euler_totient(n): """Euler's totient function or Phi function. Time Complexity: O(sqrt(n)).""" result = n; for i in range(2, int(n ** 0.5) + 1): if n % i == 0: while n % i == 0: n //= i ...
This function builds up a dictionary where the keys are the values of the list, and the values are the positions at which these values occur in the list. We then iterate over the dict and if there is more than one key with an odd number of occurrences, bail out and return False. Otherwise, we want to en...
[summary] This algorithm computes the n-th fibbonacci number very quick. approximate O(n) The algorithm use dynamic programming. Arguments: n {[int]} -- [description] Returns: [int] -- [description] def fib_list(n): """[summary] This algorithm computes the n-th fib...
[summary] Works iterative approximate O(n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] def fib_iter(n): """[summary] Works iterative approximate O(n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] ...
:param nums: List[int] :return: Set[tuple] def subsets(nums): """ :param nums: List[int] :return: Set[tuple] """ n = len(nums) total = 1 << n res = set() for i in range(total): subset = tuple(num for j, num in enumerate(nums) if i & 1 << j) res.add(subset) retu...
The length of longest common subsequence among the two given strings s1 and s2 def lcs(s1, s2, i, j): """ The length of longest common subsequence among the two given strings s1 and s2 """ if i == 0 or j == 0: return 0 elif s1[i - 1] == s2[j - 1]: return 1 + lcs(s1, s2, i - 1, j - 1...
:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode def lca(root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root is None or root is p or root is q: return root left = lca(root.left, p, q) rig...
:type root: Node :type p: Node :type q: Node :rtype: Node def lowest_common_ancestor(root, p, q): """ :type root: Node :type p: Node :type q: Node :rtype: Node """ while root: if p.val > root.val < q.val: root = root.right elif p.val < root.val > q.va...
:type n: int :rtype: int def climb_stairs(n): """ :type n: int :rtype: int """ arr = [1, 1] for _ in range(1, n): arr.append(arr[-1] + arr[-2]) return arr[-1]
find the nth digit of given number. 1. find the length of the number where the nth digit is from. 2. find the actual number where the nth digit is from 3. find the nth digit and return def find_nth_digit(n): """find the nth digit of given number. 1. find the length of the number where the nth digit...
Return the 'hailstone sequence' from n to 1 n: The starting point of the hailstone sequence def hailstone(n): """Return the 'hailstone sequence' from n to 1 n: The starting point of the hailstone sequence """ sequence = [n] while n > 1: if n%2 != 0: n = 3*n + 1 else: n = int(n/2...
:type s: str :type word_dict: Set[str] :rtype: bool def word_break(s, word_dict): """ :type s: str :type word_dict: Set[str] :rtype: bool """ dp = [False] * (len(s)+1) dp[0] = True for i in range(1, len(s)+1): for j in range(0, i): if dp[j] and s[j:i] in word...
Return True if n is a prime number Else return False. def prime_check(n): """Return True if n is a prime number Else return False. """ if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: ...
Find the length of the longest substring without repeating characters. def longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. """ if string is None: return 0 dict = {} max_length = 0 j = 0 for i in range(len(string))...
Find the length of the longest substring without repeating characters. Uses alternative algorithm. def longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. """ if string is None: return 0 start,...
Find the length of the longest substring without repeating characters. Return max_len and the substring as a tuple def get_longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. Return max_len and the substring as a tuple """ if string ...
Find the length of the longest substring without repeating characters. Uses alternative algorithm. Return max_len and the substring as a tuple def get_longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. Re...
Push the item in the priority queue. if priority is not given, priority is set to the value of item. def push(self, item, priority=None): """Push the item in the priority queue. if priority is not given, priority is set to the value of item. """ priority = item if priority is No...
Calculates factorial iteratively. If mod is not None, then return (n! % mod) Time Complexity - O(n) def factorial(n, mod=None): """Calculates factorial iteratively. If mod is not None, then return (n! % mod) Time Complexity - O(n)""" if not (isinstance(n, int) and n >= 0): raise ValueEr...
Calculates factorial recursively. If mod is not None, then return (n! % mod) Time Complexity - O(n) def factorial_recur(n, mod=None): """Calculates factorial recursively. If mod is not None, then return (n! % mod) Time Complexity - O(n)""" if not (isinstance(n, int) and n >= 0): raise V...
Selection Sort Complexity: O(n^2) def selection_sort(arr, simulation=False): """ Selection Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): minimum = i for j in range(i ...
Time Complexity: O(N) Space Complexity: O(N) def remove_dups(head): """ Time Complexity: O(N) Space Complexity: O(N) """ hashset = set() prev = Node() while head: if head.val in hashset: prev.next = head.next else: hashset.add(head.val) ...
Time Complexity: O(N^2) Space Complexity: O(1) def remove_dups_wothout_set(head): """ Time Complexity: O(N^2) Space Complexity: O(1) """ current = head while current: runner = current while runner.next: if runner.next.val == current.val: runner.ne...
replace u with v :param node_u: replaced node :param node_v: :return: None def transplant(self, node_u, node_v): """ replace u with v :param node_u: replaced node :param node_v: :return: None """ if node_u.parent is None: sel...
find the max node when node regard as a root node :param node: :return: max node def maximum(self, node): """ find the max node when node regard as a root node :param node: :return: max node """ temp_node = node while temp_node.right is n...
find the minimum node when node regard as a root node :param node: :return: minimum node def minimum(self, node): """ find the minimum node when node regard as a root node :param node: :return: minimum node """ temp_node = node while temp_n...
Computes (base ^ exponent) % mod. Time complexity - O(log n) Use similar to Python in-built function pow. def modular_exponential(base, exponent, mod): """Computes (base ^ exponent) % mod. Time complexity - O(log n) Use similar to Python in-built function pow.""" if exponent < 0: raise ...
:type intervals: List[Interval] :rtype: bool def can_attend_meetings(intervals): """ :type intervals: List[Interval] :rtype: bool """ intervals = sorted(intervals, key=lambda x: x.start) for i in range(1, len(intervals)): if intervals[i].start < intervals[i - 1].end: ret...
:type root: TreeNode :type key: int :rtype: TreeNode def delete_node(self, root, key): """ :type root: TreeNode :type key: int :rtype: TreeNode """ if not root: return None if root.val == key: if root.left: # Find the ...
:type path: str :rtype: str def simplify_path(path): """ :type path: str :rtype: str """ skip = {'..', '.', ''} stack = [] paths = path.split('/') for tok in paths: if tok == '..': if stack: stack.pop() elif tok not in skip: st...
O(2**n) def subsets(nums): """ O(2**n) """ def backtrack(res, nums, stack, pos): if pos == len(nums): res.append(list(stack)) else: # take nums[pos] stack.append(nums[pos]) backtrack(res, nums, stack, pos+1) stack.pop() ...
Jump Search Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target value in array reference: https://en.wikipedia.org/wiki/Jump_search def j...
Takes as input multi dimensional iterable and returns generator which produces one dimensional output. def flatten_iter(iterable): """ Takes as input multi dimensional iterable and returns generator which produces one dimensional output. """ for element in iterable: if isinstance(elemen...
Bidirectional BFS!!! :type begin_word: str :type end_word: str :type word_list: Set[str] :rtype: int def ladder_length(begin_word, end_word, word_list): """ Bidirectional BFS!!! :type begin_word: str :type end_word: str :type word_list: Set[str] :rtype: int """ if len(be...
Iterable to get every convolution window per loop iteration. For example: `convolved([1, 2, 3, 4], kernel_size=2)` will produce the following result: `[[1, 2], [2, 3], [3, 4]]`. `convolved([1, 2, 3], kernel_size=2, stride=1, padding=2, default_value=42)` will pro...
1D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevalier/python-conv-lib - MIT License, Copyright (c) 2018 Guillaume Chevalier def convolved...
2D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevalier/python-conv-lib - MIT License, Copyright (c) 2018 Guillaume Chevalier def convolved...
Convert integers to a list of integers to fit the number of dimensions if the argument is not already a list. For example: `dimensionize(3, nd=2)` will produce the following result: `(3, 3)`. `dimensionize([3, 1], nd=2)` will produce the following result: `[3, 1]`. ...
:type nums: List[int] :type k: int :rtype: List[int] def max_sliding_window(nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if not nums: return nums queue = collections.deque() res = [] for num in nums: if len(queue) < k: qu...
Merge intervals in the form of a list. def merge_intervals(intervals): """ Merge intervals in the form of a list. """ if intervals is None: return None intervals.sort(key=lambda i: i[0]) out = [intervals.pop(0)] for i in intervals: if out[-1][-1] >= i[0]: out[-1][-1] = m...
Merge two intervals into one. def merge(intervals): """ Merge two intervals into one. """ out = [] for i in sorted(intervals, key=lambda i: i.start): if out and i.start <= out[-1].end: out[-1].end = max(out[-1].end, i.end) else: out += i, ...
Print out the intervals. def print_intervals(intervals): """ Print out the intervals. """ res = [] for i in intervals: res.append(repr(i)) print("".join(res))
Rotate the entire array 'k' times T(n)- O(nk) :type array: List[int] :type k: int :rtype: void Do not return anything, modify array in-place instead. def rotate_v1(array, k): """ Rotate the entire array 'k' times T(n)- O(nk) :type array: List[int] :type k: int :rtype: void Do ...
Reverse segments of the array, followed by the entire array T(n)- O(n) :type array: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. def rotate_v2(array, k): """ Reverse segments of the array, followed by the entire array T(n)- O(n) :type array: ...
:type matrix: List[List[int]] :rtype: List[List[int]] def pacific_atlantic(matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ n = len(matrix) if not n: return [] m = len(matrix[0]) if not m: return [] res = [] atlantic = [[False for _ in range (n)] for _ ...
Quick sort Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2) def quick_sort(arr, simulation=False): """ Quick sort Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) arr, _ = quick_s...
:type s: str :rtype: bool def is_palindrome(s): """ :type s: str :rtype: bool """ i = 0 j = len(s)-1 while i < j: while i < j and not s[i].isalnum(): i += 1 while i < j and not s[j].isalnum(): j -= 1 if s[i].lower() != s[j].lower(): ...
:type digits: List[int] :rtype: List[int] def plus_one_v1(digits): """ :type digits: List[int] :rtype: List[int] """ digits[-1] = digits[-1] + 1 res = [] ten = 0 i = len(digits)-1 while i >= 0 or ten == 1: summ = 0 if i >= 0: summ += digits[i] ...
:type head: ListNode :type k: int :rtype: ListNode def rotate_right(head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next: return head current = head length = 1 # count length of the list while current.next: cur...
:type s: str :rtype: int def num_decodings(s): """ :type s: str :rtype: int """ if not s or s[0] == "0": return 0 wo_last, wo_last_two = 1, 1 for i in range(1, len(s)): x = wo_last if s[i] != "0" else 0 y = wo_last_two if int(s[i-1:i+1]) < 27 and s[i-1] != "0" el...
:type nums: List[int] :type target: int :rtype: List[int] def search_range(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ low = 0 high = len(nums) - 1 while low <= high: mid = low + (high - low) // 2 if target < nums[mid]: ...
:type head: Node :rtype: Node def first_cyclic_node(head): """ :type head: Node :rtype: Node """ runner = walker = head while runner and runner.next: runner = runner.next.next walker = walker.next if runner is walker: break if runner is None or runne...
Heap Sort that uses a max heap to sort an array in ascending order Complexity: O(n log(n)) def max_heap_sort(arr, simulation=False): """ Heap Sort that uses a max heap to sort an array in ascending order Complexity: O(n log(n)) """ iteration = 0 if simulation: print("iteration",...
Max heapify helper for max_heap_sort def max_heapify(arr, end, simulation, iteration): """ Max heapify helper for max_heap_sort """ last_parent = (end - 1) // 2 # Iterate from last parent to first for parent in range(last_parent, -1, -1): current_parent = parent # Iterate from cur...
Heap Sort that uses a min heap to sort an array in ascending order Complexity: O(n log(n)) def min_heap_sort(arr, simulation=False): """ Heap Sort that uses a min heap to sort an array in ascending order Complexity: O(n log(n)) """ iteration = 0 if simulation: print("iteration",...
Min heapify helper for min_heap_sort def min_heapify(arr, start, simulation, iteration): """ Min heapify helper for min_heap_sort """ # Offset last_parent by the start (last_parent calculated as if start index was 0) # All array accesses need to be offset by start end = len(arr) - 1 last_parent...
the RSA key generating algorithm k is the number of bits in n def generate_key(k, seed=None): """ the RSA key generating algorithm k is the number of bits in n """ def modinv(a, m): """calculate the inverse of a mod m that is, find b such that (a * b) % m == 1""" b = 1 ...
Return square root of n, with maximum absolute error epsilon def square_root(n, epsilon=0.001): """Return square root of n, with maximum absolute error epsilon""" guess = n / 2 while abs(guess * guess - n) > epsilon: guess = (guess + (n / guess)) / 2 return guess
Counting_sort Sorting a array which has no element greater than k Creating a new temp_arr,where temp_arr[i] contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the result_arr return the result_arr Complexity: 0(n) def counting_so...
Calculate the powerset of any iterable. For a range of integers up to the length of the given list, make all possible combinations and chain them together as one object. From https://docs.python.org/3/library/itertools.html#itertools-recipes def powerset(iterable): """Calculate the powerset of any ite...
Optimal algorithm - DONT USE ON BIG INPUTS - O(2^n) complexity! Finds the minimum cost subcollection os S that covers all elements of U Args: universe (list): Universe of elements subsets (dict): Subsets of U {S1:elements,S2:elements} costs (dict): Costs of each subset in S - {S1:cost, ...
Approximate greedy algorithm for set-covering. Can be used on large inputs - though not an optimal solution. Args: universe (list): Universe of elements subsets (dict): Subsets of U {S1:elements,S2:elements} costs (dict): Costs of each subset in S - {S1:cost, S2:cost...} def greedy_set...
:type n: int :rtype: int def num_trees(n): """ :type n: int :rtype: int """ dp = [0] * (n+1) dp[0] = 1 dp[1] = 1 for i in range(2, n+1): for j in range(i+1): dp[i] += dp[i-j] * dp[j-1] return dp[-1]
:type val: int :rtype: float def next(self, val): """ :type val: int :rtype: float """ self.queue.append(val) return sum(self.queue) / len(self.queue)
n: int nums: list[object] target: object sum_closure: function, optional Given two elements of nums, return sum of both. compare_closure: function, optional Given one object of nums and target, return -1, 1, or 0. same_closure: function, optional Given two object of nums, ret...
:type pattern: str :type string: str :rtype: bool def pattern_match(pattern, string): """ :type pattern: str :type string: str :rtype: bool """ def backtrack(pattern, string, dic): if len(pattern) == 0 and len(string) > 0: return False if len(pattern) == le...
Bogo Sort Best Case Complexity: O(n) Worst Case Complexity: O(∞) Average Case Complexity: O(n(n-1)!) def bogo_sort(arr, simulation=False): """Bogo Sort Best Case Complexity: O(n) Worst Case Complexity: O(∞) Average Case Complexity: O(n(n-1)!) """ iterati...
Insert new key into node def insert(self, key): """ Insert new key into node """ # Create new node n = TreeNode(key) if not self.node: self.node = n self.node.left = AvlTree() self.node.right = AvlTree() elif key < self.node.va...
Re balance tree. After inserting or deleting a node, def re_balance(self): """ Re balance tree. After inserting or deleting a node, """ self.update_heights(recursive=False) self.update_balances(False) while self.balance < -1 or self.balance > 1: if self.bala...
Update tree height def update_heights(self, recursive=True): """ Update tree height """ if self.node: if recursive: if self.node.left: self.node.left.update_heights() if self.node.right: self.node.right....
Calculate tree balance factor def update_balances(self, recursive=True): """ Calculate tree balance factor """ if self.node: if recursive: if self.node.left: self.node.left.update_balances() if self.node.right: ...
Right rotation def rotate_right(self): """ Right rotation """ new_root = self.node.left.node new_left_sub = new_root.right.node old_root = self.node self.node = new_root old_root.left.node = new_left_sub new_root.right.node = old_root
Left rotation def rotate_left(self): """ Left rotation """ new_root = self.node.right.node new_left_sub = new_root.left.node old_root = self.node self.node = new_root old_root.right.node = new_left_sub new_root.left.node = old_root
In-order traversal of the tree def in_order_traverse(self): """ In-order traversal of the tree """ result = [] if not self.node: return result result.extend(self.node.left.in_order_traverse()) result.append(self.node.key) result.extend(self....
:type low: str :type high: str :rtype: int def strobogrammatic_in_range(low, high): """ :type low: str :type high: str :rtype: int """ res = [] count = 0 low_len = len(low) high_len = len(high) for i in range(low_len, high_len + 1): res.extend(helper2(i, i)) ...
:type words: List[str] :rtype: List[str] def find_keyboard_row(words): """ :type words: List[str] :rtype: List[str] """ keyboard = [ set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm'), ] result = [] for word in words: for key in keyboard: ...
This is a suboptimal, hacky method using eval(), which is not safe for user input. We guard against danger by ensuring k in an int def kth_to_last_eval(head, k): """ This is a suboptimal, hacky method using eval(), which is not safe for user input. We guard against danger by ensuring k in an int ...
This is a brute force method where we keep a dict the size of the list Then we check it for the value we need. If the key is not in the dict, our and statement will short circuit and return False def kth_to_last_dict(head, k): """ This is a brute force method where we keep a dict the size of the list ...
This is an optimal method using iteration. We move p1 k steps ahead into the list. Then we move p1 and p2 together until p1 hits the end. def kth_to_last(head, k): """ This is an optimal method using iteration. We move p1 k steps ahead into the list. Then we move p1 and p2 together until p1 hit...
Wortst Time Complexity: O(NlogN) :type buildings: List[List[int]] :rtype: List[List[int]] def get_skyline(lrh): """ Wortst Time Complexity: O(NlogN) :type buildings: List[List[int]] :rtype: List[List[int]] """ skyline, live = [], [] i, n = 0, len(lrh) while i < n or live: ...
:type array: List[int] :rtype: List[] def summarize_ranges(array): """ :type array: List[int] :rtype: List[] """ res = [] if len(array) == 1: return [str(array[0])] i = 0 while i < len(array): num = array[i] while i + 1 < len(array) and array[i + 1] - array[i...