Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Find the bug: version numbers stored as strings are sorted to find the smallest. What does each sort produce?
Problem: Find the bug: version numbers stored as strings are sorted to find the smallest. What does each sort produce?
print(sorted(["10", "9", "100", "25"]), sorted(["10", "9", "100", "25"], key=int))What is printed?
- A. ['9', '10', '25', '100'] ['9', '10', '25', '100']
- B. ['100', '10', '25', '9'] ['9', '10', '25', '100']
- C. ['10', '100', '25', '9'] ['9', '10', '25', '100']
- D. ['10', '100', '25', '9'] ['10', '100', '25', '9']
Correct answer: C. ['10', '100', '25', '9'] ['9', '10', '25', '100']
Strings compare character by character, so "100" < "25" < "9" ('1' < '2' < '9') and "10" < "100" (prefix). Numeric order needs key=int (or storing ints). This lexicographic-vs-numeric mix-up is a common silent bug when reading input with split(). O(n log n) either way.
More Coding Interview Problems questions
- Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024? python def cnt(n): c = 0 for i in…
- Problem: Find the bug: a backtracking routine collects all subsets of [1, 2]. python def subsets(a): res, path = [], [] def bt(i): if i ==…
- Problem: Find the bug: a range-sum helper over a prefix array (pre[0] = 0, pre[i] = sum of the first i values) should return a[l] + … +…
- Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas. python fs = [lambda x: x i for i in range(1, 4)] gs…
- Problem: Find the bug: even values are removed from a list while iterating over that same list. python nums = [2, 4, 4, 6, 5, 8] for x in…
- 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…