Prompt
stringlengths 16
11.5k
| Completions
stringlengths 84
25.3k
|
---|---|
Given a list lst and a number N, create a new list that contains each number of the list at most N times without reordering. For example if N 2, and the input is 1,2,3,1,2,1,2,3, you take 1,2,3,1,2, drop the next 1,2 since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to 1,2,3,1,2,3 Time complexity On2 Time Complexity On, using hash tables. | import collections
# Time complexity O(n^2)
def delete_nth_naive(array, n):
ans = []
for num in array:
if ans.count(num) < n:
ans.append(num)
return ans
# Time Complexity O(n), using hash tables.
def delete_nth(array, n):
result = []
counts = collections.defaultdict(int) # keep track of occurrences
for i in array:
if counts[i] < n:
result.append(i)
counts[i] += 1
return result
|
Implement Flatten Arrays. Given an array that may contain nested arrays, produce a single resultant array. return list returns iterator Takes as input multi dimensional iterable and returns generator which produces one dimensional output. | from collections.abc import Iterable
# return list
def flatten(input_arr, output_arr=None):
if output_arr is None:
output_arr = []
for ele in input_arr:
if not isinstance(ele, str) and isinstance(ele, Iterable):
flatten(ele, output_arr) #tail-recursion
else:
output_arr.append(ele) #produce the result
return output_arr
# returns iterator
def flatten_iter(iterable):
"""
Takes as input multi dimensional iterable and
returns generator which produces one dimensional output.
"""
for element in iterable:
if not isinstance(element, str) and isinstance(element, Iterable):
yield from flatten_iter(element)
else:
yield element
|
There is a parking lot with only one empty spot. Given the initial state of the parking lot and the final state. Each step we are only allowed to move a car out of its place and move it into the empty spot. The goal is to find out the least movement needed to rearrange the parking lot from the initial state to the final state. Say the initial state is an array: 1, 2, 3, 0, 4, where 1, 2, 3, 4 are different cars, and 0 is the empty spot. And the final state is 0, 3, 2, 1, 4. We can swap 1 with 0 in the initial array to get 0, 2, 3, 1, 4 and so on. Each step swap with 0 only. Edit: Now also prints the sequence of changes in states. Output of this example : initial: 1, 2, 3, 0, 4 final: 0, 3, 2, 1, 4 Steps 4 Sequence : 0 2 3 1 4 2 0 3 1 4 2 3 0 1 4 0 3 2 1 4 e.g.: 4, 0, 2, 3, 1, 4, 2, 0, 3, 1, 4, 2, 3, 0, 1, 4, 0, 3, 2, 1, 4 thus: 1 2 3 0 4 zero 3, true, cartomove final3 1, pos initial.index1 0, switched 0, 3 0 2 3 1 4 zero 0, f, initial1 ! final1, switched 0,1 2 0 3 1 4 zero 1, t, cartomove final1 3, pos initial.index3 2, switched 1, 2 2 3 0 1 4 zero 2, t, cartomove final2 2, pos initial.index2 0, switched 0, 2 0 3 2 1 4 initial final | def garage(initial, final):
initial = initial[::] # prevent changes in original 'initial'
seq = [] # list of each step in sequence
steps = 0
while initial != final:
zero = initial.index(0)
if zero != final.index(0): # if zero isn't where it should be,
car_to_move = final[zero] # what should be where zero is,
pos = initial.index(car_to_move) # and where is it?
initial[zero], initial[pos] = initial[pos], initial[zero]
else:
for i in range(len(initial)):
if initial[i] != final[i]:
initial[zero], initial[i] = initial[i], initial[zero]
break
seq.append(initial[::])
steps += 1
return steps, seq
# e.g.: 4, [{0, 2, 3, 1, 4}, {2, 0, 3, 1, 4},
# {2, 3, 0, 1, 4}, {0, 3, 2, 1, 4}]
"""
thus:
1 2 3 0 4 -- zero = 3, true, car_to_move = final[3] = 1,
pos = initial.index(1) = 0, switched [0], [3]
0 2 3 1 4 -- zero = 0, f, initial[1] != final[1], switched 0,1
2 0 3 1 4 -- zero = 1, t, car_to_move = final[1] = 3,
pos = initial.index(3) = 2, switched [1], [2]
2 3 0 1 4 -- zero = 2, t, car_to_move = final[2] = 2,
pos = initial.index(2) = 0, switched [0], [2]
0 3 2 1 4 -- initial == final
""" |
There are people sitting in a circular fashion, print every third member while removing them, the next counter starts immediately after the member is removed. Print till all the members are exhausted. For example: Input: consider 123456789 members sitting in a circular fashion, Output: 369485271 | def josephus(int_list, skip):
skip = skip - 1 # list starts with 0 index
idx = 0
len_list = (len(int_list))
while len_list > 0:
idx = (skip + idx) % len_list # hash index to every 3rd
yield int_list.pop(idx)
len_list -= 1
|
Sometimes you need to limit array result to use. Such as you only need the value over 10 or, you need value under than 100. By use this algorithms, you can limit your array to specific value If array, Min, Max value was given, it returns array that contains values of given array which was larger than Min, and lower than Max. You need to give 'unlimit' to use only Min or Max. ex limit1,2,3,4,5, None, 3 1,2,3 Complexity On tl:dr array slicing by value | # tl:dr -- array slicing by value
def limit(arr, min_lim=None, max_lim=None):
if len(arr) == 0:
return arr
if min_lim is None:
min_lim = min(arr)
if max_lim is None:
max_lim = max(arr)
return list(filter(lambda x: (min_lim <= x <= max_lim), arr))
|
Given a string, find the length of the longest substring without repeating characters. Examples: Given abcabcbb, the answer is abc, which the length is 3. Given bbbbb, the answer is b, with the length of 1. Given pwwkew, the answer is wke, with the length of 3. Note that the answer must be a substring, pwke is a subsequence and not a substring. Find the length of the longest substring without repeating characters. Find the length of the longest substring without repeating characters. Uses alternative algorithm. get functions of above, returning the maxlen and substring Find the length of the longest substring without repeating characters. Return maxlen and the substring as a tuple Find the length of the longest substring without repeating characters. Uses alternative algorithm. Return maxlen and the substring as a tuple | def longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
"""
if string is None:
return 0
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
dict[string[i]] = i + 1
max_length = max(max_length, i - j + 1)
return max_length
def longest_non_repeat_v2(string):
"""
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
"""
if string is None:
return 0
start, max_len = 0, 0
used_char = {}
for index, char in enumerate(string):
if char in used_char and start <= used_char[char]:
start = used_char[char] + 1
else:
max_len = max(max_len, index - start + 1)
used_char[char] = index
return max_len
# get functions of above, returning the max_len and substring
def get_longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
dict[string[i]] = i + 1
if i - j + 1 > max_length:
max_length = i - j + 1
sub_string = string[j: i + 1]
return max_length, sub_string
def get_longest_non_repeat_v2(string):
"""
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
start, max_len = 0, 0
used_char = {}
for index, char in enumerate(string):
if char in used_char and start <= used_char[char]:
start = used_char[char] + 1
else:
if index - start + 1 > max_len:
max_len = index - start + 1
sub_string = string[start: index + 1]
used_char[char] = index
return max_len, sub_string |
Find the index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array. Returns index of 0 to be replaced with 1 to get longest continuous sequence of 1s. If there is no 0 in array, then it returns 1. e.g. let input array 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1 If we replace 0 at index 3 with 1, we get the longest continuous sequence of 1s in the array. So the function return 3 If current element is 0, then calculate the difference between curr and prevprevzero | def max_ones_index(arr):
n = len(arr)
max_count = 0
max_index = 0
prev_zero = -1
prev_prev_zero = -1
for curr in range(n):
# If current element is 0,
# then calculate the difference
# between curr and prev_prev_zero
if arr[curr] == 0:
if curr - prev_prev_zero > max_count:
max_count = curr - prev_prev_zero
max_index = prev_zero
prev_prev_zero = prev_zero
prev_zero = curr
if n - prev_prev_zero > max_count:
max_index = prev_zero
return max_index
|
In mathematics, a real interval is a set of real numbers with the property that any number that lies between two numbers in the set is also included in the set. A set of real numbers with methods to determine if other numbers are included in the set. Includes related methods to merge and print interval sets. Return interval as list. return listself staticmethod def mergeintervals: Print out the intervals. res for i in intervals: res.appendrepri print.joinres def mergeintervalsintervals: | class Interval:
"""
A set of real numbers with methods to determine if other
numbers are included in the set.
Includes related methods to merge and print interval sets.
"""
def __init__(self, start=0, end=0):
self.start = start
self.end = end
def __repr__(self):
return "Interval ({}, {})".format(self.start, self.end)
def __iter__(self):
return iter(range(self.start, self.end))
def __getitem__(self, index):
if index < 0:
return self.end + index
return self.start + index
def __len__(self):
return self.end - self.start
def __contains__(self, item):
if self.start >= item >= self.end:
return True
return False
def __eq__(self, other):
if self.start == other.start and self.end == other.end:
return True
return False
def as_list(self):
""" Return interval as list. """
return list(self)
@staticmethod
def merge(intervals):
""" Merge two intervals into one. """
out = []
for i in sorted(intervals, key=lambda i: i.start):
if out and i.start <= out[-1].end:
out[-1].end = max(out[-1].end, i.end)
else:
out += i,
return out
@staticmethod
def print_intervals(intervals):
""" Print out the intervals. """
res = []
for i in intervals:
res.append(repr(i))
print("".join(res))
def merge_intervals(intervals):
""" Merge intervals in the form of a list. """
if intervals is None:
return None
intervals.sort(key=lambda i: i[0])
out = [intervals.pop(0)]
for i in intervals:
if out[-1][-1] >= i[0]:
out[-1][-1] = max(out[-1][-1], i[-1])
else:
out.append(i)
return out
|
Find missing ranges between low and high in the given array. Ex 3, 5 lo1 hi10 answer: 1, 2, 4, 4, 6, 10 | def missing_ranges(arr, lo, hi):
res = []
start = lo
for n in arr:
if n == start:
start += 1
elif n > start:
res.append((start, n-1))
start = n + 1
if start <= hi: # after done iterating thru array,
res.append((start, hi)) # append remainder to list
return res
|
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. movezerosfalse, 1, 0, 1, 2, 0, 1, 3, a returns false, 1, 1, 2, 1, 3, a, 0, 0 The time complexity of the below algorithm is On. False 0 is True | # False == 0 is True
def move_zeros(array):
result = []
zeros = 0
for i in array:
if i == 0 and type(i) != bool: # not using `not i` to avoid `False`, `[]`, etc.
zeros += 1
else:
result.append(i)
result.extend([0] * zeros)
return result
print(move_zeros([False, 1, 0, 1, 2, 0, 1, 3, "a"])) |
Given an array of n integers, are there elements a, b, .. , n in nums such that a b .. n target? Find all unique ntuplets in the array which gives the sum of target. Example: basic: Given: n 4 nums 1, 0, 1, 0, 2, 2 target 0, return 2, 1, 1, 2, 2, 0, 0, 2, 1, 0, 0, 1 advanced: Given: n 2 nums 3, 0, 2, 1, 2, 2, 3, 3, 8, 4, 9, 5 target 5 def suma, b: return a0 b1, a1 b0 def comparenum, target: if num0 target: return 1 elif if num0 target: return 1 else: return 0 return 9, 5, 8, 4 TL:DR because 9 4 5 n: int nums: listobject target: object sumclosure: function, optional Given two elements of nums, return sum of both. compareclosure: function, optional Given one object of nums and target, return 1, 1, or 0. sameclosure: function, optional Given two object of nums, return bool. return: listlistobject Note: 1. type of sumclosure's return should be same as type of compareclosure's first param above, below, or right on? if num target: return 1 elif num target: return 1 else: return 0 def sameclosuredefaulta, b: return a b def nsumn, nums, target: if n 2: want answers with only 2 terms? easy! results twosumnums, target else: results prevnum None for index, num in enumeratenums: if prevnum is not None and sameclosureprevnum, num: continue prevnum num nminus1results nsum recursive call n 1, a numsindex 1:, b target num c x nsum a, b, c nminus1results x nminus1results appendelemtoeachlistnum, nminus1results results nminus1results return unionresults def twosumnums, target: nums.sort lt 0 rt lennums 1 results while lt rt: sum sumclosurenumslt, numsrt flag compareclosuresum, target if flag 1: lt 1 elif flag 1: rt 1 else: results.appendsortednumslt, numsrt lt 1 rt 1 while lt lennums and sameclosurenumslt 1, numslt: lt 1 while 0 rt and sameclosurenumsrt, numsrt 1: rt 1 return results def appendelemtoeachlistelem, container: results for elems in container: elems.appendelem results.appendsortedelems return results def unionduplicateresults: results if lenduplicateresults ! 0: duplicateresults.sort results.appendduplicateresults0 for result in duplicateresults1:: if results1 ! result: results.appendresult return results sumclosure kv.get'sumclosure', sumclosuredefault sameclosure kv.get'sameclosure', sameclosuredefault compareclosure kv.get'compareclosure', compareclosuredefault nums.sort return nsumn, nums, target | def n_sum(n, nums, target, **kv):
"""
n: int
nums: list[object]
target: object
sum_closure: function, optional
Given two elements of nums, return sum of both.
compare_closure: function, optional
Given one object of nums and target, return -1, 1, or 0.
same_closure: function, optional
Given two object of nums, return bool.
return: list[list[object]]
Note:
1. type of sum_closure's return should be same
as type of compare_closure's first param
"""
def sum_closure_default(a, b):
return a + b
def compare_closure_default(num, target):
""" above, below, or right on? """
if num < target:
return -1
elif num > target:
return 1
else:
return 0
def same_closure_default(a, b):
return a == b
def n_sum(n, nums, target):
if n == 2: # want answers with only 2 terms? easy!
results = two_sum(nums, target)
else:
results = []
prev_num = None
for index, num in enumerate(nums):
if prev_num is not None and \
same_closure(prev_num, num):
continue
prev_num = num
n_minus1_results = (
n_sum( # recursive call
n - 1, # a
nums[index + 1:], # b
target - num # c
) # x = n_sum( a, b, c )
) # n_minus1_results = x
n_minus1_results = (
append_elem_to_each_list(num, n_minus1_results)
)
results += n_minus1_results
return union(results)
def two_sum(nums, target):
nums.sort()
lt = 0
rt = len(nums) - 1
results = []
while lt < rt:
sum_ = sum_closure(nums[lt], nums[rt])
flag = compare_closure(sum_, target)
if flag == -1:
lt += 1
elif flag == 1:
rt -= 1
else:
results.append(sorted([nums[lt], nums[rt]]))
lt += 1
rt -= 1
while (lt < len(nums) and
same_closure(nums[lt - 1], nums[lt])):
lt += 1
while (0 <= rt and
same_closure(nums[rt], nums[rt + 1])):
rt -= 1
return results
def append_elem_to_each_list(elem, container):
results = []
for elems in container:
elems.append(elem)
results.append(sorted(elems))
return results
def union(duplicate_results):
results = []
if len(duplicate_results) != 0:
duplicate_results.sort()
results.append(duplicate_results[0])
for result in duplicate_results[1:]:
if results[-1] != result:
results.append(result)
return results
sum_closure = kv.get('sum_closure', sum_closure_default)
same_closure = kv.get('same_closure', same_closure_default)
compare_closure = kv.get('compare_closure', compare_closure_default)
nums.sort()
return n_sum(n, nums, target)
|
Given a nonnegative number represented as an array of digits, adding one to each numeral. The digits are stored bigendian, such that the most significant digit is at the head of the list. :type digits: Listint :rtype: Listint | def plus_one_v1(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] = digits[-1] + 1
res = []
ten = 0
i = len(digits)-1
while i >= 0 or ten == 1:
summ = 0
if i >= 0:
summ += digits[i]
if ten:
summ += 1
res.append(summ % 10)
ten = summ // 10
i -= 1
return res[::-1]
def plus_one_v2(digits):
n = len(digits)
for i in range(n-1, -1, -1):
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
digits.insert(0, 1)
return digits
def plus_one_v3(num_arr):
for idx in reversed(list(enumerate(num_arr))):
num_arr[idx[0]] = (num_arr[idx[0]] + 1) % 10
if num_arr[idx[0]]:
return num_arr
return [1] + num_arr
|
Rotate an array of n elements to the right by k steps. For example, with n 7 and k 3, the array 1,2,3,4,5,6,7 is rotated to 5,6,7,1,2,3,4. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Rotate the entire array 'k' times Tn Onk :type array: Listint :type k: int :rtype: void Do not return anything, modify array inplace instead. Reverse segments of the array, followed by the entire array Tn On :type array: Listint :type k: int :rtype: void Do not return anything, modify nums inplace instead. | def rotate_v1(array, k):
"""
Rotate the entire array 'k' times
T(n)- O(nk)
:type array: List[int]
:type k: int
:rtype: void Do not return anything, modify array in-place instead.
"""
array = array[:]
n = len(array)
for i in range(k): # unused variable is not a problem
temp = array[n - 1]
for j in range(n-1, 0, -1):
array[j] = array[j - 1]
array[0] = temp
return array
def rotate_v2(array, k):
"""
Reverse segments of the array, followed by the entire array
T(n)- O(n)
:type array: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
array = array[:]
def reverse(arr, a, b):
while a < b:
arr[a], arr[b] = arr[b], arr[a]
a += 1
b -= 1
n = len(array)
k = k % n
reverse(array, 0, n - k - 1)
reverse(array, n - k, n - 1)
reverse(array, 0, n - 1)
return array
def rotate_v3(array, k):
if array is None:
return None
length = len(array)
k = k % length
return array[length - k:] + array[:length - k]
|
Given a sorted integer array without duplicates, return the summary of its ranges. For example, given 0, 1, 2, 4, 5, 7, return 0, 2, 4, 5, 7, 7. :type array: Listint :rtype: List | def summarize_ranges(array):
"""
:type array: List[int]
:rtype: List[]
"""
res = []
if len(array) == 1:
return [str(array[0])]
i = 0
while i < len(array):
num = array[i]
while i + 1 < len(array) and array[i + 1] - array[i] == 1:
i += 1
if array[i] != num:
res.append((num, array[i]))
else:
res.append((num, num))
i += 1
return res
|
Given an array S of n integers, are there three distinct elements a, b, c in S such that a b c 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S 1, 0, 1, 2, 1, 4, A solution set is: 1, 0, 1, 1, 1, 2 :param array: Listint :return: Set Tupleint, int, int found three sum remove duplicates | def three_sum(array):
"""
:param array: List[int]
:return: Set[ Tuple[int, int, int] ]
"""
res = set()
array.sort()
for i in range(len(array) - 2):
if i > 0 and array[i] == array[i - 1]:
continue
l, r = i + 1, len(array) - 1
while l < r:
s = array[i] + array[l] + array[r]
if s > 0:
r -= 1
elif s < 0:
l += 1
else:
# found three sum
res.add((array[i], array[l], array[r]))
# remove duplicates
while l < r and array[l] == array[l + 1]:
l += 1
while l < r and array[r] == array[r - 1]:
r -= 1
l += 1
r -= 1
return res
|
This algorithm receives an array and returns mostfrequentvalue Also, sometimes it is possible to have multiple 'mostfrequentvalue's, so this function returns a list. This result can be used to find a representative value in an array. This algorithm gets an array, makes a dictionary of it, finds the most frequent count, and makes the result list. For example: top11, 1, 2, 2, 3, 4 will return 1, 2 TL:DR Get mathematical Mode Complexity: On reserve each value which first appears on keys reserve how many time each value appears by index number on values | def top_1(arr):
values = {}
#reserve each value which first appears on keys
#reserve how many time each value appears by index number on values
result = []
f_val = 0
for i in arr:
if i in values:
values[i] += 1
else:
values[i] = 1
f_val = max(values.values())
for i in values.keys():
if values[i] == f_val:
result.append(i)
else:
continue
return result
|
When make reliable means, we need to neglect best and worst values. For example, when making average score on athletes we need this option. So, this algorithm affixes some percentage to neglect when making mean. For example, if you suggest 20, it will neglect the best 10 of values and the worst 10 of values. This algorithm takes an array and percentage to neglect. After sorted, if index of array is larger or smaller than desired ratio, we don't compute it. Compleity: On 100 for easy calculation by , and 2 for easy adaption to best and worst parts. sum value to be calculated to trimmean. | def trimmean(arr, per):
ratio = per/200
# /100 for easy calculation by *, and /2 for easy adaption to best and worst parts.
cal_sum = 0
# sum value to be calculated to trimmean.
arr.sort()
neg_val = int(len(arr)*ratio)
arr = arr[neg_val:len(arr)-neg_val]
for i in arr:
cal_sum += i
return cal_sum/len(arr)
|
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums 2, 7, 11, 15, target 9, Because nums0 nums1 2 7 9, return 0, 1 | def two_sum(array, target):
dic = {}
for i, num in enumerate(array):
if num in dic:
return dic[num], i
else:
dic[target - num] = i
return None
|
Given a string that contains only digits 09 and a target value, return all possibilities to add binary operators not unary , , or between the digits so they prevuate to the target value. Examples: 123, 6 123, 123 232, 8 232, 232 105, 5 105,105 00, 0 00, 00, 00 3456237490, 9191 :type num: str :type target: int :rtype: Liststr | def add_operators(num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
def dfs(res, path, num, target, pos, prev, multed):
if pos == len(num):
if target == prev:
res.append(path)
return
for i in range(pos, len(num)):
if i != pos and num[pos] == '0': # all digits have to be used
break
cur = int(num[pos:i+1])
if pos == 0:
dfs(res, path + str(cur), num, target, i+1, cur, cur)
else:
dfs(res, path + "+" + str(cur), num, target,
i+1, prev + cur, cur)
dfs(res, path + "-" + str(cur), num, target,
i+1, prev - cur, -cur)
dfs(res, path + "*" + str(cur), num, target,
i+1, prev - multed + multed * cur, multed * cur)
res = []
if not num:
return res
dfs(res, "", num, target, 0, 0, 0)
return res
|
Given two strings, determine if they are equal after reordering. Examples: apple, pleap True apple, cherry False | def anagram(s1, s2):
c1 = [0] * 26
c2 = [0] * 26
for c in s1:
pos = ord(c)-ord('a')
c1[pos] = c1[pos] + 1
for c in s2:
pos = ord(c)-ord('a')
c2[pos] = c2[pos] + 1
return c1 == c2
|
WAP to take one element from each of the array add it to the target sum. Print all those threeelement combinations. A 1, 2, 3, 3 B 2, 3, 3, 4 C 2, 3, 3, 4 target 7 Result: 1, 2, 4, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 4, 2, 2, 2, 3, 2, 2, 3, 2, 3, 2, 2, 3, 2, 3, 2, 2, 3, 2, 2 1. Sort all the arrays a,b,c. This improves average time complexity. 2. If ci Sum, then look for Sum ci in array a and b. When pair found, insert ci, aj bk into the result list. This can be done in On. 3. Keep on doing the above procedure while going through complete c array. Complexity: Onmp | import itertools
from functools import partial
def array_sum_combinations(A, B, C, target):
def over(constructed_sofar):
sum = 0
to_stop, reached_target = False, False
for elem in constructed_sofar:
sum += elem
if sum >= target or len(constructed_sofar) >= 3:
to_stop = True
if sum == target and 3 == len(constructed_sofar):
reached_target = True
return to_stop, reached_target
def construct_candidates(constructed_sofar):
array = A
if 1 == len(constructed_sofar):
array = B
elif 2 == len(constructed_sofar):
array = C
return array
def backtrack(constructed_sofar=[], res=[]):
to_stop, reached_target = over(constructed_sofar)
if to_stop:
if reached_target:
res.append(constructed_sofar)
return
candidates = construct_candidates(constructed_sofar)
for candidate in candidates:
constructed_sofar.append(candidate)
backtrack(constructed_sofar[:], res)
constructed_sofar.pop()
res = []
backtrack([], res)
return res
def unique_array_sum_combinations(A, B, C, target):
"""
1. Sort all the arrays - a,b,c. - This improves average time complexity.
2. If c[i] < Sum, then look for Sum - c[i] in array a and b.
When pair found, insert c[i], a[j] & b[k] into the result list.
This can be done in O(n).
3. Keep on doing the above procedure while going through complete c array.
Complexity: O(n(m+p))
"""
def check_sum(n, *nums):
if sum(x for x in nums) == n:
return (True, nums)
else:
return (False, nums)
pro = itertools.product(A, B, C)
func = partial(check_sum, target)
sums = list(itertools.starmap(func, pro))
res = set()
for s in sums:
if s[0] is True and s[1] not in res:
res.add(s[1])
return list(res)
|
Given a set of candidate numbers C without duplicates and a target number T, find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers including target will be positive integers. The solution set must not contain duplicate combinations. For example, given candidate set 2, 3, 6, 7 and target 7, A solution set is: 7, 2, 2, 3 | def combination_sum(candidates, target):
def dfs(nums, target, index, path, res):
if target < 0:
return # backtracking
if target == 0:
res.append(path)
return
for i in range(index, len(nums)):
dfs(nums, target-nums[i], i, path+[nums[i]], res)
res = []
candidates.sort()
dfs(candidates, target, 0, [], res)
return res
|
Numbers can be regarded as product of its factors. For example, 8 2 x 2 x 2; 2 x 4. Write a function that takes an integer n and return all possible combinations of its factors. Note: You may assume that n is always positive. Factors should be greater than 1 and less than n. Examples: input: 1 output: input: 37 output: input: 12 output: 2, 6, 2, 2, 3, 3, 4 input: 32 output: 2, 16, 2, 2, 8, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 4, 4, 4, 8 Iterative: Recursive: | # Iterative:
def get_factors(n):
todo, combis = [(n, 2, [])], []
while todo:
n, i, combi = todo.pop()
while i * i <= n:
if n % i == 0:
combis.append(combi + [i, n//i])
todo.append((n//i, i, combi+[i]))
i += 1
return combis
# Recursive:
def recursive_get_factors(n):
def factor(n, i, combi, combis):
while i * i <= n:
if n % i == 0:
combis.append(combi + [i, n//i]),
factor(n//i, i, combi+[i], combis)
i += 1
return combis
return factor(n, 2, [], [])
|
Given a matrix of words and a list of words to search, return a list of words that exists in the board This is Word Search II on LeetCode board 'o','a','a','n', 'e','t','a','e', 'i','h','k','r', 'i','f','l','v' words oath,pea,eat,rain backtrack tries to build each words from the board and return all words found param: board, the passed in board of characters param: i, the row index param: j, the column index param: trie, a trie of the passed in words param: pre, a buffer of currently build string that differs by recursion stack param: used, a replica of the board except in booleans to state whether a character has been used param: result, the resulting set that contains all words found return: list of words found make a trie structure that is essentially dictionaries of dictionaries that map each character to a potential next character result is a set of found words since we do not want repeats | def find_words(board, words):
def backtrack(board, i, j, trie, pre, used, result):
'''
backtrack tries to build each words from
the board and return all words found
@param: board, the passed in board of characters
@param: i, the row index
@param: j, the column index
@param: trie, a trie of the passed in words
@param: pre, a buffer of currently build string that differs
by recursion stack
@param: used, a replica of the board except in booleans
to state whether a character has been used
@param: result, the resulting set that contains all words found
@return: list of words found
'''
if '#' in trie:
result.add(pre)
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
return
if not used[i][j] and board[i][j] in trie:
used[i][j] = True
backtrack(board, i+1, j, trie[board[i][j]],
pre+board[i][j], used, result)
backtrack(board, i, j+1, trie[board[i][j]],
pre+board[i][j], used, result)
backtrack(board, i-1, j, trie[board[i][j]],
pre+board[i][j], used, result)
backtrack(board, i, j-1, trie[board[i][j]],
pre+board[i][j], used, result)
used[i][j] = False
# make a trie structure that is essentially dictionaries of dictionaries
# that map each character to a potential next character
trie = {}
for word in words:
curr_trie = trie
for char in word:
if char not in curr_trie:
curr_trie[char] = {}
curr_trie = curr_trie[char]
curr_trie['#'] = '#'
# result is a set of found words since we do not want repeats
result = set()
used = [[False]*len(board[0]) for _ in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
backtrack(board, i, j, trie, '', used, result)
return list(result)
|
given input word, return the list of abbreviations. ex word 'word', 'wor1', 'wo1d', 'wo2', 'w1rd', 'w1r1', 'w2d', 'w3', '1ord', '1or1', '1o1d', '1o2', '2rd', '2r1', '3d', '4' skip the current word | def generate_abbreviations(word):
def backtrack(result, word, pos, count, cur):
if pos == len(word):
if count > 0:
cur += str(count)
result.append(cur)
return
if count > 0: # add the current word
backtrack(result, word, pos+1, 0, cur+str(count)+word[pos])
else:
backtrack(result, word, pos+1, 0, cur+word[pos])
# skip the current word
backtrack(result, word, pos+1, count+1, cur)
result = []
backtrack(result, word, 0, 0, "")
return result
|
Given n pairs of parentheses, write a function to generate all combinations of wellformed parentheses. For example, given n 3, a solution set is: , , , , | def generate_parenthesis_v1(n):
def add_pair(res, s, left, right):
if left == 0 and right == 0:
res.append(s)
return
if right > 0:
add_pair(res, s + ")", left, right - 1)
if left > 0:
add_pair(res, s + "(", left - 1, right + 1)
res = []
add_pair(res, "", n, 0)
return res
def generate_parenthesis_v2(n):
def add_pair(res, s, left, right):
if left == 0 and right == 0:
res.append(s)
if left > 0:
add_pair(res, s + "(", left - 1, right)
if right > 0 and left < right:
add_pair(res, s + ")", left, right - 1)
res = []
add_pair(res, "", n, n)
return res
|
Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters just like on the telephone buttons is given below: 2: abc 3: def 4: ghi 5: jkl 6: mno 7: pqrs 8: tuv 9: wxyz Input:Digit string 23 Output: ad, ae, af, bd, be, bf, cd, ce, cf. | def letter_combinations(digits):
if digits == "":
return []
kmaps = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"
}
ans = [""]
for num in digits:
tmp = []
for an in ans:
for char in kmaps[num]:
tmp.append(an + char)
ans = tmp
return ans
|
It looks like you need to be looking not for all palindromic substrings, but rather for all the ways you can divide the input string up into palindromic substrings. There's always at least one way, since onecharacter substrings are always palindromes. ex 'abcbab' 'abcba', 'b', 'a', 'bcb', 'a', 'b', 'a', 'b', 'c', 'bab', 'a', 'b', 'c', 'b', 'a', 'b' There's two loops. The outer loop checks each length of initial substring in descending length order to see if it is a palindrome. If so, it recurses on the rest of the string and loops over the returned values, adding the initial substring to each item before adding it to the results. A slightly more Pythonic approach with a recursive generator | def palindromic_substrings(s):
if not s:
return [[]]
results = []
for i in range(len(s), 0, -1):
sub = s[:i]
if sub == sub[::-1]:
for rest in palindromic_substrings(s[i:]):
results.append([sub] + rest)
return results
"""
There's two loops.
The outer loop checks each length of initial substring
(in descending length order) to see if it is a palindrome.
If so, it recurses on the rest of the string and loops over the returned
values, adding the initial substring to
each item before adding it to the results.
"""
def palindromic_substrings_iter(s):
"""
A slightly more Pythonic approach with a recursive generator
"""
if not s:
yield []
return
for i in range(len(s), 0, -1):
sub = s[:i]
if sub == sub[::-1]:
for rest in palindromic_substrings_iter(s[i:]):
yield [sub] + rest
|
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a nonempty substring in str. Examples: pattern abab, str redblueredblue should return true. pattern aaaa, str asdasdasdasd should return true. pattern aabb, str xyzabcxzyabc should return false. Notes: You may assume both pattern and str contains only lowercase letters. :type pattern: str :type string: str :rtype: bool | def pattern_match(pattern, string):
"""
:type pattern: str
:type string: str
:rtype: bool
"""
def backtrack(pattern, string, dic):
if len(pattern) == 0 and len(string) > 0:
return False
if len(pattern) == len(string) == 0:
return True
for end in range(1, len(string)-len(pattern)+2):
if pattern[0] not in dic and string[:end] not in dic.values():
dic[pattern[0]] = string[:end]
if backtrack(pattern[1:], string[end:], dic):
return True
del dic[pattern[0]]
elif pattern[0] in dic and dic[pattern[0]] == string[:end]:
if backtrack(pattern[1:], string[end:], dic):
return True
return False
return backtrack(pattern, string, {})
|
Given a collection of distinct numbers, return all possible permutations. For example, 1,2,3 have the following permutations: 1,2,3, 1,3,2, 2,1,3, 2,3,1, 3,1,2, 3,2,1 returns a list with the permuations. iterator: returns a perumation by each call. DFS Version | def permute(elements):
"""
returns a list with the permuations.
"""
if len(elements) <= 1:
return [elements]
else:
tmp = []
for perm in permute(elements[1:]):
for i in range(len(elements)):
tmp.append(perm[:i] + elements[0:1] + perm[i:])
return tmp
def permute_iter(elements):
"""
iterator: returns a perumation by each call.
"""
if len(elements) <= 1:
yield elements
else:
for perm in permute_iter(elements[1:]):
for i in range(len(elements)):
yield perm[:i] + elements[0:1] + perm[i:]
# DFS Version
def permute_recursive(nums):
def dfs(res, nums, path):
if not nums:
res.append(path)
for i in range(len(nums)):
print(nums[:i]+nums[i+1:])
dfs(res, nums[:i]+nums[i+1:], path+[nums[i]])
res = []
dfs(res, nums, [])
return res
|
Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, 1,1,2 have the following unique permutations: 1,1,2, 1,2,1, 2,1,1 | def permute_unique(nums):
perms = [[]]
for n in nums:
new_perms = []
for l in perms:
for i in range(len(l)+1):
new_perms.append(l[:i]+[n]+l[i:])
if i < len(l) and l[i] == n:
break # handles duplication
perms = new_perms
return perms
|
Given a set of distinct integers, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums 1,2,3, a solution is: 3, 1, 2, 1,2,3, 1,3, 2,3, 1,2, O2n take numspos dont take numspos simplified backtrack def backtrackres, nums, cur, pos: if pos lennums: res.appendcur else: backtrackres, nums, curnumspos, pos1 backtrackres, nums, cur, pos1 Iteratively | def subsets(nums):
"""
O(2**n)
"""
def backtrack(res, nums, stack, pos):
if pos == len(nums):
res.append(list(stack))
else:
# take nums[pos]
stack.append(nums[pos])
backtrack(res, nums, stack, pos+1)
stack.pop()
# dont take nums[pos]
backtrack(res, nums, stack, pos+1)
res = []
backtrack(res, nums, [], 0)
return res
"""
simplified backtrack
def backtrack(res, nums, cur, pos):
if pos >= len(nums):
res.append(cur)
else:
backtrack(res, nums, cur+[nums[pos]], pos+1)
backtrack(res, nums, cur, pos+1)
"""
# Iteratively
def subsets_v2(nums):
res = [[]]
for num in sorted(nums):
res += [item+[num] for item in res]
return res
|
Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums 1,2,2, a solution is: 2, 1, 1,2,2, 2,2, 1,2, take don't take | def subsets_unique(nums):
def backtrack(res, nums, stack, pos):
if pos == len(nums):
res.add(tuple(stack))
else:
# take
stack.append(nums[pos])
backtrack(res, nums, stack, pos+1)
stack.pop()
# don't take
backtrack(res, nums, stack, pos+1)
res = set()
backtrack(res, nums, [], 0)
return list(res)
|
This is a bfsversion of countingislands problem in dfs section. Given a 2d grid map of '1's land and '0's water, count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3 Example 3: 111000 110000 100001 001101 001100 Answer: 3 Example 4: 110011 001100 000001 111100 Answer: 5 | def count_islands(grid):
row = len(grid)
col = len(grid[0])
num_islands = 0
visited = [[0] * col for i in range(row)]
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
queue = []
for i in range(row):
for j, num in enumerate(grid[i]):
if num == 1 and visited[i][j] != 1:
visited[i][j] = 1
queue.append((i, j))
while queue:
x, y = queue.pop(0)
for k in range(len(directions)):
nx_x = x + directions[k][0]
nx_y = y + directions[k][1]
if nx_x >= 0 and nx_y >= 0 and nx_x < row and nx_y < col:
if visited[nx_x][nx_y] != 1 and grid[nx_x][nx_y] == 1:
queue.append((nx_x, nx_y))
visited[nx_x][nx_y] = 1
num_islands += 1
return num_islands
|
BFS time complexity : OE V BFS space complexity : OE V do BFS from 0,0 of the grid and get the minimum number of steps needed to get to the lower right column only step on the columns whose value is 1 if there is no path, it returns 1 Ex 1 If grid is 1,0,1,1,1,1, 1,0,1,0,1,0, 1,0,1,0,1,1, 1,1,1,0,1,1, the answer is: 14 Ex 2 If grid is 1,0,0, 0,1,1, 0,1,1, the answer is: 1 | from collections import deque
'''
BFS time complexity : O(|E| + |V|)
BFS space complexity : O(|E| + |V|)
do BFS from (0,0) of the grid and get the minimum number of steps needed to get to the lower right column
only step on the columns whose value is 1
if there is no path, it returns -1
Ex 1)
If grid is
[[1,0,1,1,1,1],
[1,0,1,0,1,0],
[1,0,1,0,1,1],
[1,1,1,0,1,1]],
the answer is: 14
Ex 2)
If grid is
[[1,0,0],
[0,1,1],
[0,1,1]],
the answer is: -1
'''
def maze_search(maze):
BLOCKED, ALLOWED = 0, 1
UNVISITED, VISITED = 0, 1
initial_x, initial_y = 0, 0
if maze[initial_x][initial_y] == BLOCKED:
return -1
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
height, width = len(maze), len(maze[0])
target_x, target_y = height - 1, width - 1
queue = deque([(initial_x, initial_y, 0)])
is_visited = [[UNVISITED for w in range(width)] for h in range(height)]
is_visited[initial_x][initial_y] = VISITED
while queue:
x, y, steps = queue.popleft()
if x == target_x and y == target_y:
return steps
for dx, dy in directions:
new_x = x + dx
new_y = y + dy
if not (0 <= new_x < height and 0 <= new_y < width):
continue
if maze[new_x][new_y] == ALLOWED and is_visited[new_x][new_y] == UNVISITED:
queue.append((new_x, new_y, steps + 1))
is_visited[new_x][new_y] = VISITED
return -1
|
do BFS from each building, and decrement all empty place for every building visit when gridij bnums, it means that gridij are already visited from all bnums and use dist to record distances from bnums only the position be visited by count times will append to queue | import collections
"""
do BFS from each building, and decrement all empty place for every building visit
when grid[i][j] == -b_nums, it means that grid[i][j] are already visited from all b_nums
and use dist to record distances from b_nums
"""
def shortest_distance(grid):
if not grid or not grid[0]:
return -1
matrix = [[[0,0] for i in range(len(grid[0]))] for j in range(len(grid))]
count = 0 # count how many building we have visited
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
bfs(grid, matrix, i, j, count)
count += 1
res = float('inf')
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j][1]==count:
res = min(res, matrix[i][j][0])
return res if res!=float('inf') else -1
def bfs(grid, matrix, i, j, count):
q = [(i, j, 0)]
while q:
i, j, step = q.pop(0)
for k, l in [(i-1,j), (i+1,j), (i,j-1), (i,j+1)]:
# only the position be visited by count times will append to queue
if 0<=k<len(grid) and 0<=l<len(grid[0]) and \
matrix[k][l][1]==count and grid[k][l]==0:
matrix[k][l][0] += step+1
matrix[k][l][1] = count+1
q.append((k, l, step+1))
|
Given two words beginword and endword, and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time Each intermediate word must exist in the word list For example, Given: beginword hit endword cog wordlist hot,dot,dog,lot,log As one shortest transformation is hit hot dot dog cog, return its length 5. Note: Return 1 if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters. Bidirectional BFS!!! :type beginword: str :type endword: str :type wordlist: Setstr :rtype: int when only differ by 1 character printbeginset printresult | def ladder_length(begin_word, end_word, word_list):
"""
Bidirectional BFS!!!
:type begin_word: str
:type end_word: str
:type word_list: Set[str]
:rtype: int
"""
if len(begin_word) != len(end_word):
return -1 # not possible
if begin_word == end_word:
return 0
# when only differ by 1 character
if sum(c1 != c2 for c1, c2 in zip(begin_word, end_word)) == 1:
return 1
begin_set = set()
end_set = set()
begin_set.add(begin_word)
end_set.add(end_word)
result = 2
while begin_set and end_set:
if len(begin_set) > len(end_set):
begin_set, end_set = end_set, begin_set
next_begin_set = set()
for word in begin_set:
for ladder_word in word_range(word):
if ladder_word in end_set:
return result
if ladder_word in word_list:
next_begin_set.add(ladder_word)
word_list.remove(ladder_word)
begin_set = next_begin_set
result += 1
# print(begin_set)
# print(result)
return -1
def word_range(word):
for ind in range(len(word)):
temp = word[ind]
for c in [chr(x) for x in range(ord('a'), ord('z') + 1)]:
if c != temp:
yield word[:ind] + c + word[ind + 1:]
|
The following code adds two positive integers without using the '' operator. The code uses bitwise operations to add two numbers. Input: 2 3 Output: 5 | def add_bitwise_operator(x, y):
while y:
carry = x & y
x = x ^ y
y = carry << 1
return x
|
Given a positive integer N, find and return the longest distance between two consecutive 1' in the binary representation of N. If there are not two consecutive 1's, return 0 For example: Input: 22 Output: 2 Explanation: 22 in binary is 10110 In the binary representation of 22, there are three ones, and two consecutive pairs of 1's. The first consecutive pair of 1's have distance 2. The second consecutive pair of 1's have distance 1. The answer is the largest of these two distances, which is 2 binarygap2 binarygapimproved The original method is binarygap, but the experimental results show that the algorithm seems to be wrong, regardless of the number, the output value is up to 2. The improved method is binarygapimproved. | # 原方法为 binary_gap,但通过实验发现算法有误,不论是什么数,输出值最多为2。
# 改进方法为binary_gap_improved。
# The original method is binary_gap,
# but the experimental results show that the algorithm seems to be wrong,
# regardless of the number, the output value is up to 2.
# The improved method is binary_gap_improved.
def binary_gap(N):
last = None
ans = 0
index = 0
while N != 0:
if N & 1:
if last is not None:
ans = max(ans, index - last)
last = index
index = index + 1
N = N >> 1
return ans
def binary_gap_improved(N):
last = None
ans = 0
index = 0
while N != 0:
tes = N & 1
if tes:
if last is not None:
ans = max(ans, index - last + 1)
else:
last = index
else:
last = index + 1
index = index + 1
N = N >> 1
return ans
print(binary_gap(111))
print(binary_gap_improved(111)) |
Fundamental bit operation: getbitnum, i: get an exact bit at specific index setbitnum, i: set a bit at specific index clearbitnum, i: clear a bit at specific index updatebitnum, i, bit: update a bit at specific index This function shifts 1 over by i bits, creating a value being like 0001000. By performing an AND with num, we clear all bits other than the bit at bit i. Finally we compare that to 0 This function shifts 1 over by i bits, creating a value being like 0001000. By performing an OR with num, only value at bit i will change. This method operates in almost the reverse of setbit To set the ith bit to value, we first clear the bit at position i by using a mask. Then, we shift the intended value. Finally we OR these two numbers | """
This function shifts 1 over by i bits, creating a value being like 0001000. By
performing an AND with num, we clear all bits other than the bit at bit i.
Finally we compare that to 0
"""
def get_bit(num, i):
return (num & (1 << i)) != 0
"""
This function shifts 1 over by i bits, creating a value being like 0001000. By
performing an OR with num, only value at bit i will change.
"""
def set_bit(num, i):
return num | (1 << i)
"""
This method operates in almost the reverse of set_bit
"""
def clear_bit(num, i):
mask = ~(1 << i)
return num & mask
"""
To set the ith bit to value, we first clear the bit at position i by using a
mask. Then, we shift the intended value. Finally we OR these two numbers
"""
def update_bit(num, i, bit):
mask = ~(1 << i)
return (num & mask) | (bit << i)
|
list.insert0, ... is inefficient | from collections import deque
def int_to_bytes_big_endian(num):
bytestr = deque()
while num > 0:
# list.insert(0, ...) is inefficient
bytestr.appendleft(num & 0xff)
num >>= 8
return bytes(bytestr)
def int_to_bytes_little_endian(num):
bytestr = []
while num > 0:
bytestr.append(num & 0xff)
num >>= 8
return bytes(bytestr)
def bytes_big_endian_to_int(bytestr):
num = 0
for b in bytestr:
num <<= 8
num += b
return num
def bytes_little_endian_to_int(bytestr):
num = 0
e = 0
for b in bytestr:
num += b << e
e += 8
return num
|
Write a function to determine the minimal number of bits you would need to flip to convert integer A to integer B. For example: Input: 29 or: 11101, 15 or: 01111 Output: 2 count number of ones in diff | def count_flips_to_convert(a, b):
diff = a ^ b
# count number of ones in diff
count = 0
while diff:
diff &= (diff - 1)
count += 1
return count
|
Write a function that takes an unsigned integer and returns the number of '1' bits it has also known as the Hamming weight. For example, the 32bit integer '11' has binary representation 00000000000000000000000000001011, so the function should return 3. Tn Ok : k is the number of 1s present in binary representation. NOTE: this complexity is better than Olog n. e.g. for n 00010100000000000000000000000000 only 2 iterations are required. Number of loops is equal to the number of 1s in the binary representation. def countonesrecurn: Using Brian Kernighan's Algorithm. Iterative Approach count 0 while n: n n1 count 1 return count | def count_ones_recur(n):
"""Using Brian Kernighan's Algorithm. (Recursive Approach)"""
if not n:
return 0
return 1 + count_ones_recur(n & (n-1))
def count_ones_iter(n):
"""Using Brian Kernighan's Algorithm. (Iterative Approach)"""
count = 0
while n:
n &= (n-1)
count += 1
return count
|
Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter that was added in t. For example: Input: s abcd t abecd Output: 'e' Explanation: 'e' is the letter that was added. We use the characteristic equation of XOR. A xor B xor C A xor C xor B If A C, then A xor C 0 and then, B xor 0 B ordch return an integer representing the Unicode code point of that character chri Return the string representing a character whose Unicode code point is the integer i | """
We use the characteristic equation of XOR.
A xor B xor C = A xor C xor B
If A == C, then A xor C = 0
and then, B xor 0 = B
"""
def find_difference(s, t):
ret = 0
for ch in s + t:
# ord(ch) return an integer representing the Unicode code point of that character
ret = ret ^ ord(ch)
# chr(i) Return the string representing a character whose Unicode code point is the integer i
return chr(ret)
|
Returns the missing number from a sequence of unique integers in range 0..n in On time and space. The difference between consecutive integers cannot be more than 1. If the sequence is already complete, the next integer in the sequence will be returned. For example: Input: nums 4, 1, 3, 0, 6, 5, 2 Output: 7 | def find_missing_number(nums):
missing = 0
for i, num in enumerate(nums):
missing ^= num
missing ^= i + 1
return missing
def find_missing_number2(nums):
num_sum = sum(nums)
n = len(nums)
total_sum = n*(n+1) // 2
missing = total_sum - num_sum
return missing
|
You have an integer and you can flip exactly one bit from a 0 to 1. Write code to find the length of the longest sequence of 1s you could create. For example: Input: 1775 or: 11011101111 Output: 8 | def flip_bit_longest_seq(num):
curr_len = 0
prev_len = 0
max_len = 0
while num:
if num & 1 == 1: # last digit is 1
curr_len += 1
elif num & 1 == 0: # last digit is 0
if num & 2 == 0: # second last digit is 0
prev_len = 0
else:
prev_len = curr_len
curr_len = 0
max_len = max(max_len, prev_len + curr_len)
num = num >> 1 # right shift num
return max_len + 1
|
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. For example: Input: 5 Output: True because the binary representation of 5 is: 101. Input: 7 Output: False because the binary representation of 7 is: 111. Input: 11 Output: False because the binary representation of 11 is: 1011. Input: 10 Output: True because The binary representation of 10 is: 1010. Time Complexity Onumber of bits in n Time Complexity O1 | # Time Complexity - O(number of bits in n)
def has_alternative_bit(n):
first_bit = 0
second_bit = 0
while n:
first_bit = n & 1
if n >> 1:
second_bit = (n >> 1) & 1
if not first_bit ^ second_bit:
return False
else:
return True
n = n >> 1
return True
# Time Complexity - O(1)
def has_alternative_bit_fast(n):
mask1 = int('aaaaaaaa', 16) # for bits ending with zero (...1010)
mask2 = int('55555555', 16) # for bits ending with one (...0101)
return mask1 == (n + (n ^ mask1)) or mask2 == (n + (n ^ mask2))
|
Insertion: insertonebitnum, bit, i: insert exact one bit at specific position For example: Input: num 10101 21 insertonebitnum, 1, 2: 101101 45 insertonebitnum, 0, 2: 101001 41 insertonebitnum, 1, 5: 110101 53 insertonebitnum, 1, 0: 101011 43 insertmultbitsnum, bits, len, i: insert multiple bits with len at specific position For example: Input: num 101 5 insertmultbitsnum, 7, 3, 1: 101111 47 insertmultbitsnum, 7, 3, 0: 101111 47 insertmultbitsnum, 7, 3, 3: 111101 61 Insert exact one bit at specific position Algorithm: 1. Create a mask having bit from i to the most significant bit, and append the new bit at 0 position 2. Keep the bit from 0 position to i position like 000...001111 3. Merge mask and num Create mask Keep the bit from 0 position to i position | """
Insert exact one bit at specific position
Algorithm:
1. Create a mask having bit from i to the most significant bit, and append the new bit at 0 position
2. Keep the bit from 0 position to i position ( like 000...001111)
3. Merge mask and num
"""
def insert_one_bit(num, bit, i):
# Create mask
mask = num >> i
mask = (mask << 1) | bit
mask = mask << i
# Keep the bit from 0 position to i position
right = ((1 << i) - 1) & num
return right | mask
def insert_mult_bits(num, bits, len, i):
mask = num >> i
mask = (mask << len) | bits
mask = mask << i
right = ((1 << i) - 1) & num
return right | mask
|
given an integer, write a function to determine if it is a power of two :type n: int :rtype: bool | def is_power_of_two(n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and not n & (n-1)
|
Removebitnum, i: remove a bit at specific position. For example: Input: num 10101 21 removebitnum, 2: output 1001 9 removebitnum, 4: output 101 5 removebitnum, 0: output 1010 10 | def remove_bit(num, i):
mask = num >> (i + 1)
mask = mask << i
right = ((1 << i) - 1) & num
return mask | right
|
Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 represented in binary as 00000010100101000001111010011100, return 964176192 represented in binary as 00111001011110000010100101000000. | def reverse_bits(n):
m = 0
i = 0
while i < 32:
m = (m << 1) + (n & 1)
n >>= 1
i += 1
return m
|
Given an array of integers, every element appears twice except for one. Find that single one. NOTE: This also works for finding a number occurring odd number of times, where all the other numbers appear even number of times. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Returns single number, if found. Else if all numbers appear twice, returns 0. :type nums: Listint :rtype: int | def single_number(nums):
"""
Returns single number, if found.
Else if all numbers appear twice, returns 0.
:type nums: List[int]
:rtype: int
"""
i = 0
for num in nums:
i ^= num
return i
|
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Solution: 32 bits for each integer. Consider 1 bit in it, the sum of each integer's corresponding bit except for the single number should be 0 if mod by 3. Hence, we sum the bits of all integers and mod by 3, the remaining should be the exact bit of the single number. In this way, you get the 32 bits of the single number. Another awesome answer | # Another awesome answer
def single_number2(nums):
ones, twos = 0, 0
for i in range(len(nums)):
ones = (ones ^ nums[i]) & ~twos
twos = (twos ^ nums[i]) & ~ones
return ones
|
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. Limitation: Time Complexity: ON and Space Complexity O1 For example: Given nums 1, 2, 1, 3, 2, 5, return 3, 5. Note: The order of the result is not important. So in the above example, 5, 3 is also correct. Solution: 1. Use XOR to cancel out the pairs and isolate AB 2. It is guaranteed that at least 1 bit exists in AB since A and B are different numbers. ex 010 111 101 3. Single out one bit R right most bit in this solution to use it as a pivot 4. Divide all numbers into two groups. One group with a bit in the position R One group without a bit in the position R 5. Use the same strategy we used in step 1 to isolate A and B from each group. :type nums: Listint :rtype: Listint isolate ab from pairs using XOR isolate right most bit from ab isolate a and b from ab | def single_number3(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# isolate a^b from pairs using XOR
ab = 0
for n in nums:
ab ^= n
# isolate right most bit from a^b
right_most = ab & (-ab)
# isolate a and b from a^b
a, b = 0, 0
for n in nums:
if n & right_most:
a ^= n
else:
b ^= n
return [a, b]
|
Given a set of distinct integers, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums 1,2,3, a solution is: 1, 2, 1, 3, 1,, 2,, 3,, 1, 2, 3, , 2, 3 :param nums: Listint :return: Settuple this explanation is from leetnik leetcode This is an amazing solution. Learnt a lot. Number of subsets for 1 , 2 , 3 23 . why ? case possible outcomes for the set of subsets 1 Take or dont take 2 2 Take or dont take 2 3 Take or dont take 2 therefore, total 222 23 , 1, 2, 3, 1,2, 1,3, 2,3, 1,2,3 Lets assign bits to each outcome First bit to 1 , Second bit to 2 and third bit to 3 Take 1 Dont take 0 0 0 0 0 Dont take 3 , Dont take 2 , Dont take 1 1 0 0 1 Dont take 3 , Dont take 2 , take 1 1 2 0 1 0 Dont take 3 , take 2 , Dont take 1 2 3 0 1 1 Dont take 3 , take 2 , take 1 1 , 2 4 1 0 0 take 3 , Dont take 2 , Dont take 1 3 5 1 0 1 take 3 , Dont take 2 , take 1 1 , 3 6 1 1 0 take 3 , take 2 , Dont take 1 2 , 3 7 1 1 1 take 3 , take 2 , take 1 1 , 2 , 3 In the above logic ,Insert Si only if ji1 true j E 0,1,2,3,4,5,6,7 i ith element in the input array element 1 is inserted only into those places where 1st bit of j is 1 if j 0 1 for above above eg. this is true for sl.no. j 1 , 3 , 5 , 7 element 2 is inserted only into those places where 2nd bit of j is 1 if j 1 1 for above above eg. this is true for sl.no. j 2 , 3 , 6 , 7 element 3 is inserted only into those places where 3rd bit of j is 1 if j 2 1 for above above eg. this is true for sl.no. j 4 , 5 , 6 , 7 Time complexity : On2n , for every input element loop traverses the whole solution set length i.e. 2n | def subsets(nums):
"""
:param nums: List[int]
:return: Set[tuple]
"""
n = len(nums)
total = 1 << n
res = set()
for i in range(total):
subset = tuple(num for j, num in enumerate(nums) if i & 1 << j)
res.add(subset)
return res
"""
this explanation is from leet_nik @ leetcode
This is an amazing solution. Learnt a lot.
Number of subsets for {1 , 2 , 3 } = 2^3 .
why ?
case possible outcomes for the set of subsets
1 -> Take or dont take = 2
2 -> Take or dont take = 2
3 -> Take or dont take = 2
therefore,
total = 2*2*2 = 2^3 = {{}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}}
Lets assign bits to each outcome ->
First bit to 1 , Second bit to 2 and third bit to 3
Take = 1
Dont take = 0
0) 0 0 0 -> Dont take 3 , Dont take 2 , Dont take 1 = { }
1) 0 0 1 -> Dont take 3 , Dont take 2 , take 1 = { 1 }
2) 0 1 0 -> Dont take 3 , take 2 , Dont take 1 = { 2 }
3) 0 1 1 -> Dont take 3 , take 2 , take 1 = { 1 , 2 }
4) 1 0 0 -> take 3 , Dont take 2 , Dont take 1 = { 3 }
5) 1 0 1 -> take 3 , Dont take 2 , take 1 = { 1 , 3 }
6) 1 1 0 -> take 3 , take 2 , Dont take 1 = { 2 , 3 }
7) 1 1 1 -> take 3 , take 2 , take 1 = { 1 , 2 , 3 }
In the above logic ,Insert S[i] only if (j>>i)&1 ==true
{ j E { 0,1,2,3,4,5,6,7 } i = ith element in the input array }
element 1 is inserted only into those places where 1st bit of j is 1
if( j >> 0 &1 ) ==> for above above eg.
this is true for sl.no.( j )= 1 , 3 , 5 , 7
element 2 is inserted only into those places where 2nd bit of j is 1
if( j >> 1 &1 ) == for above above eg.
this is true for sl.no.( j ) = 2 , 3 , 6 , 7
element 3 is inserted only into those places where 3rd bit of j is 1
if( j >> 2 & 1 ) == for above above eg.
this is true for sl.no.( j ) = 4 , 5 , 6 , 7
Time complexity : O(n*2^n) , for every input element loop traverses
the whole solution set length i.e. 2^n
"""
|
Swappair: A function swap odd and even bits in an integer with as few instructions as possible Ex bit and bit 1 are swapped, bit 2 and bit 3 are swapped For example: 22: 010110 41: 101001 10: 1010 5 : 0101 We can approach this as operating on the odds bit first, and then the even bits. We can mask all odd bits with 10101010 in binary 'AA' then shift them right by 1 Similarly, we mask all even bit with 01010101 in binary '55' then shift them left by 1. Finally, we merge these two values by OR operation. odd bit arithmetic right shift 1 bit even bit left shift 1 bit | """
We can approach this as operating on the odds bit first, and then the even bits.
We can mask all odd bits with 10101010 in binary ('AA') then shift them right by 1
Similarly, we mask all even bit with 01010101 in binary ('55') then shift them left
by 1. Finally, we merge these two values by OR operation.
"""
def swap_pair(num):
# odd bit arithmetic right shift 1 bit
odd = (num & int('AAAAAAAA', 16)) >> 1
# even bit left shift 1 bit
even = (num & int('55555555', 16)) << 1
return odd | even
|
Elias code or Elias gamma code is a universal code encoding positive integers. It is used most commonly when coding integers whose upperbound cannot be determined beforehand. Elias code or Elias delta code is a universal code encoding the positive integers, that includes Elias code when calculating. Both were developed by Peter Elias. Calculates the binary number Calculates the unary number The compressed data is calculated in two parts. The first part is the unary number of 1 log2x. The second part is the binary number of x 2log2x. For the final result we add these two parts. For the first part we put the unary number of x. For the first part we put the eliasg of the number. | from math import log
log2 = lambda x: log(x, 2)
# Calculates the binary number
def binary(x, l=1):
fmt = '{0:0%db}' % l
return fmt.format(x)
# Calculates the unary number
def unary(x):
return (x-1)*'1'+'0'
def elias_generic(lencoding, x):
"""
The compressed data is calculated in two parts.
The first part is the unary number of 1 + ⌊log2(x)⌋.
The second part is the binary number of x - 2^(⌊log2(x)⌋).
For the final result we add these two parts.
"""
if x == 0:
return '0'
first_part = 1 + int(log2(x))
a = x - 2**(int(log2(x)))
k = int(log2(x))
return lencoding(first_part) + binary(a, k)
def elias_gamma(x):
"""
For the first part we put the unary number of x.
"""
return elias_generic(unary, x)
def elias_delta(x):
"""
For the first part we put the elias_g of the number.
"""
return elias_generic(elias_gamma, x)
|
Huffman coding is an efficient method of compressing data without losing information. This algorithm analyzes the symbols that appear in a message. Symbols that appear more often will be encoded as a shorterbit string while symbols that aren't used as much will be encoded as longer strings. Load tree from file :return: Load values to tree after reading tree :param leavesqueue: :return: Load next byte is buffer is less than bufflimit :param bufflimit: :return: True if there is enough bits in buffer to read Generate and save tree code to file :param tree: :return: Overwrite first three bits in the file :param additionalbits: number of bits that were appended to fill last byte :return: overwrite first three bits Class to help find signs in tree Find sign in tree :param bit: :return: True if sign is found | from collections import defaultdict, deque
import heapq
class Node:
def __init__(self, frequency=0, sign=None, left=None, right=None):
self.frequency = frequency
self.sign = sign
self.left = left
self.right = right
def __lt__(self, other):
return self.frequency < other.frequency
def __gt__(self, other):
return self.frequency > other.frequency
def __eq__(self, other):
return self.frequency == other.frequency
def __str__(self):
return "<ch: {0}: {1}>".format(self.sign, self.frequency)
def __repr__(self):
return "<ch: {0}: {1}>".format(self.sign, self.frequency)
class HuffmanReader:
def __init__(self, file):
self.file = file
self.buffer = []
self.is_last_byte = False
def get_number_of_additional_bits_in_the_last_byte(self) -> int:
bin_num = self.get_bit() + self.get_bit() + self.get_bit()
return int(bin_num, 2)
def load_tree(self) -> Node:
"""
Load tree from file
:return:
"""
node_stack = deque()
queue_leaves = deque()
root = Node()
current_node = root
is_end_of_tree = False
while not is_end_of_tree:
current_bit = self.get_bit()
if current_bit == "0":
current_node.left = Node()
current_node.right = Node()
node_stack.append(current_node.right) # going to left node, right push on stack
current_node = current_node.left
else:
queue_leaves.append(current_node)
if node_stack:
current_node = node_stack.pop()
else:
is_end_of_tree = True
self._fill_tree(queue_leaves)
return root
def _fill_tree(self, leaves_queue):
"""
Load values to tree after reading tree
:param leaves_queue:
:return:
"""
leaves_queue.reverse()
while leaves_queue:
node = leaves_queue.pop()
s = int(self.get_byte(), 2)
node.sign = s
def _load_byte(self, buff_limit=8) -> bool:
"""
Load next byte is buffer is less than buff_limit
:param buff_limit:
:return: True if there is enough bits in buffer to read
"""
if len(self.buffer) <= buff_limit:
byte = self.file.read(1)
if not byte:
return False
i = int.from_bytes(byte, "big")
self.buffer.extend(list("{0:08b}".format(i)))
return True
def get_bit(self, buff_limit=8):
if self._load_byte(buff_limit):
bit = self.buffer.pop(0)
return bit
else:
return -1
def get_byte(self):
if self._load_byte():
byte_list = self.buffer[:8]
self.buffer = self.buffer[8:]
return "".join(byte_list)
else:
return -1
class HuffmanWriter:
def __init__(self, file):
self.file = file
self.buffer = ""
self.saved_bits = 0
def write_char(self, char):
self.write_int(ord(char))
def write_int(self, num):
bin_int = "{0:08b}".format(num)
self.write_bits(bin_int)
def write_bits(self, bits):
self.saved_bits += len(bits)
self.buffer += bits
while len(self.buffer) >= 8:
i = int(self.buffer[:8], 2)
self.file.write(bytes([i]))
self.buffer = self.buffer[8:]
def save_tree(self, tree):
"""
Generate and save tree code to file
:param tree:
:return:
"""
signs = []
tree_code = ""
def get_code_tree(T):
nonlocal tree_code
if T.sign is not None:
signs.append(T.sign)
if T.left:
tree_code += "0"
get_code_tree(T.left)
if T.right:
tree_code += "1"
get_code_tree(T.right)
get_code_tree(tree)
self.write_bits(tree_code + "1") # "1" indicates that tree ended (it will be needed to load the tree)
for int_sign in signs:
self.write_int(int_sign)
def _save_information_about_additional_bits(self, additional_bits: int):
"""
Overwrite first three bits in the file
:param additional_bits: number of bits that were appended to fill last byte
:return:
"""
self.file.seek(0)
first_byte_raw = self.file.read(1)
self.file.seek(0)
first_byte = "{0:08b}".format(int.from_bytes(first_byte_raw, "big"))
# overwrite first three bits
first_byte = first_byte[3:]
first_byte = "{0:03b}".format(additional_bits) + first_byte
self.write_bits(first_byte)
def close(self):
additional_bits = 8 - len(self.buffer)
if additional_bits != 8: # buffer is empty, no need to append extra "0"
self.write_bits("0" * additional_bits)
self._save_information_about_additional_bits(additional_bits)
class TreeFinder:
"""
Class to help find signs in tree
"""
def __init__(self, tree):
self.root = tree
self.current_node = tree
self.found = None
def find(self, bit):
"""
Find sign in tree
:param bit:
:return: True if sign is found
"""
if bit == "0":
self.current_node = self.current_node.left
elif bit == "1":
self.current_node = self.current_node.right
else:
self._reset()
return True
if self.current_node.sign is not None:
self._reset(self.current_node.sign)
return True
else:
return False
def _reset(self, found=""):
self.found = found
self.current_node = self.root
class HuffmanCoding:
def __init__(self):
pass
@staticmethod
def decode_file(file_in_name, file_out_name):
with open(file_in_name, "rb") as file_in, open(file_out_name, "wb") as file_out:
reader = HuffmanReader(file_in)
additional_bits = reader.get_number_of_additional_bits_in_the_last_byte()
tree = reader.load_tree()
HuffmanCoding._decode_and_write_signs_to_file(file_out, reader, tree, additional_bits)
print("File decoded.")
@staticmethod
def _decode_and_write_signs_to_file(file, reader: HuffmanReader, tree: Node, additional_bits: int):
tree_finder = TreeFinder(tree)
is_end_of_file = False
while not is_end_of_file:
bit = reader.get_bit()
if bit != -1:
while not tree_finder.find(bit): # read whole code
bit = reader.get_bit(0)
file.write(bytes([tree_finder.found]))
else: # There is last byte in buffer to parse
is_end_of_file = True
last_byte = reader.buffer
last_byte = last_byte[:-additional_bits] # remove additional "0" used to fill byte
for bit in last_byte:
if tree_finder.find(bit):
file.write(bytes([tree_finder.found]))
@staticmethod
def encode_file(file_in_name, file_out_name):
with open(file_in_name, "rb") as file_in, open(file_out_name, mode="wb+") as file_out:
signs_frequency = HuffmanCoding._get_char_frequency(file_in)
file_in.seek(0)
tree = HuffmanCoding._create_tree(signs_frequency)
codes = HuffmanCoding._generate_codes(tree)
writer = HuffmanWriter(file_out)
writer.write_bits("000") # leave space to save how many bits will be appended to fill the last byte
writer.save_tree(tree)
HuffmanCoding._encode_and_write_signs_to_file(file_in, writer, codes)
writer.close()
print("File encoded.")
@staticmethod
def _encode_and_write_signs_to_file(file, writer: HuffmanWriter, codes: dict):
sign = file.read(1)
while sign:
int_char = int.from_bytes(sign, "big")
writer.write_bits(codes[int_char])
sign = file.read(1)
@staticmethod
def _get_char_frequency(file) -> dict:
is_end_of_file = False
signs_frequency = defaultdict(lambda: 0)
while not is_end_of_file:
prev_pos = file.tell()
sign = file.read(1)
curr_pos = file.tell()
if prev_pos == curr_pos:
is_end_of_file = True
else:
signs_frequency[int.from_bytes(sign, "big")] += 1
return signs_frequency
@staticmethod
def _generate_codes(tree: Node) -> dict:
codes = dict()
HuffmanCoding._go_through_tree_and_create_codes(tree, "", codes)
return codes
@staticmethod
def _create_tree(signs_frequency: dict) -> Node:
nodes = [Node(frequency=frequency, sign=char_int) for char_int, frequency in signs_frequency.items()]
heapq.heapify(nodes)
while len(nodes) > 1:
left = heapq.heappop(nodes)
right = heapq.heappop(nodes)
new_node = Node(frequency=left.frequency + right.frequency, left=left, right=right)
heapq.heappush(nodes, new_node)
return nodes[0] # root
@staticmethod
def _go_through_tree_and_create_codes(tree: Node, code: str, dict_codes: dict):
if tree.sign is not None:
dict_codes[tree.sign] = code
if tree.left:
HuffmanCoding._go_through_tree_and_create_codes(tree.left, code + "0", dict_codes)
if tree.right:
HuffmanCoding._go_through_tree_and_create_codes(tree.right, code + "1", dict_codes)
|
Runlength encoding RLE is a simple compression algorithm that gets a stream of data as the input and returns a sequence of counts of consecutive data values in a row. When decompressed the data will be fully recovered as RLE is a lossless data compression. Gets a stream of data and compresses it under a RunLength Encoding. :param input: The data to be encoded. :return: The encoded string. Check If the subsequent character does not match Add the count and character Reset the count and set the character Otherwise increment the counter Gets a stream of data and decompresses it under a RunLength Decoding. :param input: The data to be decoded. :return: The decoded string. If not numerical Expand it for the decoding Add it in the counter | def encode_rle(input):
"""
Gets a stream of data and compresses it
under a Run-Length Encoding.
:param input: The data to be encoded.
:return: The encoded string.
"""
if not input: return ''
encoded_str = ''
prev_ch = ''
count = 1
for ch in input:
# Check If the subsequent character does not match
if ch != prev_ch:
# Add the count and character
if prev_ch:
encoded_str += str(count) + prev_ch
# Reset the count and set the character
count = 1
prev_ch = ch
else:
# Otherwise increment the counter
count += 1
else:
return encoded_str + (str(count) + prev_ch)
def decode_rle(input):
"""
Gets a stream of data and decompresses it
under a Run-Length Decoding.
:param input: The data to be decoded.
:return: The decoded string.
"""
decode_str = ''
count = ''
for ch in input:
# If not numerical
if not ch.isdigit():
# Expand it for the decoding
decode_str += ch * int(count)
count = ''
else:
# Add it in the counter
count += ch
return decode_str
|
Numbers can be regarded as product of its factors. For example, 8 2 x 2 x 2; 2 x 4. Write a function that takes an integer n and return all possible combinations of its factors.Numbers can be regarded as product of its factors. For example, 8 2 x 2 x 2; 2 x 4. Examples: input: 1 output: input: 37 output: input: 32 output: 2, 16, 2, 2, 8, 2, 2, 2, 4, 2, 2, 2, 2, 2, summary Arguments: n int to analysed number Returns: list of lists all factors of the number n summary helper function Arguments: n int number i int to tested divisor combi list catch divisors res list all factors of the number n Returns: list res summary Computes all factors of n. Translated the function getfactors... in a callstack modell. Arguments: n int to analysed number Returns: list of lists all factors summary analog as above Arguments: n int description Returns: list of lists all factors of n | def get_factors(n):
"""[summary]
Arguments:
n {[int]} -- [to analysed number]
Returns:
[list of lists] -- [all factors of the number n]
"""
def factor(n, i, combi, res):
"""[summary]
helper function
Arguments:
n {[int]} -- [number]
i {[int]} -- [to tested divisor]
combi {[list]} -- [catch divisors]
res {[list]} -- [all factors of the number n]
Returns:
[list] -- [res]
"""
while i * i <= n:
if n % i == 0:
res += combi + [i, int(n/i)],
factor(n/i, i, combi+[i], res)
i += 1
return res
return factor(n, 2, [], [])
def get_factors_iterative1(n):
"""[summary]
Computes all factors of n.
Translated the function get_factors(...) in
a call-stack modell.
Arguments:
n {[int]} -- [to analysed number]
Returns:
[list of lists] -- [all factors]
"""
todo, res = [(n, 2, [])], []
while todo:
n, i, combi = todo.pop()
while i * i <= n:
if n % i == 0:
res += combi + [i, n//i],
todo.append((n//i, i, combi+[i])),
i += 1
return res
def get_factors_iterative2(n):
"""[summary]
analog as above
Arguments:
n {[int]} -- [description]
Returns:
[list of lists] -- [all factors of n]
"""
ans, stack, x = [], [], 2
while True:
if x > n // x:
if not stack:
return ans
ans.append(stack + [n])
x = stack.pop()
n *= x
x += 1
elif n % x == 0:
stack.append(x)
n //= x
else:
x += 1
|
Given a 2d grid map of '1's land and '0's water, count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3 | def num_islands(grid):
count = 0
for i in range(len(grid)):
for j, col in enumerate(grid[i]):
if col == 1:
dfs(grid, i, j)
count += 1
return count
def dfs(grid, i, j):
if (i < 0 or i >= len(grid)) or (j < 0 or j >= len(grid[0])):
return
if grid[i][j] != 1:
return
grid[i][j] = 0
dfs(grid, i+1, j)
dfs(grid, i-1, j)
dfs(grid, i, j+1)
dfs(grid, i, j-1)
|
Find shortest path from top left column to the right lowest column using DFS. only step on the columns whose value is 1 if there is no path, it returns 1 The first columntop left column is not included in the answer. Ex 1 If maze is 1,0,1,1,1,1, 1,0,1,0,1,0, 1,0,1,0,1,1, 1,1,1,0,1,1, the answer is: 14 Ex 2 If maze is 1,0,0, 0,1,1, 0,1,1, the answer is: 1 | def find_path(maze):
cnt = dfs(maze, 0, 0, 0, -1)
return cnt
def dfs(maze, i, j, depth, cnt):
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
row = len(maze)
col = len(maze[0])
if i == row - 1 and j == col - 1:
if cnt == -1:
cnt = depth
else:
if cnt > depth:
cnt = depth
return cnt
maze[i][j] = 0
for k in range(len(directions)):
nx_i = i + directions[k][0]
nx_j = j + directions[k][1]
if nx_i >= 0 and nx_i < row and nx_j >= 0 and nx_j < col:
if maze[nx_i][nx_j] == 1:
cnt = dfs(maze, nx_i, nx_j, depth + 1, cnt)
maze[i][j] = 1
return cnt
|
Given an m x n matrix of nonnegative integers representing the height of each unit cell in a continent, the Pacific ocean touches the left and top edges of the matrix and the Atlantic ocean touches the right and bottom edges. Water can only flow in four directions up, down, left, or right from a cell to another one with height equal or lower. Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean. Note: The order of returned grid coordinates does not matter. Both m and n are less than 150. Example: Given the following 5x5 matrix: Pacific 1 2 2 3 5 3 2 3 4 4 2 4 5 3 1 6 7 1 4 5 5 1 1 2 4 Atlantic Return: 0, 4, 1, 3, 1, 4, 2, 2, 3, 0, 3, 1, 4, 0 positions with parentheses in above matrix. :type matrix: ListListint :rtype: ListListint | # Given an m x n matrix of non-negative integers representing
# the height of each unit cell in a continent,
# the "Pacific ocean" touches the left and top edges of the matrix
# and the "Atlantic ocean" touches the right and bottom edges.
# Water can only flow in four directions (up, down, left, or right)
# from a cell to another one with height equal or lower.
# Find the list of grid coordinates where water can flow to both the
# Pacific and Atlantic ocean.
# Note:
# The order of returned grid coordinates does not matter.
# Both m and n are less than 150.
# Example:
# Given the following 5x5 matrix:
# Pacific ~ ~ ~ ~ ~
# ~ 1 2 2 3 (5) *
# ~ 3 2 3 (4) (4) *
# ~ 2 4 (5) 3 1 *
# ~ (6) (7) 1 4 5 *
# ~ (5) 1 1 2 4 *
# * * * * * Atlantic
# Return:
# [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]
# (positions with parentheses in above matrix).
def pacific_atlantic(matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
n = len(matrix)
if not n: return []
m = len(matrix[0])
if not m: return []
res = []
atlantic = [[False for _ in range (n)] for _ in range(m)]
pacific = [[False for _ in range (n)] for _ in range(m)]
for i in range(n):
dfs(pacific, matrix, float("-inf"), i, 0)
dfs(atlantic, matrix, float("-inf"), i, m-1)
for i in range(m):
dfs(pacific, matrix, float("-inf"), 0, i)
dfs(atlantic, matrix, float("-inf"), n-1, i)
for i in range(n):
for j in range(m):
if pacific[i][j] and atlantic[i][j]:
res.append([i, j])
return res
def dfs(grid, matrix, height, i, j):
if i < 0 or i >= len(matrix) or j < 0 or j >= len(matrix[0]):
return
if grid[i][j] or matrix[i][j] < height:
return
grid[i][j] = True
dfs(grid, matrix, matrix[i][j], i-1, j)
dfs(grid, matrix, matrix[i][j], i+1, j)
dfs(grid, matrix, matrix[i][j], i, j-1)
dfs(grid, matrix, matrix[i][j], i, j+1)
|
It's similar to how human solve Sudoku. create a hash table dictionary val to store possible values in every location. Each time, start from the location with fewest possible values, choose one value from it and then update the board and possible values at other locations. If this update is valid, keep solving DFS. If this update is invalid leaving zero possible values at some locations or this value doesn't lead to the solution, undo the updates and then choose the next value. Since we calculated val at the beginning and start filling the board from the location with fewest possible values, the amount of calculation and thus the runtime can be significantly reduced: The run time is 4868 ms on LeetCode OJ, which seems to be among the fastest python solutions here. The PossibleVals function may be further simplifiedoptimized, but it works just fine for now. it would look less lengthy if we are allowed to use numpy array for the board lol. summary Generates a board representation as string. Returns: str board representation | class Sudoku:
def __init__ (self, board, row, col):
self.board = board
self.row = row
self.col = col
self.val = self.possible_values()
def possible_values(self):
a = "123456789"
d, val = {}, {}
for i in range(self.row):
for j in range(self.col):
ele = self.board[i][j]
if ele != ".":
d[("r", i)] = d.get(("r", i), []) + [ele]
d[("c", j)] = d.get(("c", j), []) + [ele]
d[(i//3, j//3)] = d.get((i//3, j//3), []) + [ele]
else:
val[(i,j)] = []
for (i,j) in val.keys():
inval = d.get(("r",i),[])+d.get(("c",j),[])+d.get((i/3,j/3),[])
val[(i,j)] = [n for n in a if n not in inval ]
return val
def solve(self):
if len(self.val)==0:
return True
kee = min(self.val.keys(), key=lambda x: len(self.val[x]))
nums = self.val[kee]
for n in nums:
update = {kee:self.val[kee]}
if self.valid_one(n, kee, update): # valid choice
if self.solve(): # keep solving
return True
self.undo(kee, update) # invalid choice or didn't solve it => undo
return False
def valid_one(self, n, kee, update):
self.board[kee[0]][kee[1]] = n
del self.val[kee]
i, j = kee
for ind in self.val.keys():
if n in self.val[ind]:
if ind[0]==i or ind[1]==j or (ind[0]/3,ind[1]/3)==(i/3,j/3):
update[ind] = n
self.val[ind].remove(n)
if len(self.val[ind])==0:
return False
return True
def undo(self, kee, update):
self.board[kee[0]][kee[1]]="."
for k in update:
if k not in self.val:
self.val[k]= update[k]
else:
self.val[k].append(update[k])
return None
def __str__(self):
"""[summary]
Generates a board representation as string.
Returns:
[str] -- [board representation]
"""
resp = ""
for i in range(self.row):
for j in range(self.col):
resp += " {0} ".format(self.board[i][j])
resp += "\n"
return resp
|
You are given a m x n 2D grid initialized with these three possible values: 1: A wall or an obstacle. 0: A gate. INF: Infinity means an empty room. We use the value 231 1 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill the empty room with distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. For example, given the 2D grid: INF 1 0 INF INF INF INF 1 INF 1 INF 1 0 1 INF INF After running your function, the 2D grid should be: 3 1 0 1 2 2 1 1 1 1 2 1 0 1 3 4 | def walls_and_gates(rooms):
for i in range(len(rooms)):
for j in range(len(rooms[0])):
if rooms[i][j] == 0:
dfs(rooms, i, j, 0)
def dfs(rooms, i, j, depth):
if (i < 0 or i >= len(rooms)) or (j < 0 or j >= len(rooms[0])):
return # out of bounds
if rooms[i][j] < depth:
return # crossed
rooms[i][j] = depth
dfs(rooms, i+1, j, depth+1)
dfs(rooms, i-1, j, depth+1)
dfs(rooms, i, j+1, depth+1)
dfs(rooms, i, j-1, depth+1)
|
Histogram function. Histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable. https:en.wikipedia.orgwikiHistogram Example: list1 3, 3, 2, 1 :return 1: 1, 2: 1, 3: 2 list2 2, 3, 5, 5, 5, 6, 4, 3, 7 :return 2: 1, 3: 2, 4: 1, 5: 3, 6: 1, 7: 1 Get histogram representation :param inputlist: list with different and unordered values :return histogram: dict with histogram of inputlist Create dict to store histogram For each list value, add one to the respective histogram dict position | def get_histogram(input_list: list) -> dict:
"""
Get histogram representation
:param input_list: list with different and unordered values
:return histogram: dict with histogram of input_list
"""
# Create dict to store histogram
histogram = {}
# For each list value, add one to the respective histogram dict position
for i in input_list:
histogram[i] = histogram.get(i, 0) + 1
return histogram
|
Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction ie, buy one and sell one share of the stock, design an algorithm to find the maximum profit. Example 1: Input: 7, 1, 5, 3, 6, 4 Output: 5 max. difference 61 5 not 71 6, as selling price needs to be larger than buying price Example 2: Input: 7, 6, 4, 3, 1 Output: 0 In this case, no transaction is done, i.e. max profit 0. On2 time :type prices: Listint :rtype: int On time input: 7, 1, 5, 3, 6, 4 diff : X, 6, 4, 2, 3, 2 :type prices: Listint :rtype: int | # O(n^2) time
def max_profit_naive(prices):
"""
:type prices: List[int]
:rtype: int
"""
max_so_far = 0
for i in range(0, len(prices) - 1):
for j in range(i + 1, len(prices)):
max_so_far = max(max_so_far, prices[j] - prices[i])
return max_so_far
# O(n) time
def max_profit_optimized(prices):
"""
input: [7, 1, 5, 3, 6, 4]
diff : [X, -6, 4, -2, 3, -2]
:type prices: List[int]
:rtype: int
"""
cur_max, max_so_far = 0, 0
for i in range(1, len(prices)):
cur_max = max(0, cur_max + prices[i] - prices[i-1])
max_so_far = max(max_so_far, cur_max)
return max_so_far
|
You are climbing a stair case. It takes steps number of steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given argument steps will be a positive integer. On space :type steps: int :rtype: int the above function can be optimized as: O1 space :type steps: int :rtype: int | # O(n) space
def climb_stairs(steps):
"""
:type steps: int
:rtype: int
"""
arr = [1, 1]
for _ in range(1, steps):
arr.append(arr[-1] + arr[-2])
return arr[-1]
# the above function can be optimized as:
# O(1) space
def climb_stairs_optimized(steps):
"""
:type steps: int
:rtype: int
"""
a_steps = b_steps = 1
for _ in range(steps):
a_steps, b_steps = b_steps, a_steps + b_steps
return a_steps
|
Problem Given a value value, if we want to make change for value cents, and we have infinite supply of each of coins S1, S2, .. , Sm valued coins, how many ways can we make the change? The order of coins doesn't matter. For example, for value 4 and coins 1, 2, 3, there are four solutions: 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 3. So output should be 4. For value 10 and coins 2, 5, 3, 6, there are five solutions: 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 6, 2, 3, 5 and 5, 5. So the output should be 5. Time complexity: On m where n is the value and m is the number of coins Space complexity: On Find number of combination of coins that adds upp to value Keyword arguments: coins int value int initialize dp array and set base case as 1 fill dp in a bottom up manner | def count(coins, value):
""" Find number of combination of `coins` that adds upp to `value`
Keyword arguments:
coins -- int[]
value -- int
"""
# initialize dp array and set base case as 1
dp_array = [1] + [0] * value
# fill dp in a bottom up manner
for coin in coins:
for i in range(coin, value+1):
dp_array[i] += dp_array[i-coin]
return dp_array[value]
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums 1, 2, 3 target 4 The possible combination ways are: 1, 1, 1, 1 1, 1, 2 1, 2, 1 1, 3 2, 1, 1 2, 2 3, 1 Note that different sequences are counted as different combinations. Therefore the output is 7. Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers? Generates DP and finds result. Keyword arguments: nums positive integer array without duplicates target integer describing what a valid combination should add to Find number of possible combinations in nums that add up to target, in topdown manner. Keyword arguments: nums positive integer array without duplicates target integer describing what a valid combination should add to Find number of possible combinations in nums that add up to target, in bottomup manner. Keyword arguments: nums positive integer array without duplicates target integer describing what a valid combination should add to | DP = None
def helper_topdown(nums, target):
"""Generates DP and finds result.
Keyword arguments:
nums -- positive integer array without duplicates
target -- integer describing what a valid combination should add to
"""
if DP[target] != -1:
return DP[target]
res = 0
for num in nums:
if target >= num:
res += helper_topdown(nums, target - num)
DP[target] = res
return res
def combination_sum_topdown(nums, target):
"""Find number of possible combinations in nums that add up to target, in top-down manner.
Keyword arguments:
nums -- positive integer array without duplicates
target -- integer describing what a valid combination should add to
"""
global DP
DP = [-1] * (target + 1)
DP[0] = 1
return helper_topdown(nums, target)
def combination_sum_bottom_up(nums, target):
"""Find number of possible combinations in nums that add up to target, in bottom-up manner.
Keyword arguments:
nums -- positive integer array without duplicates
target -- integer describing what a valid combination should add to
"""
combs = [0] * (target + 1)
combs[0] = 1
for i in range(0, len(combs)):
for num in nums:
if i - num >= 0:
combs[i] += combs[i - num]
return combs[target]
|
The edit distance between two words is the minimum number of letter insertions, letter deletions, and letter substitutions required to transform one word into another. For example, the edit distance between FOOD and MONEY is at most four: FOOD MOOD MOND MONED MONEY Given two words A and B, find the minimum number of operations required to transform one string into the other. In other words, find the edit distance between A and B. Thought process: Let editi, j denote the edit distance between the prefixes A1..i and B1..j. Then, the function satifies the following recurrence: editi, j i if j 0 j if i 0 minediti1, j 1, editi, j1, 1, editi1, j1 cost otherwise There are two base cases, both of which occur when one string is empty and the other is not. 1. To convert an empty string A into a string B of length n, perform n insertions. 2. To convert a string A of length m into an empty string B, perform m deletions. Here, the cost is 1 if a substitution is required, or 0 if both chars in words A and B are the same at indexes i and j, respectively. To find the edit distance between two words A and B, we need to find editlengtha, lengthb. Time: Olengthalengthb Space: Olengthalengthb Finds edit distance between worda and wordb Kwyword arguments: worda string wordb string | def edit_distance(word_a, word_b):
"""Finds edit distance between word_a and word_b
Kwyword arguments:
word_a -- string
word_b -- string
"""
length_a, length_b = len(word_a) + 1, len(word_b) + 1
edit = [[0 for _ in range(length_b)] for _ in range(length_a)]
for i in range(1, length_a):
edit[i][0] = i
for j in range(1, length_b):
edit[0][j] = j
for i in range(1, length_a):
for j in range(1, length_b):
cost = 0 if word_a[i - 1] == word_b[j - 1] else 1
edit[i][j] = min(edit[i - 1][j] + 1, edit[i][j - 1] + 1, edit[i - 1][j - 1] + cost)
return edit[-1][-1] # this is the same as edit[length_a][length_b]
|
You are given K eggs, and you have access to a building with N floors from 1 to N. Each egg is identical in function, and if an egg breaks, you cannot drop it again. You know that there exists a floor F with 0 F N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break. Each move, you may take an egg if you have an unbroken one and drop it from any floor X with 1 X N. Your goal is to know with certainty what the value of F is. What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F? Example: Input: K 1, N 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know with certainty that F 0. Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F 1. If it didn't break, then we know with certainty F 2. Hence, we needed 2 moves in the worst case to know what F is with certainty. A Dynamic Programming based Python Program for the Egg Dropping Puzzle Keyword arguments: n number of floors k number of eggs A 2D table where entery eggFloorij will represent minimum number of trials needed for i eggs and j floors. We need one trial for one floor and 0 trials for 0 floors We always need j trials for one egg and j floors. Fill rest of the entries in table using optimal substructure property eggFloornk holds the result | # A Dynamic Programming based Python Program for the Egg Dropping Puzzle
INT_MAX = 32767
def egg_drop(n, k):
"""
Keyword arguments:
n -- number of floors
k -- number of eggs
"""
# A 2D table where entery eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j floors.
egg_floor = [[0 for _ in range(k + 1)] for _ in range(n + 1)]
# We need one trial for one floor and 0 trials for 0 floors
for i in range(1, n+1):
egg_floor[i][1] = 1
egg_floor[i][0] = 0
# We always need j trials for one egg and j floors.
for j in range(1, k+1):
egg_floor[1][j] = j
# Fill rest of the entries in table using optimal substructure
# property
for i in range(2, n+1):
for j in range(2, k+1):
egg_floor[i][j] = INT_MAX
for x in range(1, j+1):
res = 1 + max(egg_floor[i-1][x-1], egg_floor[i][j-x])
if res < egg_floor[i][j]:
egg_floor[i][j] = res
# eggFloor[n][k] holds the result
return egg_floor[n][k]
|
In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F00 , F11 and Fn Fn1 Fn2 The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, . In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Here, given a number n, print nth Fibonacci Number. summary Computes the nth fibonacci number recursive. Problem: This implementation is very slow. approximate O2n Arguments: n int description Returns: int description precondition printfibrecursive35 9227465 slow summary This algorithm computes the nth fibbonacci number very quick. approximate On The algorithm use dynamic programming. Arguments: n int description Returns: int description precondition printfiblist100 354224848179261915075 summary Works iterative approximate On Arguments: n int description Returns: int description precondition printfibiter100 354224848179261915075 | def fib_recursive(n):
"""[summary]
Computes the n-th fibonacci number recursive.
Problem: This implementation is very slow.
approximate O(2^n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a positive integer'
if n <= 1:
return n
return fib_recursive(n-1) + fib_recursive(n-2)
# print(fib_recursive(35)) # => 9227465 (slow)
def fib_list(n):
"""[summary]
This algorithm computes the n-th fibbonacci number
very quick. approximate O(n)
The algorithm use dynamic programming.
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a positive integer'
list_results = [0, 1]
for i in range(2, n+1):
list_results.append(list_results[i-1] + list_results[i-2])
return list_results[n]
# print(fib_list(100)) # => 354224848179261915075
def fib_iter(n):
"""[summary]
Works iterative approximate O(n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be positive integer'
fib_1 = 0
fib_2 = 1
res = 0
if n <= 1:
return n
for _ in range(n-1):
res = fib_1 + fib_2
fib_1 = fib_2
fib_2 = res
return res
# print(fib_iter(100)) # => 354224848179261915075
|
Hosoya triangle originally Fibonacci triangle is a triangular arrangement of numbers, where if you take any number it is the sum of 2 numbers above. First line is always 1, and second line is always 1 1. This printHosoya function takes argument n which is the height of the triangle number of lines. For example: printHosoya 6 would return: 1 1 1 2 1 2 3 2 2 3 5 3 4 3 5 8 5 6 6 5 8 The complexity is On3. Calculates the hosoya triangle height height of the triangle Prints the hosoya triangle height height of the triangle Test hosoya function height height of the triangle | def hosoya(height, width):
""" Calculates the hosoya triangle
height -- height of the triangle
"""
if (width == 0) and (height in (0,1)):
return 1
if (width == 1) and (height in (1,2)):
return 1
if height > width:
return hosoya(height - 1, width) + hosoya(height - 2, width)
if width == height:
return hosoya(height - 1, width - 1) + hosoya(height - 2, width - 2)
return 0
def print_hosoya(height):
"""Prints the hosoya triangle
height -- height of the triangle
"""
for i in range(height):
for j in range(i + 1):
print(hosoya(i, j) , end = " ")
print ("\n", end = "")
def hosoya_testing(height):
"""Test hosoya function
height -- height of the triangle
"""
res = []
for i in range(height):
for j in range(i + 1):
res.append(hosoya(i, j))
return res
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of nonnegative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. | def house_robber(houses):
last, now = 0, 0
for house in houses:
last, now = now, max(last + house, now)
return now
|
Given positive integer decompose, find an algorithm to find the number of nonnegative number division, or decomposition. The complexity is On2. Example 1: Input: 4 Output: 5 Explaination: 44 431 422 4211 41111 Example : Input: 7 Output: 15 Explaination: 77 761 752 7511 743 7421 74111 7331 7322 73211 731111 72221 722111 7211111 71111111 Find number of decompositions from decompose decompose integer | def int_divide(decompose):
"""Find number of decompositions from `decompose`
decompose -- integer
"""
arr = [[0 for i in range(decompose + 1)] for j in range(decompose + 1)]
arr[1][1] = 1
for i in range(1, decompose + 1):
for j in range(1, decompose + 1):
if i < j:
arr[i][j] = arr[i][i]
elif i == j:
arr[i][j] = 1 + arr[i][j - 1]
else:
arr[i][j] = arr[i][j - 1] + arr[i - j][j]
return arr[decompose][decompose]
|
Python program for weighted job scheduling using Dynamic Programming and Binary Search Class to represent a job A Binary Search based function to find the latest job before current job that doesn't conflict with current job. index is index of the current job. This function returns 1 if all jobs before index conflict with it. The array jobs is sorted in increasing order of finish time. Perform binary Search iteratively The main function that returns the maximum possible profit from given array of jobs Sort jobs according to finish time Create an array to store solutions of subproblems. tablei stores the profit for jobs till arri including arri Fill entries in table using recursive property Find profit including the current job Store maximum of including and excluding | class Job:
"""
Class to represent a job
"""
def __init__(self, start, finish, profit):
self.start = start
self.finish = finish
self.profit = profit
def binary_search(job, start_index):
"""
A Binary Search based function to find the latest job
(before current job) that doesn't conflict with current
job. "index" is index of the current job. This function
returns -1 if all jobs before index conflict with it.
The array jobs[] is sorted in increasing order of finish
time.
"""
left = 0
right = start_index - 1
# Perform binary Search iteratively
while left <= right:
mid = (left + right) // 2
if job[mid].finish <= job[start_index].start:
if job[mid + 1].finish <= job[start_index].start:
left = mid + 1
else:
return mid
else:
right = mid - 1
return -1
def schedule(job):
"""
The main function that returns the maximum possible
profit from given array of jobs
"""
# Sort jobs according to finish time
job = sorted(job, key = lambda j: j.finish)
# Create an array to store solutions of subproblems. table[i]
# stores the profit for jobs till arr[i] (including arr[i])
length = len(job)
table = [0 for _ in range(length)]
table[0] = job[0].profit
# Fill entries in table[] using recursive property
for i in range(1, length):
# Find profit including the current job
incl_prof = job[i].profit
pos = binary_search(job, i)
if pos != -1:
incl_prof += table[pos]
# Store maximum of including and excluding
table[i] = max(incl_prof, table[i - 1])
return table[length-1]
|
The K factor of a string is defined as the number of times 'abba' appears as a substring. Given two numbers length and kfactor, find the number of strings of length length with 'K factor' kfactor. The algorithms is as follows: dplengthkfactor will be a 4 element array, wherein each element can be the number of strings of length length and 'K factor' kfactor which belong to the criteria represented by that index: dplengthkfactor0 can be the number of strings of length length and Kfactor kfactor which end with substring 'a' dplengthkfactor1 can be the number of strings of length length and Kfactor kfactor which end with substring 'ab' dplengthkfactor2 can be the number of strings of length length and Kfactor kfactor which end with substring 'abb' dplengthkfactor3 can be the number of strings of length and Kfactor kfactor which end with anything other than the above substrings anything other than 'a' 'ab' 'abb' Example inputs length4 kfactor1 no of strings 1 length7 kfactor1 no of strings 70302 length10 kfactor2 no of strings 74357 Find the number of strings of length length with K factor kfactor. Keyword arguments: length integer kfactor integer base cases adding a at the end adding b at the end adding any other lowercase character adding a at the end adding b at the end adding any other lowercase character | def find_k_factor(length, k_factor):
"""Find the number of strings of length `length` with K factor = `k_factor`.
Keyword arguments:
length -- integer
k_factor -- integer
"""
mat=[[[0 for i in range(4)]for j in range((length-1)//3+2)]for k in range(length+1)]
if 3*k_factor+1>length:
return 0
#base cases
mat[1][0][0]=1
mat[1][0][1]=0
mat[1][0][2]=0
mat[1][0][3]=25
for i in range(2,length+1):
for j in range((length-1)//3+2):
if j==0:
#adding a at the end
mat[i][j][0]=mat[i-1][j][0]+mat[i-1][j][1]+mat[i-1][j][3]
#adding b at the end
mat[i][j][1]=mat[i-1][j][0]
mat[i][j][2]=mat[i-1][j][1]
#adding any other lowercase character
mat[i][j][3]=mat[i-1][j][0]*24+mat[i-1][j][1]*24+mat[i-1][j][2]*25+mat[i-1][j][3]*25
elif 3*j+1<i:
#adding a at the end
mat[i][j][0]=mat[i-1][j][0]+mat[i-1][j][1]+mat[i-1][j][3]+mat[i-1][j-1][2]
#adding b at the end
mat[i][j][1]=mat[i-1][j][0]
mat[i][j][2]=mat[i-1][j][1]
#adding any other lowercase character
mat[i][j][3]=mat[i-1][j][0]*24+mat[i-1][j][1]*24+mat[i-1][j][2]*25+mat[i-1][j][3]*25
elif 3*j+1==i:
mat[i][j][0]=1
mat[i][j][1]=0
mat[i][j][2]=0
mat[i][j][3]=0
else:
mat[i][j][0]=0
mat[i][j][1]=0
mat[i][j][2]=0
mat[i][j][3]=0
return sum(mat[length][k_factor])
|
Given the capacity of the knapsack and items specified by weights and values, return the maximum summarized value of the items that can be fit in the knapsack. Example: capacity 5, itemsvalue, weight 60, 5, 50, 3, 70, 4, 30, 2 result 80 items valued 50 and 30 can both be fit in the knapsack The time complexity is On m and the space complexity is Om, where n is the total number of items and m is the knapsack's capacity. | class Item:
def __init__(self, value, weight):
self.value = value
self.weight = weight
def get_maximum_value(items, capacity):
dp = [0] * (capacity + 1)
for item in items:
for cur_weight in reversed(range(item.weight, capacity+1)):
dp[cur_weight] = max(dp[cur_weight], item.value + dp[cur_weight - item.weight])
return dp[capacity]
|
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. For example, 'abd' is a subsequence of 'abcd' whereas 'adc' is not Given 2 strings containing lowercase english alphabets, find the length of the Longest Common Subsequence L.C.S.. Example: Input: 'abcdgh' 'aedfhr' Output: 3 Explanation: The longest subsequence common to both the string is adh Time Complexity : OMN Space Complexity : OMN, where M and N are the lengths of the 1st and 2nd string respectively. :param s1: string :param s2: string :return: int matij : contains length of LCS of s10..i1 and s20..j1 | def longest_common_subsequence(s_1, s_2):
"""
:param s1: string
:param s2: string
:return: int
"""
m = len(s_1)
n = len(s_2)
mat = [[0] * (n + 1) for i in range(m + 1)]
# mat[i][j] : contains length of LCS of s_1[0..i-1] and s_2[0..j-1]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
mat[i][j] = 0
elif s_1[i - 1] == s_2[j - 1]:
mat[i][j] = mat[i - 1][j - 1] + 1
else:
mat[i][j] = max(mat[i - 1][j], mat[i][j - 1])
return mat[m][n]
|
Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: 10,9,2,5,3,7,101,18 Output: 4 Explanation: The longest increasing subsequence is 2,3,7,101, therefore the length is 4. Time complexity: First algorithm is On2. Second algorithm is Onlogx where x is the max element in the list Third algorithm is Onlogn Space complexity: First algorithm is On Second algorithm is Ox where x is the max element in the list Third algorithm is On Dynamic Programming Algorithm for counting the length of longest increasing subsequence type sequence: listint rtype: int Optimized dynamic programming algorithm for couting the length of the longest increasing subsequence using segment tree data structure to achieve better complexity if max element is larger than 105 then use longestincreasingsubsequenceoptimied2 instead type sequence: listint rtype: int Optimized dynamic programming algorithm for counting the length of the longest increasing subsequence using segment tree data structure to achieve better complexity type sequence: listint rtype: int | def longest_increasing_subsequence(sequence):
"""
Dynamic Programming Algorithm for
counting the length of longest increasing subsequence
type sequence: list[int]
rtype: int
"""
length = len(sequence)
counts = [1 for _ in range(length)]
for i in range(1, length):
for j in range(0, i):
if sequence[i] > sequence[j]:
counts[i] = max(counts[i], counts[j] + 1)
print(counts)
return max(counts)
def longest_increasing_subsequence_optimized(sequence):
"""
Optimized dynamic programming algorithm for
couting the length of the longest increasing subsequence
using segment tree data structure to achieve better complexity
if max element is larger than 10^5 then use
longest_increasing_subsequence_optimied2() instead
type sequence: list[int]
rtype: int
"""
max_seq = max(sequence)
tree = [0] * (max_seq<<2)
def update(pos, left, right, target, vertex):
if left == right:
tree[pos] = vertex
return
mid = (left+right)>>1
if target <= mid:
update(pos<<1, left, mid, target, vertex)
else:
update((pos<<1)|1, mid+1, right, target, vertex)
tree[pos] = max_seq(tree[pos<<1], tree[(pos<<1)|1])
def get_max(pos, left, right, start, end):
if left > end or right < start:
return 0
if left >= start and right <= end:
return tree[pos]
mid = (left+right)>>1
return max_seq(get_max(pos<<1, left, mid, start, end),
get_max((pos<<1)|1, mid+1, right, start, end))
ans = 0
for element in sequence:
cur = get_max(1, 0, max_seq, 0, element-1)+1
ans = max_seq(ans, cur)
update(1, 0, max_seq, element, cur)
return ans
def longest_increasing_subsequence_optimized2(sequence):
"""
Optimized dynamic programming algorithm for
counting the length of the longest increasing subsequence
using segment tree data structure to achieve better complexity
type sequence: list[int]
rtype: int
"""
length = len(sequence)
tree = [0] * (length<<2)
sorted_seq = sorted((x, -i) for i, x in enumerate(sequence))
def update(pos, left, right, target, vertex):
if left == right:
tree[pos] = vertex
return
mid = (left+right)>>1
if target <= mid:
vertex(pos<<1, left, mid, target, vertex)
else:
vertex((pos<<1)|1, mid+1, right, target, vertex)
tree[pos] = max(tree[pos<<1], tree[(pos<<1)|1])
def get_max(pos, left, right, start, end):
if left > end or right < start:
return 0
if left >= start and right <= end:
return tree[pos]
mid = (left+right)>>1
return max(get_max(pos<<1, left, mid, start, end),
get_max((pos<<1)|1, mid+1, right, start, end))
ans = 0
for tup in sorted_seq:
i = -tup[1]
cur = get_max(1, 0, length-1, 0, i-1)+1
ans = max(ans, cur)
update(1, 0, length-1, i, cur)
return ans
|
Dynamic Programming Implementation of matrix Chain Multiplication Time Complexity: On3 Space Complexity: On2 Finds optimal order to multiply matrices array int Print order of matrix with Ai as matrix Print the solution optimalsolution int i int j int Testing for matrixchainordering Size of matrix created from above array will be 3035 3515 155 510 1020 2025 | INF = float("inf")
def matrix_chain_order(array):
"""Finds optimal order to multiply matrices
array -- int[]
"""
n = len(array)
matrix = [[0 for x in range(n)] for x in range(n)]
sol = [[0 for x in range(n)] for x in range(n)]
for chain_length in range(2, n):
for a in range(1, n-chain_length+1):
b = a+chain_length-1
matrix[a][b] = INF
for c in range(a, b):
cost = matrix[a][c] + matrix[c+1][b] + array[a-1]*array[c]*array[b]
if cost < matrix[a][b]:
matrix[a][b] = cost
sol[a][b] = c
return matrix, sol
# Print order of matrix with Ai as matrix
def print_optimal_solution(optimal_solution,i,j):
"""Print the solution
optimal_solution -- int[][]
i -- int[]
j -- int[]
"""
if i==j:
print("A" + str(i),end = " ")
else:
print("(", end=" ")
print_optimal_solution(optimal_solution, i, optimal_solution[i][j])
print_optimal_solution(optimal_solution, optimal_solution[i][j]+1, j)
print(")", end=" ")
def main():
"""
Testing for matrix_chain_ordering
"""
array=[30,35,15,5,10,20,25]
length=len(array)
#Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25
matrix, optimal_solution = matrix_chain_order(array)
print("No. of Operation required: "+str((matrix[1][length-1])))
print_optimal_solution(optimal_solution,1,length-1)
if __name__ == '__main__':
main()
|
Find the contiguous subarray within an array containing at least one number which has the largest product. For example, given the array 2,3,2,4, the contiguous subarray 2,3 has the largest product 6. :type nums: Listint :rtype: int Another approach that would print max product and the subarray Examples: subarraywithmaxproduct2,3,6,1,1,9,5 maxproductsofar: 45, 1, 1, 9, 5 subarraywithmaxproduct2,3,6,0,7,5 maxproductsofar: 36, 2, 3, 6 subarraywithmaxproduct4,3,2,1 maxproductsofar: 24, 4, 3, 2, 1 subarraywithmaxproduct3,0,1 maxproductsofar: 1, 1 arr is list of positivenegative numbers ''' length lenarr productsofar maxproductend 1 maxstarti 0 sofarstarti sofarendi 0 allnegativeflag True for i in rangelength: maxproductend arri if arri 0: allnegativeflag False if maxproductend 0: maxproductend arri maxstarti i if productsofar maxproductend: productsofar maxproductend sofarendi i sofarstarti maxstarti if allnegativeflag: printfmaxproductsofar: reducelambda x, y: x y, arr, arr else: printfmaxproductsofar: productsofar,arrsofarstarti:sofarendi 1 | from functools import reduce
def max_product(nums):
"""
:type nums: List[int]
:rtype: int
"""
lmin = lmax = gmax = nums[0]
for num in nums:
t_1 = num * lmax
t_2 = num * lmin
lmax = max(max(t_1, t_2), num)
lmin = min(min(t_1, t_2), num)
gmax = max(gmax, lmax)
"""
Another approach that would print max product and the subarray
Examples:
subarray_with_max_product([2,3,6,-1,-1,9,5])
#=> max_product_so_far: 45, [-1, -1, 9, 5]
subarray_with_max_product([-2,-3,6,0,-7,-5])
#=> max_product_so_far: 36, [-2, -3, 6]
subarray_with_max_product([-4,-3,-2,-1])
#=> max_product_so_far: 24, [-4, -3, -2, -1]
subarray_with_max_product([-3,0,1])
#=> max_product_so_far: 1, [1]
"""
def subarray_with_max_product(arr):
''' arr is list of positive/negative numbers '''
length = len(arr)
product_so_far = max_product_end = 1
max_start_i = 0
so_far_start_i = so_far_end_i = 0
all_negative_flag = True
for i in range(length):
max_product_end *= arr[i]
if arr[i] > 0:
all_negative_flag = False
if max_product_end <= 0:
max_product_end = arr[i]
max_start_i = i
if product_so_far <= max_product_end:
product_so_far = max_product_end
so_far_end_i = i
so_far_start_i = max_start_i
if all_negative_flag:
print(f"max_product_so_far: {reduce(lambda x, y: x * y, arr)}, {arr}")
else:
print(f"max_product_so_far: {product_so_far},{arr[so_far_start_i:so_far_end_i + 1]}")
|
author goswamirahul To find minimum cost path from station 0 to station N1, where cost of moving from ith station to jth station is given as: Matrix of size N x N where Matrixij denotes the cost of moving from station i station j for i j NOTE that values where Matrixij and i j does not mean anything, and hence represented by 1 or INF For the input below cost matrix, Minimum cost is obtained as from 0 1 3 cost01 cost13 65 the Output will be: The Minimum cost to reach station 4 is 65 Time Complexity: On2 Space Complexity: On Find minimum cost. Keyword arguments: cost matrix containing costs disti stores minimum cost from 0 i. | INF = float("inf")
def min_cost(cost):
"""Find minimum cost.
Keyword arguments:
cost -- matrix containing costs
"""
length = len(cost)
# dist[i] stores minimum cost from 0 --> i.
dist = [INF] * length
dist[0] = 0 # cost from 0 --> 0 is zero.
for i in range(length):
for j in range(i+1,length):
dist[j] = min(dist[j], dist[i] + cost[i][j])
return dist[length-1]
if __name__ == '__main__':
costs = [ [ 0, 15, 80, 90], # cost[i][j] is the cost of
[-1, 0, 40, 50], # going from i --> j
[-1, -1, 0, 70],
[-1, -1, -1, 0] ] # cost[i][j] = -1 for i > j
TOTAL_LEN = len(costs)
mcost = min_cost(costs)
assert mcost == 65
print(f"The minimum cost to reach station {TOTAL_LEN} is {mcost}")
|
A message containing letters from AZ is being encoded to numbers using the following mapping: 'A' 1 'B' 2 ... 'Z' 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message 12, it could be decoded as AB 1 2 or L 12. The number of ways decoding 12 is 2. :type s: str :rtype: int :type s: str :rtype: int only '10', '20' is valid '01 09' is not allowed other case '01, 09, 27' | def num_decodings(enc_mes):
"""
:type s: str
:rtype: int
"""
if not enc_mes or enc_mes[0] == "0":
return 0
last_char, last_two_chars = 1, 1
for i in range(1, len(enc_mes)):
last = last_char if enc_mes[i] != "0" else 0
last_two = last_two_chars if int(enc_mes[i-1:i+1]) < 27 and enc_mes[i-1] != "0" else 0
last_two_chars = last_char
last_char = last+last_two
return last_char
def num_decodings2(enc_mes):
"""
:type s: str
:rtype: int
"""
if not enc_mes or enc_mes.startswith('0'):
return 0
stack = [1, 1]
for i in range(1, len(enc_mes)):
if enc_mes[i] == '0':
if enc_mes[i-1] == '0' or enc_mes[i-1] > '2':
# only '10', '20' is valid
return 0
stack.append(stack[-2])
elif 9 < int(enc_mes[i-1:i+1]) < 27:
# '01 - 09' is not allowed
stack.append(stack[-2]+stack[-1])
else:
# other case '01, 09, 27'
stack.append(stack[-1])
return stack[-1]
|
An even number of trees are left along one side of a country road. You've been assigned the job to plant these trees at an even interval on both sides of the road. The length and width of the road are variable, and a pair of trees must be planted at the beginning at 0 and at the end at length of the road. Only one tree can be moved at a time. The goal is to calculate the lowest amount of distance that the trees have to be moved before they are all in a valid position. Returns the minimum distance that trees have to be moved before they are all in a valid state. Parameters: tree listint: A sorted list of integers with all trees' position along the road. length int: An integer with the length of the road. width int: An integer with the width of the road. Returns: A float number with the total distance trees have been moved. | from math import sqrt
def planting_trees(trees, length, width):
"""
Returns the minimum distance that trees have to be moved before they
are all in a valid state.
Parameters:
tree (list<int>): A sorted list of integers with all trees'
position along the road.
length (int): An integer with the length of the road.
width (int): An integer with the width of the road.
Returns:
A float number with the total distance trees have been moved.
"""
trees = [0] + trees
n_pairs = int(len(trees)/2)
space_between_pairs = length/(n_pairs-1)
target_locations = [location*space_between_pairs for location in range(n_pairs)]
cmatrix = [[0 for _ in range(n_pairs+1)] for _ in range(n_pairs+1)]
for r_i in range(1, n_pairs+1):
cmatrix[r_i][0] = cmatrix[r_i-1][0] + sqrt(
width + abs(trees[r_i]-target_locations[r_i-1])**2)
for l_i in range(1, n_pairs+1):
cmatrix[0][l_i] = cmatrix[0][l_i-1] + abs(trees[l_i]-target_locations[l_i-1])
for r_i in range(1, n_pairs+1):
for l_i in range(1, n_pairs+1):
cmatrix[r_i][l_i] = min(
cmatrix[r_i-1][l_i] + sqrt(width + (trees[l_i + r_i]-target_locations[r_i-1])**2),
cmatrix[r_i][l_i-1] + abs(trees[l_i + r_i]-target_locations[l_i-1])
)
return cmatrix[n_pairs][n_pairs]
|
Implement regular expression matching with support for '.' and ''. '.' Matches any single character. '' Matches zero or more of the preceding element. The matching should cover the entire input string not partial. The function prototype should be: bool ismatchconst char s, const char p Some examples: ismatchaa,a false ismatchaa,aa true ismatchaaa,aa false ismatchaa, a true ismatchaa, . true ismatchab, . true ismatchaab, cab true Finds if stra matches strb Keyword arguments: stra string strb string Match empty string with empty pattern Match empty string with . The previous character has matched and the current one has to be matched. Two possible matches: the same or . Horizontal look up j 2. Not use the character before . Vertical look up i 1. Use at least one character before . p a b s 1 0 0 0 a 0 1 0 1 b 0 0 1 1 b 0 0 0 ? | def is_match(str_a, str_b):
"""Finds if `str_a` matches `str_b`
Keyword arguments:
str_a -- string
str_b -- string
"""
len_a, len_b = len(str_a) + 1, len(str_b) + 1
matches = [[False] * len_b for _ in range(len_a)]
# Match empty string with empty pattern
matches[0][0] = True
# Match empty string with .*
for i, element in enumerate(str_b[1:], 2):
matches[0][i] = matches[0][i - 2] and element == '*'
for i, char_a in enumerate(str_a, 1):
for j, char_b in enumerate(str_b, 1):
if char_b != '*':
# The previous character has matched and the current one
# has to be matched. Two possible matches: the same or .
matches[i][j] = matches[i - 1][j - 1] and \
char_b in (char_a, '.')
else:
# Horizontal look up [j - 2].
# Not use the character before *.
matches[i][j] |= matches[i][j - 2]
# Vertical look up [i - 1].
# Use at least one character before *.
# p a b *
# s 1 0 0 0
# a 0 1 0 1
# b 0 0 1 1
# b 0 0 0 ?
if char_a == str_b[j - 2] or str_b[j - 2] == '.':
matches[i][j] |= matches[i - 1][j]
return matches[-1][-1]
|
A Dynamic Programming solution for Rod cutting problem Returns the best obtainable price for a rod of length n and price as prices of different pieces Build the table val in bottom up manner and return the last entry from the table Driver program to test above functions This code is contributed by Bhavya Jain | INT_MIN = -32767
def cut_rod(price):
"""
Returns the best obtainable price for a rod of length n and
price[] as prices of different pieces
"""
n = len(price)
val = [0]*(n+1)
# Build the table val[] in bottom up manner and return
# the last entry from the table
for i in range(1, n+1):
max_val = INT_MIN
for j in range(i):
max_val = max(max_val, price[j] + val[i-j-1])
val[i] = max_val
return val[n]
# Driver program to test above functions
arr = [1, 5, 8, 9, 10, 17, 17, 20]
print("Maximum Obtainable Value is " + str(cut_rod(arr)))
# This code is contributed by Bhavya Jain
|
Given a nonempty string s and a dictionary wordDict containing a list of nonempty words, determine if word can be segmented into a spaceseparated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. For example, given word leetcode, dict leet, code. Return true because leetcode can be segmented as leet code. word abc worddict a,bc True False False False TC: ON2 SC: ON :type word: str :type worddict: Setstr :rtype: bool | # TC: O(N^2) SC: O(N)
def word_break(word, word_dict):
"""
:type word: str
:type word_dict: Set[str]
:rtype: bool
"""
dp_array = [False] * (len(word)+1)
dp_array[0] = True
for i in range(1, len(word)+1):
for j in range(0, i):
if dp_array[j] and word[j:i] in word_dict:
dp_array[i] = True
break
return dp_array[-1]
if __name__ == "__main__":
STR = "keonkim"
dic = ["keon", "kim"]
print(word_break(str, dic))
|
Collection of algorithms on graphs. | from .tarjan import *
from .check_bipartite import *
from .maximum_flow import *
from .maximum_flow_bfs import *
from .maximum_flow_dfs import *
from .all_pairs_shortest_path import *
from .bellman_ford import *
from .prims_minimum_spanning import *
|
Given a nn adjacency array. it will give you all pairs shortest path length. use deepcopy to preserve the original information. Time complexity : OE3 example a 0 , 0.1 , 0.101, 0.142, 0.277, 0.465, 0 , 0.191, 0.192, 0.587, 0.245, 0.554, 0 , 0.333, 0.931, 1.032, 0.668, 0.656, 0 , 0.151, 0.867, 0.119, 0.352, 0.398, 0 result 0 , 0.1 , 0.101, 0.142, 0.277, 0.436, 0 , 0.191, 0.192, 0.343, 0.245, 0.345, 0 , 0.333, 0.484, 0.706, 0.27 , 0.461, 0 , 0.151, 0.555, 0.119, 0.31 , 0.311, 0 Given a matrix of the edge weights between respective nodes, returns a matrix containing the shortest distance distance between the two nodes. | import copy
def all_pairs_shortest_path(adjacency_matrix):
"""
Given a matrix of the edge weights between respective nodes, returns a
matrix containing the shortest distance distance between the two nodes.
"""
new_array = copy.deepcopy(adjacency_matrix)
size = len(new_array)
for k in range(size):
for i in range(size):
for j in range(size):
if new_array[i][j] > new_array[i][k] + new_array[k][j]:
new_array[i][j] = new_array[i][k] + new_array[k][j]
return new_array
|
Determination of singlesource shortestpath. This BellmanFord Code is for determination whether we can get shortest path from given graph or not for singlesource shortestpaths problem. In other words, if given graph has any negativeweight cycle that is reachable from the source, then it will give answer False for no solution exits. For argument graph, it should be a dictionary type such as graph 'a': 'b': 6, 'e': 7, 'b': 'c': 5, 'd': 4, 'e': 8, 'c': 'b': 2, 'd': 'a': 2, 'c': 7, 'e': 'b': 3 Initialize data structures for BellmanFord algorithm. | def bellman_ford(graph, source):
"""
This Bellman-Ford Code is for determination whether we can get
shortest path from given graph or not for single-source shortest-paths problem.
In other words, if given graph has any negative-weight cycle that is reachable
from the source, then it will give answer False for "no solution exits".
For argument graph, it should be a dictionary type
such as
graph = {
'a': {'b': 6, 'e': 7},
'b': {'c': 5, 'd': -4, 'e': 8},
'c': {'b': -2},
'd': {'a': 2, 'c': 7},
'e': {'b': -3}
}
"""
weight = {}
pre_node = {}
initialize_single_source(graph, source, weight, pre_node)
for _ in range(1, len(graph)):
for node in graph:
for adjacent in graph[node]:
if weight[adjacent] > weight[node] + graph[node][adjacent]:
weight[adjacent] = weight[node] + graph[node][adjacent]
pre_node[adjacent] = node
for node in graph:
for adjacent in graph[node]:
if weight[adjacent] > weight[node] + graph[node][adjacent]:
return False
return True
def initialize_single_source(graph, source, weight, pre_node):
"""
Initialize data structures for Bellman-Ford algorithm.
"""
for node in graph:
weight[node] = float('inf')
pre_node[node] = None
weight[source] = 0
|
Bipartite graph is a graph whose vertices can be divided into two disjoint and independent sets. https:en.wikipedia.orgwikiBipartitegraph Determine if the given graph is bipartite. Time complexity is OE Space complexity is OV Divide vertexes in the graph into settype 0 and 1 Initialize all settypes as 1 If there is a selfloop, it cannot be bipartite set type of u opposite of v | def check_bipartite(adj_list):
"""
Determine if the given graph is bipartite.
Time complexity is O(|E|)
Space complexity is O(|V|)
"""
vertices = len(adj_list)
# Divide vertexes in the graph into set_type 0 and 1
# Initialize all set_types as -1
set_type = [-1 for v in range(vertices)]
set_type[0] = 0
queue = [0]
while queue:
current = queue.pop(0)
# If there is a self-loop, it cannot be bipartite
if adj_list[current][current]:
return False
for adjacent in range(vertices):
if adj_list[current][adjacent]:
if set_type[adjacent] == set_type[current]:
return False
if set_type[adjacent] == -1:
# set type of u opposite of v
set_type[adjacent] = 1 - set_type[current]
queue.append(adjacent)
return True
|
In a directed graph, a strongly connected component is a set of vertices such that for any pairs of vertices u and v there exists a path u...v that connects them. A graph is strongly connected if it is a single strongly connected component. A directed graph where edges are oneway a twoway edge can be represented by using two edges. Create a new graph with vertexcount vertices. Add an edge going from source to target Determine if all nodes are reachable from node 0 Determine if all nodes are reachable from the given node Create a new graph where every edge ab is replaced with an edge ba Note: we reverse the order of arguments pylint: disableargumentsoutoforder Determine if the graph is strongly connected. | from collections import defaultdict
class Graph:
"""
A directed graph where edges are one-way (a two-way edge can be represented by using two edges).
"""
def __init__(self,vertex_count):
"""
Create a new graph with vertex_count vertices.
"""
self.vertex_count = vertex_count
self.graph = defaultdict(list)
def add_edge(self,source,target):
"""
Add an edge going from source to target
"""
self.graph[source].append(target)
def dfs(self):
"""
Determine if all nodes are reachable from node 0
"""
visited = [False] * self.vertex_count
self.dfs_util(0,visited)
if visited == [True]*self.vertex_count:
return True
return False
def dfs_util(self,source,visited):
"""
Determine if all nodes are reachable from the given node
"""
visited[source] = True
for adjacent in self.graph[source]:
if not visited[adjacent]:
self.dfs_util(adjacent,visited)
def reverse_graph(self):
"""
Create a new graph where every edge a->b is replaced with an edge b->a
"""
reverse_graph = Graph(self.vertex_count)
for source, adjacent in self.graph.items():
for target in adjacent:
# Note: we reverse the order of arguments
# pylint: disable=arguments-out-of-order
reverse_graph.add_edge(target,source)
return reverse_graph
def is_strongly_connected(self):
"""
Determine if the graph is strongly connected.
"""
if self.dfs():
reversed_graph = self.reverse_graph()
if reversed_graph.dfs():
return True
return False
|
import collections class UndirectedGraphNode: def initself, label: self.label label self.neighbors def shallowcopyself: return UndirectedGraphNodeself.label def addneighborself, node: self.neighbors.appendnode def clonegraph1node: if not node: return None nodecopy node.shallowcopy dic node: nodecopy queue collections.dequenode while queue: node queue.popleft for neighbor in node.neighbors: if neighbor not in dic: neighbor is not visited neighborcopy neighbor.shallowcopy dicneighbor neighborcopy dicnode.addneighborneighborcopy queue.appendneighbor else: dicnode.addneighbordicneighbor return nodecopy def clonegraph2node: if not node: return None nodecopy node.shallowcopy dic node: nodecopy stack node while stack: node stack.pop for neighbor in node.neighbors: if neighbor not in dic: neighborcopy neighbor.shallowcopy dicneighbor neighborcopy dicnode.addneighborneighborcopy stack.appendneighbor else: dicnode.addneighbordicneighbor return nodecopy def clonegraphnode: if not node: return None nodecopy node.shallowcopy dic node: nodecopy dfsnode, dic return nodecopy def dfsnode, dic: for neighbor in node.neighbors: if neighbor not in dic: neighborcopy neighbor.shallowcopy dicneighbor neighborcopy dicnode.addneighborneighborcopy dfsneighbor, dic else: dicnode.addneighbordicneighbor | r"""
Clone an undirected graph. Each node in the graph contains a label and a list
of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and
each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as
separated by #.
First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a
self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
"""
import collections
class UndirectedGraphNode:
"""
A node in an undirected graph. Contains a label and a list of neighbouring
nodes (initially empty).
"""
def __init__(self, label):
self.label = label
self.neighbors = []
def shallow_copy(self):
"""
Return a shallow copy of this node (ignoring any neighbors)
"""
return UndirectedGraphNode(self.label)
def add_neighbor(self, node):
"""
Adds a new neighbor
"""
self.neighbors.append(node)
def clone_graph1(node):
"""
Returns a new graph as seen from the given node using a breadth first search (BFS).
"""
if not node:
return None
node_copy = node.shallow_copy()
dic = {node: node_copy}
queue = collections.deque([node])
while queue:
node = queue.popleft()
for neighbor in node.neighbors:
if neighbor not in dic: # neighbor is not visited
neighbor_copy = neighbor.shallow_copy()
dic[neighbor] = neighbor_copy
dic[node].add_neighbor(neighbor_copy)
queue.append(neighbor)
else:
dic[node].add_neighbor(dic[neighbor])
return node_copy
def clone_graph2(node):
"""
Returns a new graph as seen from the given node using an iterative depth first search (DFS).
"""
if not node:
return None
node_copy = node.shallow_copy()
dic = {node: node_copy}
stack = [node]
while stack:
node = stack.pop()
for neighbor in node.neighbors:
if neighbor not in dic:
neighbor_copy = neighbor.shallow_copy()
dic[neighbor] = neighbor_copy
dic[node].add_neighbor(neighbor_copy)
stack.append(neighbor)
else:
dic[node].add_neighbor(dic[neighbor])
return node_copy
def clone_graph(node):
"""
Returns a new graph as seen from the given node using a recursive depth first search (DFS).
"""
if not node:
return None
node_copy = node.shallow_copy()
dic = {node: node_copy}
dfs(node, dic)
return node_copy
def dfs(node, dic):
"""
Clones a graph using a recursive depth first search. Stores the clones in
the dictionary, keyed by the original nodes.
"""
for neighbor in node.neighbors:
if neighbor not in dic:
neighbor_copy = neighbor.shallow_copy()
dic[neighbor] = neighbor_copy
dic[node].add_neighbor(neighbor_copy)
dfs(neighbor, dic)
else:
dic[node].add_neighbor(dic[neighbor])
|
count connected no of component using DFS In graph theory, a component, sometimes called a connected component, of an undirected graph is a subgraph in which any two vertices are connected to each other by paths. Example: 1 37 24 output 2 65 Code is Here Function that performs DFS ''' visitedsource True for child in adjacencylistsource: if not visitedchild: dfschild,visited,adjacencylist def countcomponentsadjacencylist,size: count 0 visited Falsesize1 for i in range1,size1: if not visitedi: dfsi,visited,adjacencylist count1 return count def main: nodecount,edgecount mapint, inputEnter the Number of Nodes and Edges n.split' ' adjacency for in rangenodecount1 for in rangeedgecount: printEnter the edge's Nodes in form of source targetn source,target mapint,input.split' ' adjacencysource.appendtarget adjacencytarget.appendsource printTotal number of Connected Components are : , countcomponentsadjacency,nodecount Driver code if name 'main': main | #count connected no of component using DFS
'''
In graph theory, a component, sometimes called a connected component,
of an undirected graph is a subgraph in which any
two vertices are connected to each other by paths.
Example:
1 3------------7
|
|
2--------4
| |
| | output = 2
6--------5
'''
# Code is Here
def dfs(source,visited,adjacency_list):
''' Function that performs DFS '''
visited[source] = True
for child in adjacency_list[source]:
if not visited[child]:
dfs(child,visited,adjacency_list)
def count_components(adjacency_list,size):
'''
Function that counts the Connected components on bases of DFS.
return type : int
'''
count = 0
visited = [False]*(size+1)
for i in range(1,size+1):
if not visited[i]:
dfs(i,visited,adjacency_list)
count+=1
return count
def main():
"""
Example application
"""
node_count,edge_count = map(int, input("Enter the Number of Nodes and Edges \n").split(' '))
adjacency = [[] for _ in range(node_count+1)]
for _ in range(edge_count):
print("Enter the edge's Nodes in form of `source target`\n")
source,target = map(int,input().split(' '))
adjacency[source].append(target)
adjacency[target].append(source)
print("Total number of Connected Components are : ", count_components(adjacency,node_count))
# Driver code
if __name__ == '__main__':
main()
|
Given a directed graph, check whether it contains a cycle. Reallife scenario: deadlock detection in a system. Processes may be represented by vertices, then and an edge A B could mean that process A is waiting for B to release its lock on a resource. For a given node: WHITE: has not been visited yet GRAY: is currently being investigated for a cycle BLACK: is not part of a cycle Determines if the given vertex is in a cycle. :param: traversalstates: for each vertex, the state it is in Determines if there is a cycle in the given graph. The graph should be given as a dictionary: graph 'A': 'B', 'C', 'B': 'D', 'C': 'F', 'D': 'E', 'F', 'E': 'B', 'F': | from enum import Enum
class TraversalState(Enum):
"""
For a given node:
- WHITE: has not been visited yet
- GRAY: is currently being investigated for a cycle
- BLACK: is not part of a cycle
"""
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph, traversal_states, vertex):
"""
Determines if the given vertex is in a cycle.
:param: traversal_states: for each vertex, the state it is in
"""
if traversal_states[vertex] == TraversalState.GRAY:
return True
traversal_states[vertex] = TraversalState.GRAY
for neighbor in graph[vertex]:
if is_in_cycle(graph, traversal_states, neighbor):
return True
traversal_states[vertex] = TraversalState.BLACK
return False
def contains_cycle(graph):
"""
Determines if there is a cycle in the given graph.
The graph should be given as a dictionary:
graph = {'A': ['B', 'C'],
'B': ['D'],
'C': ['F'],
'D': ['E', 'F'],
'E': ['B'],
'F': []}
"""
traversal_states = {vertex: TraversalState.WHITE for vertex in graph}
for vertex, state in traversal_states.items():
if (state == TraversalState.WHITE and
is_in_cycle(graph, traversal_states, vertex)):
return True
return False
|
Dijkstra's singlesource shortestpath algorithm A fully connected directed graph with edge weights Find the vertex that is closest to the visited set Given a node, returns the shortest distance to every other node minimum distance vertex that is not processed put minimum distance vertex in shortest tree Update dist value of the adjacent vertices | class Dijkstra():
"""
A fully connected directed graph with edge weights
"""
def __init__(self, vertex_count):
self.vertex_count = vertex_count
self.graph = [[0 for _ in range(vertex_count)] for _ in range(vertex_count)]
def min_distance(self, dist, min_dist_set):
"""
Find the vertex that is closest to the visited set
"""
min_dist = float("inf")
for target in range(self.vertex_count):
if min_dist_set[target]:
continue
if dist[target] < min_dist:
min_dist = dist[target]
min_index = target
return min_index
def dijkstra(self, src):
"""
Given a node, returns the shortest distance to every other node
"""
dist = [float("inf")] * self.vertex_count
dist[src] = 0
min_dist_set = [False] * self.vertex_count
for _ in range(self.vertex_count):
#minimum distance vertex that is not processed
source = self.min_distance(dist, min_dist_set)
#put minimum distance vertex in shortest tree
min_dist_set[source] = True
#Update dist value of the adjacent vertices
for target in range(self.vertex_count):
if self.graph[source][target] <= 0 or min_dist_set[target]:
continue
if dist[target] > dist[source] + self.graph[source][target]:
dist[target] = dist[source] + self.graph[source][target]
return dist
|
Finds all cliques in an undirected graph. A clique is a set of vertices in the graph such that the subgraph is fully connected ie. for any pair of nodes in the subgraph there is an edge between them. takes dict of sets each key is a vertex value is set of all edges connected to vertex returns list of lists each sub list is a maximal clique implementation of the basic algorithm described in: Bron, Coen; Kerbosch, Joep 1973, Algorithm 457: finding all cliques of an undirected graph, | def find_all_cliques(edges):
"""
takes dict of sets
each key is a vertex
value is set of all edges connected to vertex
returns list of lists (each sub list is a maximal clique)
implementation of the basic algorithm described in:
Bron, Coen; Kerbosch, Joep (1973), "Algorithm 457: finding all cliques of an undirected graph",
"""
def expand_clique(candidates, nays):
nonlocal compsub
if not candidates and not nays:
nonlocal solutions
solutions.append(compsub.copy())
else:
for selected in candidates.copy():
candidates.remove(selected)
candidates_temp = get_connected(selected, candidates)
nays_temp = get_connected(selected, nays)
compsub.append(selected)
expand_clique(candidates_temp, nays_temp)
nays.add(compsub.pop())
def get_connected(vertex, old_set):
new_set = set()
for neighbor in edges[str(vertex)]:
if neighbor in old_set:
new_set.add(neighbor)
return new_set
compsub = []
solutions = []
possibles = set(edges.keys())
expand_clique(possibles, set())
return solutions
|
Functions for finding paths in graphs. pylint: disabledangerousdefaultvalue Find a path between two nodes using recursion and backtracking. pylint: disabledangerousdefaultvalue Find all paths between two nodes using recursion and backtracking find the shortest path between two nodes | # pylint: disable=dangerous-default-value
def find_path(graph, start, end, path=[]):
"""
Find a path between two nodes using recursion and backtracking.
"""
path = path + [start]
if start == end:
return path
if not start in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
return newpath
return None
# pylint: disable=dangerous-default-value
def find_all_path(graph, start, end, path=[]):
"""
Find all paths between two nodes using recursion and backtracking
"""
path = path + [start]
if start == end:
return [path]
if not start in graph:
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_path(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
def find_shortest_path(graph, start, end, path=[]):
"""
find the shortest path between two nodes
"""
path = path + [start]
if start == end:
return path
if start not in graph:
return None
shortest = None
for node in graph[start]:
if node not in path:
newpath = find_shortest_path(graph, node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest
|
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 9