Prompt
stringlengths
16
11.5k
Completions
stringlengths
84
25.3k
These are classes to represent a Graph and its elements. It can be shared across graph algorithms. A nodevertex in a graph. Return the name of the node A directed edge in a directed graph. Stores the source and target node of the edge. A directed graph. Stores a set of nodes, edges and adjacency matrix. pylint: disable...
class Node: """ A node/vertex in a graph. """ def __init__(self, name): self.name = name @staticmethod def get_name(obj): """ Return the name of the node """ if isinstance(obj, Node): return obj.name if isinstance(obj, str): ...
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
import random def __choose_state(state_map): """ Choose the next state randomly """ choice = random.random() probability_reached = 0 for state, probability in state_map.items(): probability_reached += probability if probability_reached > choice: return state retu...
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 shou...
from queue import Queue # pylint: disable=too-many-arguments def dfs(capacity, flow, visit, vertices, idx, sink, current_flow = 1 << 63): """ Depth First Search implementation for Ford-Fulkerson algorithm. """ # DFS function for ford_fulkerson algorithm. if idx == sink: return current_flow...
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...
import copy import queue import math def maximum_flow_bfs(adjacency_matrix): """ Get the maximum flow through a graph using a breadth first search """ #initial setting new_array = copy.deepcopy(adjacency_matrix) total = 0 while True: #setting min to max_value min_flow = mat...
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...
import copy import math def maximum_flow_dfs(adjacency_matrix): """ Get the maximum flow through a graph using a depth first search """ #initial setting new_array = copy.deepcopy(adjacency_matrix) total = 0 while True: #setting min to max_value min = math.inf #save...
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...
import sys # pylint: disable=too-few-public-methods class Edge: """ An edge of an undirected graph """ def __init__(self, source, target, weight): self.source = source self.target = target self.weight = weight class DisjointSet: """ The disjoint set is represented wit...
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 determin...
from collections import defaultdict class Graph: """ A directed 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): """ Add a new directed edge 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' ...
import heapq # for priority queue def prims_minimum_spanning(graph_used): """ Prim's algorithm to find weight of minimum spanning tree """ vis=[] heap=[[0,1]] prim = set() mincost=0 while len(heap) > 0: cost, node = heapq.heappop(heap) if node in vis: conti...
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 identifi...
def dfs_transposed(vertex, graph, order, visited): """ Perform a depth first search traversal of the graph starting at the given vertex. Stores the order in which nodes were visited to the list, in transposed order. """ visited[vertex] = True for adjacent in graph[vertex]: if not visite...
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 s...
from algorithms.graph.graph import DirectedGraph # pylint: disable=too-few-public-methods class Tarjan: """ A directed graph used for finding strongly connected components """ def __init__(self, dict_graph): self.graph = DirectedGraph(dict_graph) self.index = 0 self.stack = [] ...
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 tha...
class Graph: """ This class represents a directed graph using adjacency lists """ def __init__(self, vertices): # No. of vertices self.vertex_count = vertices # default dictionary to store graph self.graph = {} # To store transitive closure self.closure ...
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 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. # def dfs_traverse(graph, start): """ Traversal by depth first search. """ visited, stack = set(), [start] while stack: n...
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 ...
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] ...
from abc import ABCMeta, abstractmethod class AbstractHeapmetaclassABCMeta: Pass. abstractmethod def percupself, i: Pass. abstractmethod def percdownself, i: Pass. abstractmethod def removeminself: Binary Heap Class def initself: self.currentsize 0 self.heap 0 def percupself, i: while i 2 0: if self.heapi self.hea...
r""" Binary Heap. A min heap is a complete binary tree where each node is smaller than its children. The root, therefore, is the minimum element in the tree. The min heap uses an array to represent the data and operation. For example a min heap: 4 / \ 50 7 / \ / 55 90 87 Heap [0, 4, 50, 7, 55, 90, 8...
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 cont...
from heapq import heapify, heappushpop def k_closest(points, k, origin=(0, 0)): # Time: O(k+(n-k)logk) # Space: O(k) """Initialize max heap with first k points. Python does not support a max heap; thus we can use the default min heap where the keys (distance) are negated. """ heap = [(-dis...
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.va...
from heapq import heappop, heapreplace, heapify from queue import PriorityQueue # Definition for singly-linked list. class ListNode(object): """ ListNode Class""" def __init__(self, val): self.val = val self.next = None def merge_k_lists(lists): """ Merge Lists """ dummy = node = Li...
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 coll...
# -*- coding: utf-8 -*- """ 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 thes...
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 ...
import collections def max_sliding_window(nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if not nums: return nums queue = collections.deque() res = [] for num in nums: if len(queue) < k: queue.append(num) else: ...
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 ...
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
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): """ :type head: RandomListNode :rtype: RandomListNode """ dic = dict() m = n = hea...
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 ...
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
import unittest class Node: def __init__(self, x): self.val = x self.next = None def first_cyclic_node(head): """ :type head: Node :rtype: Node """ runner = walker = head while runner and runner.next: runner = runner.next.next walker = walker.next ...
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 ca...
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
class Node: def __init__(self, x): self.val = x self.next = None def is_cyclic(head): """ :type head: Node :rtype: bool """ if not head: return False runner = head walker = head while runner.next and runner.next.next: runner = runner.next.next ...
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 va...
def is_palindrome(head): if not head: return True # split the list to two parts fast, slow = head.next, head while fast and fast.next: fast = fast.next.next slow = slow.next second = slow.next slow.next = None # Don't forget here! But forget still works! # reverse th...
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 F...
class Node(): def __init__(self, val=None): self.val = val self.next = None def kth_to_last_eval(head, k): """ 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 """ if not isinstance(k, int) or no...
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 ac...
# Pros # Linked Lists have constant-time insertions and deletions in any position, # in comparison, arrays require O(n) 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 co...
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
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 ne...
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
class Node(): def __init__(self, val = None): self.val = val self.next = None def remove_dups(head): """ Time Complexity: O(N) Space Complexity: O(N) """ hashset = set() prev = Node() while head: if head.val in hashset: prev.next = head.next e...
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...
def remove_range(head, start, end): assert(start <= end) # Case: remove node at head if start == 0: for i in range(0, end+1): if head != None: head = head.next else: current = head # Move pointer to start position for i in range(0,start-1): ...
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) # def reverse_list(head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head prev = None while head: current = head head = head.next current.next = prev prev = current return ...
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 i...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None def rotate_right(head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next: return head current = 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...
class HashTable(object): """ HashMap Data Type HashMap() Create a new, empty map. It returns an empty map collection. put(key, val) Add a new key-value pair to the map. If the key is already in the map then replace the old value with the new value. get(key) Given a key, return th...
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:...
def is_anagram(s, t): """ :type s: str :type t: str :rtype: bool """ 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 ma...
def is_isomorphic(s, t): """ :type s: str :type t: str :rtype: bool """ 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...
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
def max_common_sub_string(s1, s2): # Assuming s2 has all unique chars 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]:...
from icecream import ic ics, logestSubStr
def longest_palindromic_subsequence(s): k = len(s) olist = [0] * k # 申请长度为n的列表,并初始化 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 be...
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 ...
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): """ HashTable Data Type: By having each bucket contain a linked list of elements that are hashe...
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: ...
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
import string def int_to_base(num, base): """ :type num: int :type base: int :rtype: str """ is_negative = False if num == 0: return '0' if num < 0: is_negative = True num *= -1 digit = string.digits + string.ascii_uppercase res = '' while...
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, ...
from typing import List from algorithms.maths.gcd import gcd def solve_chinese_remainder(nums : List[int], rems : List[int]): """ Computes the smallest x that satisfies the chinese remainder theorem for a system of equations. The system of equations has the form: x % nums[0] = rems[0] x % nums[...
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:
def combination(n, r): """This function calculates nCr.""" if n == r or r == 0: return 1 return combination(n-1, r-1) + combination(n-1, r) def combination_memo(n, r): """This function calculates nCr using memoization method.""" memo = {} def recur(n, r): if n == r or r == 0: ...
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 prod...
import math def _l2_distance(vec): """ Calculate l2 distance from two given vectors. """ norm = 0. for element in vec: norm += element * element norm = math.sqrt(norm) return norm def cosine_similarity(vec1, vec2): """ Calculate cosine similarity between given two vectors...
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 bi...
def decimal_to_binary_util(val): """ Convert 8-bit decimal number to binary representation :type val: str :rtype: str """ 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 -= bi...
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 inte...
import math from random import randint """ Code from /algorithms/maths/prime_check.py, written by 'goswami-rahul' and 'Hai Honag Dang' """ def prime_check(num): """Return True if num is a prime number Else return False. """ if num <= 1: return False if num == 2 or num == 3: return...
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 ...
def euler_totient(n): """Euler's totient function or Phi function. Time Complexity: O(sqrt(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 ...
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.
def extended_gcd(num1, num2): """Extended GCD algorithm. Return s, t, g such that num1 * s + num2 * t = GCD(num1, num2) and s and t are co-prime. """ 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 - quot...
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:...
def factorial(n, mod=None): """Calculates factorial iteratively. If mod is not None, then return (n! % mod) Time Complexity - O(n)""" 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):...
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, 2...
from cmath import exp, pi def fft(x): """ Recursive implementation of the Cooley-Tukey""" N = len(x) if N == 1: return x # get the elements at even/odd indices 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)*od...
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...
import math def find_order(a, n): """ Find order for positive integer n and given integer a that satisfies gcd(a, n) = 1. """ if (a == 1) & (n == 1): # Exception Handeling : 1 is the order of of 1 return 1 if math.gcd(a, n) != 1: print ("a and n should be relative prime!") ...
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 p...
import math """ For positive integer n and given integer a that satisfies gcd(a, n) = 1, the order of a modulo n is the smallest positive integer k that satisfies pow (a, k) % n = 1. In other words, (a^k) ≡ 1 (mod n). Order of certain number may or may not be exist. If so, return -1. """ def find_order(a, n): """ ...
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. retu...
def gcd(a, b): """Computes the greatest common divisor of integers a and b using Euclid's Algorithm. gcd{𝑎,𝑏}=gcd{−𝑎,𝑏}=gcd{𝑎,−𝑏}=gcd{−𝑎,−𝑏} See proof: https://proofwiki.org/wiki/GCD_for_Negative_Integers """ a_int = isinstance(a, int) b_int = isinstance(b, int) a = abs(a) b ...
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:...
def gen_strobogrammatic(n): """ Given n, generate all strobogrammatic numbers of length n. :type n: int :rtype: List[str] """ 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 ...
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
def hailstone(n): """ Return the 'hailstone sequence' from n to 1 n: The starting point of the hailstone sequence """ sequence = [n] while n > 1: if n%2 != 0: n = 3*n + 1 else: n = int(n/2) sequence.append(n) return sequence
A strobogrammatic number is a number that looks the same when rotated 180 degrees looked at upside down. Write a function to determine if a number is strobogrammatic. The number is represented as a string. For example, the numbers 69, 88, and 818 are all strobogrammatic. :type num: str :rtype: bool Another implementati...
def is_strobogrammatic(num): """ :type num: str :rtype: bool """ comb = "00 11 88 69 96" i = 0 j = len(num) - 1 while i <= j: if comb.find(num[i]+num[j]) == -1: return False i += 1 j -= 1 return True def is_strobogrammatic2(num: str): """Anot...
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 N...
def find_factorial(n): """ Calculates the factorial of a given number 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 # will hold sum of FACTORIAL of digits temp = n while temp !...
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 N...
def magic_number(n): """ Checks if n is a magic number """ total_sum = 0 # will end when n becomes 0 # AND # sum becomes single digit. while n > 0 or total_sum > 9: # when n becomes 0 but we have a total_sum, # we update the value of n with the value of the sum digits if...
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...
def modular_exponential(base, exponent, mod): """Computes (base ^ exponent) % mod. Time complexity - O(log n) Use similar to Python in-built function pow.""" if exponent < 0: raise ValueError("Exponent must be positive.") base %= mod result = 1 while exponent > 0: # If the l...
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/algorithms/maths/extended_gcd.py def extended_gcd(a: int, b: int) -> [int, int, int]: """Extended GCD algorithm. Return s, t, g such that a * s + b * t = GCD(a, b) and s and t are co-prime. """ old_s, s = 1, 0 ...
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 l...
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 # no such number exists pivot = digits[idx-1] swap_idx = len(digits) - 1 while pivot >= dig...
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 ...
def find_next_square(sq): root = sq ** 0.5 if root.is_integer(): return (root + 1)**2 return -1 def find_next_square2(sq): """ Alternative method, works by evaluating anything non-zero as True (0.000001 --> True) """ 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
def find_nth_digit(n): """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 """ length = 1 count = 9 start = 1 while n > length * count: n -=...
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 represent...
import math def num_perfect_squares(number): """ Returns the smallest number of perfect squares that sum to the specified number. :return: int between 1 - 4 """ # If the number is a perfect square then we only need 1 number. if int(math.sqrt(number))**2 == number: return 1 # We che...
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 numb...
# from __future__ import annotations from fractions import Fraction from typing import Dict, Union, Set, Iterable from numbers import Rational from functools import reduce class Monomial: """ A simple Monomial class to record the details of all variables that a typical monomial is composed of. ""...
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 exponentiatio...
def power(a: int, n: int, mod: int = None): """ Iterative version of binary exponentiation Calculate a ^ n if mod is specified, return the result modulo mod Time Complexity : O(log(n)) Space Complexity : O(1) """ ans = 1 while n: if n & 1: ans = ans * a ...
Return True if n is a prime number Else return False.
def prime_check(n): """Return True if n is a prime number Else return False. """ 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: retu...
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 exclud...
def get_primes(n): """Return list of all primes less than n, Using sieve of Eratosthenes. """ if n <= 0: raise ValueError("'n' must be a positive integer.") # If x is even, exclude x from list (-1): sieve_size = (n // 2 - 1) if n % 2 == 0 else (n // 2) sieve = [True for _ in range(si...
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.
def pythagoras(opposite, adjacent, hypotenuse): """ Returns length of a third side of a right angled triangle. Passing "?" will indicate the unknown side. """ try: if opposite == str("?"): return ("Opposite = " + str(((hypotenuse**2) - (adjacent**2))**0.5)) if adjacent ==...
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 o...
import random def is_prime(n, k): def pow2_factor(num): """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 valid_witness(a): """ returns true if a is a valid 'wit...
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 5054949849935535817667719165973249533761635252733275327088189563256...
def recursive_binomial_coefficient(n,k): """Calculates the binomial coefficient, C(n,k), with n>=k using recursion Time complexity is O(k), so can calculate fairly quickly for large values of k. >>> recursive_binomial_coefficient(5,0) 1 >>> recursive_binomial_coefficient(8,2) 28 >>> recur...
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 t...
# sample usage: # n,e,d = generate_key(16) # data = 20 # encrypted = pow(data,e,n) # decrypted = pow(encrypted,d,n) # assert decrypted == data import random def generate_key(k, seed=None): """ the RSA key generating algorithm k is the number of bits in n """ def modinv(a, m): """calculat...
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...
def square_root(n, epsilon=0.001): """Return square root of n, with maximum absolute error epsilon""" 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 1...
def sum_dig_pow(low, high): result = [] for number in range(low, high + 1): exponent = 1 # set to 1 summation = 0 # set to 1 number_as_string = str(number) tokens = list(map(int, number_as_string)) # parse the string into individual digits for k in tokens: ...
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 grou...
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: """ Given two monomials (from the cycle index of a symmetry group), compute the resultant monomial in the car...
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...
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 # iterates over all cells in the grid for i in range(m): for j in range(n): # makes sure we are next to a wall. if j == 0 or grid[i]...
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 matr...
import math def cholesky_decomposition(A): """ :param A: Hermitian positive-definite matrix of type List[List[float]] :return: matrix of type List[List[float]] if A can be decomposed, otherwise None """ n = len(A) for ai in A: if len(ai) != n: return None V = [[0.0]...
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 ma...
# # Count the number of unique paths from a[0][0] to a[m-1][n-1] # We are allowed to move either right or down from a cell in the matrix. # Approaches- # (i) Recursion- Recurse starting from a[m-1][n-1], upwards and leftwards, # add the path count of both recursions and return count. # (ii) Dynamic Progr...
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 equ...
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
def multiply(matA: list, matB: list) -> list: """ Multiplies two square matrices matA and matB of size n x n Time Complexity: O(n^3) """ 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): ...
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 b...
import fractions def invert_matrix(m): """invert an n x n matrix""" # Error conditions 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 ...
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 mat...
def multiply(multiplicand: list, multiplier: list) -> list: """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ multiplicand_row, multiplicand_col = len( multiplicand), len(multiplicand[0]) multiplier_row, multiplier_col = len(multiplier), len(multiplier...
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 8 9 7 4 1 # 4 5 6 => 4 5 6 => 8 5 2 # 7 8 9 1 2 3 9 6 3 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...
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 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 Pro...
from heapq import heappush, heappop from typing import List def sort_diagonally(mat: List[List[int]]) -> List[List[int]]: # If the input is a vector, return the vector if len(mat) == 1 or len(mat[0]) == 1: return mat # Rows + columns - 1 # The -1 helps you to not repeat a column for i in ...
! 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 product of them """ 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_l...
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: ListListin...
# Python solution without table (~156ms): def multiply(self, a, b): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ 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 ...
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...
# Using dict/hash-table 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] ...
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 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): ...
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
import math def distance(x,y): """[summary] HELPER-FUNCTION calculates the (eulidean) distance between vector x and y. Arguments: x {[tuple]} -- [vector] y {[tuple]} -- [vector] """ assert len(x) == len(y), "The vector must have same length" result = () sum = 0 for ...
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 ...
import collections def max_sliding_window(arr, k): qi = collections.deque() # queue storing indexes of elements 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...
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.
from __future__ import division from collections import deque class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. :type size: int """ self.queue = deque(maxlen=size) def next(self, val): """ :type val: int ...
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, priorit...
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): """Create a ...