Prompt
stringlengths
16
11.5k
Completions
stringlengths
84
25.3k
Queue Abstract Data Type ADT Queue creates a new queue that is empty. It needs no parameters and returns an empty queue. enqueueitem adds a new item to the rear of the queue. It needs the item and returns nothing. dequeue removes the front item from the queue. It needs no parameters and returns the item. The queue is modified. isEmpty tests to see whether the queue is empty. It needs no parameters and returns a boolean value. size returns the number of items in the queue. It needs no parameters and returns an integer. peek returns the front element of the queue. Initialize python List with capacity 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 front element of queue. if self.isempty: raise IndexErrorQueue is empty return self.arrayself.front def expandself: self.array None lenself.array class QueueNode: def initself, value: self.value value self.next None class LinkedListQueueAbstractQueue: def initself: super.init self.front None self.rear None def iterself: probe self.front while True: if probe is None: return yield probe.value probe probe.next def enqueueself, value: node QueueNodevalue if self.front is None: self.front node self.rear node else: self.rear.next node self.rear node self.size 1 def dequeueself: if self.isempty: raise IndexErrorQueue is empty value self.front.value if self.front is self.rear: self.front None self.rear None else: self.front self.front.next self.size 1 return value def peekself:
from abc import ABCMeta, abstractmethod class AbstractQueue(metaclass=ABCMeta): def __init__(self): self._size = 0 def __len__(self): return self._size def is_empty(self): return self._size == 0 @abstractmethod def enqueue(self, value): pass @abstractmethod def dequeue(self): pass @abstractmethod def peek(self): pass @abstractmethod def __iter__(self): pass class ArrayQueue(AbstractQueue): def __init__(self, capacity=10): """ Initialize python List with capacity 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. """ super().__init__() self._array = [None] * capacity self._front = 0 self._rear = 0 def __iter__(self): probe = self._front while True: if probe == self._rear: return yield self._array[probe] probe += 1 def enqueue(self, value): if self._rear == len(self._array): self._expand() self._array[self._rear] = value self._rear += 1 self._size += 1 def dequeue(self): if self.is_empty(): raise IndexError("Queue is empty") value = self._array[self._front] self._array[self._front] = None self._front += 1 self._size -= 1 return value def peek(self): """returns the front element of queue.""" if self.is_empty(): raise IndexError("Queue is empty") return self._array[self._front] def _expand(self): """expands size of the array. Time Complexity: O(n) """ self._array += [None] * len(self._array) class QueueNode: def __init__(self, value): self.value = value self.next = None class LinkedListQueue(AbstractQueue): def __init__(self): super().__init__() self._front = None self._rear = None def __iter__(self): probe = self._front while True: if probe is None: return yield probe.value probe = probe.next def enqueue(self, value): node = QueueNode(value) if self._front is None: self._front = node self._rear = node else: self._rear.next = node self._rear = node self._size += 1 def dequeue(self): if self.is_empty(): raise IndexError("Queue is empty") value = self._front.value if self._front is self._rear: self._front = None self._rear = None else: self._front = self._front.next self._size -= 1 return value def peek(self): """returns the front element of queue.""" if self.is_empty(): raise IndexError("Queue is empty") return self._front.value
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers h, k, where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Note: The number of people is less than 1,100. Example Input: 7,0, 4,4, 7,1, 5,0, 6,1, 5,2 Output: 5,0, 7,0, 5,2, 6,1, 4,4, 7,1 :type people: ListListint :rtype: ListListint
# Suppose you have a random list of people standing in a queue. # Each person is described by a pair of integers (h, k), # where h is the height of the person and k is the number of people # in front of this person who have a height greater than or equal to h. # Write an algorithm to reconstruct the queue. # Note: # The number of people is less than 1,100. # Example # Input: # [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] # Output: # [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] def reconstruct_queue(people): """ :type people: List[List[int]] :rtype: List[List[int]] """ queue = [] people.sort(key=lambda x: (-x[0], x[1])) for h, k in people: queue.insert(k, [h, k]) return queue
Initialize your data structure here. :type v1: Listint :type v2: Listint :rtype: int :rtype: bool
class ZigZagIterator: def __init__(self, v1, v2): """ Initialize your data structure here. :type v1: List[int] :type v2: List[int] """ self.queue = [_ for _ in (v1, v2) if _] print(self.queue) def next(self): """ :rtype: int """ v = self.queue.pop(0) ret = v.pop(0) if v: self.queue.append(v) return ret def has_next(self): """ :rtype: bool """ if self.queue: return True return False l1 = [1, 2] l2 = [3, 4, 5, 6] it = ZigZagIterator(l1, l2) while it.has_next(): print(it.next())
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)) def binary_search(array, query): """ Worst-case Complexity: O(log(n)) reference: https://en.wikipedia.org/wiki/Binary_search_algorithm """ 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 #In this below function we are passing array, it's first index , last index and value to be searched def binary_search_recur(array, low, high, val): """ 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 if low > high: return -1 mid = low + (high-low)//2 #This mid will not break integer range if val < array[mid]: return binary_search_recur(array, low, mid - 1, val) #Go search in the left subarray if val > array[mid]: return binary_search_recur(array, mid + 1, high, val) #Go search in the right subarray 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.
def find_min_rotate(array): """ Finds the minimum element in a sorted array that has been rotated. """ 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): """ Finds the minimum element in a sorted array that has been rotated. """ 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
def first_occurrence(array, query): """ Returns the index of the first occurance of the given element in an array. The array has to be sorted in increasing order. """ low, high = 0, len(array) - 1 while low <= high: mid = low + (high-low)//2 #Now mid will be ininteger range #print("lo: ", lo, " hi: ", hi, " mid: ", mid) 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
from typing import List def interpolation_search(array: List[int], search_key: int) -> int: """ :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 high = len(array) - 1 low = 0 while (low <= high) and (array[low] <= search_key <= array[high]): # calculate the search position pos = low + int(((search_key - array[low]) * (high - low) / (array[high] - array[low]))) # search_key is found if array[pos] == search_key: return pos # if search_key is larger, search_key is in upper part if array[pos] < search_key: low = pos + 1 # if search_key is smaller, search_key is in lower part 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
import math def jump_search(arr,target): """ 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 """ length = len(arr) block_size = int(math.sqrt(length)) block_prev = 0 block= block_size # return -1 means that array doesn't contain target value # find block that contains target value if arr[length - 1] < target: return -1 while block <= length and arr[block - 1] < target: block_prev = block block += block_size # find target value in block while arr[block_prev] < target : block_prev += 1 if block_prev == min(block, length) : return -1 # if there is target value in array, return it 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.
def last_occurrence(array, query): """ Returns the index of the last occurance of the given element in an array. The array has to be sorted in increasing order. """ 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.
def linear_search(array, query): """ 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. """ 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
import bisect def next_greatest_letter(letters, target): """ Using bisect libarary """ index = bisect.bisect(letters, target) return letters[index % len(letters)] def next_greatest_letter_v1(letters, target): """ Using binary search: complexity O(logN) """ 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): """ Brute force: complexity O(N) """ 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
def search_insert(array, val): """ 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 """ 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
def search_range(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ low = 0 high = len(nums) - 1 # breaks at low == high # both pointing to first occurence of target 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.
def search_rotate(array, val): """ Finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot. """ 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 # Recursion technique def search_rotate_recur(array, low, high, val): """ Finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot. """ if low >= high: return -1 mid = (low + high) // 2 if val == array[mid]: # found element return mid if array[low] <= array[mid]: if array[low] <= val <= array[mid]: return search_rotate_recur(array, low, mid - 1, val) # Search left return search_rotate_recur(array, mid + 1, high, val) # Search right if array[mid] <= val <= array[high]: return search_rotate_recur(array, mid + 1, high, val) # Search right return search_rotate_recur(array, low, mid - 1, val) # Search left
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
def ternary_search(left, right, key, arr): """ 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. """ 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]: # key lies between l and mid1 right = mid1 - 1 elif key > arr[mid2]: # key lies between mid2 and r left = mid2 + 1 else: # key lies between mid1 and mid2 left = mid1 + 1 right = mid2 - 1 # key not found 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.
def two_sum(numbers, target): """ 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. """ 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): """ Given a list of numbers, find the indices of two numbers such that their sum is the given target. Using a hash table. """ 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): """ 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. """ left = 0 # pointer 1 holds from left of array numbers right = len(numbers) - 1 # pointer 2 holds from right of array numbers 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
def find_keyboard_row(words): """ :type words: List[str] :rtype: List[str] """ keyboard = [ set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm'), ] result = [] for word in words: for key in keyboard: 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. """ import random class RandomizedSet(): """ idea: shoot """ def __init__(self): self.elements = [] self.index_map = {} # element -> index 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) # Remove a half 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
from itertools import chain, combinations """ 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 """ def powerset(iterable): """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 """ "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): """ 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...} """ 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): """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 = set(e for s in subsets.keys() for e in subsets[s]) # elements don't cover universe -> invalid input for set cover if elements != universe: return None # track elements of universe covered covered = set() cover_sets = [] while covered != universe: min_cost_elem_ratio = float("inf") min_set = None # find set with minimum cost:elements_added ratio for s, elements in subsets.items(): new_elements = len(elements - covered) # set may have same elements as already covered -> new_elements = 0 # check to avoid division by 0 error 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) # union 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
def bitonic_sort(arr, reverse=False): """ 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 """ 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 #end of function(compare and bitionic_merge) definition n = len(arr) if n <= 1: return arr # checks if n is power of two 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
import random def bogo_sort(arr, simulation=False): """Bogo Sort Best Case Complexity: O(n) Worst Case Complexity: O(∞) Average Case Complexity: O(n(n-1)!) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) def is_sorted(arr): #check the array is inorder 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.
def bucket_sort(arr): ''' Bucket Sort Complexity: O(n^2) The complexity is dominated by nextSort ''' # The number of buckets and make buckets num_buckets = len(arr) buckets = [[] for bucket in range(num_buckets)] # Assign values into bucket_sort for value in arr: index = value * num_buckets // (max(arr) + 1) buckets[index].append(value) # Sort sorted_list = [] for i in range(num_buckets): sorted_list.extend(next_sort(buckets[i])) return sorted_list def next_sort(arr): # We will use insertion sort here. 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
def cocktail_shaker_sort(arr): """ 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 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
def counting_sort(arr): """ 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) """ m = min(arr) # in case there are negative elements, change the array to all positive element different = 0 if m < 0: # save the change, so that we can convert the array back to all positive number 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 # temp_array[i] contain the times the number i appear in arr for i in range(1, k + 1): temp_arr[i] = temp_arr[i] + temp_arr[i - 1] # temp_array[i] contain the number of element less than or equal i in arr result_arr = arr.copy() # creating a result_arr an put the element in a correct positon 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.
def cycle_sort(arr): """ 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) """ len_arr = len(arr) # Finding cycle to rotate. for cur in range(len_arr - 1): item = arr[cur] # Finding an indx to put items in. index = cur for i in range(cur + 1, len_arr): if arr[i] < item: index += 1 # Case of there is not a cycle if index == cur: continue # Putting the item immediately right after the duplicate item or on the right. while item == arr[index]: index += 1 arr[index], item = item, arr[index] # Rotating the remaining cycle. while index != cur: # Finding where to put the item. index = cur for i in range(cur + 1, len_arr): if arr[i] < item: index += 1 # After item is duplicated, put it in place or put it there. while item == arr[index]: index += 1 arr[index], item = item, arr[index] return arr
Reference : https:en.wikipedia.orgwikiSortingalgorithmExchangesort Complexity : On2
def exchange_sort(arr): """ Reference : https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort Complexity : O(n^2) """ 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
def max_heap_sort(arr, simulation=False): """ Heap Sort that uses a max heap to sort an array in ascending order Complexity: O(n log(n)) """ iteration = 0 if simulation: print("iteration",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): """ Max heapify helper for max_heap_sort """ last_parent = (end - 1) // 2 # Iterate from last parent to first for parent in range(last_parent, -1, -1): current_parent = parent # Iterate from current_parent to last_parent while current_parent <= last_parent: # Find greatest child of current_parent child = 2 * current_parent + 1 if child + 1 <= end and arr[child] < arr[child + 1]: child = child + 1 # Swap if child is greater than parent 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) # If no swap occurred, no need to keep iterating else: break arr[0], arr[end] = arr[end], arr[0] return iteration def min_heap_sort(arr, simulation=False): """ Heap Sort that uses a min heap to sort an array in ascending order Complexity: O(n log(n)) """ iteration = 0 if simulation: print("iteration",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): """ Min heapify helper for min_heap_sort """ # Offset last_parent by the start (last_parent calculated as if start index was 0) # All array accesses need to be offset by start end = len(arr) - 1 last_parent = (end - start - 1) // 2 # Iterate from last parent to first for parent in range(last_parent, -1, -1): current_parent = parent # Iterate from current_parent to last_parent while current_parent <= last_parent: # Find lesser child of current_parent child = 2 * current_parent + 1 if child + 1 <= end - start and arr[child + start] > arr[ child + 1 + start]: child = child + 1 # Swap if child is less than parent 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) # If no swap occurred, no need to keep iterating else: break return iteration
Insertion Sort Complexity: On2 Swap the number down the list Break and do the final swap
def insertion_sort(arr, simulation=False): """ Insertion Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cursor: # Swap the number down the list arr[pos] = arr[pos - 1] pos = pos - 1 # Break and do the final swap 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
def can_attend_meetings(intervals): """ :type intervals: List[Interval] :rtype: bool """ intervals = sorted(intervals, key=lambda x: x.start) for i in range(1, len(intervals)): if intervals[i].start < intervals[i - 1].end: 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.
def merge_sort(arr): """ Merge Sort Complexity: O(n log(n)) """ # Our recursive base case if len(arr) <= 1: return arr mid = len(arr) // 2 # Perform merge_sort recursively on both halves left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:]) # Merge each side together # return merge(left, right, arr.copy()) # changed, no need to copy, mutate inplace. merge(left,right,arr) return arr def merge(left, right, merged): """ Merge helper Complexity: O(n) """ left_cursor, right_cursor = 0, 0 while left_cursor < len(left) and right_cursor < len(right): # Sort each one and place into the result 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 # Add the left overs if there's any left to the result for left_cursor in range(left_cursor, len(left)): merged[left_cursor + right_cursor] = left[left_cursor] # Add the left overs if there's any left to the result for right_cursor in range(right_cursor, len(right)): merged[left_cursor + right_cursor] = right[right_cursor] # Return result # return merged # do not return anything, as it is replacing inplace.
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
def pancake_sort(arr): """ Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time complexity : O(N^2) """ len_arr = len(arr) if len_arr <= 1: return arr for cur in range(len(arr), 1, -1): #Finding index of maximum number in arr index_max = arr.index(max(arr[0:cur])) if index_max+1 != cur: #Needs moving if index_max != 0: #reverse from 0 to index_max arr[:index_max+1] = reversed(arr[:index_max+1]) # Reverse list 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
def quick_sort(arr, simulation=False): """ Quick sort Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) arr, _ = quick_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) # Start our two recursive calls 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]: # last is the pivot 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
def selection_sort(arr, simulation=False): """ Selection Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): # "Select" the correct value 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
def shell_sort(arr): ''' Shell Sort Complexity: O(n^2) ''' n = len(arr) # Initialize size of the gap gap = n//2 while gap > 0: y_index = gap while y_index < len(arr): y = arr[y_index] x_index = y_index - 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
def stoogesort(arr, l, h): if l >= h: return # If first element is smaller # than last, swap them if arr[l]>arr[h]: t = arr[l] arr[l] = arr[h] arr[h] = t # If there are more than 2 elements in # the array if h-l + 1 > 2: t = (int)((h-l + 1)/3) # Recursively sort first 2 / 3 elements stoogesort(arr, l, (h-t)) # Recursively sort last 2 / 3 elements stoogesort(arr, l + t, (h)) # Recursively sort first 2 / 3 elements # again to confirm 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
GRAY, BLACK = 0, 1 def top_sort_recursive(graph): """ Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) """ order, enter, state = [], set(graph), {} def dfs(node): state[node] = GRAY #print(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) dfs(k) order.append(node) state[node] = BLACK while enter: dfs(enter.pop()) return order def top_sort(graph): """ Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) """ order, enter, state = [], set(graph), {} def is_ready(node): lst = graph.get(node, ()) 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
import collections def first_is_consecutive(stack): storage_stack = [] for i in range(len(stack)): first_value = stack.pop() if len(stack) == 0: # Case odd number of values in stack return True second_value = stack.pop() if first_value - second_value != 1: # Not consecutive return False stack.append(second_value) # Backup second value storage_stack.append(first_value) # Back up stack from storage stack 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: # Case odd number of values in stack return True second_value = stack.pop() if first_value - second_value != 1: # Not consecutive return False stack.append(second_value) # Backup second value q.append(first_value) # Back up stack from queue 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
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) # Backup stack 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 def length_longest_path(input): """ :type input: str :rtype: int """ curr_len, max_len = 0, 0 # running length and max length stack = [] # keep track of the name length for s in input.split('\n'): print("---------") print("<path>:", s) depth = s.count('\t') # the depth of current dir or file print("depth: ", depth) print("stack: ", stack) print("curlen: ", curr_len) while len(stack) > depth: # go back to the correct depth curr_len -= stack.pop() stack.append(len(s.strip('\t'))+1) # 1 is the length of '/' curr_len += stack[-1] # increase current length print("stack: ", stack) print("curlen: ", curr_len) if '.' in s: # update maxlen only when it is a file max_len = max(max_len, curr_len-1) # -1 is to minus one '/' 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 class OrderedStack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push_t(self, item): self.items.append(item) # push method to maintain order when pushing new elements 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
def remove_min(stack): storage_stack = [] if len(stack) == 0: # Stack is empty return stack # Find the smallest value min = stack.pop() stack.append(min) for i in range(len(stack)): val = stack.pop() if val <= min: min = val storage_stack.append(val) # Back up stack and remove min value 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
def simplify_path(path): """ :type path: str :rtype: str """ skip = {'..', '.', ''} stack = [] paths = path.split('/') for tok in paths: if tok == '..': if stack: stack.pop() elif tok not in skip: 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
from abc import ABCMeta, abstractmethod class AbstractStack(metaclass=ABCMeta): """Abstract Class for Stacks.""" 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): """ 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. """ 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): """returns the current top element of the stack.""" if self.is_empty(): raise IndexError("Stack is empty") return self._array[self._top] def _expand(self): """ expands size of the array. Time Complexity: O(n) """ self._array += [None] * len(self._array) # double the size of the array class StackNode: """Represents a single stack node.""" 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
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() # Put all values into queue from stack for i in range(len(stack)): q.append(stack.pop()) # Put values back into stack from queue for i in range(len(q)): stack.append(q.pop()) # Now, stack is reverse, put all values into queue from stack for i in range(len(stack)): q.append(stack.pop()) # Put 2 times value into stack from queue 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
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: # case: odd number of values in stack stack.append(first) break second = storage_stack.pop() stack.append(second) stack.append(first) return stack def second_switch_pairs(stack): q = collections.deque() # Put all values into queue from stack for i in range(len(stack)): q.append(stack.pop()) # Put values back into stack from queue for i in range(len(q)): stack.append(q.pop()) # Now, stack is reverse, put all values into queue from stack for i in range(len(stack)): q.append(stack.pop()) # Swap pairs by appending the 2nd value before appending 1st value for i in range(len(q)): if len(q) == 0: break first = q.pop() if len(q) == 0: # case: odd number of values in stack 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
def misras_gries(array,k=2): """Misra-Gries algorithm Keyword arguments: array -- list of integers k -- value of k (default 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
def one_sparse(array): """1-sparse algorithm Keyword arguments: array -- stream of tuples """ 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 #Helper function to check that every entry in the list is either 0 or the same as the #sum of signs def _check_every_number_in_bitsum(bitsum,sum_signs): for val in bitsum: if val != 0 and val != sum_signs : return False return True # Adds bit representation value to bitsum array 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:
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 = [] # reversely sort the symbols according to their lengths. symbols = sorted(symbols, key=lambda _: len(_), reverse=True) for word in words: for symbol in symbols: word_replaced = '' # once match, append the `word_replaced` to res, process next word if word.find(symbol) != -1: word_replaced = word.replace(symbol, '[' + symbol + ']') res.append(word_replaced) break # if this word matches no symbol, append it. if word_replaced == '': res.append(word) return res """ 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: """ 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". def decode_string(s): """ :type s: str :rtype: str """ 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 def domain_name_1(url): #grab only the non http(s) part full_domain_name = url.split('//')[-1] #grab the actual one depending on the len of the list actual_domain = full_domain_name.split('.') # case when www is in the url if (len(actual_domain) > 2): return actual_domain[1] # case when www is not in the url return actual_domain[0] # pythonic one liner 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. def encode(strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ res = '' for string in strs.split(): res += str(len(string)) + ":" + string return res def decode(s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ 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
def first_unique_char(s): """ :type s: str :rtype: int """ 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) """ def fizzbuzz(n): # Validate the input 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 # Alternative solution 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
def int_to_roman(num): """ :type num: int :rtype: str """ 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
from string import ascii_letters from collections import deque def is_palindrome(s): """ :type s: str :rtype: bool """ 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 """ 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 """ def remove_punctuation(s): """ Remove punctuation, case sensitivity and spaces """ return "".join(i.lower() for i in s if i in ascii_letters) # Variation 1 def string_reverse(s): return s[::-1] def is_palindrome_reverse(s): s = remove_punctuation(s) # can also get rid of the string_reverse function and just do this return s == s[::-1] in one line. if (s == string_reverse(s)): return True return False # Variation 2 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 # Variation 3 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 # Variation 4 (using deque) 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
def is_rotated(s1, s2): if len(s1) == len(s2): return s2 in s1 + s1 else: return False """ Another solution: brutal force Complexity: O(N^2) """ 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
from typing import Sequence, List def knuth_morris_pratt(text : Sequence, pattern : Sequence) -> List[int]: """ 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. """ n = len(text) m = len(pattern) pi = [0 for i in range(m)] i = 0 j = 0 # making pi table 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 # finding pattern 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 """ 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 """ Second solution: Vertical scanning """ 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] """ Third solution: Divide and Conquer """ 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)
Given string s, find the longest palindromic substring. Example1: input: dasdasdasdasdasdadsa output: asdadsa Example2: input: acdbbdaa output: dbbd Manacher's algorithm
def longest_palindrome(s): if len(s) < 2: return s n_str = '#' + '#'.join(s) + '#' p = [0] * len(n_str) mx, loc = 0, 0 index, maxlen = 0, 0 for i in range(len(n_str)): if i < mx and 2 * loc - i < len(n_str): p[i] = min(mx - i, p[2 * loc - i]) else: p[i] = 1 while p[i] + i < len(n_str) and i - p[i] >= 0 and n_str[ i - p[i]] == n_str[i + p[i]]: p[i] += 1 if i + p[i] > mx: mx = i + p[i] loc = i if p[i] > maxlen: index = i maxlen = p[i] s = n_str[index - p[index] + 1:index + p[index]] return s.replace('#', '')
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 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 # An iterative approach 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
def min_distance(word1, word2): """ Finds minimum distance by getting longest common subsequence :type word1: str :type word2: str :rtype: int """ return len(word1) + len(word2) - 2 * lcs(word1, word2, len(word1), len(word2)) def lcs(word1, word2, i, j): """ The length of longest common subsequence among the two given strings word1 and word2 """ 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): """ Finds minimum distance in a dynamic programming manner TC: O(length1*length2), SC: O(length1*length2) :type word1: str :type word2: str :rtype: int """ 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
def is_one_edit(s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) > len(t): return is_one_edit(t, s) if len(t) - len(s) > 1 or t == s: return False for i in range(len(s)): if s[i] != t[i]: 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:] # modify else: s = s[:i]+t[i]+s[i:] # insertion 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.
from string import ascii_lowercase def panagram(string): """ 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. """ 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 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): #ord maps the character to a number #subtract out the ASCII value of "a" to start the indexing at zero self.hash += (ord(self.text[i]) - ord("a")+1)*(26**(size_word - i -1)) #start index of current window self.window_start = 0 #end of index window self.window_end = size_word def move_window(self): if self.window_end <= len(self.text) - 1: #remove left letter from hash value 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)) #word_hash.move_window() 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
def repeat_substring(s): """ :type s: str :rtype: bool """ 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
from collections import defaultdict import urllib import urllib.parse # Here is a very non-pythonic grotesque solution def strip_url_params1(url, params_to_strip=None): if not params_to_strip: params_to_strip = [] if url: result = '' # final result to be returned tokens = url.split('?') domain = tokens[0] query_string = tokens[-1] result += domain # add the '?' to our result if it is in the url if len(tokens) > 1: result += '?' if not query_string: return url else: # logic for removing duplicate query strings # build up the list by splitting the query_string using digits 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) # logic for checking whether we should add the string to our result 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 # A very friendly pythonic solution (easy to follow) 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) # Here is my friend's solution using python's builtin libraries 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()
The signup page required her to input a name and a password. However, the password must be strong. The website considers a password to be strong if it satisfies the following criteria: 1 Its length is at least 6. 2 It contains at least one digit. 3 It contains at least one lowercase English character. 4 It contains at least one uppercase English character. 5 It contains at least one special character. The special characters are: ! She typed a random string of length in the password field but wasn't sure if it was strong. Given the string she typed, can you find the minimum number of characters she must add to make her password strong? Note: Here's the set of types of characters in a form you can paste in your solution: numbers 0123456789 lowercase abcdefghijklmnopqrstuvwxyz uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ specialcharacters ! Input Format The first line contains an integer denoting the length of the string. The second line contains a string consisting of characters, the password typed by Louise. Each character is either a lowercaseuppercase English alphabet, a digit, or a special character. Sample Input 1: strongpassword3,Ab1 Output: 3 Because She can make the password strong by adding characters,for example, hk, turning the password into Ab1hk which is strong. 2 characters aren't enough since the length must be at least 6. Sample Output 2: strongpassword11,Algorithms Output: 1 Because the password isn't strong, but she can make it strong by adding a single digit. Return the minimum number of characters to make the password strong
def strong_password(n, password): count_error = 0 # Return the minimum number of characters to make the password strong if any(i.isdigit() for i in password) == False: count_error = count_error + 1 if any(i.islower() for i in password) == False: count_error = count_error + 1 if any(i.isupper() for i in password) == False: count_error = count_error + 1 if any(i in '!@#$%^&*()-+' for i in password) == False: count_error = count_error + 1 return max(count_error, 6 - n)
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
def text_justification(words, max_width): ''' :type words: list :type max_width: int :rtype: list ''' ret = [] # return value row_len = 0 # current length of strs in a row row_words = [] # current words in a row index = 0 # the index of current word in words is_first_word = True # is current word the first in a row 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 # except for the first word, each word should have at least a ' ' before it. if tmp > max_width: row_words.pop() break row_len = tmp index += 1 is_first_word = False # here we have already got a row of str , then we should supplement enough ' ' to make sure the length is max_width. row = "" # if the row is the last if index == len(words): for word in row_words: row += (word + ' ') row = row[:-1] row += ' ' * (max_width - len(row)) # not the last row and more than one word 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 # row with only one word else: row += row_words[0] row += ' ' * (max_width - len(row)) ret.append(row) # after a row , reset those value 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 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 # friends solutions 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 # using regular expression 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
from tree.tree import TreeNode class AvlTree(object): """ An avl tree. """ def __init__(self): # Root node of the tree. self.node = None self.height = -1 self.balance = 0 def insert(self, key): """ Insert new key into node """ # Create new node 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): """ Re balance tree. After inserting or deleting a node, """ self.update_heights(recursive=False) self.update_balances(False) while self.balance < -1 or self.balance > 1: if self.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): """ Update tree height """ 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): """ Calculate tree balance factor """ 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): """ Right rotation """ new_root = self.node.left.node new_left_sub = new_root.right.node old_root = self.node self.node = new_root old_root.left.node = new_left_sub new_root.right.node = old_root def rotate_left(self): """ Left rotation """ new_root = self.node.right.node new_left_sub = new_root.left.node old_root = self.node self.node = new_root old_root.right.node = new_left_sub new_root.left.node = old_root def in_order_traverse(self): """ In-order traversal of the tree """ result = [] if not self.node: return result result.extend(self.node.left.in_order_traverse()) result.append(self.node.key) result.extend(self.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 Node: """ Class of Node""" def __init__(self): # self.is_leaf = is_leaf self.keys = [] self.children = [] def __repr__(self): return "<id_node: {0}>".format(self.keys) @property def is_leaf(self): """ Return if it is a leaf""" return len(self.children) == 0 class BTree: """ Class of 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] # child is left child of parent after splitting 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): """ overflow, tree increases in height """ 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: # find position where insert key i -= 1 if node.is_leaf: node.keys.insert(i + 1, key) else: # overflow if len(node.children[i + 1].keys) >= self.max_number_of_keys: self._split_child(node, i + 1) # decide which child is going to have a new key if node.keys[i + 1] < key: i += 1 self._insert_to_nonfull_node(node.children[i + 1], key) def find(self, key) -> bool: """ Finds key """ 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: # key not found in node if node.is_leaf: print("Key not found.") return False # key not found else: i = 0 number_of_keys = len(node.keys) # decide in which subtree may be key 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] # The leaf/node is correct 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): # 0 <-- 1 self._rotate_left(node, child_index) return True if child_index > 0: # merge child with brother on the left self._merge(node, child_index - 1, child_index) else: # merge child with brother on the right self._merge(node, child_index, child_index + 1) return True def _rotate_left(self, parent_node: Node, child_index: int): """ Take key from right brother of the child and transfer to the child """ 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) # make ownerless_child as a new biggest child (with highest key) # -> transfer from right subtree to left subtree parent_node.children[child_index].children.append(ownerless_child) def _rotate_right(self, parent_node: Node, child_index: int): """ Take key from left brother of the child and transfer to the child """ 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() # make ownerless_child as a new lowest child (with lowest key) # -> transfer from left subtree to right subtree 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]) # self._repair_tree(node, ch_index) 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]) # self._repair_tree(node, ch_index) 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
from tree.tree import TreeNode def bin_tree_to_list(root): """ type root: root class """ 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
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 """ Get the number of elements Using recursion. Complexity O(logN) """ 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) """ Search data in bst Using recursion. Complexity O(logN) """ 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: # Go to right root return self.recur_search(root.right, data) else: # Go to left root return self.recur_search(root.left, data) """ Insert data in bst Using recursion. Complexity O(logN) """ 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: # The data is already there return False elif data < root.data: # Go to left root if root.left: # If left root is a node return self.recur_insert(root.left, data) else: # left root is a None root.left = Node(data) return True else: # Go to right root if root.right: # If right root is a node return self.recur_insert(root.right, data) else: root.right = Node(data) return True """ Preorder, Postorder, Inorder traversal bst """ 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 = ' ') """ The tree is created for testing: 10 / \ 6 15 / \ / \ 4 9 12 24 / / \ 7 20 30 / 18 """ 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 def closest_value(root, target): """ :type root: TreeNode :type target: float :rtype: int """ 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))