def merge_lists(my_list: list, alices_list: list) -> list: """ Handle i = 1st, j = 2nd pointers Handle for last elem O(n) """ merged_list = [] i = 0 j = 0 for counter in range(len(my_list) + len(alices_list) - 1): print(my_list[i], alices_list[j]) if my_list[i] < alices_list[j]: merged_list.append(my_list[i]) i += 1 else: merged_list.append(alices_list[j]) j += 1 counter += 1 print(merged_list, counter) # For the last element (and up for loop counter is len + len - 1) if i == len(my_list): merged_list.append(alices_list[j]) elif j == len(alices_list): merged_list.append(my_list[i]) return merged_list
def word_cloud(text_list): word_list = [] word_dict = {} for text in text_list: word_list.extend(text.split()) for word in word_list: word = ''.join(letter for letter in word if letter.isalpha()) # Most imp line, removes all punctuation if word.lower() not in word_dict: # removes all caps word_dict[word.lower()] = 1 else: word_dict[word.lower()] += 1 print(word_dict)
def can_two_movies_fill_flight(movie_lengths: list, flight_length: int): # Convert list to dict movie_dict = {} for movie in movie_lengths: if movie not in movie_dict: movie_dict[movie] = 1 print(movie_dict) # Look up the difference since it O(1) for movie in movie_dict: rem_movie = flight_length - movie if rem_movie in movie_dict: return True return False
def balance_parenthesis(string): swaps = 0 left = 0 right = 0 swap_count = 0 for i in string: if i == '(': left += 1 elif i == ')': right += 1 if right > left + 1: swap_count += 1 print(left, right, swap_count) swaps = swap_count return swaps
def served_order_checker(take_out_orders, dine_in_orders, served_orders): i = 0 j = 0 orders = 0 # Imp: i == len(take_out_orders) is done to avoid out of index error for order in served_orders: print(i, j) if i == len(take_out_orders) or order == take_out_orders[i]: orders += 1 i += 1 elif j == len(dine_in_orders) or order == dine_in_orders[j]: orders += 1 j += 1 print(orders) if orders == len(take_out_orders) + len(dine_in_orders): return True else: return False
def findMin(nums): print(nums) left = 0 right = len(nums) - 1 min_n = nums[0] while left <= right: # time.sleep(1) mid = (left + right) // 2 # print(mid, nums[mid])å if nums[mid] > nums[left]: if nums[left] < min_n: min_n = nums[left] left = mid + 1 else: if nums[mid] < min_n: min_n = nums[mid] right = mid - 1 print(min_n)
def merge_ranges(meet_times): # In place sort - .sort() method, original dict is lost meet_times.sort() print(meet_times) meet_ranges = [] previous_meet = meet_times[0] for start, end in meet_times[1:]: # Comparing start of current to end of previous meet if start <= previous_meet[1]: previous_meet = (previous_meet[0], end) print(previous_meet) else: meet_ranges.append(previous_meet) previous_meet = (start, end) # Appending last meet range meet_ranges.append(previous_meet) return meet_ranges
def addTwoNumbers(l1, l2): head = None last = None carry = 0 while l1 or l2: res_val = l1.val + l2.val + carry carry = 0 if res_val >= 10: res_val = res_val % 10 carry = 1 if head is None: head = ListNode(res_val) last = head else: last.next = ListNode(res_val) last = last.next print(l1.val, l2.val, res_val) l1 = l1.next l2 = l2.next while l1.next: last.next = ListNode(l1.val+carry) last = last.next while l2.next: last.next = ListNode(l2.val+carry) last = last.next if carry == 1: last.next = ListNode(carry) last = last.next while head: print(head.val) head = head.next
def infix(text): numbers = [] operators = [] output = 0 temp_output = 0 for op in text: num = 0 print(op) # spaces if op == ' ': continue # nums try: if int(op): num = int(op) numbers.append(num) if len(operators) == 0: output += int(op) except: pass # operators if op == '/' or op == '*': operators.append(op) if not temp_output: temp_output = numbers.pop() temp_output = operator.floordiv(temp_output, numbers.pop()) elif op == '+' or op == '-': if len(operators) == 0: operators.append(op) elif len(numbers) > 1: opr = operators.pop() if opr == '+': output = operator.add(output, numbers.pop()) elif opr == '-': output = operator.sub(output, numbers.pop()) operators.append(op) print(numbers, output, operators) output += temp_output print(numbers, operators) print(output)
def top_scores(unsorted_scores, highest_possible_score): """ here we are finding max by ourselves and not using the given 'highest_possible_score' Logic - Create map, find max Iterate over our own 0 - max range, whenever that num is in map, append to sorted list """ # A map of all numbers score_counts = {} for score in unsorted_scores: score_counts[score] = 1 print(score_counts) # Find max min = unsorted_scores[0] max = unsorted_scores[0] for i in unsorted_scores[1:]: if i > max: max = i if i < min: min = i print(max) sorted_scores = [] # For each item in score_counts for score in range(min, max + 1): try: if score_counts[score]: sorted_scores.append(score) except: continue sorted_scores_desc = [] for score in range(max + 1, min - 1, -1): try: if score_counts[score]: sorted_scores_desc.append(score) except: continue print(sorted_scores) print(sorted_scores_desc)
def find_first_occurrence(arr, target) -> int: left = 0 right = len(arr) - 1 if target == arr[0]: return 0 while left <= right: time.sleep(1) mid = (left + right) // 2 # print(left, right, mid, arr[mid]) if target <= arr[mid]: if target == arr[mid] and target > arr[mid - 1]: return mid right = mid - 1 elif target > arr[mid]: left = mid + 1 return -1 print("First occurance :", find_first_occurrence([1, 3, 3, 3, 3, 6, 10, 10, 10, 100], 3)) print("First occurance :", find_first_occurrence([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 1)) print("First occurance :", find_first_occurrence([1, 22, 22, 33, 50, 100, 20000], 33)) print("First occurance :", find_first_occurrence([4, 6, 7, 7, 7, 20], 8)) print("First occurance :", find_first_occurrence([6, 7, 9, 10, 10, 10, 90], 10)) print("First occurance :", find_first_occurrence([4], 4))
# operators if op == '/' or op == '*': operators.append(op) if not temp_output: temp_output = numbers.pop() temp_output = operator.floordiv(temp_output, numbers.pop()) elif op == '+' or op == '-': if len(operators) == 0: operators.append(op) elif len(numbers) > 1: opr = operators.pop() if opr == '+': output = operator.add(output, numbers.pop()) elif opr == '-': output = operator.sub(output, numbers.pop()) operators.append(op) print(numbers, output, operators) output += temp_output print(numbers, operators) print(output) # or op == '*' or op == '/' text = '1 + 3 + 2/2 ' # text = '1 + 2 + 2 - 3 + 3 - 1' print(infix(text))
# Brute force # def can_two_movies_fill_flight(movie_lengths: list, flight_length: int): # for index, movie1 in enumerate(movie_lengths): # for movie2 in movie_lengths[index+1:]: # if movie1 + movie2 == flight_length: # print(movie1, movie2) # return True # return False # Using dict def can_two_movies_fill_flight(movie_lengths: list, flight_length: int): # Convert list to dict movie_dict = {} for movie in movie_lengths: if movie not in movie_dict: movie_dict[movie] = 1 print(movie_dict) # Look up the difference since it O(1) for movie in movie_dict: rem_movie = flight_length - movie if rem_movie in movie_dict: return True return False print(can_two_movies_fill_flight([1, 1, 3, 6, 9], 8)) print(can_two_movies_fill_flight([1, 1, 3, 5, 9], 6))
right = len(arr) - 1 index = -1 # 1 element in array if len(arr) == 1: return 0 # If array is sorted if arr[0] < arr[-1]: return 0 # Special binary search logic else: while left < right: mid = (left + right) // 2 # print(left, right, mid, arr[mid]) if arr[mid] > arr[left]: left = mid + 1 index = mid elif arr[mid] < arr[right]: right = mid - 1 index = mid return index print("Find minimum rotated :", find_min_rotated([30, 40, 50, 10, 20])) print("Find minimum rotated :", find_min_rotated([70, 10, 20, 30, 40, 50, 60])) print("Find minimum rotated :", find_min_rotated([0, 1, 2, 3, 4, 5])) print("Find minimum rotated :", find_min_rotated([0]))
from icecream import ic as print def served_order_checker(take_out_orders, dine_in_orders, served_orders): i = 0 j = 0 orders = 0 # Imp: i == len(take_out_orders) is done to avoid out of index error for order in served_orders: print(i, j) if i == len(take_out_orders) or order == take_out_orders[i]: orders += 1 i += 1 elif j == len(dine_in_orders) or order == dine_in_orders[j]: orders += 1 j += 1 print(orders) if orders == len(take_out_orders) + len(dine_in_orders): return True else: return False take_out_orders = [17, 8, 24] dine_in_orders = [12, 19, 2] served_orders = [17, 8, 12, 19, 2, 24] print(served_order_checker(take_out_orders, dine_in_orders, served_orders))
from icecream import ic as print def merge_ranges(meet_times): # In place sort - .sort() method, original dict is lost meet_times.sort() print(meet_times) meet_ranges = [] previous_meet = meet_times[0] for start, end in meet_times[1:]: # Comparing start of current to end of previous meet if start <= previous_meet[1]: previous_meet = (previous_meet[0], end) print(previous_meet) else: meet_ranges.append(previous_meet) previous_meet = (start, end) # Appending last meet range meet_ranges.append(previous_meet) return meet_ranges ranges = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)] print(merge_ranges(ranges))
while left <= right: mid = (left + right) // 2 # print(left, right, mid) if words[left] <= words[mid]: left = mid + 1 if words[mid] > words[left]: return mid + 1 else: right = mid - 1 if words[mid] < words[right]: return mid words = [ 'othellolagkage', 'ptolemaic', 'retrograde', 'supplant', 'undulate', 'xenoepist', 'asymptote', # <-- rotates here! 'babka', 'banoffee', 'engender', 'karpatka', ] print(find_rotation_point(words))
https://www.educative.io/courses/algorithms-ds-interview/YV6DxN7PyN9 First Element Not Smaller Than Target """ from icecream import ic as print def first_not_smaller(arr, target) -> int: left = 0 right = len(arr) - 1 if target == arr[0]: return 0 while left <= right: mid = (left + right) // 2 # print(left, right, mid, arr[mid]) if arr[mid] <= target <= arr[mid + 1]: return mid + 1 elif target < arr[mid]: right = mid - 1 elif target > arr[mid]: left = mid + 1 return -1 print("Find first element :", first_not_smaller([1, 3, 3, 5, 8, 8, 10], 2)) print("Find first element :", first_not_smaller([0], 0)) print("Find first element :", first_not_smaller([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10)) print("Find first element :", first_not_smaller([1, 1, 1, 1, 4, 5], 3))
''' Binary Search https://www.educative.io/courses/algorithms-ds-interview/JE6qXJ3RWVJ ''' from icecream import ic as print def binary_search(arr: list, target: int) -> int: left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 # print(left, right, mid, arr[mid]) if target == arr[mid]: return mid elif target > arr[mid]: left = mid + 1 elif target < arr[mid]: right = mid - 1 return -1 arr = [10, 20, 30, 40, 50, 60] target = 50 print('Binary Search, Index of target -', binary_search(arr, target))
Peak of mountain array """ from icecream import ic as print import time def peak_of_mountain_array(arr): left = 0 right = len(arr) - 1 index = 1 if len(arr) == 1: return 0 while left <= right: mid = (left + right) // 2 # print(left, right, mid, arr[mid]) if arr[mid] >= arr[mid + 1]: index = mid right = mid - 1 else: left = mid + 1 return index # print("Find Peak of mountain :", peak_of_mountain_array([0, 1, 2, 3, 2, 1, 0])) print("Find Peak of mountain :", peak_of_mountain_array([0, 10, 3, 2, 1, 2])) # print("Find Peak of mountain :", peak_of_mountain_array([0, 10, 0]))
prev_max = max prev_max_2 = max_2 for i in range(1, len(list_of_ints)): # Calculate all maxes num = list_of_ints[i] if num > max: max = num product_2 = num * prev_max if product_2 > max_2: max_2 = product_2 # print(max_2, prev_max, list_of_ints[i]) product_3 = num * prev_max_2 if product_3 > max_3: max_3 = product_3 # print(max_3, prev_max_2, list_of_ints[i]) # Storing prev_max = max prev_max_2 = max_2 return max_3 # Basic logic is finding max and max_2 and storing in prev_max and prev_max_2 list_of_ints = [19, 5, 2, 9, 1, 45, 3, 100] print(highest_product(list_of_ints))
stock_prices = [10, 7, 5, 8, 11, 9] get_max_profit(stock_prices) # Returns 6 (buying for $5 and selling for $11) """ from icecream import ic as print def get_max_profit(stock_prices): if len(stock_prices) < 2: raise ValueError('Getting a profit requires at least 2 prices') min_price = stock_prices[0] max_profit = stock_prices[1] - stock_prices[0] # this is important, having some default max profit for current_price in stock_prices[1:]: profit = current_price - min_price if profit > max_profit: max_profit = profit if current_price < min_price: min_price = current_price return max_profit # stock_prices = [20, 7, 2, 5, 1, 1] print(get_max_profit([20, 7, 6, 5, 1])) print(get_max_profit([10, 7, 5, 8, 11, 9])) print(get_max_profit([10, 7, 5, 2, 11, 9]))
l1 = l1.next l2 = l2.next while l1.next: last.next = ListNode(l1.val+carry) last = last.next while l2.next: last.next = ListNode(l2.val+carry) last = last.next if carry == 1: last.next = ListNode(carry) last = last.next while head: print(head.val) head = head.next # l1 = [2,4,3] l1 = ListNode(2) l1.next = ListNode(2) l1.next.next = ListNode(9) # l2 = [5,6,5] l2 = ListNode(5) l2.next = ListNode(6) l2.next.next = ListNode(5) print(addTwoNumbers(l1, l2))
""" https://www.interviewcake.com/question/python3/merge-sorted-arrays?course=fc1§ion=array-and-string-manipulation my_list = [3, 4, 6, 10, 11, 15] alices_list = [1, 5, 8, 12, 14, 19] # Prints [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19] print(merge_lists(my_list, alices_list)) """ from icecream import ic as print def merge_lists(my_list: list, alices_list: list) -> list: """ Handle i = 1st, j = 2nd pointers Handle for last elem O(n) """ merged_list = [] i = 0 j = 0 for counter in range(len(my_list) + len(alices_list) - 1): print(my_list[i], alices_list[j]) if my_list[i] < alices_list[j]: merged_list.append(my_list[i]) i += 1 else: merged_list.append(alices_list[j]) j += 1
""" Square root using binary search https://www.educative.io/courses/algorithms-ds-interview/YV3ElMP53yM """ from icecream import ic as print import time def square_root(n): if n == 0: return 0 left, right = 1, n res = -1 while left <= right: mid = (left + right) // 2 # print(left, right, mid, n) if mid * mid <= n: res = mid left = mid + 1 else: right = mid - 1 return res print("Square root:", square_root(4)) print("Square root:", square_root(8)) print("Square root:", square_root(10))
For eg: ))(( Ans - 1, Swap first and last bracket -> ()() eg: (()()) Ans - 0 """ from icecream import ic as print def balance_parenthesis(string): swaps = 0 left = 0 right = 0 swap_count = 0 for i in string: if i == '(': left += 1 elif i == ')': right += 1 if right > left + 1: swap_count += 1 print(left, right, swap_count) swaps = swap_count return swaps string = '(())()' print(balance_parenthesis(string))