Tech Interview Flashcards

1
Q

Alg. complexity of (Hash)Set - Add/Remove/Contains/Size operations

A

O(1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write an optimized Disjoint Set Class in Python with Path Compression and Union-by-Rank

A
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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Time Complexity for Find, Union, Connected operations of Disjoint Set with Path Compression and Union-by-Rank

A

O(1) on average

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Write a Binary Search function in Python for a list (array)

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Every time you ‘union’ two nodes in a disjoint set that aren’t already connected, what happens to the number of distinct sets?

A

Decreases by 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to sort a list of lists in Python by the first element of each inner list

A

Call sort() on the list of lists

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to clear a set in Python

A

set.clear()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to determine if a graph is a valid tree?

A
  • All nodes should be connected in some way

- Only one path connecting any 2 nodes (no cycles)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to get union of a set

Ex. get {1,4,6,7} from {1,4} + {6,7}

A

A | B

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to get absolute value in Python

A

abs()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Give a high-level description of Kruskal’s algorithm to get the minimum spanning tree

A
  1. Create a new UnionFind() for all points
  2. Get the list of all possible edges for the points, and sort by weight of an edge ascending.
  3. For each edge, check if connected points are already connected in UF. Skip if so.
  4. If not, that edge (weight) is included, and connect the points
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to construct a heap in Python

A

import heapq

heapWithValues = [3,1,2]
heapq.heapify(heapWithValues)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

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

A heap

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Time complexity of insertion, deletion, getMax/getMin of a heap?

A

O(log N), O(log N), O(1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Time complexity to convert data to a heap using Heapify

A

O(N)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to get the K largest/smallest elements from a collection of data?

A

Add K elements to a heap
For every next element in data, delete top of the heap if larger/smaller, add current element to top of heap (keep only K in heap)
At the end of iteration, will have K smallest/largest
Time complexity: O(N log K)

17
Q

How to find the Kth largest/smallest element in a collection of data?

A

Add K elements to min/max heap, respectively
Iterate over remaining data. For current element, if larger/smaller than current element, remove top of heap and add current value
At the end, the top of heap is the Kth largest/smallest element.
Time complexity: O(N log K)

18
Q

Python code for finding Kth largest element in array

A

import heapq

def findKthLargest(self, nums: List[int], k: int) -> int:
    minHeap = []
    for i in range(k):
        minHeap.append(nums[i])
    heapq.heapify(minHeap)
    for i in range(k,len(nums)):
        if nums[i] > minHeap[0]:
            heapq.heappop(minHeap)
            heapq.heappush(minHeap, nums[i])
    return minHeap[0]
19
Q

What needs to be done to create and use a max heap in Python (heapq) ?

A

Every value added or removed (popped) needs to be multiplied by -1

20
Q

What’s the sort mechanism when sorting a list of lists/tuples in Python?

A

Calling list.sort() will sort ascending by first element in each list/tuple. If first element is equal, it will sort on the second element

21
Q

How to remove an element from a Python list by index?

A
a = [1, 2, 3, 4]
del a[1]
# a = [1, 3, 4]
22
Q

How to insert a value at beginning of List in Python

A

arr = [2, 3, 4]
arr.insert(0, 5)
// arr = [5, 2, 3, 4]

23
Q

How to sum two positive numbers using bitwise operations?

A

x ^ y is the answer without the “carry”
(x & y) &laquo_space;1 is the carry
Keep summing the above two in a loop until carry = 0

24
Q

How to find difference of two positive numbers using bitwise operations?

A

x ^ y Is the answer without the “borrow”
((~x) & y) &laquo_space;1 is the borrow
Keep summing the above two in a loop until borrow = 0

25
Q

How to zero out the least significant ‘1’ bit of an int?

A

x & (x - 1)

26
Q

How to find index of substring in string?

A

str.index(substr)

27
Q

What’s the built-in Python tool for memoization?

A

from functors import lru_cache

@lru_cache
def myFunc(…):

28
Q

What’s the problem with using @lru_cache with a function with lists as input?

A

Lists are unhashable, so this will fail.

Need to use tuples instead as a potential option

29
Q

How to create a list with first n numbers in Python?

A

list(range(1, n))

30
Q

How to initialize 2D array of zeros in Python?

A

zeros = [ [0] * cols for _ in range(rows)]

31
Q

How to join strings in Python with separator

A

strs = [“hello”,”world”]
separator = “.”
separator.join(x for x in strs)

32
Q

What can happen to mutable objects (sets, lists, dicts, etc.) when passed as an arg to a function in Python?

A

The original reference is passed as argument, and can be changed by the function