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?

  1. A. O(n) – both are O(1)
  2. B. O(n log n) – amortised doubling
  3. C. O(n²) – both operations are O(n) each time (shifting elements / copying the string)
  4. 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

Exams that ask this topic