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 * fr...
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 complexi...
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 binar...
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 min...
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...
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...
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: retur...
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 olog2lo...
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) / (ar...
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 doe...
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_s...
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 ...
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...
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 t...
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 inp...
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[...
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 th...
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 list...
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: ...
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 or...
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: ...
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 pa...
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 = m...
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 index...
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...
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 pr...
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 remov...
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 powerse...
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): ...
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...
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) i...
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 ...
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(...
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 ...
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_...
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 swap...
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 = ...
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 arr...
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...
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...
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 whil...
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...
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 ...
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...
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 t...
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...
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 geeks...
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] = rever...
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 retur...
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 =...
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...
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 ...
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] ...
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 ...
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, ...
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 ...
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, ...
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 s...
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...
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.app...
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 t...
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.appe...
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 lengthlongestpathinpu...
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) wh...
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...
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 valu...
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...
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 ...
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 ret...
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): r...
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 solut...
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): ...
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 i...
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: ...
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...
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...
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 en...
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...
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...
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...
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 cr...
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): re...
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 al...
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 ar...
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 we...
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 * ...
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...
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("...
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...
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 = ind...
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 i...
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: re...
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[(...
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 th...
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...
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 ...
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(...
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...
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 te...
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 pa...
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 comproblems...
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 ...
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, diction...
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 ...
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[...
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 compr...
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 ...
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 in...
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_po...
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), le...
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 pana...
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 implementatio...
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_...
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 n...
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 refere...
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__ ...
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...
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] re...
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...
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 e...
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...
morse_code = { 'a':".-", 'b':"-...", 'c':"-.-.", 'd': "-..", 'e':".", 'f':"..-.", 'g':"--.", 'h':"....", 'i':"..", 'j':".---", 'k':"-.-", 'l':".-..", 'm':"--", 'n':"-.", 'o':"---", 'p':".--.", 'q':"--.-", 'r':".-.", 's':"...", 't':"-", ...
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...
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]) e...
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 ...
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 prefi...
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 ins...
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.nod...
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 ...
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): ...
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...
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+...
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...
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(s...
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 ...
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 1...
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): ...
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 ex...
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.r...
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 1...
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.da...
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 t...
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.in...
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 b...
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