Algorithms Flashcards
Tree: Number of nodes in a full binary tree with L levels?
Nodes = (2 ^ L) - 1
Tree: What numbers of calls does recursive function with branching do with input N?
Ncalls = (Branches ^ Levels) - 1, where
Levels = ceiling(N / Decrement) - BaseCaseValue + 1 Levels = ceiling(logN) - ceiling(logBaseCaseValue) + 1
Example: def f(N): if N <= 0: # BaseCaseValue = 0 return 1 return f(N-1) + f(N-1) # Branches = 2, Decrement = 1
Tree: Number of leaves in a full tree with L levels?
Leaves = branches ^ (L - 1)
Tree: In a complete binary tree represented as an array what is index of children of a node with index N?
Left child: 2 * N + 1
Right child: 2 * N + 2
KMP: What is KMP algorithm?
KMP stands for Knuth-Moris-Pratt and it is an efficient algorithm for finding specific substring in a given string.
Time complexity: O(n + m), where n is a length of the string and m is a length of the substring.
Space complexity: O(m)
KMP: In the context of KMP algorithm what will the P-table be for the pattern “abcdabca” ?
0 1 2 3 4 5 6 7
a b c d a b c a
[0, 0, 0, 0, 1, 2, 3, 1]
KMP: In the context of KMP algorithm what a value inside P-table means?
Every value in the table means how many characters in the prefix are already matched. Those values help us to skip comparisons which we already know will succeed, and that is where the efficiency of KMP comes from.
Bit tricks: Isolate the first set bit from the right?
x = x & ~(x - 1)
Example:
x = 1010
- (x - 1) = 1001
- ~(x - 1) = 0110
- x & ~(x - 1) = 0010
Bit tricks: Unset the last set bit from the right?
x = x & (x - 1)
Example:
x = 1110
1. (x - 1) = 1101
2. x & (x - 1) = 1100
What is LCM of two numbers and how to find it?
LCM stands for least common multiple and it is a first number that is divisible by the given two numbers A and B.
LCM(a, b) = (a * b) / GCD(a, b)
What is the Euclidean Algorithm?
It is an efficient algorithm for finding GCD:
r = a % b while r: a = b b = r r = a % b return b
Graph: What are common algorithms used to solve shortest path problem in graphs?
- BFS (unweighted graphs)
- Dijkstra (without negative weights)
- Bellman-Ford
- Floyd-Warshall
- A*
Graph: What are common algorithms used to solve connectivity problem in graphs (does there exist path from one node to another)?
- use union find data structure
- DFS
Graph: What are common algorithms used to detect negative cycles?
- Bellman-Ford
- Floyd-Warshall
Graph: What are common algorithms used to find strongly connected components in a directed graph?
- Tarjan’s algorithm
- Kosaraju’s algorithm