Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Edge case: A helper collects items into a list using a default argument.
Edge case: A helper collects items into a list using a default argument.
def collect(x, out=[]):
out.append(x)
return out
a = collect(1)
b = collect(2, [])
c = collect(3)
print(a, b, c)What is printed?- A. [1] [2] [3]
- B. [1, 3] [2] [1, 3]
- C. [1] [2] [1, 3]
- D. [1, 3] [2] [3]
Correct answer: B. [1, 3] [2] [1, 3]
The default list is created once, when the function is defined, so the first and third calls share it: a and c are the same object, which holds [1, 3] by the time it is printed. The second call passes its own fresh list. Use out=None and create the list inside to avoid the bug.
More Coding Interview Problems questions
- Problem: n servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined…
- Problem: Task IDs 0..5 with dependencies u → v (u before v). The scheduler always runs the SMALLEST available ID next. python import heapq…
- Problem: Dijkstra with a lazy binary heap: outdated heap entries are skipped when popped. Report the distance to node 4 and how many stale…
- Problem: Longest increasing subsequence in O(n log n) with a 'tails' array (tails[i] = smallest possible tail of an increasing subsequence…
- Problem: Return the length of the shortest string that contains both a and b as subsequences. python def scs(a, b): m, n = len(a), len(b)…
- Problem: The reflected binary Gray code of i is i ^ (i >> 1). At which position of the 3-bit Gray sequence does the code 6 (110) appear?…