Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Orders (name, priority) are sorted by priority only, using Python's sorted with a key.

Problem: Orders (name, priority) are sorted by priority only, using Python's sorted with a key.
orders = [("ravi", 3), ("asha", 1), ("john", 3), ("mei", 2), ("ola", 1)]
print([n for n, p in sorted(orders, key=lambda t: t[1])])
What is printed?
  1. A. ['asha', 'ola', 'mei', 'john', 'ravi']
  2. B. ['ola', 'asha', 'mei', 'john', 'ravi']
  3. C. ['asha', 'ola', 'mei', 'ravi', 'john']
  4. D. ['ravi', 'john', 'mei', 'asha', 'ola']

Correct answer: C. ['asha', 'ola', 'mei', 'ravi', 'john']

Python's sort (Timsort) is stable: records with equal keys keep their original relative order. Priority 1: asha before ola; priority 3: ravi before john, exactly as in the input. Alphabetical tie-breaking would need key=(p, name). O(n log n).

More Coding Interview Problems questions

Exams that ask this topic