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?
  1. A. ['9', '10', '25', '100'] ['9', '10', '25', '100']
  2. B. ['100', '10', '25', '9'] ['9', '10', '25', '100']
  3. C. ['10', '100', '25', '9'] ['9', '10', '25', '100']
  4. 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

Exams that ask this topic