Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Find the bug: even values are removed from a list while iterating over that same list.
Problem: Find the bug: even values are removed from a list while iterating over that same list.
nums = [2, 4, 4, 6, 5, 8]
for x in nums:
if x % 2 == 0:
nums.remove(x)
print(nums, [x for x in [2, 4, 4, 6, 5, 8] if x % 2])What is printed?- A. [4, 4, 6, 5] [5]
- B. [4, 6, 5] [5]
- C. [6, 5] [5]
- D. [5] [5]
Correct answer: B. [4, 6, 5] [5]
The for loop walks by index while remove() shifts later elements left, so the element after each removed one is skipped. Index 0: remove 2 → [4, 4, 6, 5, 8]; index 1 is now the second 4 → remove (the first 4) → [4, 6, 5, 8]; index 2 is 5; index 3 is 8 → remove → [4, 6, 5]. Build a new list (comprehension) or iterate over a copy. remove() is also O(n) per call.
More Coding Interview Problems questions
- Problem: n ≤ 2·10⁵ values; count pairs i < j with (a[i] + a[j]) divisible by k. The O(n²) check times out; bucket by remainder and pair…
- Problem: A divide-and-conquer routine makes 3 recursive calls on halves and does linear extra work: T(n) = 3T(n/2) + n. The code evaluates…
- Problem: A sliding-window routine has a while loop nested inside a for loop. For a 12 000-character string, how many inner (left-pointer)…
- Problem: Find the inefficiency: two BFS versions on an R × C open grid. One marks a cell visited when it is pushed, the other only when it…
- Problem: Find the bug: binary search for the LAST x in [lo, hi] with ok(x) true (here the largest x with x² ≤ 30). The first version uses…
- Problem: n ≤ 2·10⁵ meetings [s, e); choose the maximum number of non-overlapping ones. Compare three greedy orders: by end time, by start…