Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
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 space. Which technique achieves this?
- A. Cyclic placement: swap each value v in 1..n into index v − 1, then scan for the first index i with a[i] ≠ i + 1
- B. Sort, then scan – O(n) time
- C. Hash set of values – O(1) extra space
- D. Binary search on the answer – O(log n) total
Correct answer: A. Cyclic placement: swap each value v in 1..n into index v − 1, then scan for the first index i with a[i] ≠ i + 1
The answer lies in 1..n + 1, so values outside that range can be ignored, and each swap puts one value in its final slot – at most n swaps overall. Sorting is O(n log n); a hash set needs O(n) space; feasibility is not monotonic in a way binary search can test cheaply.
More Coding Interview Problems questions
- 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…
- Problem: Detect whether an undirected graph has a cycle with DFS: python def dfs(u): seen.add(u) for v in adj[u]: if v in seen: return…
- Problem: Climbing-stairs memoisation in Python: python def ways(n, memo={}): if n <= 1: return 1 if n in memo: return memo[n] memo[n] =…