Description
stringlengths
18
161k
Code
stringlengths
15
300k
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 time complexity o n 2 time complexity o n using hash tables keep track of occurrences
import collections def delete_nth_naive(array, n): ans = [] for num in array: if ans.count(num) < n: ans.append(num) return ans def delete_nth(array, n): result = [] counts = collections.defaultdict(int) 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 return list tail recursion produce the result returns iterator takes as input multi dimensional iterable and returns generator which produces one dimensional output
from collections.abc import Iterable 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) else: output_arr.append(ele) return output_arr def flatten_iter(iterable): 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 prevent changes in original initial list of each step in sequence if zero isn t where it should be what should be where zero is and where is it 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
def garage(initial, final): initial = initial[::] seq = [] steps = 0 while initial != final: zero = initial.index(0) if zero != final.index(0): car_to_move = final[zero] pos = initial.index(car_to_move) 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
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 list starts with 0 index hash index to every 3rd
def josephus(int_list, skip): skip = skip - 1 idx = 0 len_list = (len(int_list)) while len_list > 0: idx = (skip + idx) % len_list 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 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 max_len and substring find the length of the longest substring without repeating characters return max_len and the substring as a tuple find the length of the longest substring without repeating characters uses alternative algorithm return max_len and the substring as a tuple
def longest_non_repeat_v1(string): 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): 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 def get_longest_non_repeat_v1(string): 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): 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 if current element is 0 then calculate the difference between curr and prev_prev_zero
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 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 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 merge two intervals into one print out the intervals merge intervals in the form of a list
class Interval: 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 list(self) @staticmethod def merge(intervals): 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): res = [] for i in intervals: res.append(repr(i)) print("".join(res)) def merge_intervals(intervals): 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 after done iterating thru array append remainder to list
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: res.append((start, hi)) 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 not using not i to avoid false etc
def move_zeros(array): result = [] zeros = 0 for i in array: if i == 0 and type(i) != bool: 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 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 above below or right on want answers with only 2 terms easy recursive call a b c x n_sum a b c n_minus1_results x
def n_sum(n, nums, target, **kv): def sum_closure_default(a, b): return a + b def compare_closure_default(num, target): 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: 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( n - 1, nums[index + 1:], target - num ) ) 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 type digits list int rtype list int
def plus_one_v1(digits): 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 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 unused variable is not a problem 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
def rotate_v1(array, k): array = array[:] n = len(array) for i in range(k): 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): 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 type array list int rtype list
def summarize_ranges(array): 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 param array list int return set tuple int int int found three sum remove duplicates
def three_sum(array): 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: res.add((array[i], array[l], array[r])) 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 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 = {} 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 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 cal_sum = 0 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 type num str type target int rtype list str all digits have to be used
def add_operators(num, target): 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': 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 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
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): 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 backtracking
def combination_sum(candidates, target): def dfs(nums, target, index, path, res): if target < 0: return 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 recursive
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 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 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 add the current word 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: backtrack(result, word, pos+1, 0, cur+str(count)+word[pos]) else: backtrack(result, word, pos+1, 0, cur+word[pos]) 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 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 def palindromic_substrings_iter(s): 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 type pattern str type string str rtype bool
def pattern_match(pattern, string): 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 returns a list with the permuations iterator returns a perumation by each call dfs version
def permute(elements): 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): 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:] 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 handles duplication
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 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 o 2 n take nums pos dont take nums pos 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(nums): def backtrack(res, nums, stack, pos): if pos == len(nums): res.append(list(stack)) else: stack.append(nums[pos]) backtrack(res, nums, stack, pos+1) stack.pop() backtrack(res, nums, stack, pos+1) res = [] backtrack(res, nums, [], 0) return res 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 take don t take
def subsets_unique(nums): def backtrack(res, nums, stack, pos): if pos == len(nums): res.add(tuple(stack)) else: stack.append(nums[pos]) backtrack(res, nums, stack, pos+1) stack.pop() 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 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
from collections import deque 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 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 count how many building we have visited only the position be visited by count times will append to queue
import collections 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 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)]: 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 bidirectional bfs type begin_word str type end_word str type word_list set str rtype int not possible when only differ by 1 character print begin_set print result
def ladder_length(begin_word, end_word, word_list): if len(begin_word) != len(end_word): return -1 if begin_word == end_word: return 0 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 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 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 set_bit 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 get_bit(num, i): return (num & (1 << i)) != 0 def set_bit(num, i): return num | (1 << i) def clear_bit(num, i): mask = ~(1 << i) return num & mask def update_bit(num, i, bit): mask = ~(1 << i) return (num & mask) | (bit << i)
list insert0 is inefficient list insert 0 is inefficient
from collections import deque def int_to_bytes_big_endian(num): bytestr = deque() while num > 0: 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 count number of ones in diff
def count_flips_to_convert(a, b): diff = a ^ b 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 using brian kernighan s algorithm recursive approach using brian kernighan s algorithm iterative approach
def count_ones_recur(n): if not n: return 0 return 1 + count_ones_recur(n & (n-1)) def count_ones_iter(n): 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 ord ch return an integer representing the unicode code point of that character chr i return the string representing a character whose unicode code point is the integer i
def find_difference(s, t): ret = 0 for ch in s + t: ret = ret ^ ord(ch) 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 last digit is 1 last digit is 0 second last digit is 0 right shift num
def flip_bit_longest_seq(num): curr_len = 0 prev_len = 0 max_len = 0 while num: if num & 1 == 1: curr_len += 1 elif num & 1 == 0: if num & 2 == 0: prev_len = 0 else: prev_len = curr_len curr_len = 0 max_len = max(max_len, prev_len + curr_len) num = num >> 1 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 time complexity o 1 for bits ending with zero 1010 for bits ending with one 0101
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 def has_alternative_bit_fast(n): mask1 = int('aaaaaaaa', 16) mask2 = int('55555555', 16) 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 create mask keep the bit from 0 position to i position
def insert_one_bit(num, bit, i): mask = num >> i mask = (mask << 1) | bit mask = mask << i 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 type n int rtype bool
def is_power_of_two(n): 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 returns single number if found else if all numbers appear twice returns 0 type nums list int rtype int
def single_number(nums): 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 type nums list int rtype list int isolate a b from pairs using xor isolate right most bit from a b isolate a and b from a b
def single_number3(nums): ab = 0 for n in nums: ab ^= n right_most = ab & (-ab) 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 param nums list int return set tuple 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
def subsets(nums): 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
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 odd bit arithmetic right shift 1 bit even bit left shift 1 bit
def swap_pair(num): odd = (num & int('AAAAAAAA', 16)) >> 1 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 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 log2 x the second part is the binary number of x 2 log2 x 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 elias_g of the number
from math import log log2 = lambda x: log(x, 2) def binary(x, l=1): fmt = '{0:0%db}' % l return fmt.format(x) def unary(x): return (x-1)*'1'+'0' def elias_generic(lencoding, x): 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): return elias_generic(unary, x) def elias_delta(x): 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 load tree from file return going to left node right push on stack load values to tree after reading tree param leaves_queue return load next byte is buffer is less than buff_limit param buff_limit return true if there is enough bits in buffer to read generate and save tree code to file param tree return 1 indicates that tree ended it will be needed to load the tree overwrite first three bits in the file param additional_bits number of bits that were appended to fill last byte return overwrite first three bits buffer is empty no need to append extra 0 class to help find signs in tree find sign in tree param bit return true if sign is found read whole code there is last byte in buffer to parse remove additional 0 used to fill byte leave space to save how many bits will be appended to fill the last byte root
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: 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) 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): 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: 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): 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") for int_sign in signs: self.write_int(int_sign) def _save_information_about_additional_bits(self, additional_bits: int): 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")) 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: self.write_bits("0" * additional_bits) self._save_information_about_additional_bits(additional_bits) class TreeFinder: def __init__(self, tree): self.root = tree self.current_node = tree self.found = None def find(self, bit): 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): bit = reader.get_bit(0) file.write(bytes([tree_finder.found])) else: is_end_of_file = True last_byte = reader.buffer last_byte = last_byte[:-additional_bits] 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") 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] @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 gets a stream of data and compresses it under a run length 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 run length 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): if not input: return '' encoded_str = '' prev_ch = '' count = 1 for ch in input: if ch != prev_ch: if prev_ch: encoded_str += str(count) + prev_ch count = 1 prev_ch = ch else: count += 1 else: return encoded_str + (str(count) + prev_ch) def decode_rle(input): decode_str = '' count = '' for ch in input: if not ch.isdigit(): decode_str += ch * int(count) count = '' else: 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 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 get_factors in a call stack 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): def factor(n, i, combi, 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): 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): 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 type matrix list list int rtype list list int
def pacific_atlantic(matrix): 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 valid choice keep solving invalid choice or didn t solve it undo 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): if self.solve(): return True self.undo(kee, update) 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): 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 out of bounds crossed
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 if rooms[i][j] < depth: return 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 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 for each list value add one to the respective histogram dict position
def get_histogram(input_list: list) -> dict: histogram = {} 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 type prices list int rtype int o n time input 7 1 5 3 6 4 diff x 6 4 2 3 2 type prices list int rtype int
def max_profit_naive(prices): 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 def max_profit_optimized(prices): 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 type steps int rtype int the above function can be optimized as o 1 space type steps int rtype int
def climb_stairs(steps): arr = [1, 1] for _ in range(1, steps): arr.append(arr[-1] + arr[-2]) return arr[-1] def climb_stairs_optimized(steps): 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 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): dp_array = [1] + [0] * value 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 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 top down 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 bottom up 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): 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): global DP DP = [-1] * (target + 1) DP[0] = 1 return helper_topdown(nums, target) def combination_sum_bottom_up(nums, target): 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 finds edit distance between word_a and word_b kwyword arguments word_a string word_b string this is the same as edit length_a length_b
def edit_distance(word_a, word_b): 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]
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 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 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 eggfloor n k holds the result
INT_MAX = 32767 def egg_drop(n, k): egg_floor = [[0 for _ in range(k + 1)] for _ in range(n + 1)] for i in range(1, n+1): egg_floor[i][1] = 1 egg_floor[i][0] = 0 for j in range(1, k+1): egg_floor[1][j] = j 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 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 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 print fib_recursive 35 9227465 slow 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 print fib_list 100 354224848179261915075 summary works iterative approximate o n arguments n int description returns int description precondition print fib_iter 100 354224848179261915075
def fib_recursive(n): assert n >= 0, 'n must be a positive integer' if n <= 1: return n return fib_recursive(n-1) + fib_recursive(n-2) def fib_list(n): 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] def fib_iter(n): 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
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 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): 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): for i in range(height): for j in range(i + 1): print(hosoya(i, j) , end = " ") print ("\n", end = "") def hosoya_testing(height): 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 find number of decompositions from decompose decompose integer
def int_divide(decompose): 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 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 table i stores the profit for jobs till arr i including arr i fill entries in table using recursive property find profit including the current job store maximum of including and excluding
class Job: def __init__(self, start, finish, profit): self.start = start self.finish = finish self.profit = profit def binary_search(job, start_index): left = 0 right = start_index - 1 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): job = sorted(job, key = lambda j: j.finish) length = len(job) table = [0 for _ in range(length)] table[0] = job[0].profit for i in range(1, length): incl_prof = job[i].profit pos = binary_search(job, i) if pos != -1: incl_prof += table[pos] 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 find the number of strings of length length with k factor k_factor keyword arguments length integer k_factor 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): 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 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: mat[i][j][0]=mat[i-1][j][0]+mat[i-1][j][1]+mat[i-1][j][3] mat[i][j][1]=mat[i-1][j][0] mat[i][j][2]=mat[i-1][j][1] 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]=mat[i-1][j][0]+mat[i-1][j][1]+mat[i-1][j][3]+mat[i-1][j-1][2] mat[i][j][1]=mat[i-1][j][0] mat[i][j][2]=mat[i-1][j][1] 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 param s1 string param s2 string return int mat i j contains length of lcs of s_1 0 i 1 and s_2 0 j 1
def longest_common_subsequence(s_1, s_2): m = len(s_1) n = len(s_2) mat = [[0] * (n + 1) for i in range(m + 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 dynamic programming algorithm for counting the length of longest increasing subsequence type sequence list int 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 10 5 then use longest_increasing_subsequence_optimied2 instead type sequence list int 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 list int rtype int
def longest_increasing_subsequence(sequence): 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): 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): 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 finds optimal order to multiply matrices array int print order of matrix with ai as matrix print the solution optimal_solution int i int j int testing for matrix_chain_ordering size of matrix created from above array will be 30 35 35 15 15 5 5 10 10 20 20 25
INF = float("inf") def matrix_chain_order(array): 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 def print_optimal_solution(optimal_solution,i,j): 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(): array=[30,35,15,5,10,20,25] length=len(array) 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 type nums list int rtype int 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 arr is list of positive negative numbers
from functools import reduce def max_product(nums): 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) def subarray_with_max_product(arr): 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]}")
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 find minimum cost keyword arguments cost matrix containing costs dist i stores minimum cost from 0 i cost from 0 0 is zero cost i j is the cost of going from i j cost i j 1 for i j
INF = float("inf") def min_cost(cost): length = len(cost) dist = [INF] * length dist[0] = 0 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], [-1, 0, 40, 50], [-1, -1, 0, 70], [-1, -1, -1, 0] ] 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 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): 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): 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': return 0 stack.append(stack[-2]) elif 9 < int(enc_mes[i-1:i+1]) < 27: stack.append(stack[-2]+stack[-1]) else: 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 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
from math import sqrt def planting_trees(trees, length, width): 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 finds if str_a matches str_b keyword arguments str_a string str_b 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): len_a, len_b = len(str_a) + 1, len(str_b) + 1 matches = [[False] * len_b for _ in range(len_a)] matches[0][0] = True 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 != '*': matches[i][j] = matches[i - 1][j - 1] and \ char_b in (char_a, '.') else: matches[i][j] |= matches[i][j - 2] 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 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): n = len(price) val = [0]*(n+1) 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] arr = [1, 5, 8, 9, 10, 17, 17, 20] print("Maximum Obtainable Value is " + str(cut_rod(arr)))
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 type word str type word_dict set str rtype bool
def word_break(word, word_dict): 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 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): 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 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 initialize data structures for bellman ford algorithm
def bellman_ford(graph, source): 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): 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 determine if the given graph is bipartite time complexity is o e space complexity is o v divide vertexes in the graph into set_type 0 and 1 initialize all set_types as 1 if there is a self loop it cannot be bipartite set type of u opposite of v
def check_bipartite(adj_list): vertices = len(adj_list) set_type = [-1 for v in range(vertices)] set_type[0] = 0 queue = [0] while queue: current = queue.pop(0) 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[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 a directed graph where edges are one way a two way edge can be represented by using two edges create a new graph with vertex_count 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 a b is replaced with an edge b a note we reverse the order of arguments pylint disable arguments out of order determine if the graph is strongly connected
from collections import defaultdict class Graph: def __init__(self,vertex_count): self.vertex_count = vertex_count self.graph = defaultdict(list) def add_edge(self,source,target): self.graph[source].append(target) def dfs(self): 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): visited[source] = True for adjacent in self.graph[source]: if not visited[adjacent]: self.dfs_util(adjacent,visited) def reverse_graph(self): reverse_graph = Graph(self.vertex_count) for source, adjacent in self.graph.items(): for target in adjacent: reverse_graph.add_edge(target,source) return reverse_graph def is_strongly_connected(self): 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 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 _ a node in an undirected graph contains a label and a list of neighbouring nodes initially empty return a shallow copy of this node ignoring any neighbors adds a new neighbor returns a new graph as seen from the given node using a breadth first search bfs neighbor is not visited returns a new graph as seen from the given node using an iterative depth first search dfs returns a new graph as seen from the given node using a recursive depth first search dfs clones a graph using a recursive depth first search stores the clones in the dictionary keyed by the original nodes
r import collections class UndirectedGraphNode: def __init__(self, label): self.label = label self.neighbors = [] def shallow_copy(self): return UndirectedGraphNode(self.label) def add_neighbor(self, node): self.neighbors.append(node) def clone_graph1(node): 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_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): 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): if not node: return None node_copy = node.shallow_copy() dic = {node: node_copy} dfs(node, dic) return node_copy def dfs(node, dic): 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 function that performs dfs function that counts the connected components on bases of dfs return type int example application driver code
def dfs(source,visited,adjacency_list): visited[source] = True for child in adjacency_list[source]: if not visited[child]: dfs(child,visited,adjacency_list) def count_components(adjacency_list,size): 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(): 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)) 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 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 traversal_states 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): WHITE = 0 GRAY = 1 BLACK = 2 def is_in_cycle(graph, traversal_states, vertex): 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): 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 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(): 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): 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): dist = [float("inf")] * self.vertex_count dist[src] = 0 min_dist_set = [False] * self.vertex_count for _ in range(self.vertex_count): source = self.min_distance(dist, min_dist_set) min_dist_set[source] = True 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 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): 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 find a path between two nodes using recursion and backtracking pylint disable dangerous default value find all paths between two nodes using recursion and backtracking find the shortest path between two nodes
def find_path(graph, start, end, path=[]): 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 def find_all_path(graph, start, end, path=[]): 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=[]): 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
these are classes to represent a graph and its elements it can be shared across graph algorithms a nodevertex in a graph return the name of the node a directed edge in a directed graph stores the source and target node of the edge a directed graph stores a set of nodes edges and adjacency matrix pylint disabledangerousdefaultvalue add a new named node to the graph add a new edge to the graph between two nodes a node vertex in a graph return the name of the node a directed edge in a directed graph stores the source and target node of the edge a directed graph stores a set of nodes edges and adjacency matrix pylint disable dangerous default value add a new named node to the graph add a new edge to the graph between two nodes
class Node: def __init__(self, name): self.name = name @staticmethod def get_name(obj): if isinstance(obj, Node): return obj.name if isinstance(obj, str): return obj return'' def __eq__(self, obj): return self.name == self.get_name(obj) def __repr__(self): return self.name def __hash__(self): return hash(self.name) def __ne__(self, obj): return self.name != self.get_name(obj) def __lt__(self, obj): return self.name < self.get_name(obj) def __le__(self, obj): return self.name <= self.get_name(obj) def __gt__(self, obj): return self.name > self.get_name(obj) def __ge__(self, obj): return self.name >= self.get_name(obj) def __bool__(self): return self.name class DirectedEdge: def __init__(self, node_from, node_to): self.source = node_from self.target = node_to def __eq__(self, obj): if isinstance(obj, DirectedEdge): return obj.source == self.source and obj.target == self.target return False def __repr__(self): return f"({self.source} -> {self.target})" class DirectedGraph: def __init__(self, load_dict={}): self.nodes = [] self.edges = [] self.adjacency_list = {} if load_dict and isinstance(load_dict, dict): for vertex in load_dict: node_from = self.add_node(vertex) self.adjacency_list[node_from] = [] for neighbor in load_dict[vertex]: node_to = self.add_node(neighbor) self.adjacency_list[node_from].append(node_to) self.add_edge(vertex, neighbor) def add_node(self, node_name): try: return self.nodes[self.nodes.index(node_name)] except ValueError: node = Node(node_name) self.nodes.append(node) return node def add_edge(self, node_name_from, node_name_to): try: node_from = self.nodes[self.nodes.index(node_name_from)] node_to = self.nodes[self.nodes.index(node_name_to)] self.edges.append(DirectedEdge(node_from, node_to)) except ValueError: pass