Prompt stringlengths 16 11.5k | Completions stringlengths 84 25.3k |
|---|---|
Given a list lst and a number N, create a new list that contains each number of the list at most N times without reordering. For example if N 2, and the input is 1,2,3,1,2,1,2,3, you take 1,2,3,1,2, drop the next 1,2 since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to 1,2,3,1,... | import collections
# Time complexity O(n^2)
def delete_nth_naive(array, n):
ans = []
for num in array:
if ans.count(num) < n:
ans.append(num)
return ans
# Time Complexity O(n), using hash tables.
def delete_nth(array, n):
result = []
counts = collections.defaultdict(int) # k... |
Implement Flatten Arrays. Given an array that may contain nested arrays, produce a single resultant array. return list returns iterator Takes as input multi dimensional iterable and returns generator which produces one dimensional output. | from collections.abc import Iterable
# return list
def flatten(input_arr, output_arr=None):
if output_arr is None:
output_arr = []
for ele in input_arr:
if not isinstance(ele, str) and isinstance(ele, Iterable):
flatten(ele, output_arr) #tail-recursion
else:
... |
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 fina... | def garage(initial, final):
initial = initial[::] # prevent changes in original 'initial'
seq = [] # list of each step in sequence
steps = 0
while initial != final:
zero = initial.index(0)
if zero != final.index(0): # if zero isn't where it should be,
... |
There are people sitting in a circular fashion, print every third member while removing them, the next counter starts immediately after the member is removed. Print till all the members are exhausted. For example: Input: consider 123456789 members sitting in a circular fashion, Output: 369485271 | def josephus(int_list, skip):
skip = skip - 1 # list starts with 0 index
idx = 0
len_list = (len(int_list))
while len_list > 0:
idx = (skip + idx) % len_list # hash index to every 3rd
yield int_list.pop(idx)
len_list -= 1
|
Sometimes you need to limit array result to use. Such as you only need the value over 10 or, you need value under than 100. By use this algorithms, you can limit your array to specific value If array, Min, Max value was given, it returns array that contains values of given array which was larger than Min, and lower tha... | # 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 subseq... | def longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
"""
if string is None:
return 0
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
... |
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 wi... | def max_ones_index(arr):
n = len(arr)
max_count = 0
max_index = 0
prev_zero = -1
prev_prev_zero = -1
for curr in range(n):
# If current element is 0,
# then calculate the difference
# between curr and prev_prev_zero
if arr[curr] == 0:
if curr - prev... |
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 int... | class Interval:
"""
A set of real numbers with methods to determine if other
numbers are included in the set.
Includes related methods to merge and print interval sets.
"""
def __init__(self, start=0, end=0):
self.start = start
self.end = end
def __repr__(self):
ret... |
Find missing ranges between low and high in the given array. Ex 3, 5 lo1 hi10 answer: 1, 2, 4, 4, 6, 10 | def missing_ranges(arr, lo, hi):
res = []
start = lo
for n in arr:
if n == start:
start += 1
elif n > start:
res.append((start, n-1))
start = n + 1
if start <= hi: # after done iterating thru array,
res.append((start, hi)) ... |
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. movezerosfalse, 1, 0, 1, 2, 0, 1, 3, a returns false, 1, 1, 2, 1, 3, a, 0, 0 The time complexity of the below algorithm is On. False 0 is True | # False == 0 is True
def move_zeros(array):
result = []
zeros = 0
for i in array:
if i == 0 and type(i) != bool: # not using `not i` to avoid `False`, `[]`, etc.
zeros += 1
else:
result.append(i)
result.extend([0] * zeros)
return result
... |
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, ... | def n_sum(n, nums, target, **kv):
"""
n: int
nums: list[object]
target: object
sum_closure: function, optional
Given two elements of nums, return sum of both.
compare_closure: function, optional
Given one object of nums and target, return -1, 1, or 0.
same_closure: function, ... |
Given a nonnegative number represented as an array of digits, adding one to each numeral. The digits are stored bigendian, such that the most significant digit is at the head of the list. :type digits: Listint :rtype: Listint | def plus_one_v1(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] = digits[-1] + 1
res = []
ten = 0
i = len(digits)-1
while i >= 0 or ten == 1:
summ = 0
if i >= 0:
summ += digits[i]
if ten:
summ += 1
res.appe... |
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... | def rotate_v1(array, k):
"""
Rotate the entire array 'k' times
T(n)- O(nk)
:type array: List[int]
:type k: int
:rtype: void Do not return anything, modify array in-place instead.
"""
array = array[:]
n = len(array)
for i in range(k): # unused variable is not a problem
... |
Given a sorted integer array without duplicates, return the summary of its ranges. For example, given 0, 1, 2, 4, 5, 7, return 0, 2, 4, 5, 7, 7. :type array: Listint :rtype: List | def summarize_ranges(array):
"""
:type array: List[int]
:rtype: List[]
"""
res = []
if len(array) == 1:
return [str(array[0])]
i = 0
while i < len(array):
num = array[i]
while i + 1 < len(array) and array[i + 1] - array[i] == 1:
i += 1
if array... |
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 a... | def three_sum(array):
"""
:param array: List[int]
:return: Set[ Tuple[int, int, int] ]
"""
res = set()
array.sort()
for i in range(len(array) - 2):
if i > 0 and array[i] == array[i - 1]:
continue
l, r = i + 1, len(array) - 1
while l < r:
s = ar... |
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,... | def top_1(arr):
values = {}
#reserve each value which first appears on keys
#reserve how many time each value appears by index number on values
result = []
f_val = 0
for i in arr:
if i in values:
values[i] += 1
else:
values[i] = 1
f_val = max(values.... |
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 algor... | def trimmean(arr, per):
ratio = per/200
# /100 for easy calculation by *, and /2 for easy adaption to best and worst parts.
cal_sum = 0
# sum value to be calculated to trimmean.
arr.sort()
neg_val = int(len(arr)*ratio)
arr = arr[neg_val:len(arr)-neg_val]
for i in arr:
cal_sum += ... |
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 :r... | def add_operators(num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
def dfs(res, path, num, target, pos, prev, multed):
if pos == len(num):
if target == prev:
res.append(path)
return
for i in range(pos, len(num)):
... |
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. Thi... | 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:
... |
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 d... | def combination_sum(candidates, target):
def dfs(nums, target, index, path, res):
if target < 0:
return # backtracking
if target == 0:
res.append(path)
return
for i in range(index, len(nums)):
dfs(nums, target-nums[i], i, path+[nums[i]], res)... |
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 outp... | # Iterative:
def get_factors(n):
todo, combis = [(n, 2, [])], []
while todo:
n, i, combi = todo.pop()
while i * i <= n:
if n % i == 0:
combis.append(combi + [i, n//i])
todo.append((n//i, i, combi+[i]))
i += 1
return combis
# Recursive... |
Given a matrix of words and a list of words to search, return a list of words that exists in the board This is Word Search II on LeetCode board 'o','a','a','n', 'e','t','a','e', 'i','h','k','r', 'i','f','l','v' words oath,pea,eat,rain backtrack tries to build each words from the board and return all words found par... | def find_words(board, words):
def backtrack(board, i, j, trie, pre, used, result):
'''
backtrack tries to build each words from
the board and return all words found
@param: board, the passed in board of characters
@param: i, the row index
@param: j, the column index... |
given input word, return the list of abbreviations. ex word 'word', 'wor1', 'wo1d', 'wo2', 'w1rd', 'w1r1', 'w2d', 'w3', '1ord', '1or1', '1o1d', '1o2', '2rd', '2r1', '3d', '4' skip the current word | def generate_abbreviations(word):
def backtrack(result, word, pos, count, cur):
if pos == len(word):
if count > 0:
cur += str(count)
result.append(cur)
return
if count > 0: # add the current word
backtrack(result, word, pos+1, 0, cur... |
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 = []
... |
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 ... |
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... | def palindromic_substrings(s):
if not s:
return [[]]
results = []
for i in range(len(s), 0, -1):
sub = s[:i]
if sub == sub[::-1]:
for rest in palindromic_substrings(s[i:]):
results.append([sub] + rest)
return results
"""
There's two loops.
The outer ... |
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. patter... | def pattern_match(pattern, string):
"""
:type pattern: str
:type string: str
:rtype: bool
"""
def backtrack(pattern, string, dic):
if len(pattern) == 0 and len(string) > 0:
return False
if len(pattern) == len(string) == 0:
return True
for end in... |
Given a collection of distinct numbers, return all possible permutations. For example, 1,2,3 have the following permutations: 1,2,3, 1,3,2, 2,1,3, 2,3,1, 3,1,2, 3,2,1 returns a list with the permuations. iterator: returns a perumation by each call. DFS Version | def permute(elements):
"""
returns a list with the permuations.
"""
if len(elements) <= 1:
return [elements]
else:
tmp = []
for perm in permute(elements[1:]):
for i in range(len(elements)):
tmp.append(perm[:i] + elements[0:1] + perm[i:])
... |
Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, 1,1,2 have the following unique permutations: 1,1,2, 1,2,1, 2,1,1 | def permute_unique(nums):
perms = [[]]
for n in nums:
new_perms = []
for l in perms:
for i in range(len(l)+1):
new_perms.append(l[:i]+[n]+l[i:])
if i < len(l) and l[i] == n:
break # handles duplication
perms = new_perms
... |
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.app... | def subsets(nums):
"""
O(2**n)
"""
def backtrack(res, nums, stack, pos):
if pos == len(nums):
res.append(list(stack))
else:
# take nums[pos]
stack.append(nums[pos])
backtrack(res, nums, stack, pos+1)
stack.pop()
# do... |
Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums 1,2,2, a solution is: 2, 1, 1,2,2, 2,2, 1,2, take don't take | def subsets_unique(nums):
def backtrack(res, nums, stack, pos):
if pos == len(nums):
res.add(tuple(stack))
else:
# take
stack.append(nums[pos])
backtrack(res, nums, stack, pos+1)
stack.pop()
# don't take
backtrack(... |
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. Exa... | 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:
... |
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: ... | from collections import deque
'''
BFS time complexity : O(|E| + |V|)
BFS space complexity : O(|E| + |V|)
do BFS from (0,0) of the grid and get the minimum number of steps needed to get to the lower right column
only step on the columns whose value is 1
if there is no path, it returns -1
Ex 1)
If grid is
[[1,0,1,1,... |
do BFS from each building, and decrement all empty place for every building visit when gridij bnums, it means that gridij are already visited from all bnums and use dist to record distances from bnums only the position be visited by count times will append to queue | import collections
"""
do BFS from each building, and decrement all empty place for every building visit
when grid[i][j] == -b_nums, it means that grid[i][j] are already visited from all b_nums
and use dist to record distances from b_nums
"""
def shortest_distance(grid):
if not grid or not grid[0]:
return... |
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... | def ladder_length(begin_word, end_word, word_list):
"""
Bidirectional BFS!!!
:type begin_word: str
:type end_word: str
:type word_list: Set[str]
:rtype: int
"""
if len(begin_word) != len(end_word):
return -1 # not possible
if begin_word == end_word:
return 0
#... |
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 ... | # 原方法为 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 = No... |
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 n... | """
This function shifts 1 over by i bits, creating a value being like 0001000. By
performing an AND with num, we clear all bits other than the bit at bit i.
Finally we compare that to 0
"""
def get_bit(num, i):
return (num & (1 << i)) != 0
"""
This function shifts 1 over by i bits, creating a value being like 000... |
list.insert0, ... is inefficient | from collections import deque
def int_to_bytes_big_endian(num):
bytestr = deque()
while num > 0:
# list.insert(0, ...) is inefficient
bytestr.appendleft(num & 0xff)
num >>= 8
return bytes(bytestr)
def int_to_bytes_little_endian(num):
bytestr = []
while num > 0:
by... |
Write a function to determine the minimal number of bits you would need to flip to convert integer A to integer B. For example: Input: 29 or: 11101, 15 or: 01111 Output: 2 count number of ones in diff | def count_flips_to_convert(a, b):
diff = a ^ b
# count number of ones in diff
count = 0
while diff:
diff &= (diff - 1)
count += 1
return count
|
Write a function that takes an unsigned integer and returns the number of '1' bits it has also known as the Hamming weight. For example, the 32bit integer '11' has binary representation 00000000000000000000000000001011, so the function should return 3. Tn Ok : k is the number of 1s present in binary representation. N... | def count_ones_recur(n):
"""Using Brian Kernighan's Algorithm. (Recursive Approach)"""
if not n:
return 0
return 1 + count_ones_recur(n & (n-1))
def count_ones_iter(n):
"""Using Brian Kernighan's Algorithm. (Iterative Approach)"""
count = 0
while n:
n &= (n-1)
count +... |
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 charact... | """
We use the characteristic equation of XOR.
A xor B xor C = A xor C xor B
If A == C, then A xor C = 0
and then, B xor 0 = B
"""
def find_difference(s, t):
ret = 0
for ch in s + t:
# ord(ch) return an integer representing the Unicode code point of that character
ret = ret ^ ord(ch)
# chr(... |
Returns the missing number from a sequence of unique integers in range 0..n in On time and space. The difference between consecutive integers cannot be more than 1. If the sequence is already complete, the next integer in the sequence will be returned. For example: Input: nums 4, 1, 3, 0, 6, 5, 2 Output: 7 | def find_missing_number(nums):
missing = 0
for i, num in enumerate(nums):
missing ^= num
missing ^= i + 1
return missing
def find_missing_number2(nums):
num_sum = sum(nums)
n = len(nums)
total_sum = n*(n+1) // 2
missing = total_sum - num_sum
return missing
|
You have an integer and you can flip exactly one bit from a 0 to 1. Write code to find the length of the longest sequence of 1s you could create. For example: Input: 1775 or: 11011101111 Output: 8 | def flip_bit_longest_seq(num):
curr_len = 0
prev_len = 0
max_len = 0
while num:
if num & 1 == 1: # last digit is 1
curr_len += 1
elif num & 1 == 0: # last digit is 0
if num & 2 == 0: # second last digit is 0
prev_len = 0
else:
... |
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 b... | # Time Complexity - O(number of bits in n)
def has_alternative_bit(n):
first_bit = 0
second_bit = 0
while n:
first_bit = n & 1
if n >> 1:
second_bit = (n >> 1) & 1
if not first_bit ^ second_bit:
return False
else:
return True
... |
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 p... | """
Insert exact one bit at specific position
Algorithm:
1. Create a mask having bit from i to the most significant bit, and append the new bit at 0 position
2. Keep the bit from 0 position to i position ( like 000...001111)
3. Merge mask and num
"""
def insert_one_bit(num, bit, i):
# Create mask
mask = num >>... |
given an integer, write a function to determine if it is a power of two :type n: int :rtype: bool | def is_power_of_two(n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and not n & (n-1)
|
Removebitnum, i: remove a bit at specific position. For example: Input: num 10101 21 removebitnum, 2: output 1001 9 removebitnum, 4: output 101 5 removebitnum, 0: output 1010 10 | def remove_bit(num, i):
mask = num >> (i + 1)
mask = mask << i
right = ((1 << i) - 1) & num
return mask | right
|
Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 represented in binary as 00000010100101000001111010011100, return 964176192 represented in binary as 00111001011110000010100101000000. | def reverse_bits(n):
m = 0
i = 0
while i < 32:
m = (m << 1) + (n & 1)
n >>= 1
i += 1
return m
|
Given an array of integers, every element appears twice except for one. Find that single one. NOTE: This also works for finding a number occurring odd number of times, where all the other numbers appear even number of times. Note: Your algorithm should have a linear runtime complexity. Could you implement it without us... | def single_number(nums):
"""
Returns single number, if found.
Else if all numbers appear twice, returns 0.
:type nums: List[int]
:rtype: int
"""
i = 0
for num in nums:
i ^= num
return i
|
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Solution: 32 bits for each integer. Consider 1 bit in it, the sum of each integ... | # 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 no... | def single_number3(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# isolate a^b from pairs using XOR
ab = 0
for n in nums:
ab ^= n
# isolate right most bit from a^b
right_most = ab & (-ab)
# isolate a and b from a^b
a, b = 0, 0
for n in nums:
if ... |
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 solut... | def subsets(nums):
"""
:param nums: List[int]
:return: Set[tuple]
"""
n = len(nums)
total = 1 << n
res = set()
for i in range(total):
subset = tuple(num for j, num in enumerate(nums) if i & 1 << j)
res.add(subset)
return res
"""
this explanation is from leet_nik @ l... |
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 wi... | """
We can approach this as operating on the odds bit first, and then the even bits.
We can mask all odd bits with 10101010 in binary ('AA') then shift them right by 1
Similarly, we mask all even bit with 01010101 in binary ('55') then shift them left
by 1. Finally, we merge these two values by OR operation.
"""
def sw... |
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 develo... | from math import log
log2 = lambda x: log(x, 2)
# Calculates the binary number
def binary(x, l=1):
fmt = '{0:0%db}' % l
return fmt.format(x)
# Calculates the unary number
def unary(x):
return (x-1)*'1'+'0'
def elias_generic(lencoding, x):
"""
The compressed data is calculated in two parts.
The first part is t... |
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:... | 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... |
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 Encod... | def encode_rle(input):
"""
Gets a stream of data and compresses it
under a Run-Length Encoding.
:param input: The data to be encoded.
:return: The encoded string.
"""
if not input: return ''
encoded_str = ''
prev_ch = ''
count = 1
for ch in input:
# Check If the su... |
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: 3... | def get_factors(n):
"""[summary]
Arguments:
n {[int]} -- [to analysed number]
Returns:
[list of lists] -- [all factors of the number n]
"""
def factor(n, i, combi, res):
"""[summary]
helper function
Arguments:
n {[int]} -- [number]
... |
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... | 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
i... |
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... | 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 > ... |
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 wit... | # 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 cel... |
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 ... | 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.co... |
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... | def walls_and_gates(rooms):
for i in range(len(rooms)):
for j in range(len(rooms[0])):
if rooms[i][j] == 0:
dfs(rooms, i, j, 0)
def dfs(rooms, i, j, depth):
if (i < 0 or i >= len(rooms)) or (j < 0 or j >= len(rooms[0])):
return # out of bounds
if rooms[i][j] < ... |
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... | def get_histogram(input_list: list) -> dict:
"""
Get histogram representation
:param input_list: list with different and unordered values
:return histogram: dict with histogram of input_list
"""
# Create dict to store histogram
histogram = {}
# For each list value, add one to the respect... |
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 ... | # O(n^2) time
def max_profit_naive(prices):
"""
:type prices: List[int]
:rtype: int
"""
max_so_far = 0
for i in range(0, len(prices) - 1):
for j in range(i + 1, len(prices)):
max_so_far = max(max_so_far, prices[j] - prices[i])
return max_so_far
# O(n) time
def max_profi... |
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 spac... | # O(n) space
def climb_stairs(steps):
"""
:type steps: int
:rtype: int
"""
arr = [1, 1]
for _ in range(1, steps):
arr.append(arr[-1] + arr[-2])
return arr[-1]
# the above function can be optimized as:
# O(1) space
def climb_stairs_optimized(steps):
"""
:type steps: int
... |
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, ... | def count(coins, value):
""" Find number of combination of `coins` that adds upp to `value`
Keyword arguments:
coins -- int[]
value -- int
"""
# initialize dp array and set base case as 1
dp_array = [1] + [0] * value
# fill dp in a bottom up manner
for coin in coins:
for i ... |
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 differ... | DP = None
def helper_topdown(nums, target):
"""Generates DP and finds result.
Keyword arguments:
nums -- positive integer array without duplicates
target -- integer describing what a valid combination should add to
"""
if DP[target] != -1:
return DP[target]
res = 0
for num in n... |
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 o... | def edit_distance(word_a, word_b):
"""Finds edit distance between word_a and word_b
Kwyword arguments:
word_a -- string
word_b -- string
"""
length_a, length_b = len(word_a) + 1, len(word_b) + 1
edit = [[0 for _ in range(length_b)] for _ in range(length_a)]
for i in range(1, length_a... |
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 w... | # A Dynamic Programming based Python Program for the Egg Dropping Puzzle
INT_MAX = 32767
def egg_drop(n, k):
"""
Keyword arguments:
n -- number of floors
k -- number of eggs
"""
# A 2D table where entery eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j floor... |
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, ... | def fib_recursive(n):
"""[summary]
Computes the n-th fibonacci number recursive.
Problem: This implementation is very slow.
approximate O(2^n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a posit... |
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: pri... | def hosoya(height, width):
""" Calculates the hosoya triangle
height -- height of the triangle
"""
if (width == 0) and (height in (0,1)):
return 1
if (width == 1) and (height in (1,2)):
return 1
if height > width:
return hosoya(height - 1, width) + hosoya(height - 2, wid... |
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... | 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... | def int_divide(decompose):
"""Find number of decompositions from `decompose`
decompose -- integer
"""
arr = [[0 for i in range(decompose + 1)] for j in range(decompose + 1)]
arr[1][1] = 1
for i in range(1, decompose + 1):
for j in range(1, decompose + 1):
if i < j:
... |
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 ... | class Job:
"""
Class to represent a job
"""
def __init__(self, start, finish, profit):
self.start = start
self.finish = finish
self.profit = profit
def binary_search(job, start_index):
"""
A Binary Search based function to find the latest job
(before current job) th... |
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... | def find_k_factor(length, k_factor):
"""Find the number of strings of length `length` with K factor = `k_factor`.
Keyword arguments:
length -- integer
k_factor -- integer
"""
mat=[[[0 for i in range(4)]for j in range((length-1)//3+2)]for k in range(length+1)]
if 3*k_factor+1>length:
... |
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... | 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], ... |
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 Sub... | def longest_common_subsequence(s_1, s_2):
"""
:param s1: string
:param s2: string
:return: int
"""
m = len(s_1)
n = len(s_2)
mat = [[0] * (n + 1) for i in range(m + 1)]
# mat[i][j] : contains length of LCS of s_1[0..i-1] and s_2[0..j-1]
for i in range(m + 1):
for j in r... |
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... | def longest_increasing_subsequence(sequence):
"""
Dynamic Programming Algorithm for
counting the length of longest increasing subsequence
type sequence: list[int]
rtype: int
"""
length = len(sequence)
counts = [1 for _ in range(length)]
for i in range(1, length):
for j in ran... |
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... | INF = float("inf")
def matrix_chain_order(array):
"""Finds optimal order to multiply matrices
array -- int[]
"""
n = len(array)
matrix = [[0 for x in range(n)] for x in range(n)]
sol = [[0 for x in range(n)] for x in range(n)]
for chain_length in range(2, n):
for a in range(1, n-c... |
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: subarraywithma... | from functools import reduce
def max_product(nums):
"""
:type nums: List[int]
:rtype: int
"""
lmin = lmax = gmax = nums[0]
for num in nums:
t_1 = num * lmax
t_2 = num * lmin
lmax = max(max(t_1, t_2), num)
lmin = min(min(t_1, t_2), num)
gmax = max(gmax, l... |
author goswamirahul To find minimum cost path from station 0 to station N1, where cost of moving from ith station to jth station is given as: Matrix of size N x N where Matrixij denotes the cost of moving from station i station j for i j NOTE that values where Matrixij and i j does not mean anything, and hence rep... | INF = float("inf")
def min_cost(cost):
"""Find minimum cost.
Keyword arguments:
cost -- matrix containing costs
"""
length = len(cost)
# dist[i] stores minimum cost from 0 --> i.
dist = [INF] * length
dist[0] = 0 # cost from 0 --> 0 is zero.
for i in range(length):
for... |
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 1... | def num_decodings(enc_mes):
"""
:type s: str
:rtype: int
"""
if not enc_mes or enc_mes[0] == "0":
return 0
last_char, last_two_chars = 1, 1
for i in range(1, len(enc_mes)):
last = last_char if enc_mes[i] != "0" else 0
last_two = last_two_chars if int(enc_mes[i-1:i+1])... |
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... | from math import sqrt
def planting_trees(trees, length, width):
"""
Returns the minimum distance that trees have to be moved before they
are all in a valid state.
Parameters:
tree (list<int>): A sorted list of integers with all trees'
position along the ro... |
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... | def is_match(str_a, str_b):
"""Finds if `str_a` matches `str_b`
Keyword arguments:
str_a -- string
str_b -- string
"""
len_a, len_b = len(str_a) + 1, len(str_b) + 1
matches = [[False] * len_b for _ in range(len_a)]
# Match empty string with empty pattern
matches[0][0] = True
... |
A Dynamic Programming solution for Rod cutting problem Returns the best obtainable price for a rod of length n and price as prices of different pieces Build the table val in bottom up manner and return the last entry from the table Driver program to test above functions This code is contributed by Bhavya Jain | INT_MIN = -32767
def cut_rod(price):
"""
Returns the best obtainable price for a rod of length n and
price[] as prices of different pieces
"""
n = len(price)
val = [0]*(n+1)
# Build the table val[] in bottom up manner and return
# the last entry from the table
for i in range(1, n+1... |
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 bec... | # TC: O(N^2) SC: O(N)
def word_break(word, word_dict):
"""
:type word: str
:type word_dict: Set[str]
:rtype: bool
"""
dp_array = [False] * (len(word)+1)
dp_array[0] = True
for i in range(1, len(word)+1):
for j in range(0, i):
if dp_array[j] and word[j:i] in word_dict... |
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... | import copy
def all_pairs_shortest_path(adjacency_matrix):
"""
Given a matrix of the edge weights between respective nodes, returns a
matrix containing the shortest distance distance between the two nodes.
"""
new_array = copy.deepcopy(adjacency_matrix)
size = len(new_array)
for k in rang... |
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 sol... | def bellman_ford(graph, source):
"""
This Bellman-Ford Code is for determination whether we can get
shortest path from given graph or not for single-source shortest-paths problem.
In other words, if given graph has any negative-weight cycle that is reachable
from the source, then it will give answer... |
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 s... | def check_bipartite(adj_list):
"""
Determine if the given graph is bipartite.
Time complexity is O(|E|)
Space complexity is O(|V|)
"""
vertices = len(adj_list)
# Divide vertexes in the graph into set_type 0 and 1
# Initialize all set_types as -1
set_type = [-1 for v in range(verti... |
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 usi... | from collections import defaultdict
class Graph:
"""
A directed graph where edges are one-way (a two-way edge can be represented by using two edges).
"""
def __init__(self,vertex_count):
"""
Create a new graph with vertex_count vertices.
"""
self.vertex_count = vertex_... |
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 collect... | r"""
Clone an undirected graph. Each node in the graph contains a label and a list
of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and
each neighbor of the node.
As an example, consider the serialized graph ... |
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 pe... | #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
| |
| ... |
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 current... | from enum import Enum
class TraversalState(Enum):
"""
For a given node:
- WHITE: has not been visited yet
- GRAY: is currently being investigated for a cycle
- BLACK: is not part of a cycle
"""
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph, traversal_states, verte... |
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 valu... | class Dijkstra():
"""
A fully connected directed graph with edge weights
"""
def __init__(self, vertex_count):
self.vertex_count = vertex_count
self.graph = [[0 for _ in range(vertex_count)] for _ in range(vertex_count)]
def min_distance(self, dist, min_dist_set):
"""
... |
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 lis... | def find_all_cliques(edges):
"""
takes dict of sets
each key is a vertex
value is set of all edges connected to vertex
returns list of lists (each sub list is a maximal clique)
implementation of the basic algorithm described in:
Bron, Coen; Kerbosch, Joep (1973), "Algorithm 457: finding all ... |
Functions for finding paths in graphs. pylint: disabledangerousdefaultvalue Find a path between two nodes using recursion and backtracking. pylint: disabledangerousdefaultvalue Find all paths between two nodes using recursion and backtracking find the shortest path between two nodes | # pylint: disable=dangerous-default-value
def find_path(graph, start, end, path=[]):
"""
Find a path between two nodes using recursion and backtracking.
"""
path = path + [start]
if start == end:
return path
if not start in graph:
return None
for node in graph[start]:
... |
YAML Metadata Warning:The task_categories "text2text-generation" is not in the official list: text-classification, token-classification, table-question-answering, question-answering, zero-shot-classification, translation, summarization, feature-extraction, text-generation, fill-mask, sentence-similarity, text-to-speech, text-to-audio, automatic-speech-recognition, audio-to-audio, audio-classification, audio-text-to-text, voice-activity-detection, depth-estimation, image-classification, object-detection, image-segmentation, text-to-image, image-to-text, image-to-image, image-to-video, unconditional-image-generation, video-classification, reinforcement-learning, robotics, tabular-classification, tabular-regression, tabular-to-text, table-to-text, multiple-choice, text-ranking, text-retrieval, time-series-forecasting, text-to-video, image-text-to-text, image-text-to-image, image-text-to-video, visual-question-answering, document-question-answering, zero-shot-image-classification, graph-ml, mask-generation, zero-shot-object-detection, text-to-3d, image-to-3d, image-feature-extraction, video-text-to-text, keypoint-detection, visual-document-retrieval, any-to-any, video-to-video, other
- Downloads last month
- 7