Data Structures & AlgorithmsModerateTCS NQT · Python basics
Problem: What does the following print?
Problem: What does the following print?
ops = [('b', 2), ('a', 2), ('c', 1), ('d', 3)]
print([x for x, _ in sorted(ops, key=lambda t: -t[1])])- A. ['d', 'a', 'b', 'c']
- B. ['b', 'a', 'd', 'c']
- C. ['d', 'b', 'c', 'a']
- D. ['d', 'b', 'a', 'c']
Correct answer: D. ['d', 'b', 'a', 'c']
Python's sort is stable, so the two items with value 2 keep their original order b before a. Sorting by -value gives d (3), then b, a (2) and c (1).
More Coding Interview Problems questions
- Problem: Coins of values {1, 5, 6, 9} are available, unlimited copies each. What is the minimum number of coins needed to make exactly 11?
- Problem: In the O(n log n) longest increasing subsequence algorithm, the array tails[k] is maintained over the input. What does tails[k]…
- Problem: A dynamic array doubles its capacity whenever it is full and copies all elements. Which statement about n pushes is correct?
- Problem: How many ways are there to tile a 2 x 10 board completely with 2 x 1 dominoes (placed horizontally or vertically)?
- Array a = [1, -1, 2, 3, -2, 4, -3, 1]. How many contiguous non-empty subarrays have sum exactly 3? Solve it with running prefix sums and a…
- For a = [3, 4, -7, 2, -2, 5, -5, 1, 6], what is the length of the longest contiguous subarray whose elements sum to 0?