Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the smallest missing positive integer using cyclic placement.
Problem: Find the smallest missing positive integer using cyclic placement.
def first_missing(a):
n = len(a)
for i in range(n):
while 1 <= a[i] <= n and a[a[i] - 1] != a[i]:
j = a[i] - 1
a[i], a[j] = a[j], a[i]
for i in range(n):
if a[i] != i + 1: return i + 1
return n + 1
print(first_missing([3, 4, -1, 1]), first_missing([7, 8, 9]), first_missing([1, 2, 3]), first_missing([1, 1]))What is printed?- A. 2 1 3 2
- B. 2 10 4 2
- C. 2 1 4 1
- D. 2 1 4 2
Correct answer: D. 2 1 4 2
After placing every value v in 1..n at index v − 1, the first position not holding i + 1 is the answer. [1, 2, 3] → 4 (n + 1). The condition a[a[i] − 1] != a[i] (not a[i] != i + 1) stops infinite swapping on duplicates like [1, 1]. Note the swap order: j is computed before swapping. O(n), O(1).
More Coding Interview Problems questions
- 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] =…
- Problem: Reverse a singly linked list (C++): cpp Node prev = nullptr; while (head) { head->next = prev; // line 3 prev = head; head =…