Data Structures & AlgorithmsVery hard
For the 'largest number from concatenation' problem, why does the comparator compare x+y with y+x as strings?
- A. It sorts the numbers by their numeric value.
- B. It removes leading zeros.
- C. It makes all numbers the same length.
- D. It decides which of two numbers should come first in the final string, since the string order is what the answer depends on.
Correct answer: D. It decides which of two numbers should come first in the final string, since the string order is what the answer depends on.
Two numbers placed adjacent produce either xy or yx; putting x first is better exactly when x+y > y+x as strings. A comparator with this rule yields the optimal total order.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- When choosing non-adjacent positions to maximise a sum, why does the DP keep two states per position?
- Why does the lexicographically largest subsequence after deleting k digits come from a greedy stack?
- In a sliding window tracking the maximum number of vowels among windows of fixed length 3, why is O(1) update per step possible?
- Why does a circular window of length 3 require index arithmetic modulo n?
- Why is the number of Dyck-word stack sequences with n pushes and n pops equal to a Catalan number?
- A deque-based minimum of each sliding window runs in linear time because: