Tech Interview Flashcards
Alg. complexity of (Hash)Set - Add/Remove/Contains/Size operations
O(1)
Write an optimized Disjoint Set Class in Python with Path Compression and Union-by-Rank
class UnionFind: def \_\_init\_\_(self, size): self.root = [i for i in range(size)] self.rank = [1] * size
def find(self, x): if x == self.root[x]: return x self.root[x] = self.find(self.root[x]) return self.root[x]
def union(self, x, y): rootX = self.find(x) rootY = self.find(y) if rootX != rootY: if self.rank[rootX] > self.rank[rootY]: self.root[rootY] = rootX elif self.rank[rootX] < self.rank[rootY]: self.root[rootX] = rootY else: self.root[rootY] = rootX self.rank[rootX] += 1
def connected(self, x, y): return self.find(x) == self.find(y)
Time Complexity for Find, Union, Connected operations of Disjoint Set with Path Compression and Union-by-Rank
O(1) on average
Write a Binary Search function in Python for a list (array)
def BS(arr, val): if len(arr) == 0: return -1 low = 0 high = len(arr) - 1 mid = 0
while low < high: mid = (low + high) // 2
if arr[mid] == val: return mid elif arr[mid] > val: high = mid - 1 else: low = mid + 1
return -1
Every time you ‘union’ two nodes in a disjoint set that aren’t already connected, what happens to the number of distinct sets?
Decreases by 1
How to sort a list of lists in Python by the first element of each inner list
Call sort() on the list of lists
How to clear a set in Python
set.clear()
How to determine if a graph is a valid tree?
- All nodes should be connected in some way
- Only one path connecting any 2 nodes (no cycles)
How to get union of a set
Ex. get {1,4,6,7} from {1,4} + {6,7}
A | B
How to get absolute value in Python
abs()
Give a high-level description of Kruskal’s algorithm to get the minimum spanning tree
- Create a new UnionFind() for all points
- Get the list of all possible edges for the points, and sort by weight of an edge ascending.
- For each edge, check if connected points are already connected in UF. Skip if so.
- If not, that edge (weight) is included, and connect the points
How to construct a heap in Python
import heapq
heapWithValues = [3,1,2]
heapq.heapify(heapWithValues)
What data structure to use when you care about getting the max/min value of a set of data, but don’t care about the order of the rest of the data?
A heap
Time complexity of insertion, deletion, getMax/getMin of a heap?
O(log N), O(log N), O(1)
Time complexity to convert data to a heap using Heapify
O(N)