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 i... | 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... |
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 peop... | # 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:
# T... |
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
"""
... |
Collection of search algorithms: finding the needle in a haystack. | from .binary_search import *
from .ternary_search import *
from .first_occurrence import *
from .last_occurrence import *
from .linear_search import *
from .search_insert import *
from .two_sum import *
from .search_range import *
from .find_min_rotate import *
from .search_rotate import *
from .jump_search import *
fr... |
Binary Search Find an element in a sorted array in ascending order. For Binary Search, TN TN2 O1 the recurrence relation Apply Masters Theorem for computing Run time complexity of recurrence relations: TN aTNb fN Here, a 1, b 2 log a base b 1 also, here fN nc logkn k 0 c log a base b So, TN ONc logk1N ... | # 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... |
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 ... | 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 a... |
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
#pri... |
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 Compl... | 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, ... |
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 ... | 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/... |
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(arr... |
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
retu... |
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... | 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:
... |
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
"""
... |
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 ta... | 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[mi... |
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... | 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 ... |
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... | 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 ... |
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 i... | 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)-... |
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):
... |
! 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 th... | #! /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.
... |
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... | 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(S... |
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 nonparall... | 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(de... |
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):
#c... |
https:en.wikipedia.orgwikiBubblesort Worstcase performance: ON2 If you call bubblesortarr,True, you can see the process of the sort Default is simulation False | def bubble_sort(arr, simulation=False):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
n = len(arr)
swapped = True
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
x = -1
while swapped:
swapped = False
x = x + 1
for i in range(... |
Bucket Sort Complexity: On2 The complexity is dominated by nextSort The number of buckets and make buckets Assign values into bucketsort Sort We will use insertion sort here. | 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:
inde... |
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)
swap... |
https:en.wikipedia.orgwikiCombsort Worstcase performance: ON2 | def comb_sort(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
n = len(arr)
gap = n
shrink = 1.3
sorted = False
while not sorted:
gap = int(gap / shrink)
if gap > 1:
sorted = False
else:
gap = 1
sorted = True
i = ... |
Countingsort Sorting a array which has no element greater than k Creating a new temparr,where temparri contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the resultarr return the resultarr Complexity: 0n in case there are negative elements, change the a... | 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
... |
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... | 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... |
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]
r... |
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 He... | 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_heapif... |
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] > cu... |
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 resu... | 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 togethe... |
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):... |
https:en.wikipedia.orgwikiPigeonholesort Time complexity: On Range where n number of elements and Range possible values in the array Suitable for lists where the number of elements and key values are mostly the same. | def pigeonhole_sort(arr):
Max = max(arr)
Min = min(arr)
size = Max - Min + 1
holes = [0]*size
for i in arr:
holes[i-Min] += 1
i = 0
for count in range(size):
while holes[count] > 0:
holes[count] -= 1
arr[i] = count + Min
i += 1
retur... |
Quick sort Complexity: best On logn avg On logn, worst ON2 Start our two recursive calls | 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 quic... |
radix sort complexity: Onk n . n is the size of input list and k is the digit length of the number | def radix_sort(arr, simulation=False):
position = 1
max_number = max(arr)
iteration = 0
if simulation:
print("iteration", iteration, ":", *arr)
while position <= max_number:
queue_list = [list() for _ in range(10)]
for num in arr:
digit_number = num // position... |
Selection Sort Complexity: On2 Select the correct value | 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 ... |
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 ... |
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 f... | def sort_colors(nums):
i = j = 0
for k in range(len(nums)):
v = nums[k]
nums[k] = 2
if v < 2:
nums[j] = 1
j += 1
if v == 0:
nums[i] = 0
i += 1
if __name__ == "__main__":
nums = [0, 1, 1, 1, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 1, 1, ... |
Stooge Sort Time Complexity : On2.709 Reference: https:www.geeksforgeeks.orgstoogesort If first element is smaller than last, swap them If there are more than 2 elements in the array Recursively sort first 2 3 elements Recursively sort last 2 3 elements Recursively sort first 2 3 elements again to confirm | 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... |
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, ()):
s... |
Given an unsorted array nums, reorder it such that nums0 nums1 nums2 nums3.... | def wiggle_sort(nums):
for i in range(len(nums)):
if (i % 2 == 1) == (nums[i-1] > nums[i]):
nums[i-1], nums[i] = nums[i], nums[i-1]
if __name__ == "__main__":
array = [3, 5, 2, 1, 6, 4]
print(array)
wiggle_sort(array)
print(array)
|
Given a stack, a function isconsecutive takes a stack as a parameter and that returns whether or not the stack contains a sequence of consecutive integers starting from the bottom of the stack returning true if it does, returning false if it does not. For example: bottom 3, 4, 5, 6, 7 top Then the call of isconsecutive... | 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 c... |
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... | def is_sorted(stack):
storage_stack = []
for i in range(len(stack)):
if len(stack) == 0:
break
first_val = stack.pop()
if len(stack) == 0:
break
second_val = stack.pop()
if first_val < second_val:
return False
storage_stack.appe... |
def lengthLongestPathinput: maxlen 0 pathlen 0: 0 for line in input.splitlines: print printline:, line name line.strip't' printname:, name depth lenline lenname printdepth:, depth if '.' in name: maxlen maxmaxlen, pathlendepth lenname else: pathlendepth 1 pathlendepth lenname 1 printmaxlen:, maxlen return ma... | # 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)
# ... |
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 ma... |
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)
... |
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... | 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 '/' + ... |
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. p... | 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
... |
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 Not... | import collections
def first_stutter(stack):
storage_stack = []
for i in range(len(stack)):
storage_stack.append(stack.pop())
for i in range(len(storage_stack)):
val = storage_stack.pop()
stack.append(val)
stack.append(val)
return stack
def second_stutter(stack):
... |
Given a stack, switchpairs function takes a stack as a parameter and that switches successive pairs of numbers starting at the bottom of the stack. For example, if the stack initially stores these values: bottom 3, 8, 17, 9, 1, 10 top Your function should switch the first pair 3, 8, the second pair 17, 9, ...: bottom 8... | import collections
def first_switch_pairs(stack):
storage_stack = []
for i in range(len(stack)):
storage_stack.append(stack.pop())
for i in range(len(storage_stack)):
if len(storage_stack) == 0:
break
first = storage_stack.pop()
if len(storage_stack) == 0: # ... |
Given a string containing just the characters '', '', '', '', '' and '', determine if the input string is valid. The brackets must close in the correct order, and are all valid but and are not. | def is_valid(s: str) -> bool:
stack = []
dic = {")": "(",
"}": "{",
"]": "["}
for char in s:
if char in dic.values():
stack.append(char)
elif char in dic:
if not stack or dic[char] != stack.pop():
return False
return not stack... |
Implementation of the MisraGries algorithm. Given a list of items and a value k, it returns the every item in the list that appears at least nk times, where n is the length of the array By default, k is set to 2, solving the majority problem. For the majority problem, this algorithm only guarantees that if there is an ... | 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[v... |
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 ... | 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
... |
Given two binary strings, return their sum also a binary string. For example, a 11 b 1 Return 100. | def add_binary(a, b):
s = ""
c, i, j = 0, len(a)-1, len(b)-1
zero = ord('0')
while (i >= 0 or j >= 0 or c == 1):
if (i >= 0):
c += ord(a[i]) - zero
i -= 1
if (j >= 0):
c += ord(b[j]) - zero
j -= 1
s = chr(c % 2 + zero) + s
c... |
Atbash cipher is mapping the alphabet to it's reverse. So if we take a as it is the first letter, we change it to the last z. Example: Attack at dawn Zggzxp zg wzdm Complexity: On | def atbash(s):
translated = ""
for i in range(len(s)):
n = ord(s[i])
if s[i].isalpha():
if s[i].isupper():
x = n - ord('A')
translated += chr(ord('Z') - x)
if s[i].islower():
x = n - ord('a... |
Given an api which returns an array of words and an array of symbols, display the word with their matched symbol surrounded by square brackets. If the word string matches more than one symbol, then choose the one with longest length. ex. 'Microsoft' matches 'i' and 'cro': Example: Words array: 'Amazon', 'Microsoft', 'G... | from functools import reduce
def match_symbol(words, symbols):
import re
combined = []
for s in symbols:
for c in words:
r = re.search(s, c)
if r:
combined.append(re.sub(s, "[{}]".format(s), c))
return combined
def match_symbol_1(words, symbols):
re... |
Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c. O... | 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: ... | 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 bracket... | # 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... |
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 exp... | # 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 act... |
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... | # 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 t... |
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 valu... | """
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):
... |
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"];
... |
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 p... | 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].l... |
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)):
... |
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 outpu... | 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... | 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
patt... |
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:leetco... | """
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_prefi... |
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:
... |
For a given string and dictionary, how many sentences can you make from the string, such that all the words are contained in the dictionary. eg: for given string appletablet apple, tablet applet, able, t apple, table, t app, let, able, t applet, app, let, apple, t, applet 3 thing, thing 1 | count = 0
def make_sentence(str_piece, dictionaries):
global count
if len(str_piece) == 0:
return True
for i in range(0, len(str_piece)):
prefix, suffix = str_piece[0:i], str_piece[i:]
if prefix in dictionaries:
if suffix in dictionaries or make_sentence(suffix, diction... |
At a job interview, you are challenged to write an algorithm to check if a given string, s, can be formed from two other strings, part1 and part2. The restriction is that the characters in part1 and part2 are in the same order as in s. The interviewer gives you the following example and tells you to figure out the rest... | # 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 ... |
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:leet... | 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 c... |
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 input... | def multiply(num1: "str", num2: "str") -> "str":
interm = []
zero = ord('0')
i_pos = 1
for i in reversed(num1):
j_pos = 1
add = 0
for j in reversed(num2):
mult = (ord(i)-zero) * (ord(j)-zero) * j_pos * i_pos
j_pos *= 10
add += mult
i_po... |
Given two strings S and T, determine if they are both one edit distance apart. :type s: str :type t: str :rtype: bool | 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:]
... |
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 Fin... | 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)
... |
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
#su... |
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... | 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 t... | 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__ ... |
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... | 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... |
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 ... | 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... |
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... | 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 = T... |
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... | morse_code = {
'a':".-",
'b':"-...",
'c':"-.-.",
'd': "-..",
'e':".",
'f':"..-.",
'g':"--.",
'h':"....",
'i':"..",
'j':".---",
'k':"-.-",
'l':".-..",
'm':"--",
'n':"-.",
'o':"---",
'p':".--.",
'q':"--.-",
'r':".-.",
's':"...",
't':"-",
... |
Create a function that will validate if given parameters are valid geographical coordinates. Valid coordinates look like the following: 23.32353342, 32.543534534. The return value should be either true or false. Latitude which is first float can be between 0 and 90, positive or negative. Longitude which is second float... | # 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:
... |
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 t... | # 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 ... |
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: sel... | 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
"""
# Cre... |
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 sub... | 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.... |
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 ... |
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def array_to_bst(nums):
if not nums:
return None
mid = len(nums)//2
node = TreeNode(nums[mid])
node.left = array_to_bst(nums[:mid])
node.right = array_to_bst(nums[mid+... |
Implement Binary Search Tree. It has method: 1. Insert 2. Search 3. Size 4. Traversal Preorder, Inorder, Postorder Get the number of elements Using recursion. Complexity OlogN Search data in bst Using recursion. Complexity OlogN Insert data in bst Using recursion. Complexity OlogN Preorder, Postorder, Inorder traversal... | 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 ... |
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,... | # 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(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.