Description
stringlengths
18
161k
Code
stringlengths
15
300k
implements a markov chain chains are described using a dictionary mychain a a 0 6 e 0 4 e a 0 7 e 0 3 choose the next state randomly given a markovchain randomly chooses the next state given the current state yield a sequence of states given a markov chain and the initial state choose the next state randomly given a ma...
import random def __choose_state(state_map): choice = random.random() probability_reached = 0 for state, probability in state_map.items(): probability_reached += probability if probability_reached > choice: return state return None def next_state(chain, current_state):...
given the capacity source and sink of a graph computes the maximum flow from source to sink input capacity source sink output maximum flow from source to sink capacity is a twodimensional array that is vv capacityij implies the capacity of the edge from i to j if there is no edge from i to j capacityij should be zero p...
from queue import Queue def dfs(capacity, flow, visit, vertices, idx, sink, current_flow = 1 << 63): if idx == sink: return current_flow visit[idx] = True for nxt in range(vertices): if not visit[nxt] and flow[idx][nxt] < capacity[idx][nxt]: available_flow = min(curr...
given a nn adjacency array it will give you a maximum flow this version use bfs to search path assume the first is the source and the last is the sink time complexity oef example graph 0 16 13 0 0 0 0 0 10 12 0 0 0 4 0 0 14 0 0 0 9 0 0 20 0 0 0 7 0 4 0 0 0 0 0 0 answer should be 23 get the maximum flow through a graph ...
import copy import queue import math def maximum_flow_bfs(adjacency_matrix): new_array = copy.deepcopy(adjacency_matrix) total = 0 while True: min_flow = math.inf visited = [0]*len(new_array) path = [0]*len(new_array) bfs = que...
given a nn adjacency array it will give you a maximum flow this version use dfs to search path assume the first is the source and the last is the sink time complexity oef example graph 0 16 13 0 0 0 0 0 10 12 0 0 0 4 0 0 14 0 0 0 9 0 0 20 0 0 0 7 0 4 0 0 0 0 0 0 answer should be 23 get the maximum flow through a graph ...
import copy import math def maximum_flow_dfs(adjacency_matrix): new_array = copy.deepcopy(adjacency_matrix) total = 0 while True: min = math.inf visited = [0]*len(new_array) path = [0]*len(new_array) stack = [] ...
minimum spanning tree mst is going to use an undirected graph pylint disabletoofewpublicmethods an edge of an undirected graph the disjoint set is represented with an list n of integers where ni is the parent of the node at position i if ni i i it s a root or a head of a set args n int number of vertices in the graph a...
import sys class Edge: def __init__(self, source, target, weight): self.source = source self.target = target self.weight = weight class DisjointSet: def __init__(self, size): self.parent = [None] * size self.size = [1] * size for i in r...
determine if there is a path between nodes in a graph a directed graph add a new directed edge to the graph determine if there is a path from source to target using a depth first search determine if there is a path from source to target using a depth first search param visited should be an array of booleans determining...
from collections import defaultdict class Graph: def __init__(self,vertex_count): self.vertex_count = vertex_count self.graph = defaultdict(list) self.has_path = False def add_edge(self,source,target): self.graph[source].append(target) def dfs(self,source,t...
this prim s algorithm code is for finding weight of minimum spanning tree of a connected graph for argument graph it should be a dictionary type such as graph a 3 b 8 c b 3 a 5 d c 8 a 2 d 4 e d 5 b 2 c 6 e e 4 c 6 d where a b c d e are nodes these can be 1 2 3 4 5 as well prim s algorithm to find weight of minimum spa...
import heapq def prims_minimum_spanning(graph_used): vis=[] heap=[[0,1]] prim = set() mincost=0 while len(heap) > 0: cost, node = heapq.heappop(heap) if node in vis: continue mincost += cost prim.add(node) vis.append(node) for di...
given a formula in conjunctive normal form 2cnf finds a way to assign truefalse values to all variables to satisfy all clauses or reports there is no solution https en wikipedia orgwiki2satisfiability format each clause is a pair of literals each literal in the form name isneg where name is an arbitrary identifier and ...
def dfs_transposed(vertex, graph, order, visited): visited[vertex] = True for adjacent in graph[vertex]: if not visited[adjacent]: dfs_transposed(adjacent, graph, order, visited) order.append(vertex) def dfs(vertex, current_comp, vertex_scc, graph, visited): visited[ver...
implements tarjan s algorithm for finding strongly connected components in a graph https en wikipedia orgwikitarjan27sstronglyconnectedcomponentsalgorithm pylint disabletoofewpublicmethods a directed graph used for finding strongly connected components runs tarjan set all node index to none given a vertex adds all succ...
from algorithms.graph.graph import DirectedGraph class Tarjan: def __init__(self, dict_graph): self.graph = DirectedGraph(dict_graph) self.index = 0 self.stack = [] for vertex in self.graph.nodes: vertex.index = None self.sccs = [] ...
finds the transitive closure of a graph reference https en wikipedia orgwikitransitiveclosureingraphtheory this class represents a directed graph using adjacency lists no of vertices default dictionary to store graph to store transitive closure adds a directed edge to the graph a recursive dfs traversal function that f...
class Graph: def __init__(self, vertices): self.vertex_count = vertices self.graph = {} self.closure = [[0 for j in range(vertices)] for i in range(vertices)] def add_edge(self, source, target): if source in self.graph: self...
different ways to traverse a graph dfs and bfs are the ultimately same except that they are visiting nodes in different order to simulate this ordering we would use stack for dfs and queue for bfs traversal by depth first search traversal by breadth first search traversal by recursive depth first search dfs and bfs are...
def dfs_traverse(graph, start): visited, stack = set(), [start] while stack: node = stack.pop() if node not in visited: visited.add(node) for next_node in graph[node]: if next_node not in visited: stack.append(next_node) return...
algorithm used kadane s algorithm kadane s algorithm is used for finding the maximum sum of contiguous subsequence in a sequence it is considered a greedydp algorithm but i think they more greedy than dp here are some of the examples to understand the use case more clearly example1 2 3 8 1 4 result 3 8 1 4 14 example2 ...
def max_contiguous_subsequence_sum(arr) -> int: arr_size = len(arr) if arr_size == 0: return 0 max_till_now = arr[0] curr_sub_sum = 0 for i in range(0, arr_size): if curr_sub_sum + arr[i] < arr[i]: curr_sub_sum = arr[i] else: curr_sub_sum += arr[i] ...
given a list of points find the k closest to the origin idea maintain a max heap of k elements we can iterate through all points if a point p has a smaller distance to the origin than the top element of a heap we add point p to the heap and remove the top element after iterating through all points our heap contains the...
from heapq import heapify, heappushpop def k_closest(points, k, origin=(0, 0)): heap = [(-distance(p, origin), p) for p in points[:k]] heapify(heap) for point in points[k:]: dist = distance(point, origin) heappushpop(heap, (-dist, point)) return [point...
merge k sorted linked lists and return it as one sorted list analyze and describe its complexity definition for singlylinked list listnode class def initself val self val val self next none def mergeklistslists merge list dummy listnodenone curr dummy q priorityqueue for node in lists if node q putnode val node while n...
from heapq import heappop, heapreplace, heapify from queue import PriorityQueue class ListNode(object): def __init__(self, val): self.val = val self.next = None def merge_k_lists(lists): dummy = node = ListNode(0) list_h = [(n.val, n) for n in lists if n] heapify(list_h) ...
coding utf8 a city s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance now suppose you are given the locations and height of all the buildings as shown on a cityscape photo figure a write a program to output the skyline formed by these buildings collecti...
import heapq def get_skyline(lrh): skyline, live = [], [] i, n = 0, len(lrh) while i < n or live: if not live or i < n and lrh[i][0] <= -live[0][1]: x = lrh[i][0] while i < n and lrh[i][0] == x: heapq.heappush(live, (-lrh[i][2], -lrh[i][1])) ...
given an array nums there is a sliding window of size k which is moving from the very left of the array to the very right you can only see the k numbers in the window each time the sliding window moves right by one position for example given nums 1 3 1 3 5 3 6 7 and k 3 window position max 1 3 1 3 5 3 6 7 3 1 3 1 3 5 3...
import collections def max_sliding_window(nums, k): if not nums: return nums queue = collections.deque() res = [] for num in nums: if len(queue) < k: queue.append(num) else: res.append(max(queue)) queue.popleft() queue.append...
you are given two nonempty linked lists representing two nonnegative integers the digits are stored in reverse order and each of their nodes contain a single digit add the two numbers and return it as a linked list you may assume the two numbers do not contain any leading zero except the number 0 itself input 2 4 3 5 6...
import unittest class Node: def __init__(self, x): self.val = x self.next = None def add_two_numbers(left: Node, right: Node) -> Node: head = Node(0) current = head sum = 0 while left or right: print("adding: ", left.val, right.val) sum //= 10 if left: ...
a linked list is given such that each node contains an additional random pointer which could point to any node in the list or null return a deep copy of the list type head randomlistnode rtype randomlistnode on type head randomlistnode rtype randomlistnode type head randomlistnode rtype randomlistnode o n type head ran...
from collections import defaultdict class RandomListNode(object): def __init__(self, label): self.label = label self.next = None self.random = None def copy_random_pointer_v1(head): dic = dict() m = n = head while m: dic[m] = RandomListNode(m.label) m = m...
write a function to delete a node except the tail in a singly linked list given only access to that node supposed the linked list is 1 2 3 4 and you are given the third node with value 3 the linked list should become 1 2 4 after calling your function make linkedlist 1 2 3 4 node3 3 after deletenode 1 2 4 make linkedlis...
import unittest class Node: def __init__(self, x): self.val = x self.next = None def delete_node(node): if node is None or node.next is None: raise ValueError node.val = node.next.val node.next = node.next.next class TestSuite(unittest.TestCase): def test_delete_node(s...
given a linked list find the first node of a cycle in it 1 2 3 4 5 1 1 a b c d e c c note the solution is a direct implementation floyd s cyclefinding algorithm floyd s tortoise and hare type head node rtype node create linked list a b c d e c type head node rtype node create linked list a b c d e c
import unittest class Node: def __init__(self, x): self.val = x self.next = None def first_cyclic_node(head): runner = walker = head while runner and runner.next: runner = runner.next.next walker = walker.next if runner is walker: break if r...
this function takes two lists and returns the node they have in common if any in this example 1 3 5 7 9 11 2 4 6 we would return 7 note that the node itself is the unique identifier not the value of the node we hit the end of one of the lists set a flag for this force the longer of the two lists to catch up the nodes m...
import unittest class Node(object): def __init__(self, val=None): self.val = val self.next = None def intersection(h1, h2): count = 0 flag = None h1_orig = h1 h2_orig = h2 while h1 or h2: count += 1 if not flag and (h1.next is None or h2.next is None): ...
given a linked list determine if it has a cycle in it follow up can you solve it without using extra space type head node rtype bool type head node rtype bool
class Node: def __init__(self, x): self.val = x self.next = None def is_cyclic(head): if not head: return False runner = head walker = head while runner.next and runner.next.next: runner = runner.next.next walker = walker.next if runner == walke...
split the list to two parts reverse the second part compare two parts second part has the same or one less node 1 get the midpoint slow 2 push the second half into the stack 3 comparison this function builds up a dictionary where the keys are the values of the list and the values are the positions at which these values...
def is_palindrome(head): if not head: return True fast, slow = head.next, head while fast and fast.next: fast = fast.next.next slow = slow.next second = slow.next slow.next = None node = None while second: nxt = second.next second.next = no...
given a linked list issort function returns true if the list is in sorted increasing order and return false otherwise an empty list is considered to be sorted for example null list is sorted 1 2 3 4 list is sorted 1 2 1 3 list is not sorted
def is_sorted(head): if not head: return True current = head while current.next: if current.val > current.next.val: return False current = current.next return True
this is a suboptimal hacky method using eval which is not safe for user input we guard against danger by ensuring k in an int this is a brute force method where we keep a dict the size of the list then we check it for the value we need if the key is not in the dict our and statement will short circuit and return false ...
class Node(): def __init__(self, val=None): self.val = val self.next = None def kth_to_last_eval(head, k): if not isinstance(k, int) or not head.val: return False nexts = '.'.join(['next' for n in range(1, k+1)]) seeker = str('.'.join(['head', nexts])) while head: ...
pros linked lists have constanttime insertions and deletions in any position in comparison arrays require on time to do the same thing linked lists can continue to expand without having to specify their size ahead of time remember our lectures on array sizing from the array sequence section of the course cons to access...
class DoublyLinkedListNode(object): def __init__(self, value): self.value = value self.next = None self.prev = None class SinglyLinkedListNode(object): def __init__(self, value): self.value = value self.next = None
merge two sorted linked lists and return it as a new list the new list should be made by splicing together the nodes of the first two lists for example input 124 134 output 112344 recursively recursively
class Node: def __init__(self, x): self.val = x self.next = None def merge_two_list(l1, l2): ret = cur = Node(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cu...
write code to partition a linked list around a value x such that all nodes less than x come before all nodes greater than or equal to x if x is contained within the list the values of x only need to be after the elements less than x the partition element x can appear anywhere in the right partition it does not need to ...
class Node(): def __init__(self, val=None): self.val = int(val) self.next = None def print_linked_list(head): string = "" while head.next: string += str(head.val) + " -> " head = head.next string += str(head.val) print(string) def partition(head, x): left = No...
time complexity on space complexity on time complexity on2 space complexity o1 a a b c d c f g time complexity o n space complexity o n time complexity o n 2 space complexity o 1 a a b c d c f g
class Node(): def __init__(self, val = None): self.val = val self.next = None def remove_dups(head): hashset = set() prev = Node() while head: if head.val in hashset: prev.next = head.next else: hashset.add(head.val) prev = head ...
given a linked list removerange function accepts a starting and ending index as parameters and removes the elements at those indexes inclusive from the list for example list 8 13 17 4 9 12 98 41 7 23 0 92 removerangelist 3 8 list becomes 8 13 17 23 0 92 legal range of the list 0 start index end index size of list case ...
def remove_range(head, start, end): assert(start <= end) if start == 0: for i in range(0, end+1): if head != None: head = head.next else: current = head for i in range(0,start-1): current = current.next for i in r...
reverse a singly linked list for example 1 2 3 4 after reverse 4 3 2 1 iterative solution tn on type head listnode rtype listnode recursive solution tn on type head listnode rtype listnode iterative solution t n o n type head listnode rtype listnode recursive solution t n o n type head listnode rtype listnode
def reverse_list(head): if not head or not head.next: return head prev = None while head: current = head head = head.next current.next = prev prev = current return prev def reverse_list_recursive(head): if head is None or head.next is None: ...
given a list rotate the list to the right by k places where k is nonnegative for example given 12345null and k 2 return 45123null definition for singlylinked list class listnodeobject def initself x self val x self next none type head listnode type k int rtype listnode count length of the list make it circular rotate u...
def rotate_right(head, k): if not head or not head.next: return head current = head length = 1 while current.next: current = current.next length += 1 current.next = head k = k % length for i in range(length-k): current = current.next he...
given a linked list swap every two adjacent nodes and return its head for example given 1234 you should return the list as 2143 your algorithm should use only constant space you may not modify the values in the list only nodes itself can be changed
class Node(object): def __init__(self, x): self.val = x self.next = None def swap_pairs(head): if not head: return head start = Node(0) start.next = head current = start while current.next and current.next.next: first = current.next second = current.next....
hashmap data type hashmap create a new empty map it returns an empty map collection putkey val add a new keyvalue pair to the map if the key is already in the map then replace the old value with the new value getkey given a key return the value stored in the map or none otherwise delkey or del mapkey delete the keyvalu...
class HashTable(object): _empty = object() _deleted = object() def __init__(self, size=11): self.size = size self._len = 0 self._keys = [self._empty] * size self._values = [self._empty] * size def put(self, key, value): initial_hash = hash_ = self.hash...
given two strings s and t write a function to determine if t is an anagram of s example 1 input s anagram t nagaram output true example 2 input s rat t car output false note you may assume the string contains only lowercase alphabets reference https leetcode comproblemsvalidanagramdescription type s str type t str rtyp...
def is_anagram(s, t): maps = {} mapt = {} for i in s: maps[i] = maps.get(i, 0) + 1 for i in t: mapt[i] = mapt.get(i, 0) + 1 return maps == mapt
given two strings s and t determine if they are isomorphic two strings are isomorphic if the characters in s can be replaced to get t all occurrences of a character must be replaced with another character while preserving the order of characters no two characters may map to the same character but a character may map to...
def is_isomorphic(s, t): if len(s) != len(t): return False dict = {} set_value = set() for i in range(len(s)): if s[i] not in dict: if t[i] in set_value: return False dict[s[i]] = t[i] set_value.add(t[i]) else: ...
given string a and b with b containing all distinct characters find the longest common sub sequence s length expected complexity on logn assuming s2 has all unique chars assuming s2 has all unique chars
def max_common_sub_string(s1, s2): s2dic = {s2[i]: i for i in range(len(s2))} maxr = 0 subs = '' i = 0 while i < len(s1): if s1[i] in s2dic: j = s2dic[s1[i]] k = i while j < len(s2) and k < len(s1) and s1[k] == s2[j]: k += 1 ...
from icecream import ic ics logestsubstr 申请长度为n的列表 并初始化 同上 当 j 时 第 i 个子串为回文子串 判断长度 当j i 1时 判断s i 是否等于s j 并判断当j 1时 第i 1个子串是否为回文子串 当 j 时 第 i 个子串为回文子串 覆盖旧的列表 新的列表清空 from icecream import ic ic s logestsubstr logestsubstr
def longest_palindromic_subsequence(s): k = len(s) olist = [0] * k nList = [0] * k logestSubStr = "" logestLen = 0 for j in range(0, k): for i in range(0, j + 1): if j - i <= 1: if s[i] == s[j]: nList[i] = 1 ...
design a data structure that supports all following operations in average o1 time insertval inserts an item val to the set if not already present removeval removes an item val from the set if present getrandom returns a random element from current set of elements each element must have the same probability of being ret...
import random class RandomizedSet: def __init__(self): self.nums = [] self.idxs = {} def insert(self, val): if val not in self.idxs: self.nums.append(val) self.idxs[val] = len(self.nums)-1 return True return False def remove(self, val):...
hashtable data type by having each bucket contain a linked list of elements that are hashed to that bucket usage table separatechaininghashtable create a new empty map table put hello world add a new keyvalue pair lentable return the number of keyvalue pairs stored in the map 1 table get hello get value by key world de...
import unittest class Node(object): def __init__(self, key=None, value=None, next=None): self.key = key self.value = value self.next = next class SeparateChainingHashTable(object): _empty = None def __init__(self, size=11): self.size = size self._len = 0 ...
determine if a sudoku is valid according to sudoku puzzles the rules the sudoku board could be partially filled where empty cells are filled with the character
def is_valid_sudoku(self, board): seen = [] for i, row in enumerate(board): for j, c in enumerate(row): if c != '.': seen += [(c,j),(i,c),(i/3,j/3,c)] return len(seen) == len(set(seen))
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 word in str example 1 input pattern abba str dog cat cat dog output true example 2 input pattern abba str dog cat cat fish output false example 3...
def word_pattern(pattern, str): dict = {} set_value = set() list_str = str.split() if len(list_str) != len(pattern): return False for i in range(len(pattern)): if pattern[i] not in dict: if list_str[i] in set_value: return False dict[pattern[i]...
collection of mathematical algorithms and functions
from .base_conversion import * from .decimal_to_binary_ip import * from .euler_totient import * from .extended_gcd import * from .factorial import * from .gcd import * from .generate_strobogrammtic import * from .is_strobogrammatic import * from .modular_exponential import * from .next_perfect_square import * from .pri...
integer base conversion algorithm inttobase5 2 return 101 basetoint f 16 return 15 type num int type base int rtype str note you can use int builtin function instead of this type strtoconvert str type base int rtype int type num int type base int rtype str note you can use int built in function instead of this type str...
import string def int_to_base(num, base): is_negative = False if num == 0: return '0' if num < 0: is_negative = True num *= -1 digit = string.digits + string.ascii_uppercase res = '' while num > 0: res += digit[num % base] num //= base if is_nega...
solves system of equations using the chinese remainder theorem if possible computes the smallest x that satisfies the chinese remainder theorem for a system of equations the system of equations has the form x nums0 rems0 x nums1 rems1 x numsk 1 remsk 1 where k is the number of elements in nums and rems k 0 all numbers ...
from typing import List from algorithms.maths.gcd import gcd def solve_chinese_remainder(nums : List[int], rems : List[int]): if not len(nums) == len(rems): raise Exception("nums and rems should have equal length") if not len(nums) > 0: raise Exception("Lists nums and rems need to contain ...
functions to calculate ncr ie how many ways to choose r items from n items this function calculates ncr if n r or r 0 return 1 return combinationn1 r1 combinationn1 r def combinationmemon r this function calculates ncr this function calculates ncr using memoization method
def combination(n, r): if n == r or r == 0: return 1 return combination(n-1, r-1) + combination(n-1, r) def combination_memo(n, r): memo = {} def recur(n, r): if n == r or r == 0: return 1 if (n, r) not in memo: memo[(n, r)] = recur(n - 1, r - 1...
calculate cosine similarity between given two 1d list two list must have the same length example cosinesimilarity1 1 1 1 2 1 output 0 47140452079103173 calculate l2 distance from two given vectors calculate cosine similarity between given two vectors type vec1 list type vec2 list calculate the dot product of two vector...
import math def _l2_distance(vec): norm = 0. for element in vec: norm += element * element norm = math.sqrt(norm) return norm def cosine_similarity(vec1, vec2): if len(vec1) != len(vec2): raise ValueError("The two vectors must be the same length. Got shape " + str(len(v...
given an ip address in dotteddecimal representation determine the binary representation for example decimaltobinary255 0 0 5 returns 11111111 00000000 00000000 00000101 accepts string returns string convert 8bit decimal number to binary representation type val str rtype str convert dotteddecimal ip address to binary re...
def decimal_to_binary_util(val): bits = [128, 64, 32, 16, 8, 4, 2, 1] val = int(val) binary_rep = '' for bit in bits: if val >= bit: binary_rep += str(1) val -= bit else: binary_rep += str(0) return binary_rep def decimal_to_binary_ip(ip): ...
algorithms for performing diffiehellman key exchange code from algorithmsmathsprimecheck py written by goswamirahul and hai honag dang return true if num is a prime number else return false for positive integer n and given integer a that satisfies gcda n 1 the order of a modulo n is the smallest positive integer k that...
import math from random import randint def prime_check(num): if num <= 1: return False if num == 2 or num == 3: return True if num % 2 == 0 or num % 3 == 0: return False j = 5 while j * j <= num: if num % j == 0 or num % (j + 2) == 0: return False...
euler s totient function also known as phifunction n counts the number of integers between 1 and n inclusive which are coprime to n two numbers are coprime if their greatest common divisor gcd equals 1 euler s totient function or phi function time complexity osqrtn result n for i in range2 intn 0 5 1 if n i 0 while n i...
def euler_totient(n): result = n for i in range(2, int(n ** 0.5) + 1): if n % i == 0: while n % i == 0: n //= i result -= result // i if n > 1: result -= result // n return result
provides extended gcd functionality for finding coprime numbers s and t such that num1 s num2 t gcdnum1 num2 ie the coefficients of bzout s identity extended gcd algorithm return s t g such that num1 s num2 t gcdnum1 num2 and s and t are coprime extended gcd algorithm return s t g such that num1 s num2 t gcd num1 num2 ...
def extended_gcd(num1, num2): old_s, s = 1, 0 old_t, t = 0, 1 old_r, r = num1, num2 while r != 0: quotient = old_r / r old_r, r = r, old_r - quotient * r old_s, s = s, old_s - quotient * s old_t, t = t, old_t - quotient * t return old_s, old_t, old_r
calculates the factorial with the added functionality of calculating it modulo mod calculates factorial iteratively if mod is not none then return n mod time complexity on if not isinstancen int and n 0 raise valueerror n must be a nonnegative integer if mod is not none and not isinstancemod int and mod 0 raise valueer...
def factorial(n, mod=None): if not (isinstance(n, int) and n >= 0): raise ValueError("'n' must be a non-negative integer.") if mod is not None and not (isinstance(mod, int) and mod > 0): raise ValueError("'mod' must be a positive integer") result = 1 if n == 0: return 1 ...
implementation of the cooleytukey which is the most common fft algorithm input an array of complex values which has a size of n where n is an integer power of 2 output an array of complex values which is the discrete fourier transform of the input example 1 input 2 02j 1 03j 3 01j 2 02j output 88j 2j 22j 20j pseudocode...
from cmath import exp, pi def fft(x): N = len(x) if N == 1: return x even = fft(x[0::2]) odd = fft(x[1::2]) y = [0 for i in range(N)] for k in range(N//2): q = exp(-2j*pi*k/N)*odd[k] y[k] = even[k] + q y[k + N//2] = even[k] - q return y
for positive integer n and given integer a that satisfies gcda n 1 the order of a modulo n is the smallest positive integer k that satisfies pow a k n 1 in other words ak 1 mod n order of a certain number may or may not be exist if not return 1 total time complexity onlogn on for iteration loop ologn for builtin power ...
import math def find_order(a, n): if (a == 1) & (n == 1): return 1 if math.gcd(a, n) != 1: print ("a and n should be relative prime!") return -1 for i in range(1, n): if pow(a, i) % n == 1: return i return -1
function to find the primitive root of a number for positive integer n and given integer a that satisfies gcda n 1 the order of a modulo n is the smallest positive integer k that satisfies pow a k n 1 in other words ak 1 mod n order of certain number may or may not be exist if so return 1 find order for positive intege...
import math def find_order(a, n): if (a == 1) & (n == 1): return 1 if math.gcd(a, n) != 1: print ("a and n should be relative prime!") return -1 for i in range(1, n): if pow(a, i) % n == 1: return i return -1 def euler_totient(n): re...
functions for calculating the greatest common divisor of two integers or their least common multiple computes the greatest common divisor of integers a and b using euclid s algorithm gcd gcd gcd gcd see proof https proofwiki orgwikigcdfornegativeintegers computes the lowest common multiple of integers a and b return ab...
def gcd(a, b): a_int = isinstance(a, int) b_int = isinstance(b, int) a = abs(a) b = abs(b) if not(a_int or b_int): raise ValueError("Input arguments are not integers") if (a == 0) or (b == 0) : raise ValueError("One or more input arguments equals zero") while b != 0: ...
a strobogrammatic number is a number that looks the same when rotated 180 degrees looked at upside down find all strobogrammatic numbers that are of length n for example given n 2 return 11 69 88 96 given n generate all strobogrammatic numbers of length n type n int rtype liststr type low str type high str rtype int gi...
def gen_strobogrammatic(n): return helper(n, n) def helper(n, length): if n == 0: return [""] if n == 1: return ["1", "0", "8"] middles = helper(n-2, length) result = [] for middle in middles: if n != length: result.append("0" + middle + "0") res...
implementation of hailstone function which generates a sequence for some n by following these rules n 1 done n is even the next n n2 n is odd the next n 3n 1 return the hailstone sequence from n to 1 n the starting point of the hailstone sequence return the hailstone sequence from n to 1 n the starting point of the hai...
def hailstone(n): sequence = [n] while n > 1: if n%2 != 0: n = 3*n + 1 else: n = int(n/2) sequence.append(n) return sequence
a krishnamurthy number is a number whose sum total of the factorials of each digit is equal to the number itself the following are some examples of krishnamurthy numbers 145 is a krishnamurthy number because 1 4 5 1 24 120 145 40585 is also a krishnamurthy number 4 0 5 8 5 40585 357 or 25965 is not a krishnamurthy numb...
def find_factorial(n): fact = 1 while n != 0: fact *= n n -= 1 return fact def krishnamurthy_number(n): if n == 0: return False sum_of_digits = 0 temp = n while temp != 0: sum_of_digits += find_factorial(temp % 10) ...
magic number a number is said to be a magic number if summing the digits of the number and then recursively repeating this process for the given sum untill the number becomes a single digit number equal to 1 example number 50113 5011310 101 this is a magic number number 1234 123410 101 this is a magic number number 199...
def magic_number(n): total_sum = 0 while n > 0 or total_sum > 9: if n == 0: n = total_sum total_sum = 0 total_sum += n % 10 n //= 10 return total_sum == 1
computes base exponent mod time complexity olog n use similar to python inbuilt function pow if exponent 0 raise valueerrorexponent must be positive base mod result 1 while exponent 0 if the last bit is 1 add 2k if exponent 1 result result base mod exponent exponent 1 utilize modular multiplication properties to combin...
def modular_exponential(base, exponent, mod): if exponent < 0: raise ValueError("Exponent must be positive.") base %= mod result = 1 while exponent > 0: if exponent & 1: result = (result * base) % mod exponent = exponent >> 1 base = (ba...
extendedgcda b modified from https github comkeonalgorithmsblobmasteralgorithmsmathsextendedgcd py extended gcd algorithm return s t g such that a s b t gcda b and s and t are coprime returns x such that a x 1 mod m a and m must be coprime extended_gcd a b modified from https github com keon algorithms blob master algo...
def extended_gcd(a: int, b: int) -> [int, int, int]: old_s, s = 1, 0 old_t, t = 0, 1 old_r, r = a, b while r != 0: quotient = old_r // r old_r, r = r, old_r - quotient * r old_s, s = s, old_s - quotient * s old_t, t = t, old_t - quotient * t return old_s, old...
i just bombed an interview and made pretty much zero progress on my interview question given a number find the next higher number which has the exact same set of digits as the original number for example given 38276 return 38627 given 99999 return 1 no such number exists condensed mathematical description find largest ...
import unittest def next_bigger(num): digits = [int(i) for i in str(num)] idx = len(digits) - 1 while idx >= 1 and digits[idx-1] >= digits[idx]: idx -= 1 if idx == 0: return -1 pivot = digits[idx-1] swap_idx = len(digits) - 1 while pivot >= digits[swap_idx]: ...
this program will look for the next perfect square check the argument to see if it is a perfect square itself if it is not then return 1 otherwise look for the next perfect square for instance if you pass 121 then the script should return the next perfect square which is 144 alternative method works by evaluating anyth...
def find_next_square(sq): root = sq ** 0.5 if root.is_integer(): return (root + 1)**2 return -1 def find_next_square2(sq): root = sq**0.5 return -1 if root % 1 else (root+1)**2
find the nth digit of given number 1 find the length of the number where the nth digit is from 2 find the actual number where the nth digit is from 3 find the nth digit and return find the nth digit of given number 1 find the length of the number where the nth digit is from 2 find the actual number where the nth digit ...
def find_nth_digit(n): length = 1 count = 9 start = 1 while n > length * count: n -= length * count length += 1 count *= 10 start *= 10 start += (n-1) / length s = str(start) return int(s[(n-1) % length])
numdigits method will return the number of digits of a number in o1 time using math log10 method
import math def num_digits(n): n=abs(n) if n==0: return 1 return int(math.log10(n))+1
given an integer numperfectsquares will return the minimum amount of perfect squares are required to sum to the specified number lagrange s foursquare theorem gives us that the answer will always be between 1 and 4 https en wikipedia orgwikilagrange27sfoursquaretheorem some examples number perfect squares representatio...
import math def num_perfect_squares(number): if int(math.sqrt(number))**2 == number: return 1 while number > 0 and number % 4 == 0: number /= 4 if number % 8 == 7: return 4 for i in range(1, int(math.sqrt(number...
from future import annotations a simple monomial class to record the details of all variables that a typical monomial is composed of create a monomial in the given variables examples monomial1 1 a11 monomial 1 3 2 2 4 1 5 0 12 12a13a22a4 monomial 0 monomial2 3 3 1 1 5 32a23a31 a helper for converting numbers to fractio...
from fractions import Fraction from typing import Dict, Union, Set, Iterable from numbers import Rational from functools import reduce class Monomial: def __init__(self, variables: Dict[int, int], coeff: Union[int, float, Fraction, None]= None) -> None: self.variables = dict() if co...
performs exponentiation similarly to the builtin pow or functions allows also for calculating the exponentiation modulo iterative version of binary exponentiation calculate a n if mod is specified return the result modulo mod time complexity ologn space complexity o1 recursive version of binary exponentiation calculate...
def power(a: int, n: int, mod: int = None): ans = 1 while n: if n & 1: ans = ans * a a = a * a if mod: ans %= mod a %= mod n >>= 1 return ans def power_recur(a: int, n: int, mod: int = None): if n == 0: ans = 1 e...
return true if n is a prime number else return false return true if n is a prime number else return false
def prime_check(n): if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: if n % j == 0 or n % (j + 2) == 0: return False j += 6 return True
return list of all primes less than n using sieve of eratosthenes modification we don t need to check all even numbers we can make the sieve excluding even numbers and adding 2 to the primes list by default we are going to make an array of x 2 1 if number is even else x 2 the 1 with even number it s to exclude the numb...
def get_primes(n): if n <= 0: raise ValueError("'n' must be a positive integer.") sieve_size = (n // 2 - 1) if n % 2 == 0 else (n // 2) sieve = [True for _ in range(sieve_size)] primes = [] if n >= 2: primes.append(2) for i in range(sieve_size): i...
given the lengths of two of the three sides of a right angled triangle this function returns the length of the third side returns length of a third side of a right angled triangle passing will indicate the unknown side returns length of a third side of a right angled triangle passing will indicate the unknown side
def pythagoras(opposite, adjacent, hypotenuse): try: if opposite == str("?"): return ("Opposite = " + str(((hypotenuse**2) - (adjacent**2))**0.5)) if adjacent == str("?"): return ("Adjacent = " + str(((hypotenuse**2) - (opposite**2))**0.5)) if hypotenuse == str("...
rabinmiller primality test returning false implies that n is guaranteed composite returning true means that n is probably prime with a 4 k chance of being wrong factor n into a power of 2 times an odd number power 0 while num 2 0 num 2 power 1 return power num def validwitnessa x powinta intd intn if x 1 or x n 1 retur...
import random def is_prime(n, k): def pow2_factor(num): power = 0 while num % 2 == 0: num /= 2 power += 1 return power, num def valid_witness(a): x = pow(int(a), int(d), int(n)) if x == 1 or x == n - 1: return Fal...
calculates the binomial coefficient cn k with nk using recursion time complexity is ok so can calculate fairly quickly for large values of k recursivebinomialcoefficient5 0 1 recursivebinomialcoefficient8 2 28 recursivebinomialcoefficient500 300 50549498499355358176677191659732495337616352527332753270881895632560139717...
def recursive_binomial_coefficient(n,k): if k>n: raise ValueError('Invalid Inputs, ensure that n >= k') if k == 0 or n == k: return 1 if k > n/2: return recursive_binomial_coefficient(n,n-k) return int((n/k)*recursive_binomial_coefficient(n-1...
rsa encryption algorithm a method for encrypting a number that uses seperate encryption and decryption keys this file only implements the key generation algorithm there are three important numbers in rsa called n e and d e is called the encryption exponent d is called the decryption exponent n is called the modulus the...
import random def generate_key(k, seed=None): def modinv(a, m): b = 1 while not (a * b) % m == 1: b += 1 return b def gen_prime(k, seed=None): def is_prime(num): if num == 2: return True for i in rang...
given a positive integer n and a precision factor p it produces an output with a maximum error p from the actual square root of n example given n 5 and p 0 001 can produce output x such that 2 235 x 2 237 actual square root of 5 being 2 236 return square root of n with maximum absolute error epsilon guess n 2 while abs...
def square_root(n, epsilon=0.001): guess = n / 2 while abs(guess * guess - n) > epsilon: guess = (guess + (n / guess)) / 2 return guess
recently i encountered an interview question whose description was as below the number 89 is the first integer with more than one digit whose digits when raised up to consecutive powers give the same number for example 89 81 92 gives the number 89 the next number after 89 with this property is 135 11 32 53 135 write a ...
def sum_dig_pow(low, high): result = [] for number in range(low, high + 1): exponent = 1 summation = 0 number_as_string = str(number) tokens = list(map(int, number_as_string)) for k in tokens: summation = summation + (k ** exponent) expo...
the significance of the cycle index polynomial of symmetry group is deeply rooted in counting the number of configurations of an object excluding those that are symmetric in terms of permutations for example the following problem can be solved as a direct application of the cycle index polynomial of the symmetry group ...
from fractions import Fraction from typing import Dict, Union from polynomial import ( Monomial, Polynomial ) from gcd import lcm def cycle_product(m1: Monomial, m2: Monomial) -> Monomial: assert isinstance(m1, Monomial) and isinstance(m2, Monomial) A = m1.variables B = m2.variables result_variab...
given a 2d grid each cell is either a wall w an enemy e or empty 0 the number zero return the maximum enemies you can kill using one bomb the bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed note that you can only put the bo...
def max_killed_enemies(grid): if not grid: return 0 m, n = len(grid), len(grid[0]) max_killed = 0 row_e, col_e = 0, [0] * n for i in range(m): for j in range(n): if j == 0 or grid[i][j-1] == 'W': row_e = row_kills(grid, i, j) ...
cholesky matrix decomposition is used to find the decomposition of a hermitian positivedefinite matrix a into matrix v so that v v a where v denotes the conjugate transpose of l the dimensions of the matrix a must match this method is mainly used for numeric solution of linear equations ax b example input matrix a 4 12...
import math def cholesky_decomposition(A): n = len(A) for ai in A: if len(ai) != n: return None V = [[0.0] * n for _ in range(n)] for j in range(n): sum_diagonal_element = 0 for k in range(j): sum_diagonal_element = sum_diagonal_element + math.pow(V...
count the number of unique paths from a00 to am1n1 we are allowed to move either right or down from a cell in the matrix approaches i recursion recurse starting from am1n1 upwards and leftwards add the path count of both recursions and return count ii dynamic programming start from a00 store the count in a count matrix...
def count_paths(m, n): if m < 1 or n < 1: return -1 count = [[None for j in range(n)] for i in range(m)] for i in range(n): count[0][i] = 1 for j in range(m): count[j][0] = 1 for i in range(1, m): for j in range(1, n): coun...
crout matrix decomposition is used to find two matrices that when multiplied give our input matrix so l u a l stands for lower and l has nonzero elements only on diagonal and below u stands for upper and u has nonzero elements only on diagonal and above this can for example be used to solve systems of linear equations ...
def crout_matrix_decomposition(A): n = len(A) L = [[0.0] * n for i in range(n)] U = [[0.0] * n for i in range(n)] for j in range(n): U[j][j] = 1.0 for i in range(j, n): alpha = float(A[i][j]) for k in range(j): alpha -= L[i][k]*U[k][j] ...
multiplies two square matrices mata and matb of size n x n time complexity on3 returns the identity matrix of size n x n time complexity on2 calculates matn by repeated squaring time complexity od3 logn d dimension of the square matrix mat n power the matrix is raised to multiplies two square matrices mata and matb of ...
def multiply(matA: list, matB: list) -> list: n = len(matA) matC = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): for k in range(n): matC[i][j] += matA[i][k] * matB[k][j] return matC def identity(n: int) -> list: I = ...
inverts an invertible n x n matrix i e given an n x n matrix a returns an n x n matrix b such that ab ba in the n x n identity matrix for a 2 x 2 matrix inversion is simple using the cofactor equation for larger matrices this is a four step process 1 calculate the matrix of minors create an n x n matrix by considering ...
import fractions def invert_matrix(m): if not array_is_matrix(m): print("Invalid matrix: array is not a matrix") return [[-1]] elif len(m) != len(m[0]): print("Invalid matrix: matrix is not square") return [[-2]] elif len(m) < 2: print("Invalid matrix: mat...
this algorithm takes two compatible two dimensional matrix and return their product space complexity on2 possible edge case the number of columns of multiplicand not consistent with the number of rows of multiplier will raise exception type a listlistint type b listlistint rtype listlistint create a result matrix type ...
def multiply(multiplicand: list, multiplier: list) -> list: multiplicand_row, multiplicand_col = len( multiplicand), len(multiplicand[0]) multiplier_row, multiplier_col = len(multiplier), len(multiplier[0]) if(multiplicand_col != multiplier_row): raise Exception( "Multiplica...
you are given an n x n 2d mat representing an image rotate the image by 90 degrees clockwise follow up could you do this inplace clockwise rotate first reverse up to down then swap the symmetry 1 2 3 7 8 9 7 4 1 4 5 6 4 5 6 8 5 2 7 8 9 1 2 3 9 6 3 clockwise rotate first reverse up to down then swap the symmetry 1 2 3 7...
def rotate(mat): if not mat: return mat mat.reverse() for i in range(len(mat)): for j in range(i): mat[i][j], mat[j][i] = mat[j][i], mat[i][j] return mat if __name__ == "__main__": mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(mat) rotate(m...
search a key in a row wise and column wise sorted nondecreasing matrix m number of rows in the matrix n number of columns in the matrix tn omn search a key in a row wise and column wise sorted non decreasing matrix m number of rows in the matrix n number of columns in the matrix t n o m n
def search_in_a_sorted_matrix(mat, m, n, key): i, j = m-1, 0 while i >= 0 and j < n: if key == mat[i][j]: print('Key %s found at row- %s column- %s' % (key, i+1, j+1)) return if key < mat[i][j]: i -= 1 else: j += 1 print('Key %s not fou...
given a m n matrix mat of integers sort it diagonally in ascending order from the topleft to the bottomright then return the sorted array mat 3 3 1 1 2 2 1 2 1 1 1 2 should return 1 1 1 1 1 2 2 2 1 2 3 3 if the input is a vector return the vector rows columns 1 the 1 helps you to not repeat a column process the rows in...
from heapq import heappush, heappop from typing import List def sort_diagonally(mat: List[List[int]]) -> List[List[int]]: if len(mat) == 1 or len(mat[0]) == 1: return mat for i in range(len(mat)+len(mat[0])-1): if i+1 < len(mat): h = [] ...
usrbinenv python3 suppose we have very large sparse vectors which contains a lot of zeros and double find a data structure to store them get the dot product of them 10 usr bin env python3 suppose we have very large sparse vectors which contains a lot of zeros and double find a data structure to store them get the dot p...
def vector_to_index_value_list(vector): return [(i, v) for i, v in enumerate(vector) if v != 0.0] def dot_product(iv_list1, iv_list2): product = 0 p1 = len(iv_list1) - 1 p2 = len(iv_list2) - 1 while p1 >= 0 and p2 >= 0: i1, v1 = iv_list1[p1] i2, v2 = iv_list2[p2] if i1 <...
given two sparse matrices a and b return the result of ab you may assume that a s column number is equal to b s row number example a 1 0 0 1 0 3 b 7 0 0 0 0 0 0 0 1 1 0 0 7 0 0 7 0 0 ab 1 0 3 x 0 0 0 7 0 3 0 0 1 python solution without table 156ms type a listlistint type b listlistint rtype listlistint python solution ...
def multiply(self, a, b): if a is None or b is None: return None m, n, l = len(a), len(b[0]), len(b[0]) if len(b) != n: raise Exception("A's column number must be equal to B's row number.") c = [[0 for _ in range(l)] for _ in range(m)] for i, row in enumerate(a): for k, ...
given a matrix of m x n elements m rows n columns return all elements of the matrix in spiral order for example given the following matrix 1 2 3 4 5 6 7 8 9 you should return 1 2 3 6 9 8 7 4 5
def spiral_traversal(matrix): res = [] if len(matrix) == 0: return res row_begin = 0 row_end = len(matrix) - 1 col_begin = 0 col_end = len(matrix[0]) - 1 while row_begin <= row_end and col_begin <= col_end: for i in range(col_begin, col_end+1): res.append(matrix[...
write a function validsolutionvalidatesolutionvalidsolution that accepts a 2d array representing a sudoku board and returns true if it is a valid solution or false otherwise the cells of the sudoku board may also contain 0 s which will represent empty cells boards containing one or more zeroes are considered to be inva...
from collections import defaultdict def valid_solution_hashtable(board): for i in range(len(board)): dict_row = defaultdict(int) dict_col = defaultdict(int) for j in range(len(board[0])): value_row = board[i][j] value_col = board[j][i] if not value_row o...
function to find sum of all subsquares of size k x k in a given square matrix of size n x n calculate and print sum of current subsquare function to find sum of all sub squares of size k x k in a given square matrix of size n x n calculate and print sum of current sub square
def sum_sub_squares(matrix, k): n = len(matrix) result = [[0 for i in range(k)] for j in range(k)] if k > n: return for i in range(n - k + 1): l = 0 for j in range(n - k + 1): sum = 0 for p in range(i, k + i): for q in range(...
summary helperfunction calculates the eulidean distance between vector x and y arguments x tuple vector y tuple vector summary implements the nearest neighbor algorithm arguments x tupel vector tset dict training set returns type result of the andfunction summary helper function calculates the eulidean distance between...
import math def distance(x,y): assert len(x) == len(y), "The vector must have same length" result = () sum = 0 for i in range(len(x)): result += (x[i] -y[i],) for component in result: sum += component**2 return math.sqrt(sum) def nearest_neighbor(x, tSet): assert...
given an array and a number k find the max elements of each of its subarrays of length k keep indexes of good candidates in deque d the indexes in d are from the current window they re increasing and their corresponding nums are decreasing then the first deque element is the index of the largest window value for each i...
import collections def max_sliding_window(arr, k): qi = collections.deque() result = [] for i, n in enumerate(arr): while qi and arr[qi[-1]] < n: qi.pop() qi.append(i) if qi[0] == i - k: qi.popleft() if i >= k - 1: result.append(arr[qi[...
initialize your data structure here type size int type val int rtype float given a stream of integers and a window size calculate the moving average of all integers in the sliding window initialize your data structure here type size int type val int rtype float given a stream of integers and a window size calculate the...
from __future__ import division from collections import deque class MovingAverage(object): def __init__(self, size): self.queue = deque(maxlen=size) def next(self, val): self.queue.append(val) return sum(self.queue) / len(self.queue) if __name__ == '__main__': ...
implementation of priority queue using linear array insertion on extract minmax node o1 create a priority queue with items list or iterable if items is not passed create empty priority queue self priorityqueuelist if items is none return if priorities is none priorities itertools repeatnone for item priority in zipitem...
import itertools class PriorityQueueNode: def __init__(self, data, priority): self.data = data self.priority = priority def __repr__(self): return "{}: {}".format(self.data, self.priority) class PriorityQueue: def __init__(self, items=None, priorities=None): sel...
queue abstract data type adt queue creates a new queue that is empty it needs no parameters and returns an empty queue enqueueitem adds a new item to the rear of the queue it needs the item and returns nothing dequeue removes the front item from the queue it needs no parameters and returns the item the queue is modifie...
from abc import ABCMeta, abstractmethod class AbstractQueue(metaclass=ABCMeta): def __init__(self): self._size = 0 def __len__(self): return self._size def is_empty(self): return self._size == 0 @abstractmethod def enqueue(self, value): pass @abstractmethod...
suppose you have a random list of people standing in a queue each person is described by a pair of integers h k where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h write an algorithm to reconstruct the queue note the number of people is ...
def reconstruct_queue(people): queue = [] people.sort(key=lambda x: (-x[0], x[1])) for h, k in people: queue.insert(k, [h, k]) return queue
initialize your data structure here type v1 listint type v2 listint rtype int rtype bool initialize your data structure here type v1 list int type v2 list int rtype int rtype bool
class ZigZagIterator: def __init__(self, v1, v2): self.queue = [_ for _ in (v1, v2) if _] print(self.queue) def next(self): v = self.queue.pop(0) ret = v.pop(0) if v: self.queue.append(v) return ret def has_next(self): ...