Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
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?
- A. O(n) – both are O(1)
- B. O(n log n) – amortised doubling
- C. O(n²) – both operations are O(n) each time (shifting elements / copying the string)
- D. O(n) – only the Java part is O(n)
Correct answer: C. O(n²) – both operations are O(n) each time (shifting elements / copying the string)
pop(0) shifts every remaining element left; immutable Java strings make += copy the whole string. Use collections.deque.popleft() and StringBuilder for O(1) amortised steps and an O(n) loop.
More Coding Interview Problems questions
- 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…
- 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…