Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: A recursive function on n does O(1) work and makes two calls on n/2. What is T(n)?
- A. O(log n)
- B. O(n) – T(n) = 2T(n/2) + O(1)
- C. O(n log n)
- D. O(2ⁿ)
Correct answer: B. O(n) – T(n) = 2T(n/2) + O(1)
Master theorem: a = 2, b = 2, n^(log_b a) = n, and f(n) = O(1) is polynomially smaller, so T(n) = Θ(n). The tree has about 2n nodes each doing constant work. O(n log n) needs O(n) work per level, as in merge sort.
More Coding Interview Problems questions
- Problem: Inside a loop of n iterations, the code calls Python's list.pop(0) and Java's String +=. What is the real complexity of the loop?
- Problem: For n = 10⁶ distinct integers up to 10⁹, find the smallest positive integer missing from the array in O(n) time and O(1) extra…
- Problem: Find the smallest missing positive integer using cyclic placement. python def firstmissing(a): n = len(a) for i in range(n)…
- Problem: Binary search for x in a sorted int array (C++): cpp int lo = 0, hi = n - 1; while (lo <= hi) { int mid = (lo + hi) / 2; // line…
- Problem: Kadane's algorithm (Java): java int best = 0, cur = 0; // line 1 for (int x : a) { cur = Math.max(x, cur + x); // line 3 best =…
- Problem: BFS shortest path on a grid (Python): python q = deque([start]); dist = {start: 0} while q: u = q.popleft() for v in…