Description
stringlengths
18
161k
Code
stringlengths
15
300k
collection of search algorithms finding the needle in a haystack
from .binary_search import * from .ternary_search import * from .first_occurrence import * from .last_occurrence import * from .linear_search import * from .search_insert import * from .two_sum import * from .search_range import * from .find_min_rotate import * from .search_rotate import * from .jump_search import * from .next_greatest_letter import * from .interpolation_search import *
binary search find an element in a sorted array in ascending order for binary search tn tn2 o1 the recurrence relation apply masters theorem for computing run time complexity of recurrence relations tn atnb fn here a 1 b 2 log a base b 1 also here fn nc logkn k 0 c log a base b so tn onc logk1n ologn worstcase complexity ologn reference https en wikipedia orgwikibinarysearchalgorithm in this below function we are passing array it s first index last index and value to be searched worstcase complexity ologn reference https en wikipedia orgwikibinarysearchalgorithm here in logic section first we are checking if low is greater than high which means its an error condition because low index should not move ahead of high index for binary search t n t n 2 o 1 the recurrence relation apply masters theorem for computing run time complexity of recurrence relations t n at n b f n here a 1 b 2 log a base b 1 also here f n n c log k n k 0 c log a base b so t n o n c log k 1 n o log n worst case complexity o log n reference https en wikipedia org wiki binary_search_algorithm in this below function we are passing array it s first index last index and value to be searched worst case complexity o log n reference https en wikipedia org wiki binary_search_algorithm here in logic section first we are checking if low is greater than high which means its an error condition because low index should not move ahead of high index this mid will not break integer range go search in the left subarray go search in the right subarray
def binary_search(array, query): low, high = 0, len(array) - 1 while low <= high: mid = (high + low) // 2 val = array[mid] if val == query: return mid if val < query: low = mid + 1 else: high = mid - 1 return None def binary_search_recur(array, low, high, val): if low > high: return -1 mid = low + (high-low)//2 if val < array[mid]: return binary_search_recur(array, low, mid - 1, val) if val > array[mid]: return binary_search_recur(array, mid + 1, high, val) return mid
suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand i e 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 find the minimum element the complexity must be ologn you may assume no duplicate exists in the array finds the minimum element in a sorted array that has been rotated finds the minimum element in a sorted array that has been rotated finds the minimum element in a sorted array that has been rotated finds the minimum element in a sorted array that has been rotated
def find_min_rotate(array): low = 0 high = len(array) - 1 while low < high: mid = (low + high) // 2 if array[mid] > array[high]: low = mid + 1 else: high = mid return array[low] def find_min_rotate_recur(array, low, high): mid = (low + high) // 2 if mid == low: return array[low] if array[mid] > array[high]: return find_min_rotate_recur(array, mid + 1, high) return find_min_rotate_recur(array, low, mid)
find first occurance of a number in a sorted array increasing order approach binary search tn olog n returns the index of the first occurance of the given element in an array the array has to be sorted in increasing order printlo lo hi hi mid mid returns the index of the first occurance of the given element in an array the array has to be sorted in increasing order now mid will be ininteger range print lo lo hi hi mid mid
def first_occurrence(array, query): low, high = 0, len(array) - 1 while low <= high: mid = low + (high-low)//2 if low == high: break if array[mid] < query: low = mid + 1 else: high = mid if array[low] == query: return low
python implementation of the interpolation search algorithm given a sorted array in increasing order interpolation search calculates the starting point of its search according to the search key formula startpos low x arrlowhigh low arrhigh arrlow doc https en wikipedia orgwikiinterpolationsearch time complexity olog2log2 n for average cases on for the worst case the algorithm performs best with uniformly distributed arrays param array the array to be searched param searchkey the key to be searched in the array returns index of searchkey in array if found else 1 examples interpolationsearch25 12 1 10 12 15 20 41 55 1 2 interpolationsearch5 10 12 14 17 20 21 55 1 interpolationsearch5 10 12 14 17 20 21 5 1 highest and lowest index in array calculate the search position searchkey is found if searchkey is larger searchkey is in upper part if searchkey is smaller searchkey is in lower part param array the array to be searched param search_key the key to be searched in the array returns index of search_key in array if found else 1 examples interpolation_search 25 12 1 10 12 15 20 41 55 1 2 interpolation_search 5 10 12 14 17 20 21 55 1 interpolation_search 5 10 12 14 17 20 21 5 1 highest and lowest index in array calculate the search position search_key is found if search_key is larger search_key is in upper part if search_key is smaller search_key is in lower part
from typing import List def interpolation_search(array: List[int], search_key: int) -> int: high = len(array) - 1 low = 0 while (low <= high) and (array[low] <= search_key <= array[high]): pos = low + int(((search_key - array[low]) * (high - low) / (array[high] - array[low]))) if array[pos] == search_key: return pos if array[pos] < search_key: low = pos + 1 else: high = pos - 1 return -1 if __name__ == "__main__": import doctest doctest.testmod()
jump search find an element in a sorted array worstcase complexity on rootn 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 orgwikijumpsearch return 1 means that array doesn t contain target value find block that contains target value find target value in block if there is target value in array return it 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 return 1 means that array doesn t contain target value find block that contains target value find target value in block if there is target value in array return it
import math def jump_search(arr,target): length = len(arr) block_size = int(math.sqrt(length)) block_prev = 0 block= block_size if arr[length - 1] < target: return -1 while block <= length and arr[block - 1] < target: block_prev = block block += block_size while arr[block_prev] < target : block_prev += 1 if block_prev == min(block, length) : return -1 if arr[block_prev] == target : return block_prev return -1
find last occurance of a number in a sorted array increasing order approach binary search tn olog n returns the index of the last occurance of the given element in an array the array has to be sorted in increasing order returns the index of the last occurance of the given element in an array the array has to be sorted in increasing order
def last_occurrence(array, query): low, high = 0, len(array) - 1 while low <= high: mid = (high + low) // 2 if (array[mid] == query and mid == len(array)-1) or \ (array[mid] == query and array[mid+1] > query): return mid if array[mid] <= query: low = mid + 1 else: high = mid - 1
linear search works in any array tn on find the index of the given element in the array there are no restrictions on the order of the elements in the array if the element couldn t be found returns 1 find the index of the given element in the array there are no restrictions on the order of the elements in the array if the element couldn t be found returns 1
def linear_search(array, query): for i, value in enumerate(array): if value == query: return i return -1
given a list of sorted characters letters containing only lowercase letters and given a target letter target find the smallest element in the list that is larger than the given target letters also wrap around for example if the target is target z and letters a b the answer is a input letters c f j target a output c input letters c f j target c output f input letters c f j target d output f reference https leetcode comproblemsfindsmallestlettergreaterthantargetdescription using bisect libarary using binary search complexity ologn brute force complexity on using bisect libarary using binary search complexity o logn brute force complexity o n
import bisect def next_greatest_letter(letters, target): index = bisect.bisect(letters, target) return letters[index % len(letters)] def next_greatest_letter_v1(letters, target): if letters[0] > target: return letters[0] if letters[len(letters) - 1] <= target: return letters[0] left, right = 0, len(letters) - 1 while left <= right: mid = left + (right - left) // 2 if letters[mid] > target: right = mid - 1 else: left = mid + 1 return letters[left] def next_greatest_letter_v2(letters, target): for index in letters: if index > target: return index return letters[0]
helper methods for implementing insertion sort given a sorted array and a target value return the index if the target is found if not return the index where it would be if it were inserted in order for example 1 3 5 6 5 2 1 3 5 6 2 1 1 3 5 6 7 4 1 3 5 6 0 0 given a sorted array and a target value return the index if the target is found if not return the index where it would be if it were inserted in order for example 1 3 5 6 5 2 1 3 5 6 2 1 1 3 5 6 7 4 1 3 5 6 0 0
def search_insert(array, val): low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: low = mid + 1 else: high = mid - 1 return low
given an array of integers nums sorted in ascending order find the starting and ending position of a given target value if the target is not found in the array return 1 1 for example input nums 5 7 7 8 8 8 10 target 8 output 3 5 input nums 5 7 7 8 8 8 10 target 11 output 1 1 type nums listint type target int rtype listint breaks at low high both pointing to first occurence of target type nums list int type target int rtype list int breaks at low high both pointing to first occurence of target
def search_range(nums, target): low = 0 high = len(nums) - 1 while low < high: mid = low + (high - low) // 2 if target <= nums[mid]: high = mid else: low = mid + 1 for j in range(len(nums) - 1, -1, -1): if nums[j] == target: return [low, j] return [-1, -1]
search in rotated sorted array suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand i e 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 you are given a target value to search if found in the array return its index otherwise return 1 your algorithm s runtime complexity must be in the order of olog n explanation algorithm in classic binary search we compare val with the midpoint to figure out if val belongs on the low or the high side the complication here is that the array is rotated and may have an inflection point consider for example array1 10 15 20 0 5 array2 50 5 20 30 40 note that both arrays have a midpoint of 20 but 5 appears on the left side of one and on the right side of the other therefore comparing val with the midpoint is insufficient however if we look a bit deeper we can see that one half of the array must be ordered normallyincreasing order we can therefore look at the normally ordered half to determine whether we should search the low or hight side for example if we are searching for 5 in array1 we can look at the left element 10 and middle element 20 since 10 20 the left half must be ordered normally and since 5 is not between those we know that we must search the right half in array2 we can see that since 50 20 the right half must be ordered normally we turn to the middle 20 and right 40 element to check if 5 would fall between them the value 5 would not therefore we search the left half there are 2 possible solution iterative and recursion recursion helps you understand better the above algorithm explanation finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot recursion technique finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot recursion technique finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot found element search left search right search right search left
def search_rotate(array, val): low, high = 0, len(array) - 1 while low <= high: mid = (low + high) // 2 if val == array[mid]: return mid if array[low] <= array[mid]: if array[low] <= val <= array[mid]: high = mid - 1 else: low = mid + 1 else: if array[mid] <= val <= array[high]: low = mid + 1 else: high = mid - 1 return -1 def search_rotate_recur(array, low, high, val): if low >= high: return -1 mid = (low + high) // 2 if val == array[mid]: return mid if array[low] <= array[mid]: if array[low] <= val <= array[mid]: return search_rotate_recur(array, low, mid - 1, val) return search_rotate_recur(array, mid + 1, high, val) if array[mid] <= val <= array[high]: return search_rotate_recur(array, mid + 1, high, val) return search_rotate_recur(array, low, mid - 1, val)
ternary search is a divide and conquer algorithm that can be used to find an element in an array it is similar to binary search where we divide the array into two parts but in this algorithm we divide the given array into three parts and determine which has the key searched element we can divide the array into three parts by taking mid1 and mid2 initially l and r will be equal to 0 and n1 respectively where n is the length of the array mid1 l rl3 mid2 r rl3 note array needs to be sorted to perform ternary search on it tn olog3n log3 log base 3 find the given value key in an array sorted in ascending order returns the index of the value if found and 1 otherwise if the index is not in the range left right ie left index right returns 1 key lies between l and mid1 key lies between mid2 and r key lies between mid1 and mid2 key not found find the given value key in an array sorted in ascending order returns the index of the value if found and 1 otherwise if the index is not in the range left right ie left index right returns 1 key lies between l and mid1 key lies between mid2 and r key lies between mid1 and mid2 key not found
def ternary_search(left, right, key, arr): while right >= left: mid1 = left + (right-left) // 3 mid2 = right - (right-left) // 3 if key == arr[mid1]: return mid1 if key == mid2: return mid2 if key < arr[mid1]: right = mid1 - 1 elif key > arr[mid2]: left = mid2 + 1 else: left = mid1 + 1 right = mid2 - 1 return -1
given an array of integers that is already sorted in ascending order find two numbers such that they add up to a specific target number the function twosum should return indices of the two numbers such that they add up to the target where index1 must be less than index2 please note that your returned answers both index1 and index2 are not zerobased you may assume that each input would have exactly one solution and you may not use the same element twice input numbers 2 7 11 15 target9 output index1 1 index2 2 solution twosum using binary search twosum1 using dictionary as a hash table twosum2 using two pointers given a list of numbers sorted in ascending order find the indices of two numbers such that their sum is the given target using binary search given a list of numbers find the indices of two numbers such that their sum is the given target using a hash table given a list of numbers sorted in ascending order find the indices of two numbers such that their sum is the given target using a bidirectional linear search given a list of numbers sorted in ascending order find the indices of two numbers such that their sum is the given target using binary search given a list of numbers find the indices of two numbers such that their sum is the given target using a hash table given a list of numbers sorted in ascending order find the indices of two numbers such that their sum is the given target using a bidirectional linear search pointer 1 holds from left of array numbers pointer 2 holds from right of array numbers
def two_sum(numbers, target): for i, number in enumerate(numbers): second_val = target - number low, high = i+1, len(numbers)-1 while low <= high: mid = low + (high - low) // 2 if second_val == numbers[mid]: return [i + 1, mid + 1] if second_val > numbers[mid]: low = mid + 1 else: high = mid - 1 return None def two_sum1(numbers, target): dic = {} for i, num in enumerate(numbers): if target - num in dic: return [dic[target - num] + 1, i + 1] dic[num] = i return None def two_sum2(numbers, target): left = 0 right = len(numbers) - 1 while left < right: current_sum = numbers[left] + numbers[right] if current_sum == target: return [left + 1, right + 1] if current_sum > target: right = right - 1 else: left = left + 1
given a list of words return the words that can be typed using letters of alphabet on only one row s of american keyboard for example input hello alaska dad peace output alaska dad reference https leetcode comproblemskeyboardrowdescription type words liststr rtype liststr type words list str rtype list str
def find_keyboard_row(words): keyboard = [ set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm'), ] result = [] for word in words: for key in keyboard: if set(word.lower()).issubset(key): result.append(word) return result
usrbinenv python3 design a data structure that supports all following operations in average o1 time insertval inserts an item val to the set if not already present removeval removes an item val from the set if present randomelement returns a random element from current set of elements each element must have the same probability of being returned idea shoot remove a half usr bin env python3 design a data structure that supports all following operations in average o 1 time insert val inserts an item val to the set if not already present remove val removes an item val from the set if present random_element returns a random element from current set of elements each element must have the same probability of being returned idea shoot element index remove a half
import random class RandomizedSet(): def __init__(self): self.elements = [] self.index_map = {} def insert(self, new_one): if new_one in self.index_map: return self.index_map[new_one] = len(self.elements) self.elements.append(new_one) def remove(self, old_one): if not old_one in self.index_map: return index = self.index_map[old_one] last = self.elements.pop() self.index_map.pop(old_one) if index == len(self.elements): return self.elements[index] = last self.index_map[last] = index def random_element(self): return random.choice(self.elements) def __test(): rset = RandomizedSet() ground_truth = set() n = 64 for i in range(n): rset.insert(i) ground_truth.add(i) for i in random.sample(range(n), n // 2): rset.remove(i) ground_truth.remove(i) print(len(ground_truth), len(rset.elements), len(rset.index_map)) for i in ground_truth: assert(i == rset.elements[rset.index_map[i]]) for i in range(n): print(rset.random_element(), end=' ') print() if __name__ == "__main__": __test()
universe u of n elements collection of subsets of u s s1 s2 sm where every substet si has an associated cost find a minimum cost subcollection of s that covers all elements of u example u 1 2 3 4 5 s s1 s2 s3 s1 4 1 3 costs1 5 s2 2 5 costs2 10 s3 1 4 3 2 costs3 3 output set cover s2 s3 min cost 13 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 org3libraryitertools htmlitertoolsrecipes optimal algorithm dont use on big inputs o2n 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 s2 cost approximate greedy algorithm for setcovering 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 elements don t cover universe invalid input for set cover track elements of universe covered find set with minimum cost elementsadded ratio set may have same elements as already covered newelements 0 check to avoid division by 0 error union universe u of n elements collection of subsets of u s s1 s2 sm where every substet si has an associated cost find a minimum cost subcollection of s that covers all elements of u example u 1 2 3 4 5 s s1 s2 s3 s1 4 1 3 cost s1 5 s2 2 5 cost s2 10 s3 1 4 3 2 cost s3 3 output set cover s2 s3 min cost 13 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 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 s2 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 elements don t cover universe invalid input for set cover track elements of universe covered find set with minimum cost elements_added ratio set may have same elements as already covered new_elements 0 check to avoid division by 0 error union
from itertools import chain, combinations def powerset(iterable): "list(powerset([1,2,3])) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) def optimal_set_cover(universe, subsets, costs): pset = powerset(subsets.keys()) best_set = None best_cost = float("inf") for subset in pset: covered = set() cost = 0 for s in subset: covered.update(subsets[s]) cost += costs[s] if len(covered) == len(universe) and cost < best_cost: best_set = subset best_cost = cost return best_set def greedy_set_cover(universe, subsets, costs): elements = set(e for s in subsets.keys() for e in subsets[s]) if elements != universe: return None covered = set() cover_sets = [] while covered != universe: min_cost_elem_ratio = float("inf") min_set = None for s, elements in subsets.items(): new_elements = len(elements - covered) if new_elements != 0: cost_elem_ratio = costs[s] / new_elements if cost_elem_ratio < min_cost_elem_ratio: min_cost_elem_ratio = cost_elem_ratio min_set = s cover_sets.append(min_set) covered |= subsets[min_set] return cover_sets if __name__ == '__main__': universe = {1, 2, 3, 4, 5} subsets = {'S1': {4, 1, 3}, 'S2': {2, 5}, 'S3': {1, 4, 3, 2}} costs = {'S1': 5, 'S2': 10, 'S3': 3} optimal_cover = optimal_set_cover(universe, subsets, costs) optimal_cost = sum(costs[s] for s in optimal_cover) greedy_cover = greedy_set_cover(universe, subsets, costs) greedy_cost = sum(costs[s] for s in greedy_cover) print('Optimal Set Cover:') print(optimal_cover) print('Cost = %s' % optimal_cost) print('Greedy Set Cover:') print(greedy_cover) print('Cost = %s' % greedy_cost)
bitonic sort is sorting algorithm to use multiple process but this code not containing parallel process it can sort only array that sizes power of 2 it can sort array in both increasing order and decreasing order by giving argument trueincreasing and falsedecreasing worstcase in parallel ologn2 worstcase in nonparallel onlogn2 reference https en wikipedia orgwikibitonicsorter end of functioncompare and bitionicmerge definition checks if n is power of two bitonic sort is sorting algorithm to use multiple process but this code not containing parallel process it can sort only array that sizes power of 2 it can sort array in both increasing order and decreasing order by giving argument true increasing and false decreasing worst case in parallel o log n 2 worst case in non parallel o nlog n 2 reference https en wikipedia org wiki bitonic_sorter end of function compare and bitionic_merge definition checks if n is power of two
def bitonic_sort(arr, reverse=False): def compare(arr, reverse): n = len(arr)//2 for i in range(n): if reverse != (arr[i] > arr[i+n]): arr[i], arr[i+n] = arr[i+n], arr[i] return arr def bitonic_merge(arr, reverse): n = len(arr) if n <= 1: return arr arr = compare(arr, reverse) left = bitonic_merge(arr[:n // 2], reverse) right = bitonic_merge(arr[n // 2:], reverse) return left + right n = len(arr) if n <= 1: return arr if not (n and (not(n & (n - 1))) ): raise ValueError("the size of input should be power of two") left = bitonic_sort(arr[:n // 2], True) right = bitonic_sort(arr[n // 2:], False) arr = bitonic_merge(left + right, reverse) return arr
bogo sort best case complexity on worst case complexity o average case complexity onn1 check the array is inorder bogo sort best case complexity o n worst case complexity o average case complexity o n n 1 check the array is inorder
import random def bogo_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) def is_sorted(arr): i = 0 arr_len = len(arr) while i+1 < arr_len: if arr[i] > arr[i+1]: return False i += 1 return True while not is_sorted(arr): random.shuffle(arr) if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) return arr
https en wikipedia orgwikibubblesort worstcase performance on2 if you call bubblesortarr true you can see the process of the sort default is simulation false
def bubble_sort(arr, simulation=False): def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) swapped = True iteration = 0 if simulation: print("iteration",iteration,":",*arr) x = -1 while swapped: swapped = False x = x + 1 for i in range(1, n-x): if arr[i - 1] > arr[i]: swap(i - 1, i) swapped = True if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) return arr
bucket sort complexity on2 the complexity is dominated by nextsort the number of buckets and make buckets assign values into bucketsort sort we will use insertion sort here bucket sort complexity o n 2 the complexity is dominated by nextsort the number of buckets and make buckets assign values into bucket_sort sort we will use insertion sort here
def bucket_sort(arr): num_buckets = len(arr) buckets = [[] for bucket in range(num_buckets)] for value in arr: index = value * num_buckets // (max(arr) + 1) buckets[index].append(value) sorted_list = [] for i in range(num_buckets): sorted_list.extend(next_sort(buckets[i])) return sorted_list def next_sort(arr): for i in range(1, len(arr)): j = i - 1 key = arr[i] while arr[j] > key and j >= 0: arr[j+1] = arr[j] j = j - 1 arr[j + 1] = key return arr
cocktailshakersort sorting a given array mutation of bubble sort reference https en wikipedia orgwikicocktailshakersort worstcase performance on2 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): def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) swapped = True while swapped: swapped = False for i in range(1, n): if arr[i - 1] > arr[i]: swap(i - 1, i) swapped = True if swapped == False: return arr swapped = False for i in range(n-1,0,-1): if arr[i - 1] > arr[i]: swap(i - 1, i) swapped = True return arr
https en wikipedia orgwikicombsort worstcase performance on2
def comb_sort(arr): def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) gap = n shrink = 1.3 sorted = False while not sorted: gap = int(gap / shrink) if gap > 1: sorted = False else: gap = 1 sorted = True i = 0 while i + gap < n: if arr[i] > arr[i + gap]: swap(i, i + gap) sorted = False i = i + 1 return arr
countingsort sorting a array which has no element greater than k creating a new temparr where temparri 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 resultarr return the resultarr complexity 0n in case there are negative elements change the array to all positive element save the change so that we can convert the array back to all positive number temparrayi contain the times the number i appear in arr temparrayi contain the number of element less than or equal i in arr creating a resultarr an put the element in a correct positon 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 in case there are negative elements change the array to all positive element save the change so that we can convert the array back to all positive number temp_array i contain the times the number i appear in arr temp_array i contain the number of element less than or equal i in arr creating a result_arr an put the element in a correct positon
def counting_sort(arr): m = min(arr) different = 0 if m < 0: different = -m for i in range(len(arr)): arr[i] += -m k = max(arr) temp_arr = [0] * (k + 1) for i in range(0, len(arr)): temp_arr[arr[i]] = temp_arr[arr[i]] + 1 for i in range(1, k + 1): temp_arr[i] = temp_arr[i] + temp_arr[i - 1] result_arr = arr.copy() for i in range(len(arr) - 1, -1, -1): result_arr[temp_arr[arr[i]] - 1] = arr[i] - different temp_arr[arr[i]] = temp_arr[arr[i]] - 1 return result_arr
cyclesort 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 orgwikicyclesort average time complexity on2 worst case time complexity on2 finding cycle to rotate finding an indx to put items in case of there is not a cycle putting the item immediately right after the duplicate item or on the right rotating the remaining cycle finding where to put the item after item is duplicated put it in place or put it there 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 finding cycle to rotate finding an indx to put items in case of there is not a cycle putting the item immediately right after the duplicate item or on the right rotating the remaining cycle finding where to put the item after item is duplicated put it in place or put it there
def cycle_sort(arr): len_arr = len(arr) for cur in range(len_arr - 1): item = arr[cur] index = cur for i in range(cur + 1, len_arr): if arr[i] < item: index += 1 if index == cur: continue while item == arr[index]: index += 1 arr[index], item = item, arr[index] while index != cur: index = cur for i in range(cur + 1, len_arr): if arr[i] < item: index += 1 while item == arr[index]: index += 1 arr[index], item = item, arr[index] return arr
reference https en wikipedia orgwikisortingalgorithmexchangesort complexity on2 reference https en wikipedia org wiki sorting_algorithm exchange_sort complexity o n 2
def exchange_sort(arr): arr_len = len(arr) for i in range(arr_len-1): for j in range(i+1, arr_len): if(arr[i] > arr[j]): arr[i], arr[j] = arr[j], arr[i] return arr
gnome sort best case performance is on worst case performance is on2
def gnome_sort(arr): n = len(arr) index = 0 while index < n: if index == 0 or arr[index] >= arr[index-1]: index = index + 1 else: arr[index], arr[index-1] = arr[index-1], arr[index] index = index - 1 return arr
heap sort that uses a max heap to sort an array in ascending order complexity on logn max heapify helper for maxheapsort iterate from last parent to first iterate from currentparent to lastparent find greatest child of currentparent swap if child is greater than parent if no swap occurred no need to keep iterating heap sort that uses a min heap to sort an array in ascending order complexity on logn min heapify helper for minheapsort offset lastparent by the start lastparent calculated as if start index was 0 all array accesses need to be offset by start iterate from last parent to first iterate from currentparent to lastparent find lesser child of currentparent swap if child is less than parent if no swap occurred no need to keep iterating heap sort that uses a max heap to sort an array in ascending order complexity o n log n max heapify helper for max_heap_sort iterate from last parent to first iterate from current_parent to last_parent find greatest child of current_parent swap if child is greater than parent if no swap occurred no need to keep iterating heap sort that uses a min heap to sort an array in ascending order complexity o n log n 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 iterate from last parent to first iterate from current_parent to last_parent find lesser child of current_parent swap if child is less than parent if no swap occurred no need to keep iterating
def max_heap_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr) - 1, 0, -1): iteration = max_heapify(arr, i, simulation, iteration) if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) return arr def max_heapify(arr, end, simulation, iteration): last_parent = (end - 1) // 2 for parent in range(last_parent, -1, -1): current_parent = parent while current_parent <= last_parent: child = 2 * current_parent + 1 if child + 1 <= end and arr[child] < arr[child + 1]: child = child + 1 if arr[child] > arr[current_parent]: arr[current_parent], arr[child] = arr[child], arr[current_parent] current_parent = child if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) else: break arr[0], arr[end] = arr[end], arr[0] return iteration def min_heap_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(0, len(arr) - 1): iteration = min_heapify(arr, i, simulation, iteration) return arr def min_heapify(arr, start, simulation, iteration): end = len(arr) - 1 last_parent = (end - start - 1) // 2 for parent in range(last_parent, -1, -1): current_parent = parent while current_parent <= last_parent: child = 2 * current_parent + 1 if child + 1 <= end - start and arr[child + start] > arr[ child + 1 + start]: child = child + 1 if arr[child + start] < arr[current_parent + start]: arr[current_parent + start], arr[child + start] = \ arr[child + start], arr[current_parent + start] current_parent = child if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) else: break return iteration
insertion sort complexity on2 swap the number down the list break and do the final swap insertion sort complexity o n 2 swap the number down the list break and do the final swap
def insertion_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cursor: arr[pos] = arr[pos - 1] pos = pos - 1 arr[pos] = cursor if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) return arr
given an array of meeting time intervals consisting of start and end times s1 e1 s2 e2 si ei determine if a person could attend all meetings for example given 0 30 5 10 15 20 return false type intervals listinterval rtype bool type intervals list interval rtype bool
def can_attend_meetings(intervals): intervals = sorted(intervals, key=lambda x: x.start) for i in range(1, len(intervals)): if intervals[i].start < intervals[i - 1].end: return False return True
merge sort complexity on logn our recursive base case perform mergesort recursively on both halves merge each side together return mergeleft right arr copy changed no need to copy mutate inplace merge helper complexity on sort each one and place into the result add the left overs if there s any left to the result add the left overs if there s any left to the result return result return merged do not return anything as it is replacing inplace merge sort complexity o n log n our recursive base case perform merge_sort recursively on both halves merge each side together return merge left right arr copy changed no need to copy mutate inplace merge helper complexity o n sort each one and place into the result add the left overs if there s any left to the result add the left overs if there s any left to the result return result return merged do not return anything as it is replacing inplace
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:]) merge(left,right,arr) return arr def merge(left, right, merged): left_cursor, right_cursor = 0, 0 while left_cursor < len(left) and right_cursor < len(right): if left[left_cursor] <= right[right_cursor]: merged[left_cursor+right_cursor]=left[left_cursor] left_cursor += 1 else: merged[left_cursor + right_cursor] = right[right_cursor] right_cursor += 1 for left_cursor in range(left_cursor, len(left)): merged[left_cursor + right_cursor] = left[left_cursor] for right_cursor in range(right_cursor, len(right)): merged[left_cursor + right_cursor] = right[right_cursor]
pancakesort sorting a given array mutation of selection sort reference https www geeksforgeeks orgpancakesorting overall time complexity on2 finding index of maximum number in arr needs moving reverse from 0 to indexmax reverse list pancake_sort sorting a given array mutation of selection sort reference https www geeksforgeeks org pancake sorting overall time complexity o n 2 finding index of maximum number in arr needs moving reverse from 0 to index_max reverse list
def pancake_sort(arr): len_arr = len(arr) if len_arr <= 1: return arr for cur in range(len(arr), 1, -1): index_max = arr.index(max(arr[0:cur])) if index_max+1 != cur: if index_max != 0: arr[:index_max+1] = reversed(arr[:index_max+1]) arr[:cur] = reversed(arr[:cur]) return arr
https en wikipedia orgwikipigeonholesort time complexity on range where n number of elements and range possible values in the array suitable for lists where the number of elements and key values are mostly the same
def pigeonhole_sort(arr): Max = max(arr) Min = min(arr) size = Max - Min + 1 holes = [0]*size for i in arr: holes[i-Min] += 1 i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 arr[i] = count + Min i += 1 return arr
quick sort complexity best on logn avg on logn worst on2 start our two recursive calls quick sort complexity best o n log n avg o n log n worst o n 2 start our two recursive calls last is the pivot
def quick_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) arr, _ = quick_sort_recur(arr, 0, len(arr) - 1, iteration, simulation) return arr def quick_sort_recur(arr, first, last, iteration, simulation): if first < last: pos = partition(arr, first, last) if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) _, iteration = quick_sort_recur(arr, first, pos - 1, iteration, simulation) _, iteration = quick_sort_recur(arr, pos + 1, last, iteration, simulation) return arr, iteration def partition(arr, first, last): wall = first for pos in range(first, last): if arr[pos] < arr[last]: arr[pos], arr[wall] = arr[wall], arr[pos] wall += 1 arr[wall], arr[last] = arr[last], arr[wall] return wall
radix sort complexity onk n n is the size of input list and k is the digit length of the number
def radix_sort(arr, simulation=False): position = 1 max_number = max(arr) iteration = 0 if simulation: print("iteration", iteration, ":", *arr) while position <= max_number: queue_list = [list() for _ in range(10)] for num in arr: digit_number = num // position % 10 queue_list[digit_number].append(num) index = 0 for numbers in queue_list: for num in numbers: arr[index] = num index += 1 if simulation: iteration = iteration + 1 print("iteration", iteration, ":", *arr) position *= 10 return arr
selection sort complexity on2 select the correct value selection sort complexity o n 2 select the correct value
def selection_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): if arr[j] < arr[minimum]: minimum = j arr[minimum], arr[i] = arr[i], arr[minimum] if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) return arr
shell sort complexity on2 initialize size of the gap shell sort complexity o n 2 initialize size of the gap
def shell_sort(arr): n = len(arr) gap = n//2 while gap > 0: y_index = gap while y_index < len(arr): y = arr[y_index] x_index = y_index - gap while x_index >= 0 and y < arr[x_index]: arr[x_index + gap] = arr[x_index] x_index = x_index - gap arr[x_index + gap] = y y_index = y_index + 1 gap = gap//2 return arr
given an array with n objects colored red white or blue sort them so that objects of the same color are adjacent with the colors in the order red white and blue here we will use the integers 0 1 and 2 to represent the color red white and blue respectively note you are not suppose to use the library s sort function for this problem
def sort_colors(nums): i = j = 0 for k in range(len(nums)): v = nums[k] nums[k] = 2 if v < 2: nums[j] = 1 j += 1 if v == 0: nums[i] = 0 i += 1 if __name__ == "__main__": nums = [0, 1, 1, 1, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 2, 2] sort_colors(nums) print(nums)
stooge sort time complexity on2 709 reference https www geeksforgeeks orgstoogesort if first element is smaller than last swap them if there are more than 2 elements in the array recursively sort first 2 3 elements recursively sort last 2 3 elements recursively sort first 2 3 elements again to confirm if first element is smaller than last swap them if there are more than 2 elements in the array recursively sort first 2 3 elements recursively sort last 2 3 elements recursively sort first 2 3 elements again to confirm
def stoogesort(arr, l, h): if l >= h: return if arr[l]>arr[h]: t = arr[l] arr[l] = arr[h] arr[h] = t if h-l + 1 > 2: t = (int)((h-l + 1)/3) stoogesort(arr, l, (h-t)) stoogesort(arr, l + t, (h)) stoogesort(arr, l, (h-t)) if __name__ == "__main__": array = [1,3,64,5,7,8] n = len(array) stoogesort(array, 0, n-1) for i in range(0, n): print(array[i], end = ' ')
time complexity is the same as dfs which is ov e space complexity ov printnode time complexity is the same as dfs which is ov e space complexity ov time complexity is the same as dfs which is o v e space complexity o v print node time complexity is the same as dfs which is o v e space complexity o v
GRAY, BLACK = 0, 1 def top_sort_recursive(graph): order, enter, state = [], set(graph), {} def dfs(node): state[node] = GRAY for k in graph.get(node, ()): sk = state.get(k, None) if sk == GRAY: raise ValueError("cycle") if sk == BLACK: continue enter.discard(k) dfs(k) order.append(node) state[node] = BLACK while enter: dfs(enter.pop()) return order def top_sort(graph): order, enter, state = [], set(graph), {} def is_ready(node): lst = graph.get(node, ()) if len(lst) == 0: return True for k in lst: sk = state.get(k, None) if sk == GRAY: raise ValueError("cycle") if sk != BLACK: return False return True while enter: node = enter.pop() stack = [] while True: state[node] = GRAY stack.append(node) for k in graph.get(node, ()): sk = state.get(k, None) if sk == GRAY: raise ValueError("cycle") if sk == BLACK: continue enter.discard(k) stack.append(k) while stack and is_ready(stack[-1]): node = stack.pop() order.append(node) state[node] = BLACK if len(stack) == 0: break node = stack.pop() return order
given an unsorted array nums reorder it such that nums0 nums1 nums2 nums3
def wiggle_sort(nums): for i in range(len(nums)): if (i % 2 == 1) == (nums[i-1] > nums[i]): nums[i-1], nums[i] = nums[i], nums[i-1] if __name__ == "__main__": array = [3, 5, 2, 1, 6, 4] print(array) wiggle_sort(array) print(array)
given a stack a function isconsecutive takes a stack as a parameter and that returns whether or not the stack contains a sequence of consecutive integers starting from the bottom of the stack returning true if it does returning false if it does not for example bottom 3 4 5 6 7 top then the call of isconsecutives should return true bottom 3 4 6 7 top then the call of isconsecutives should return false bottom 3 2 1 top the function should return false due to reverse order note there are 2 solutions firstisconsecutive it uses a single stack as auxiliary storage secondisconsecutive it uses a single queue as auxiliary storage back up stack from storage stack back up stack from queue case odd number of values in stack not consecutive backup second value back up stack from storage stack case odd number of values in stack not consecutive backup second value back up stack from queue
import collections def first_is_consecutive(stack): storage_stack = [] for i in range(len(stack)): first_value = stack.pop() if len(stack) == 0: return True second_value = stack.pop() if first_value - second_value != 1: return False stack.append(second_value) storage_stack.append(first_value) for i in range(len(storage_stack)): stack.append(storage_stack.pop()) return True def second_is_consecutive(stack): q = collections.deque() for i in range(len(stack)): first_value = stack.pop() if len(stack) == 0: return True second_value = stack.pop() if first_value - second_value != 1: return False stack.append(second_value) q.append(first_value) for i in range(len(q)): stack.append(q.pop()) for i in range(len(stack)): q.append(stack.pop()) for i in range(len(q)): stack.append(q.pop()) return True
given a stack a function issorted accepts a stack as a parameter and returns true if the elements in the stack occur in ascending increasing order from bottom and false otherwise that is the smallest element should be at bottom for example bottom 6 3 5 1 2 4 top the function should return false bottom 1 2 3 4 5 6 top the function should return true backup stack backup stack
def is_sorted(stack): storage_stack = [] for i in range(len(stack)): if len(stack) == 0: break first_val = stack.pop() if len(stack) == 0: break second_val = stack.pop() if first_val < second_val: return False storage_stack.append(first_val) stack.append(second_val) for i in range(len(storage_stack)): stack.append(storage_stack.pop()) return True
def lengthlongestpathinput maxlen 0 pathlen 0 0 for line in input splitlines print printline line name line strip t printname name depth lenline lenname printdepth depth if in name maxlen maxmaxlen pathlendepth lenname else pathlendepth 1 pathlendepth lenname 1 printmaxlen maxlen return maxlen def lengthlongestpathinput paths input splitn level 0 10 maxlength 0 for path in paths print levelidx path rfindt printpath path printpath rfindt path rfindt printlevelidx levelidx printlevel level levellevelidx 1 levellevelidx lenpath levelidx 1 printlevel level if in path maxlength maxmaxlength levellevelidx1 1 printmaxlen maxlength return maxlength type input str rtype int def lengthlongestpath input maxlen 0 pathlen 0 0 for line in input splitlines print print line line name line strip t print name name depth len line len name print depth depth if in name maxlen max maxlen pathlen depth len name else pathlen depth 1 pathlen depth len name 1 print maxlen maxlen return maxlen def lengthlongestpath input paths input split n level 0 10 maxlength 0 for path in paths print levelidx path rfind t print path path print path rfind t path rfind t print levelidx levelidx print level level level levelidx 1 level levelidx len path levelidx 1 print level level if in path maxlength max maxlength level levelidx 1 1 print maxlen maxlength return maxlength type input str rtype int running length and max length keep track of the name length the depth of current dir or file go back to the correct depth 1 is the length of increase current length update maxlen only when it is a file 1 is to minus one
def length_longest_path(input): curr_len, max_len = 0, 0 stack = [] for s in input.split('\n'): print("---------") print("<path>:", s) depth = s.count('\t') print("depth: ", depth) print("stack: ", stack) print("curlen: ", curr_len) while len(stack) > depth: curr_len -= stack.pop() stack.append(len(s.strip('\t'))+1) curr_len += stack[-1] print("stack: ", stack) print("curlen: ", curr_len) if '.' in s: max_len = max(max_len, curr_len-1) return max_len st = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdirectory1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" st2 = "a\n\tb1\n\t\tf1.txt\n\taaaaa\n\t\tf2.txt" print("path:", st2) print("answer:", length_longest_path(st2))
the stack remains always ordered such that the highest value is at the top and the lowest at the bottom push method to maintain order when pushing new elements the stack remains always ordered such that the highest value is at the top and the lowest at the bottom push method to maintain order when pushing new elements
class OrderedStack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push_t(self, item): self.items.append(item) def push(self, item): temp_stack = OrderedStack() if self.is_empty() or item > self.peek(): self.push_t(item) else: while item < self.peek() and not self.is_empty(): temp_stack.push_t(self.pop()) self.push_t(item) while not temp_stack.is_empty(): self.push_t(temp_stack.pop()) def pop(self): if self.is_empty(): raise IndexError("Stack is empty") return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items)
given a stack a function removemin accepts a stack as a parameter and removes the smallest value from the stack for example bottom 2 8 3 6 7 3 top after removeminstack bottom 2 8 3 7 3 top find the smallest value back up stack and remove min value stack is empty find the smallest value back up stack and remove min value
def remove_min(stack): storage_stack = [] if len(stack) == 0: return stack min = stack.pop() stack.append(min) for i in range(len(stack)): val = stack.pop() if val <= min: min = val storage_stack.append(val) for i in range(len(storage_stack)): val = storage_stack.pop() if val != min: stack.append(val) return stack
given an absolute path for a file unixstyle simplify it for example path home home path a b c c did you consider the case where path in this case you should return another corner case is the path might contain multiple slashes together such as homefoo in this case you should ignore redundant slashes and return homefoo type path str rtype str type path str rtype str
def simplify_path(path): skip = {'..', '.', ''} stack = [] paths = path.split('/') for tok in paths: if tok == '..': if stack: stack.pop() elif tok not in skip: stack.append(tok) return '/' + '/'.join(stack)
stack abstract data type adt stack creates a new stack that is empty it needs no parameters and returns an empty stack pushitem adds a new item to the top of the stack it needs the item and returns nothing pop removes the top item from the stack it needs no parameters and returns the item the stack is modified peek returns the top item from the stack but does not remove it it needs no parameters the stack is not modified isempty tests to see whether the stack is empty it needs no parameters and returns a boolean value abstract class for stacks def initself self top 1 def lenself return self top 1 def strself result joinmapstr self return top result def isemptyself return self top 1 abstractmethod def iterself pass abstractmethod def pushself value pass abstractmethod def popself pass abstractmethod def peekself pass class arraystackabstractstack def initself size10 super init self array none size def iterself probe self top while true if probe 1 return yield self arrayprobe probe 1 def pushself value self top 1 if self top lenself array self expand self arrayself top value def popself if self isempty raise indexerrorstack is empty value self arrayself top self top 1 return value def peekself expands size of the array time complexity on represents a single stack node def initself value self value value self next none class linkedliststackabstractstack def initself super init self head none def iterself probe self head while true if probe is none return yield probe value probe probe next def pushself value node stacknodevalue node next self head self head node self top 1 def popself if self isempty raise indexerrorstack is empty value self head value self head self head next self top 1 return value def peekself if self isempty raise indexerrorstack is empty return self head value abstract class for stacks initialize python list with size of 10 or user given input python list type is a dynamic array so we have to restrict its dynamic nature to make it work like a static array returns the current top element of the stack expands size of the array time complexity o n double the size of the array represents a single stack node
from abc import ABCMeta, abstractmethod class AbstractStack(metaclass=ABCMeta): def __init__(self): self._top = -1 def __len__(self): return self._top + 1 def __str__(self): result = " ".join(map(str, self)) return 'Top-> ' + result def is_empty(self): return self._top == -1 @abstractmethod def __iter__(self): pass @abstractmethod def push(self, value): pass @abstractmethod def pop(self): pass @abstractmethod def peek(self): pass class ArrayStack(AbstractStack): def __init__(self, size=10): super().__init__() self._array = [None] * size def __iter__(self): probe = self._top while True: if probe == -1: return yield self._array[probe] probe -= 1 def push(self, value): self._top += 1 if self._top == len(self._array): self._expand() self._array[self._top] = value def pop(self): if self.is_empty(): raise IndexError("Stack is empty") value = self._array[self._top] self._top -= 1 return value def peek(self): if self.is_empty(): raise IndexError("Stack is empty") return self._array[self._top] def _expand(self): self._array += [None] * len(self._array) class StackNode: def __init__(self, value): self.value = value self.next = None class LinkedListStack(AbstractStack): def __init__(self): super().__init__() self.head = None def __iter__(self): probe = self.head while True: if probe is None: return yield probe.value probe = probe.next def push(self, value): node = StackNode(value) node.next = self.head self.head = node self._top += 1 def pop(self): if self.is_empty(): raise IndexError("Stack is empty") value = self.head.value self.head = self.head.next self._top -= 1 return value def peek(self): if self.is_empty(): raise IndexError("Stack is empty") return self.head.value
given a stack stutter takes a stack as a parameter and replaces every value in the stack with two occurrences of that value for example suppose the stack stores these values bottom 3 7 1 14 9 top then the stack should store these values after the method terminates bottom 3 3 7 7 1 1 14 14 9 9 top note there are 2 solutions firststutter it uses a single stack as auxiliary storage secondstutter it uses a single queue as auxiliary storage put all values into queue from stack put values back into stack from queue now stack is reverse put all values into queue from stack put 2 times value into stack from queue put all values into queue from stack put values back into stack from queue now stack is reverse put all values into queue from stack put 2 times value into stack from queue
import collections def first_stutter(stack): storage_stack = [] for i in range(len(stack)): storage_stack.append(stack.pop()) for i in range(len(storage_stack)): val = storage_stack.pop() stack.append(val) stack.append(val) return stack def second_stutter(stack): q = collections.deque() for i in range(len(stack)): q.append(stack.pop()) for i in range(len(q)): stack.append(q.pop()) for i in range(len(stack)): q.append(stack.pop()) for i in range(len(q)): val = q.pop() stack.append(val) stack.append(val) return stack
given a stack switchpairs function takes a stack as a parameter and that switches successive pairs of numbers starting at the bottom of the stack for example if the stack initially stores these values bottom 3 8 17 9 1 10 top your function should switch the first pair 3 8 the second pair 17 9 bottom 8 3 9 17 10 1 top if there are an odd number of values in the stack the value at the top of the stack is not moved for example bottom 3 8 17 9 1 top it would again switch pairs of values but the value at the top of the stack 1 would not be moved bottom 8 3 9 17 1 top note there are 2 solutions firstswitchpairs it uses a single stack as auxiliary storage secondswitchpairs it uses a single queue as auxiliary storage put all values into queue from stack put values back into stack from queue now stack is reverse put all values into queue from stack swap pairs by appending the 2nd value before appending 1st value case odd number of values in stack put all values into queue from stack put values back into stack from queue now stack is reverse put all values into queue from stack swap pairs by appending the 2nd value before appending 1st value case odd number of values in stack
import collections def first_switch_pairs(stack): storage_stack = [] for i in range(len(stack)): storage_stack.append(stack.pop()) for i in range(len(storage_stack)): if len(storage_stack) == 0: break first = storage_stack.pop() if len(storage_stack) == 0: stack.append(first) break second = storage_stack.pop() stack.append(second) stack.append(first) return stack def second_switch_pairs(stack): q = collections.deque() for i in range(len(stack)): q.append(stack.pop()) for i in range(len(q)): stack.append(q.pop()) for i in range(len(stack)): q.append(stack.pop()) for i in range(len(q)): if len(q) == 0: break first = q.pop() if len(q) == 0: stack.append(first) break second = q.pop() stack.append(second) stack.append(first) return stack
given a string containing just the characters and determine if the input string is valid the brackets must close in the correct order and are all valid but and are not
def is_valid(s: str) -> bool: stack = [] dic = {")": "(", "}": "{", "]": "["} for char in s: if char in dic.values(): stack.append(char) elif char in dic: if not stack or dic[char] != stack.pop(): return False return not stack
implementation of the misragries algorithm given a list of items and a value k it returns the every item in the list that appears at least nk times where n is the length of the array by default k is set to 2 solving the majority problem for the majority problem this algorithm only guarantees that if there is an element that appears more than n2 times it will be outputed if there is no such element any arbitrary element is returned by the algorithm therefore we need to iterate through again at the end but since we have filtred out the suspects the memory complexity is significantly lower than it would be to create counter for every element in the list for example input misrasgries1 4 4 4 5 4 4 output 4 5 input misrasgries0 0 0 1 1 1 1 output 1 4 input misrasgries0 0 0 0 1 1 1 2 2 3 output 0 4 1 3 input misrasgries0 0 0 1 1 1 output none misragries algorithm keyword arguments array list of integers k value of k default 2 misra gries algorithm keyword arguments array list of integers k value of k default 2
def misras_gries(array,k=2): keys = {} for i in array: val = str(i) if val in keys: keys[val] = keys[val] + 1 elif len(keys) < k - 1: keys[val] = 1 else: for key in list(keys): keys[key] = keys[key] - 1 if keys[key] == 0: del keys[key] suspects = keys.keys() frequencies = {} for suspect in suspects: freq = _count_frequency(array,int(suspect)) if freq >= len(array) / k: frequencies[suspect] = freq return frequencies if len(frequencies) > 0 else None def _count_frequency(array,element): return array.count(element)
nonnegative 1sparse recovery problem this algorithm assumes we have a non negative dynamic stream given a stream of tuples where each tuple contains a number and a sign it check if the stream is 1sparse meaning if the elements in the stream cancel eacheother out in such a way that ther is only a unique number at the end examples 1 input 4 2 2 4 3 3 output 4 comment since 2 and 3 gets removed 2 input 2 2 2 2 2 2 2 output 2 comment no other numbers present 3 input 2 2 2 2 2 2 1 output none comment not 1sparse 1sparse algorithm keyword arguments array stream of tuples helper function to check that every entry in the list is either 0 or the same as the sum of signs adds bit representation value to bitsum array 1 sparse algorithm keyword arguments array stream of tuples helper function to check that every entry in the list is either 0 or the same as the sum of signs adds bit representation value to bitsum array
def one_sparse(array): sum_signs = 0 bitsum = [0]*32 sum_values = 0 for val,sign in array: if sign == "+": sum_signs += 1 sum_values += val else: sum_signs -= 1 sum_values -= val _get_bit_sum(bitsum,val,sign) if sum_signs > 0 and _check_every_number_in_bitsum(bitsum,sum_signs): return int(sum_values/sum_signs) else: return None def _check_every_number_in_bitsum(bitsum,sum_signs): for val in bitsum: if val != 0 and val != sum_signs : return False return True def _get_bit_sum(bitsum,val,sign): i = 0 if sign == "+": while val: bitsum[i] += val & 1 i +=1 val >>=1 else : while val: bitsum[i] -= val & 1 i +=1 val >>=1
given two binary strings return their sum also a binary string for example a 11 b 1 return 100
def add_binary(a, b): s = "" c, i, j = 0, len(a)-1, len(b)-1 zero = ord('0') while (i >= 0 or j >= 0 or c == 1): if (i >= 0): c += ord(a[i]) - zero i -= 1 if (j >= 0): c += ord(b[j]) - zero j -= 1 s = chr(c % 2 + zero) + s c //= 2 return s
atbash cipher is mapping the alphabet to it s reverse so if we take a as it is the first letter we change it to the last z example attack at dawn zggzxp zg wzdm complexity on
def atbash(s): translated = "" for i in range(len(s)): n = ord(s[i]) if s[i].isalpha(): if s[i].isupper(): x = n - ord('A') translated += chr(ord('Z') - x) if s[i].islower(): x = n - ord('a') translated += chr(ord('z') - x) else: translated += s[i] return translated
given an api which returns an array of words and an array of symbols display the word with their matched symbol surrounded by square brackets if the word string matches more than one symbol then choose the one with longest length ex microsoft matches i and cro example words array amazon microsoft google symbols i am cro na le abc output amazon microsoft google my solutionwrong i sorted the symbols array in descending order of length and ran loop over words array to find a symbol matchusing indexof in javascript which worked but i didn t make it through the interview i am guessing my solution was on2 and they expected an efficient algorithm output amazon microsoft google amazon microsoft google reversely sort the symbols according to their lengths once match append the wordreplaced to res process next word if this word matches no symbol append it another approach is to use a tree for the dictionary the symbols and then match brute force the complexity will depend on the dictionary if all are suffixes of the other it will be nm where m is the size of the dictionary for example in python reversely sort the symbols according to their lengths once match append the word_replaced to res process next word if this word matches no symbol append it another approach is to use a tree for the dictionary the symbols and then match brute force the complexity will depend on the dictionary if all are suffixes of the other it will be n m where m is the size of the dictionary for example in python
from functools import reduce def match_symbol(words, symbols): import re combined = [] for s in symbols: for c in words: r = re.search(s, c) if r: combined.append(re.sub(s, "[{}]".format(s), c)) return combined def match_symbol_1(words, symbols): res = [] symbols = sorted(symbols, key=lambda _: len(_), reverse=True) for word in words: for symbol in symbols: word_replaced = '' if word.find(symbol) != -1: word_replaced = word.replace(symbol, '[' + symbol + ']') res.append(word_replaced) break if word_replaced == '': res.append(word) return res class TreeNode: def __init__(self): self.c = dict() self.sym = None def bracket(words, symbols): root = TreeNode() for s in symbols: t = root for char in s: if char not in t.c: t.c[char] = TreeNode() t = t.c[char] t.sym = s result = dict() for word in words: i = 0 symlist = list() while i < len(word): j, t = i, root while j < len(word) and word[j] in t.c: t = t.c[word[j]] if t.sym is not None: symlist.append((j + 1 - len(t.sym), j + 1, t.sym)) j += 1 i += 1 if len(symlist) > 0: sym = reduce(lambda x, y: x if x[1] - x[0] >= y[1] - y[0] else y, symlist) result[word] = "{}[{}]{}".format(word[:sym[0]], sym[2], word[sym[1]:]) return tuple(word if word not in result else result[word] for word in words)
julius caesar protected his confidential information by encrypting it using a cipher caesar s cipher shifts each letter by a number of letters if the shift takes you past the end of the alphabet just rotate back to the front of the alphabet in the case of a rotation by 3 w x y and z would map to z a b and c original alphabet abcdefghijklmnopqrstuvwxyz alphabet rotated 3 defghijklmnopqrstuvwxyzabc
def caesar_cipher(s, k): result = "" for char in s: n = ord(char) if 64 < n < 91: n = ((n - 65 + k) % 26) + 65 if 96 < n < 123: n = ((n - 97 + k) % 26) + 97 result = result + chr(n) return result
algorithm that checks if a given string is a pangram or not
def check_pangram(input_string): alphabet = "abcdefghijklmnopqrstuvwxyz" for ch in alphabet: if ch not in input_string.lower(): return False return True
implement strstr return the index of the first occurrence of needle in haystack or 1 if needle is not part of haystack example 1 input haystack hello needle ll output 2 example 2 input haystack aaaaa needle bba output 1 reference https leetcode comproblemsimplementstrstrdescription
def contain_string(haystack, needle): if len(needle) == 0: return 0 if len(needle) > len(haystack): return -1 for i in range(len(haystack)): if len(haystack) - i < len(needle): return -1 if haystack[i:i+len(needle)] == needle: return i return -1
give a string s count the number of nonempty contiguous substrings that have the same number of 0 s and 1 s and all the 0 s and all the 1 s in these substrings are grouped consecutively substrings that occur multiple times are counted the number of times they occur example 1 input 00110011 output 6 explanation there are 6 substrings that have equal number of consecutive 1 s and 0 s 0011 01 1100 10 0011 and 01 notice that some of these substrings repeat and are counted the number of times they occur also 00110011 is not a valid substring because all the 0 s and 1 s are not grouped together example 2 input 10101 output 4 explanation there are 4 substrings 10 01 10 01 that have equal number of consecutive 1 s and 0 s reference https leetcode comproblemscountbinarysubstringsdescription
def count_binary_substring(s): cur = 1 pre = 0 count = 0 for i in range(1, len(s)): if s[i] != s[i - 1]: count = count + min(pre, cur) pre = cur cur = 1 else: cur = cur + 1 count = count + min(pre, cur) return count
given an encoded string return it s decoded string the encoding rule is kencodedstring where the encodedstring inside the square brackets is being repeated exactly k times note that k is guaranteed to be a positive integer you may assume that the input string is always valid no extra white spaces square brackets are wellformed etc furthermore you may assume that the original data does not contain any digits and that digits are only for those repeat numbers k for example there won t be input like 3a or 24 examples s 3a2bc return aaabcbc s 3a2c return accaccacc s 2abc3cdef return abcabccdcdcdef type s str rtype str given an encoded string return it s decoded string the encoding rule is k encoded_string where the encoded_string inside the square brackets is being repeated exactly k times note that k is guaranteed to be a positive integer you may assume that the input string is always valid no extra white spaces square brackets are well formed etc furthermore you may assume that the original data does not contain any digits and that digits are only for those repeat numbers k for example there won t be input like 3a or 2 4 examples s 3 a 2 bc return aaabcbc s 3 a2 c return accaccacc s 2 abc 3 cd ef return abcabccdcdcdef type s str rtype str
def decode_string(s): stack = []; cur_num = 0; cur_string = '' for c in s: if c == '[': stack.append((cur_string, cur_num)) cur_string = '' cur_num = 0 elif c == ']': prev_string, num = stack.pop() cur_string = prev_string + num * cur_string elif c.isdigit(): cur_num = cur_num*10 + int(c) else: cur_string += c return cur_string
question given a string as your input delete any reoccurring character and return the new string this is a google warmup interview question that was asked duirng phone screening at my university time complexity on time complexity o n
def delete_reoccurring_characters(string): seen_characters = set() output_string = '' for char in string: if char not in seen_characters: seen_characters.add(char) output_string += char return output_string
write a function that when given a url as a string parses out just the domain name and returns it as a string examples domainnamehttp github comsaadbenn github domainnamehttp www zombiebites com zombiebites domainnamehttps www cnet com cnet note the idea is not to use any builtin libraries such as re regular expression or urlparse except split builtin function non pythonic way grab only the non https part grab the actual one depending on the len of the list case when www is in the url case when www is not in the url pythonic one liner non pythonic way grab only the non http s part grab the actual one depending on the len of the list case when www is in the url case when www is not in the url pythonic one liner
def domain_name_1(url): full_domain_name = url.split('//')[-1] actual_domain = full_domain_name.split('.') if (len(actual_domain) > 2): return actual_domain[1] return actual_domain[0] def domain_name_2(url): return url.split("//")[-1].split("www.")[-1].split(".")[0]
design an algorithm to encode a list of strings to a string the encoded mystring is then sent over the network and is decoded back to the original list of strings implement the encode and decode methods encodes a list of strings to a single string type strs liststr rtype str decodes a single string to a list of strings type s str rtype liststr implement the encode and decode methods encodes a list of strings to a single string type strs list str rtype str decodes a single string to a list of strings type s str rtype list str
def encode(strs): res = '' for string in strs.split(): res += str(len(string)) + ":" + string return res def decode(s): strs = [] i = 0 while i < len(s): index = s.find(":", i) size = int(s[i:index]) strs.append(s[index+1: index+1+size]) i = index+1+size return strs
given a string find the first nonrepeating character in it and return it s index if it doesn t exist return 1 for example s leetcode return 0 s loveleetcode return 2 reference https leetcode comproblemsfirstuniquecharacterinastringdescription type s str rtype int type s str rtype int
def first_unique_char(s): if (len(s) == 1): return 0 ban = [] for i in range(len(s)): if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban: return i else: ban.append(s[i]) return -1
write a function that returns an array containing the numbers from 1 to n where n is the parametered value n will never be less than 1 replace certain values however if any of the following conditions are met if the value is a multiple of 3 use the value fizz instead if the value is a multiple of 5 use the value buzz instead if the value is a multiple of 3 5 use the value fizzbuzz instead there is no fancy algorithm to solve fizz buzz iterate from 1 through n use the mod operator to determine if the current iteration is divisible by 3 and 5 fizzbuzz 3 fizz 5 buzz else string of current iteration return the results complexity time on space on validate the input alternative solution there is no fancy algorithm to solve fizz buzz iterate from 1 through n use the mod operator to determine if the current iteration is divisible by 3 and 5 fizzbuzz 3 fizz 5 buzz else string of current iteration return the results complexity time o n space o n validate the input alternative solution
def fizzbuzz(n): if n < 1: raise ValueError('n cannot be less than one') if n is None: raise TypeError('n cannot be None') result = [] for i in range(1, n+1): if i%3 == 0 and i%5 == 0: result.append('FizzBuzz') elif i%3 == 0: result.append('Fizz') elif i%5 == 0: result.append('Buzz') else: result.append(i) return result def fizzbuzz_with_helper_func(n): return [fb(m) for m in range(1,n+1)] def fb(m): r = (m % 3 == 0) * "Fizz" + (m % 5 == 0) * "Buzz" return r if r != "" else m
given an array of strings group anagrams together for example given eat tea tan ate nat bat return ate eat tea nat tan bat
def group_anagrams(strs): d = {} ans = [] k = 0 for str in strs: sstr = ''.join(sorted(str)) if sstr not in d: d[sstr] = k k += 1 ans.append([]) ans[-1].append(str) else: ans[d[sstr]].append(str) return ans
given an integer convert it to a roman numeral input is guaranteed to be within the range from 1 to 3999 type num int rtype str type num int rtype str
def int_to_roman(num): m = ["", "M", "MM", "MMM"]; c = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]; x = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]; i = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]; return m[num//1000] + c[(num%1000)//100] + x[(num%100)//10] + i[num%10];
given a string determine if it is a palindrome considering only alphanumeric characters and ignoring cases for example a man a plan a canal panama is a palindrome race a car is not a palindrome note have you consider that the string might be empty this is a good question to ask during an interview for the purpose of this problem we define empty string as valid palindrome type s str rtype bool here is a bunch of other variations of ispalindrome function variation 1 find the reverse of the string and compare it with the original string variation 2 loop from the start to length2 and check the first character and last character and so on for instance s0 compared with sn1 s1 sn2 variation 3 using stack idea note we are assuming that we are just checking a one word string to check if a complete sentence remove punctuation case sensitivity and spaces variation 1 can also get rid of the stringreverse function and just do this return s s 1 in one line variation 2 variation 3 variation 4 using deque type s str rtype bool here is a bunch of other variations of is_palindrome function variation 1 find the reverse of the string and compare it with the original string variation 2 loop from the start to length 2 and check the first character and last character and so on for instance s 0 compared with s n 1 s 1 s n 2 variation 3 using stack idea note we are assuming that we are just checking a one word string to check if a complete sentence remove punctuation case sensitivity and spaces variation 1 can also get rid of the string_reverse function and just do this return s s 1 in one line variation 2 variation 3 variation 4 using deque
from string import ascii_letters from collections import deque def is_palindrome(s): i = 0 j = len(s)-1 while i < j: while not s[i].isalnum(): i += 1 while not s[j].isalnum(): j -= 1 if s[i].lower() != s[j].lower(): return False i, j = i+1, j-1 return True def remove_punctuation(s): return "".join(i.lower() for i in s if i in ascii_letters) def string_reverse(s): return s[::-1] def is_palindrome_reverse(s): s = remove_punctuation(s) if (s == string_reverse(s)): return True return False def is_palindrome_two_pointer(s): s = remove_punctuation(s) for i in range(0, len(s)//2): if (s[i] != s[len(s) - i - 1]): return False return True def is_palindrome_stack(s): stack = [] s = remove_punctuation(s) for i in range(len(s)//2, len(s)): stack.append(s[i]) for i in range(0, len(s)//2): if s[i] != stack.pop(): return False return True def is_palindrome_deque(s): s = remove_punctuation(s) deq = deque() for char in s: deq.appendleft(char) equal = True while len(deq) > 1 and equal: first = deq.pop() last = deq.popleft() if first != last : equal = False return equal
given two strings s1 and s2 determine if s2 is a rotated version of s1 for example isrotatedhello llohe returns true isrotatedhello helol returns false accepts two strings returns bool reference https leetcode comproblemsrotatestringdescription another solution brutal force complexity on2 another solution brutal force complexity o n 2
def is_rotated(s1, s2): if len(s1) == len(s2): return s2 in s1 + s1 else: return False def is_rotated_v1(s1, s2): if len(s1) != len(s2): return False if len(s1) == 0: return True for c in range(len(s1)): if all(s1[(c + i) % len(s1)] == s2[i] for i in range(len(s1))): return True return False
initially there is a robot at position 0 0 given a sequence of its moves judge if this robot makes a circle which means it moves back to the original place the move sequence is represented by a string and each move is represent by a character the valid robot moves are r right l left u up and d down the output should be true or false representing whether the robot makes a circle example 1 input ud output true example 2 input ll output false
def judge_circle(moves): dict_moves = { 'U' : 0, 'D' : 0, 'R' : 0, 'L' : 0 } for char in moves: dict_moves[char] = dict_moves[char] + 1 return dict_moves['L'] == dict_moves['R'] and dict_moves['U'] == dict_moves['D']
given two strings text and pattern return the list of start indexes in text that matches with the pattern using knuthmorrispratt algorithm args text text to search pattern pattern to search in the text returns list of indices of patterns found example knuthmorrispratt hello there hero he 0 7 12 if idx is in the list textidx idx m matches with pattern time complexity of the algorithm is onm with n and m the length of text and pattern respectively making pi table finding pattern given two strings text and pattern return the list of start indexes in text that matches with the pattern using knuth_morris_pratt algorithm args text text to search pattern pattern to search in the text returns list of indices of patterns found example knuth_morris_pratt hello there hero he 0 7 12 if idx is in the list text idx idx m matches with pattern time complexity of the algorithm is o n m with n and m the length of text and pattern respectively making pi table finding pattern
from typing import Sequence, List def knuth_morris_pratt(text : Sequence, pattern : Sequence) -> List[int]: n = len(text) m = len(pattern) pi = [0 for i in range(m)] i = 0 j = 0 for i in range(1, m): while j and pattern[i] != pattern[j]: j = pi[j - 1] if pattern[i] == pattern[j]: j += 1 pi[i] = j j = 0 ret = [] for i in range(n): while j and text[i] != pattern[j]: j = pi[j - 1] if text[i] == pattern[j]: j += 1 if j == m: ret.append(i - m + 1) j = pi[j - 1] return ret
write a function to find the longest common prefix string amongst an array of strings if there is no common prefix return an empty string example 1 input flower flow flight output fl example 2 input dog racecar car output explanation there is no common prefix among the input strings reference https leetcode comproblemslongestcommonprefixdescription first solution horizontal scanning second solution vertical scanning third solution divide and conquer first solution horizontal scanning second solution vertical scanning third solution divide and conquer
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] def longest_common_prefix_v1(strs): if not strs: return "" result = strs[0] for i in range(len(strs)): result = common_prefix(result, strs[i]) return result def longest_common_prefix_v2(strs): if not strs: return "" for i in range(len(strs[0])): for string in strs[1:]: if i == len(string) or string[i] != strs[0][i]: return strs[0][0:i] return strs[0] def longest_common_prefix_v3(strs): if not strs: return "" return longest_common(strs, 0, len(strs) -1) def longest_common(strs, left, right): if left == right: return strs[left] mid = (left + right) // 2 lcp_left = longest_common(strs, left, mid) lcp_right = longest_common(strs, mid + 1, right) return common_prefix(lcp_left, lcp_right)
for a given string and dictionary how many sentences can you make from the string such that all the words are contained in the dictionary eg for given string appletablet apple tablet applet able t apple table t app let able t applet app let apple t applet 3 thing thing 1
count = 0 def make_sentence(str_piece, dictionaries): global count if len(str_piece) == 0: return True for i in range(0, len(str_piece)): prefix, suffix = str_piece[0:i], str_piece[i:] if prefix in dictionaries: if suffix in dictionaries or make_sentence(suffix, dictionaries): count += 1 return True
at a job interview you are challenged to write an algorithm to check if a given string s can be formed from two other strings part1 and part2 the restriction is that the characters in part1 and part2 are in the same order as in s the interviewer gives you the following example and tells you to figure out the rest from the given test cases codewars is a merge from cdw and oears s c o d e w a r s codewars part1 c d w cdw part2 o e a r s oears recursive solution an iterative approach recursive solution an iterative approach
def is_merge_recursive(s, part1, part2): if not part1: return s == part2 if not part2: return s == part1 if not s: return part1 + part2 == '' if s[0] == part1[0] and is_merge_recursive(s[1:], part1[1:], part2): return True if s[0] == part2[0] and is_merge_recursive(s[1:], part1, part2[1:]): return True return False def is_merge_iterative(s, part1, part2): tuple_list = [(s, part1, part2)] while tuple_list: string, p1, p2 = tuple_list.pop() if string: if p1 and string[0] == p1[0]: tuple_list.append((string[1:], p1[1:], p2)) if p2 and string[0] == p2[0]: tuple_list.append((string[1:], p1, p2[1:])) else: if not p1 and not p2: return True return False
given two words word1 and word2 find the minimum number of steps required to make word1 and word2 the same where in each step you can delete one character in either string for example input sea eat output 2 explanation you need one step to make sea to ea and another step to make eat to ea reference https leetcode comproblemsdeleteoperationfortwostringsdescription finds minimum distance by getting longest common subsequence type word1 str type word2 str rtype int the length of longest common subsequence among the two given strings word1 and word2 finds minimum distance in a dynamic programming manner tc olength1length2 sc olength1length2 type word1 str type word2 str rtype int finds minimum distance by getting longest common subsequence type word1 str type word2 str rtype int the length of longest common subsequence among the two given strings word1 and word2 finds minimum distance in a dynamic programming manner tc o length1 length2 sc o length1 length2 type word1 str type word2 str rtype int
def min_distance(word1, word2): return len(word1) + len(word2) - 2 * lcs(word1, word2, len(word1), len(word2)) def lcs(word1, word2, i, j): if i == 0 or j == 0: return 0 if word1[i - 1] == word2[j - 1]: return 1 + lcs(word1, word2, i - 1, j - 1) return max(lcs(word1, word2, i - 1, j), lcs(word1, word2, i, j - 1)) def min_distance_dp(word1, word2): length1, length2 = len(word1)+1, len(word2)+1 res = [[0 for _ in range(length2)] for _ in range(length1)] if length1 == length2: for i in range(1, length1): res[i][0], res[0][i] = i, i else: for i in range(length1): res[i][0] = i for i in range(length2): res[0][i] = i for i in range(1, length1): for j in range(1, length2): if word1[i-1] == word2[j-1]: res[i][j] = res[i-1][j-1] else: res[i][j] = min(res[i-1][j], res[i][j-1]) + 1 return res[len(word1)][len(word2)]
given two nonnegative integers num1 and num2 represented as strings return the product of num1 and num2 note the length of both num1 and num2 is 110 both num1 and num2 contains only digits 09 both num1 and num2 does not contain any leading zero you must not use any builtin biginteger library or convert the inputs to integer directly
def multiply(num1: "str", num2: "str") -> "str": interm = [] zero = ord('0') i_pos = 1 for i in reversed(num1): j_pos = 1 add = 0 for j in reversed(num2): mult = (ord(i)-zero) * (ord(j)-zero) * j_pos * i_pos j_pos *= 10 add += mult i_pos *= 10 interm.append(add) return str(sum(interm)) if __name__ == "__main__": print(multiply("1", "23")) print(multiply("23", "23")) print(multiply("100", "23")) print(multiply("100", "10000"))
given two strings s and t determine if they are both one edit distance apart type s str type t str rtype bool type s str type t str rtype bool modify insertion
def is_one_edit(s, t): 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]: return s[i+1:] == t[i+1:] or s[i:] == t[i+1:] return True def is_one_edit2(s, t): l1, l2 = len(s), len(t) if l1 > l2: return is_one_edit2(t, s) if len(t) - len(s) > 1 or t == s: return False for i in range(len(s)): if s[i] != t[i]: if l1 == l2: s = s[:i]+t[i]+s[i+1:] else: s = s[:i]+t[i]+s[i:] break return s == t or s == t[:-1]
given a string check whether it is a panagram or not a panagram is a sentence that uses every letter at least once the most famous example is he quick brown fox jumps over the lazy dog note a panagram in one language isn t necessarily a panagram in another this module assumes the english language hence the finnish panagram trkylempijvongahdus won t pass for a panagram despite being considered a perfect panagram in its language however the swedish panagram yxmrdaren julia blomqvist p fktning i schweiz will pass despite including letters not used in the english alphabet this is because the swedish alphabet only extends the latin one returns whether the input string is an english panagram or not parameters string str a sentence in the form of a string returns a boolean with the result returns whether the input string is an english panagram or not parameters string str a sentence in the form of a string returns a boolean with the result
from string import ascii_lowercase def panagram(string): letters = set(ascii_lowercase) for c in string: try: letters.remove(c.lower()) except: pass return len(letters) == 0
following program is the python implementation of rabin karp algorithm ord maps the character to a number subtract out the ascii value of a to start the indexing at zero start index of current window end of index window remove left letter from hash value wordhash movewindow following program is the python implementation of rabin karp algorithm ord maps the character to a number subtract out the ascii value of a to start the indexing at zero start index of current window end of index window remove left letter from hash value word_hash move_window
class RollingHash: def __init__(self, text, size_word): self.text = text self.hash = 0 self.size_word = size_word for i in range(0, size_word): self.hash += (ord(self.text[i]) - ord("a")+1)*(26**(size_word - i -1)) self.window_start = 0 self.window_end = size_word def move_window(self): if self.window_end <= len(self.text) - 1: self.hash -= (ord(self.text[self.window_start]) - ord("a")+1)*26**(self.size_word-1) self.hash *= 26 self.hash += ord(self.text[self.window_end])- ord("a")+1 self.window_start += 1 self.window_end += 1 def window_text(self): return self.text[self.window_start:self.window_end] def rabin_karp(word, text): if word == "" or text == "": return None if len(word) > len(text): return None rolling_hash = RollingHash(text, len(word)) word_hash = RollingHash(word, len(word)) for i in range(len(text) - len(word) + 1): if rolling_hash.hash == word_hash.hash: if rolling_hash.window_text() == word: return i rolling_hash.move_window() return None
given two strings a and b find the minimum number of times a has to be repeated such that b is a substring of it if no such solution return 1 for example with a abcd and b cdabcdab return 3 because by repeating a three times abcdabcdabcd b is a substring of it and b is not a substring of a repeated two times abcdabcd note the length of a and b will be between 1 and 10000 reference https leetcode comproblemsrepeatedstringmatchdescription
def repeat_string(A, B): count = 1 tmp = A max_count = (len(B) / len(A)) + 1 while not(B in tmp): tmp = tmp + A if (count > max_count): count = -1 break count = count + 1 return count
given a nonempty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together for example input abab output true explanation it s the substring ab twice input aba output false input abcabcabcabc output true explanation it s the substring abc four times reference https leetcode comproblemsrepeatedsubstringpatterndescription type s str rtype bool type s str rtype bool
def repeat_substring(s): str = (s + s)[1:-1] return s in str
given a roman numeral convert it to an integer input is guaranteed to be within the range from 1 to 3999
def roman_to_int(s:"str")->"int": number = 0 roman = {'M':1000, 'D':500, 'C': 100, 'L':50, 'X':10, 'V':5, 'I':1} for i in range(len(s)-1): if roman[s[i]] < roman[s[i+1]]: number -= roman[s[i]] else: number += roman[s[i]] return number + roman[s[-1]] if __name__ == "__main__": roman = "DCXXI" print(roman_to_int(roman))
given a strings s and int k return a string that rotates k times k can be any positive integer for example rotatehello 2 return llohe rotatehello 5 return hello rotatehello 6 return elloh rotatehello 7 return llohe rotatehello 102 return lohel
def rotate(s, k): long_string = s * (k // len(s) + 2) if k <= len(s): return long_string[k:k + len(s)] else: return long_string[k-len(s):k] def rotate_alt(string, k): k = k % len(string) return string[k:] + string[:k]
write a function that does the following removes any duplicate query string parameters from the url removes any query string parameters specified within the 2nd argument optional array an example www saadbenn com a1b2a2 returns www saadbenn com a1b2 here is a very nonpythonic grotesque solution add the to our result if it is in the url logic for removing duplicate query strings build up the list by splitting the querystring using digits logic for checking whether we should add the string to our result a very friendly pythonic solution easy to follow here is my friend s solution using python s builtin libraries here is a very non pythonic grotesque solution final result to be returned add the to our result if it is in the url logic for removing duplicate query strings build up the list by splitting the query_string using digits logic for checking whether we should add the string to our result a very friendly pythonic solution easy to follow here is my friend s solution using python s builtin libraries
from collections import defaultdict import urllib import urllib.parse def strip_url_params1(url, params_to_strip=None): if not params_to_strip: params_to_strip = [] if url: result = '' tokens = url.split('?') domain = tokens[0] query_string = tokens[-1] result += domain if len(tokens) > 1: result += '?' if not query_string: return url else: key_value_string = [] string = '' for char in query_string: if char.isdigit(): key_value_string.append(string + char) string = '' else: string += char dict = defaultdict(int) for i in key_value_string: _token = i.split('=') if _token[0]: length = len(_token[0]) if length == 1: if _token and (not(_token[0] in dict)): if params_to_strip: if _token[0] != params_to_strip[0]: dict[_token[0]] = _token[1] result = result + _token[0] + '=' + _token[1] else: if not _token[0] in dict: dict[_token[0]] = _token[1] result = result + _token[0] + '=' + _token[1] else: check = _token[0] letter = check[1] if _token and (not(letter in dict)): if params_to_strip: if letter != params_to_strip[0]: dict[letter] = _token[1] result = result + _token[0] + '=' + _token[1] else: if not letter in dict: dict[letter] = _token[1] result = result + _token[0] + '=' + _token[1] return result def strip_url_params2(url, param_to_strip=[]): if '?' not in url: return url queries = (url.split('?')[1]).split('&') queries_obj = [query[0] for query in queries] for i in range(len(queries_obj) - 1, 0, -1): if queries_obj[i] in param_to_strip or queries_obj[i] in queries_obj[0:i]: queries.pop(i) return url.split('?')[0] + '?' + '&'.join(queries) def strip_url_params3(url, strip=None): if not strip: strip = [] parse = urllib.parse.urlparse(url) query = urllib.parse.parse_qs(parse.query) query = {k: v[0] for k, v in query.items() if k not in strip} query = urllib.parse.urlencode(query) new = parse._replace(query=query) return new.geturl()
given an array of words and a width maxwidth format the text such that each line has exactly maxwidth characters and is fully left and right justified you should pack your words in a greedy approach that is pack as many words as you can in each line pad extra spaces when necessary so that each line has exactly maxwidth characters extra spaces between words should be distributed as evenly as possible if the number of spaces on a line do not divide evenly between words the empty slots on the left will be assigned more spaces than the slots on the right for the last line of text it should be left justified and no extra space is inserted between words note a word is defined as a character sequence consisting of nonspace characters only each word s length is guaranteed to be greater than 0 and not exceed maxwidth the input array words contains at least one word example input words what must be acknowledgment shall be maxwidth 16 output what must be acknowledgment shall be type words list type maxwidth int rtype list here we have already got a row of str then we should supplement enough to make sure the length is maxwidth if the row is the last not the last row and more than one word row with only one word after a row reset those value type words list type max_width int rtype list return value current length of strs in a row current words in a row the index of current word in words is current word the first in a row except for the first word each word should have at least a before it here we have already got a row of str then we should supplement enough to make sure the length is max_width if the row is the last not the last row and more than one word row with only one word after a row reset those value
def text_justification(words, max_width): ret = [] row_len = 0 row_words = [] index = 0 is_first_word = True while index < len(words): while row_len <= max_width and index < len(words): if len(words[index]) > max_width: raise ValueError("there exists word whose length is larger than max_width") tmp = row_len row_words.append(words[index]) tmp += len(words[index]) if not is_first_word: tmp += 1 if tmp > max_width: row_words.pop() break row_len = tmp index += 1 is_first_word = False row = "" if index == len(words): for word in row_words: row += (word + ' ') row = row[:-1] row += ' ' * (max_width - len(row)) elif len(row_words) != 1: space_num = max_width - row_len space_num_of_each_interval = space_num // (len(row_words) - 1) space_num_rest = space_num - space_num_of_each_interval * (len(row_words) - 1) for j in range(len(row_words)): row += row_words[j] if j != len(row_words) - 1: row += ' ' * (1 + space_num_of_each_interval) if space_num_rest > 0: row += ' ' space_num_rest -= 1 else: row += row_words[0] row += ' ' * (max_width - len(row)) ret.append(row) row_len = 0 row_words = [] is_first_word = True return ret
international morse code defines a standard encoding where each letter is mapped to a series of dots and dashes as follows a maps to b maps to c maps to and so on for convenience the full table for the 26 letters of the english alphabet is given below a b c d e f g h i j k l m n o p q r s t u v w x y z now given a list of words each word can be written as a concatenation of the morse code of each letter for example cab can be written as which is the concatenation we ll call such a concatenation the transformation of a word return the number of different transformations among all words we have example input words gin zen gig msg output 2 explanation the transformation of each word is gin zen gig msg there are 2 different transformations and
morse_code = { 'a':".-", 'b':"-...", 'c':"-.-.", 'd': "-..", 'e':".", 'f':"..-.", 'g':"--.", 'h':"....", 'i':"..", 'j':".---", 'k':"-.-", 'l':".-..", 'm':"--", 'n':"-.", 'o':"---", 'p':".--.", 'q':"--.-", 'r':".-.", 's':"...", 't':"-", 'u':"..-", 'v':"...-", 'w':".--", 'x':"-..-", 'y':"-.--", 'z':"--.." } def convert_morse_word(word): morse_word = "" word = word.lower() for char in word: morse_word = morse_word + morse_code[char] return morse_word def unique_morse(words): unique_morse_word = [] for word in words: morse_word = convert_morse_word(word) if morse_word not in unique_morse_word: unique_morse_word.append(morse_word) return len(unique_morse_word)
create a function that will validate if given parameters are valid geographical coordinates valid coordinates look like the following 23 32353342 32 543534534 the return value should be either true or false latitude which is first float can be between 0 and 90 positive or negative longitude which is second float can be between 0 and 180 positive or negative coordinates can only contain digits or one of the following symbols including space after comma there should be no space between the minus sign and the digit after it here are some valid coordinates 23 25 43 91343345 143 4 3 and some invalid ones 23 234 23 4234 n23 43345 e32 6457 6 325624 43 34345 345 0 1 2 i ll be adding my attempt as well as my friend s solution took us 1 hour my attempt friends solutions using regular expression i ll be adding my attempt as well as my friend s solution took us 1 hour my attempt friends solutions using regular expression
import re def is_valid_coordinates_0(coordinates): for char in coordinates: if not (char.isdigit() or char in ['-', '.', ',', ' ']): return False l = coordinates.split(", ") if len(l) != 2: return False try: latitude = float(l[0]) longitude = float(l[1]) except: return False return -90 <= latitude <= 90 and -180 <= longitude <= 180 def is_valid_coordinates_1(coordinates): try: lat, lng = [abs(float(c)) for c in coordinates.split(',') if 'e' not in c] except ValueError: return False return lat <= 90 and lng <= 180 def is_valid_coordinates_regular_expression(coordinates): return bool(re.match("-?(\d|[1-8]\d|90)\.?\d*, -?(\d|[1-9]\d|1[0-7]\d|180)\.?\d*$", coordinates))
given a set of words without duplicates find all word squares you can build from them a sequence of words forms a valid word square if the kth row and column read the exact same string where 0 k maxnumrows numcolumns for example the word sequence ball area lead lady forms a word square because each word reads the same both horizontally and vertically b a l l a r e a l e a d l a d y note there are at least 1 and at most 1000 words all words will have the exact same length word length is at least 1 and at most 5 each word contains only lowercase english alphabet az example 1 input area lead wall lady ball output wall area lead lady ball area lead lady explanation the output consists of two word squares the order of output does not matter just the order of words in each word square matters given a set of words without duplicates find all word squares you can build from them a sequence of words forms a valid word square if the kth row and column read the exact same string where 0 k max numrows numcolumns for example the word sequence ball area lead lady forms a word square because each word reads the same both horizontally and vertically b a l l a r e a l e a d l a d y note there are at least 1 and at most 1000 words all words will have the exact same length word length is at least 1 and at most 5 each word contains only lowercase english alphabet a z example 1 input area lead wall lady ball output wall area lead lady ball area lead lady explanation the output consists of two word squares the order of output does not matter just the order of words in each word square matters
import collections def word_squares(words): n = len(words[0]) fulls = collections.defaultdict(list) for word in words: for i in range(n): fulls[word[:i]].append(word) def build(square): if len(square) == n: squares.append(square) return prefix = "" for k in range(len(square)): prefix += square[k][len(square)] for word in fulls[prefix]: build(square + [word]) squares = [] for word in words: build([word]) return squares
imports treenodes from tree tree import treenode class avltreeobject def initself root node of the tree self node none self height 1 self balance 0 def insertself key create new node node treenodekey if not self node self node node self node left avltree self node right avltree elif key self node val self node left insertkey elif key self node val self node right insertkey self rebalance def rebalanceself self updateheightsrecursivefalse self updatebalancesfalse while self balance 1 or self balance 1 if self balance 1 if self node left balance 0 self node left rotateleft self updateheights self updatebalances self rotateright self updateheights self updatebalances if self balance 1 if self node right balance 0 self node right rotateright self updateheights self updatebalances self rotateleft self updateheights self updatebalances def updateheightsself recursivetrue if self node if recursive if self node left self node left updateheights if self node right self node right updateheights self height 1 maxself node left height self node right height else self height 1 def updatebalancesself recursivetrue if self node if recursive if self node left self node left updatebalances if self node right self node right updatebalances self balance self node left height self node right height else self balance 0 def rotaterightself newroot self node left node newleftsub newroot right node oldroot self node self node newroot oldroot left node newleftsub newroot right node oldroot def rotateleftself newroot self node right node newleftsub newroot left node oldroot self node self node newroot oldroot right node newleftsub newroot left node oldroot def inordertraverseself result if not self node return result result extendself node left inordertraverse result appendself node key result extendself node right inordertraverse return result an avl tree root node of the tree insert new key into node create new node re balance tree after inserting or deleting a node update tree height calculate tree balance factor right rotation left rotation in order traversal of the tree
from tree.tree import TreeNode class AvlTree(object): def __init__(self): self.node = None self.height = -1 self.balance = 0 def insert(self, key): node = TreeNode(key) if not self.node: self.node = node self.node.left = AvlTree() self.node.right = AvlTree() elif key < self.node.val: self.node.left.insert(key) elif key > self.node.val: self.node.right.insert(key) self.re_balance() def re_balance(self): self.update_heights(recursive=False) self.update_balances(False) while self.balance < -1 or self.balance > 1: if self.balance > 1: if self.node.left.balance < 0: self.node.left.rotate_left() self.update_heights() self.update_balances() self.rotate_right() self.update_heights() self.update_balances() if self.balance < -1: if self.node.right.balance > 0: self.node.right.rotate_right() self.update_heights() self.update_balances() self.rotate_left() self.update_heights() self.update_balances() def update_heights(self, recursive=True): if self.node: if recursive: if self.node.left: self.node.left.update_heights() if self.node.right: self.node.right.update_heights() self.height = 1 + max(self.node.left.height, self.node.right.height) else: self.height = -1 def update_balances(self, recursive=True): if self.node: if recursive: if self.node.left: self.node.left.update_balances() if self.node.right: self.node.right.update_balances() self.balance = self.node.left.height - self.node.right.height else: self.balance = 0 def rotate_right(self): 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 def rotate_left(self): 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 def in_order_traverse(self): result = [] if not self.node: return result result.extend(self.node.left.in_order_traverse()) result.append(self.node.key) result.extend(self.node.right.in_order_traverse()) return result
btree is used to disk operations each node except root contains at least t1 keys t children and at most 2t 1 keys 2t children where t is the degree of btree it is not a kind of typical bst tree because this tree grows up btree is balanced which means that the difference between height of left subtree and right subtree is at most 1 complexity n number of elements t degree of tree tree always has height at most logt n12 algorithm average worst case space on on search olog n olog n insert olog n olog n delete olog n olog n class of node def initself self isleaf isleaf self keys self children def reprself return idnode 0 formatself keys property def isleafself class of btree def initself tval2 self minnumbersofkeys tval 1 self maxnumberofkeys 2 tval 1 self root node def splitchildself parent node childindex int newrightchild node halfmax self maxnumberofkeys 2 child parent childrenchildindex middlekey child keyshalfmax newrightchild keys child keyshalfmax 1 child keys child keys halfmax child is left child of parent after splitting if not child isleaf newrightchild children child childrenhalfmax 1 child children child children halfmax 1 parent keys insertchildindex middlekey parent children insertchildindex 1 newrightchild def insertkeyself key overflow decide which child is going to have a new key finds key currentnode self root while true i lencurrentnode keys 1 while i 0 and currentnode keysi key i 1 if i 0 and currentnode keysi key return true if currentnode isleaf return false currentnode currentnode childreni 1 def removekeyself key self removekeyself root key def removekeyself node node key bool try keyindex node keys indexkey if node isleaf node keys removekey else self removefromnonleafnodenode keyindex return true except valueerror key not found in node if node isleaf printkey not found return false key not found else i 0 numberofkeys lennode keys decide in which subtree may be key while i numberofkeys and key node keysi i 1 actionperformed self repairtreenode i if actionperformed return self removekeynode key else return self removekeynode childreni key def repairtreeself node node childindex int bool child node childrenchildindex the leafnode is correct if self minnumbersofkeys lenchild keys self maxnumberofkeys return false if childindex 0 and lennode childrenchildindex 1 keys self minnumbersofkeys self rotaterightnode childindex return true if childindex lennode children 1 and lennode childrenchildindex 1 keys self minnumbersofkeys 0 1 self rotateleftnode childindex return true if childindex 0 merge child with brother on the left self mergenode childindex 1 childindex else merge child with brother on the right self mergenode childindex childindex 1 return true def rotateleftself parentnode node childindex int newchildkey parentnode keyschildindex newparentkey parentnode childrenchildindex 1 keys pop0 parentnode childrenchildindex keys appendnewchildkey parentnode keyschildindex newparentkey if not parentnode childrenchildindex 1 isleaf ownerlesschild parentnode childrenchildindex 1 children pop0 make ownerlesschild as a new biggest child with highest key transfer from right subtree to left subtree parentnode childrenchildindex children appendownerlesschild def rotaterightself parentnode node childindex int parentkey parentnode keyschildindex 1 newparentkey parentnode childrenchildindex 1 keys pop parentnode childrenchildindex keys insert0 parentkey parentnode keyschildindex 1 newparentkey if not parentnode childrenchildindex 1 isleaf ownerlesschild parentnode childrenchildindex 1 children pop make ownerlesschild as a new lowest child with lowest key transfer from left subtree to right subtree parentnode childrenchildindex children insert 0 ownerlesschild def mergeself parentnode node tomergeindex int transferedchildindex int frommergenode parentnode children poptransferedchildindex parentkeytomerge parentnode keys poptomergeindex tomergenode parentnode childrentomergeindex tomergenode keys appendparentkeytomerge tomergenode keys extendfrommergenode keys if not tomergenode isleaf tomergenode children extendfrommergenode children if parentnode self root and not parentnode keys self root tomergenode def removefromnonleafnodeself node node keyindex int key node keyskeyindex leftsubtree node childrenkeyindex if lenleftsubtree keys self minnumbersofkeys largestkey self findlargestanddeleteinleftsubtree leftsubtree elif lennode childrenkeyindex 1 keys self minnumbersofkeys largestkey self findlargestanddeleteinrightsubtree node childrenkeyindex 1 else self mergenode keyindex keyindex 1 return self removekeynode key node keyskeyindex largestkey def findlargestanddeleteinleftsubtreeself node node if node isleaf return node keys pop else chindex lennode children 1 self repairtreenode chindex largestkeyinsubtree self findlargestanddeleteinleftsubtree node childrenlennode children 1 self repairtreenode chindex return largestkeyinsubtree def findlargestanddeleteinrightsubtreeself node node if node isleaf return node keys pop0 else chindex 0 self repairtreenode chindex largestkeyinsubtree self findlargestanddeleteinrightsubtree node children0 self repairtreenode chindex return largestkeyinsubtree def traversetreeself self traversetreeself root print def traversetreeself node node if node isleaf printnode keys end else for i key in enumeratenode keys self traversetreenode childreni printkey end self traversetreenode children1 class of node self is_leaf is_leaf return if it is a leaf class of btree child is left child of parent after splitting overflow tree increases in height find position where insert key overflow decide which child is going to have a new key finds key key not found in node key not found decide in which subtree may be key the leaf node is correct 0 1 merge child with brother on the left merge child with brother on the right take key from right brother of the child and transfer to the child make ownerless_child as a new biggest child with highest key transfer from right subtree to left subtree take key from left brother of the child and transfer to the child make ownerless_child as a new lowest child with lowest key transfer from left subtree to right subtree self _repair_tree node ch_index self _repair_tree node ch_index
class Node: def __init__(self): self.keys = [] self.children = [] def __repr__(self): return "<id_node: {0}>".format(self.keys) @property def is_leaf(self): return len(self.children) == 0 class BTree: def __init__(self, t_val=2): self.min_numbers_of_keys = t_val - 1 self.max_number_of_keys = 2 * t_val - 1 self.root = Node() def _split_child(self, parent: Node, child_index: int): new_right_child = Node() half_max = self.max_number_of_keys // 2 child = parent.children[child_index] middle_key = child.keys[half_max] new_right_child.keys = child.keys[half_max + 1:] child.keys = child.keys[:half_max] if not child.is_leaf: new_right_child.children = child.children[half_max + 1:] child.children = child.children[:half_max + 1] parent.keys.insert(child_index, middle_key) parent.children.insert(child_index + 1, new_right_child) def insert_key(self, key): if len(self.root.keys) >= self.max_number_of_keys: new_root = Node() new_root.children.append(self.root) self.root = new_root self._split_child(new_root, 0) self._insert_to_nonfull_node(self.root, key) else: self._insert_to_nonfull_node(self.root, key) def _insert_to_nonfull_node(self, node: Node, key): i = len(node.keys) - 1 while i >= 0 and node.keys[i] >= key: i -= 1 if node.is_leaf: node.keys.insert(i + 1, key) else: if len(node.children[i + 1].keys) >= self.max_number_of_keys: self._split_child(node, i + 1) if node.keys[i + 1] < key: i += 1 self._insert_to_nonfull_node(node.children[i + 1], key) def find(self, key) -> bool: current_node = self.root while True: i = len(current_node.keys) - 1 while i >= 0 and current_node.keys[i] > key: i -= 1 if i >= 0 and current_node.keys[i] == key: return True if current_node.is_leaf: return False current_node = current_node.children[i + 1] def remove_key(self, key): self._remove_key(self.root, key) def _remove_key(self, node: Node, key) -> bool: try: key_index = node.keys.index(key) if node.is_leaf: node.keys.remove(key) else: self._remove_from_nonleaf_node(node, key_index) return True except ValueError: if node.is_leaf: print("Key not found.") return False else: i = 0 number_of_keys = len(node.keys) while i < number_of_keys and key > node.keys[i]: i += 1 action_performed = self._repair_tree(node, i) if action_performed: return self._remove_key(node, key) else: return self._remove_key(node.children[i], key) def _repair_tree(self, node: Node, child_index: int) -> bool: child = node.children[child_index] if self.min_numbers_of_keys < len(child.keys) <= self.max_number_of_keys: return False if child_index > 0 and len(node.children[child_index - 1].keys) > self.min_numbers_of_keys: self._rotate_right(node, child_index) return True if (child_index < len(node.children) - 1 and len(node.children[child_index + 1].keys) > self.min_numbers_of_keys): self._rotate_left(node, child_index) return True if child_index > 0: self._merge(node, child_index - 1, child_index) else: self._merge(node, child_index, child_index + 1) return True def _rotate_left(self, parent_node: Node, child_index: int): new_child_key = parent_node.keys[child_index] new_parent_key = parent_node.children[child_index + 1].keys.pop(0) parent_node.children[child_index].keys.append(new_child_key) parent_node.keys[child_index] = new_parent_key if not parent_node.children[child_index + 1].is_leaf: ownerless_child = parent_node.children[child_index + 1].children.pop(0) parent_node.children[child_index].children.append(ownerless_child) def _rotate_right(self, parent_node: Node, child_index: int): parent_key = parent_node.keys[child_index - 1] new_parent_key = parent_node.children[child_index - 1].keys.pop() parent_node.children[child_index].keys.insert(0, parent_key) parent_node.keys[child_index - 1] = new_parent_key if not parent_node.children[child_index - 1].is_leaf: ownerless_child = parent_node.children[child_index - 1].children.pop() parent_node.children[child_index].children.insert( 0, ownerless_child) def _merge(self, parent_node: Node, to_merge_index: int, transfered_child_index: int): from_merge_node = parent_node.children.pop(transfered_child_index) parent_key_to_merge = parent_node.keys.pop(to_merge_index) to_merge_node = parent_node.children[to_merge_index] to_merge_node.keys.append(parent_key_to_merge) to_merge_node.keys.extend(from_merge_node.keys) if not to_merge_node.is_leaf: to_merge_node.children.extend(from_merge_node.children) if parent_node == self.root and not parent_node.keys: self.root = to_merge_node def _remove_from_nonleaf_node(self, node: Node, key_index: int): key = node.keys[key_index] left_subtree = node.children[key_index] if len(left_subtree.keys) > self.min_numbers_of_keys: largest_key = self._find_largest_and_delete_in_left_subtree( left_subtree) elif len(node.children[key_index + 1].keys) > self.min_numbers_of_keys: largest_key = self._find_largest_and_delete_in_right_subtree( node.children[key_index + 1]) else: self._merge(node, key_index, key_index + 1) return self._remove_key(node, key) node.keys[key_index] = largest_key def _find_largest_and_delete_in_left_subtree(self, node: Node): if node.is_leaf: return node.keys.pop() else: ch_index = len(node.children) - 1 self._repair_tree(node, ch_index) largest_key_in_subtree = self._find_largest_and_delete_in_left_subtree( node.children[len(node.children) - 1]) return largest_key_in_subtree def _find_largest_and_delete_in_right_subtree(self, node: Node): if node.is_leaf: return node.keys.pop(0) else: ch_index = 0 self._repair_tree(node, ch_index) largest_key_in_subtree = self._find_largest_and_delete_in_right_subtree( node.children[0]) return largest_key_in_subtree def traverse_tree(self): self._traverse_tree(self.root) print() def _traverse_tree(self, node: Node): if node.is_leaf: print(node.keys, end=" ") else: for i, key in enumerate(node.keys): self._traverse_tree(node.children[i]) print(key, end=" ") self._traverse_tree(node.children[-1])
type root root class type root root class
from tree.tree import TreeNode def bin_tree_to_list(root): if not root: return root root = bin_tree_to_list_util(root) while root.left: root = root.left return root def bin_tree_to_list_util(root): if not root: return root if root.left: left = bin_tree_to_list_util(root.left) while left.right: left = left.right left.right = root root.left = left if root.right: right = bin_tree_to_list_util(root.right) while right.left: right = right.left right.left = root root.right = right return root def print_tree(root): while root: print(root.val) root = root.right
given an array where elements are sorted in ascending order convert it to a height balanced bst
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def array_to_bst(nums): if not nums: return None mid = len(nums)//2 node = TreeNode(nums[mid]) node.left = array_to_bst(nums[:mid]) node.right = array_to_bst(nums[mid+1:]) return node
implement binary search tree it has method 1 insert 2 search 3 size 4 traversal preorder inorder postorder get the number of elements using recursion complexity ologn search data in bst using recursion complexity ologn insert data in bst using recursion complexity ologn preorder postorder inorder traversal bst the tree is created for testing 10 6 15 4 9 12 24 7 20 30 18 get the number of elements using recursion complexity o logn search data in bst using recursion complexity o logn go to right root go to left root insert data in bst using recursion complexity o logn the data is already there go to left root if left root is a node left root is a none go to right root if right root is a node preorder postorder inorder traversal bst the tree is created for testing 10 6 15 4 9 12 24 7 20 30 18
import unittest class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None class BST(object): def __init__(self): self.root = None def get_root(self): return self.root def size(self): return self.recur_size(self.root) def recur_size(self, root): if root is None: return 0 else: return 1 + self.recur_size(root.left) + self.recur_size(root.right) def search(self, data): return self.recur_search(self.root, data) def recur_search(self, root, data): if root is None: return False if root.data == data: return True elif data > root.data: return self.recur_search(root.right, data) else: return self.recur_search(root.left, data) def insert(self, data): if self.root: return self.recur_insert(self.root, data) else: self.root = Node(data) return True def recur_insert(self, root, data): if root.data == data: return False elif data < root.data: if root.left: return self.recur_insert(root.left, data) else: root.left = Node(data) return True else: if root.right: return self.recur_insert(root.right, data) else: root.right = Node(data) return True def preorder(self, root): if root: print(str(root.data), end = ' ') self.preorder(root.left) self.preorder(root.right) def inorder(self, root): if root: self.inorder(root.left) print(str(root.data), end = ' ') self.inorder(root.right) def postorder(self, root): if root: self.postorder(root.left) self.postorder(root.right) print(str(root.data), end = ' ') class TestSuite(unittest.TestCase): def setUp(self): self.tree = BST() self.tree.insert(10) self.tree.insert(15) self.tree.insert(6) self.tree.insert(4) self.tree.insert(9) self.tree.insert(12) self.tree.insert(24) self.tree.insert(7) self.tree.insert(20) self.tree.insert(30) self.tree.insert(18) def test_search(self): self.assertTrue(self.tree.search(24)) self.assertFalse(self.tree.search(50)) def test_size(self): self.assertEqual(11, self.tree.size()) if __name__ == '__main__': unittest.main()
given a nonempty binary search tree and a target value find the value in the bst that is closest to the target note given target value is a floating point you are guaranteed to have only one unique value in the bst that is closest to the target definition for a binary tree node class treenodeobject def initself x self val x self left none self right none type root treenode type target float rtype int given a non empty binary search tree and a target value find the value in the bst that is closest to the target note given target value is a floating point you are guaranteed to have only one unique value in the bst that is closest to the target definition for a binary tree node class treenode object def __init__ self x self val x self left none self right none type root treenode type target float rtype int
def closest_value(root, target): a = root.val kid = root.left if target < a else root.right if not kid: return a b = closest_value(kid, target) return min((a,b), key=lambda x: abs(target-x))
write a function countleftnode returns the number of left children in the tree for example the following tree has four left children the nodes storing the values 6 3 7 and 10 9 6 12 3 8 10 15 7 18 countleftnode 4 the tree is created for testing 9 6 12 3 8 10 15 7 18 countleftnode 4 the tree is created for testing 9 6 12 3 8 10 15 7 18 count_left_node 4
import unittest from bst import Node from bst import bst def count_left_node(root): if root is None: return 0 elif root.left is None: return count_left_node(root.right) else: return 1 + count_left_node(root.left) + count_left_node(root.right) class TestSuite(unittest.TestCase): def setUp(self): self.tree = bst() self.tree.insert(9) self.tree.insert(6) self.tree.insert(12) self.tree.insert(3) self.tree.insert(8) self.tree.insert(10) self.tree.insert(15) self.tree.insert(7) self.tree.insert(18) def test_count_left_node(self): self.assertEqual(4, count_left_node(self.tree.root)) if __name__ == '__main__': unittest.main()
given a root node reference of a bst and a key delete the node with the given key in the bst return the root node reference possibly updated of the bst basically the deletion can be divided into two stages search for a node to remove if the node is found delete the node note time complexity should be oheight of tree example root 5 3 6 2 4 null 7 key 3 5 3 6 2 4 7 given key to delete is 3 so we find the node with value 3 and delete it one valid answer is 5 4 6 2 null null 7 shown in the following bst 5 4 6 2 7 another valid answer is 5 2 6 null 4 null 7 5 2 6 4 7 type root treenode type key int rtype treenode find the right most leaf of the left subtree attach right child to the right of that leaf return left child instead of root a k a delete root if left or right child got deleted the returned root is the child of the deleted node type root treenode type key int rtype treenode find the right most leaf of the left sub tree attach right child to the right of that leaf return left child instead of root a k a delete root if left or right child got deleted the returned root is the child of the deleted node
class Solution(object): def delete_node(self, root, key): if not root: return None if root.val == key: if root.left: left_right_most = root.left while left_right_most.right: left_right_most = left_right_most.right left_right_most.right = root.right return root.left else: return root.right elif root.val > key: root.left = self.deleteNode(root.left, key) else: root.right = self.deleteNode(root.right, key) return root
write a function depthsum returns the sum of the values stored in a binary search tree of integers weighted by the depth of each value for example 9 6 12 3 8 10 15 7 18 depthsum 19 2612 3381015 4718 the tree is created for testing 9 6 12 3 8 10 15 7 18 depthsum 19 2612 3381015 4718 the tree is created for testing 9 6 12 3 8 10 15 7 18 depth_sum 1 9 2 6 12 3 3 8 10 15 4 7 18
import unittest from bst import Node from bst import bst def depth_sum(root, n): if root: return recur_depth_sum(root, 1) def recur_depth_sum(root, n): if root is None: return 0 elif root.left is None and root.right is None: return root.data * n else: return n * root.data + recur_depth_sum(root.left, n+1) + recur_depth_sum(root.right, n+1) class TestSuite(unittest.TestCase): def setUp(self): self.tree = bst() self.tree.insert(9) self.tree.insert(6) self.tree.insert(12) self.tree.insert(3) self.tree.insert(8) self.tree.insert(10) self.tree.insert(15) self.tree.insert(7) self.tree.insert(18) def test_depth_sum(self): self.assertEqual(253, depth_sum(self.tree.root, 4)) if __name__ == '__main__': unittest.main()
write a function height returns the height of a tree the height is defined to be the number of levels the empty tree has height 0 a tree of one node has height 1 a root node with one or two leaves as children has height 2 and so on for example height of tree is 4 9 6 12 3 8 10 15 7 18 height 4 the tree is created for testing 9 6 12 3 8 10 15 7 18 countleftnode 4 the tree is created for testing 9 6 12 3 8 10 15 7 18 count_left_node 4
import unittest from bst import Node from bst import bst def height(root): if root is None: return 0 else: return 1 + max(height(root.left), height(root.right)) class TestSuite(unittest.TestCase): def setUp(self): self.tree = bst() self.tree.insert(9) self.tree.insert(6) self.tree.insert(12) self.tree.insert(3) self.tree.insert(8) self.tree.insert(10) self.tree.insert(15) self.tree.insert(7) self.tree.insert(18) def test_height(self): self.assertEqual(4, height(self.tree.root)) if __name__ == '__main__': unittest.main()
given a binary tree determine if it is a valid binary search tree bst assume a bst is defined as follows the left subtree of a node contains only nodes with keys less than the node s key the right subtree of a node contains only nodes with keys greater than the node s key both the left and right subtrees must also be binary search trees example 1 2 1 3 binary tree 2 1 3 return true example 2 1 2 3 binary tree 1 2 3 return false type root treenode rtype bool type root treenode rtype bool
def is_bst(root): stack = [] pre = None while root or stack: while root: stack.append(root) root = root.left root = stack.pop() if pre and root.val <= pre.val: return False pre = root root = root.right return True