Data Structures & AlgorithmsVery hard
What is the lexicographically smallest array of length n with positive integers and total sum S (S ≥ n)?
- A. S, 0, …, 0 with zeros replaced by ones
- B. S/n repeated n times
- C. 1, 1, …, 1, S − (n − 1)
- D. 1, 2, …, n with the last element adjusted
Correct answer: C. 1, 1, …, 1, S − (n − 1)
Lexicographic minimality puts 1s first, and the last element absorbs the remainder. Spreading the sum evenly makes the first element larger, which is lexicographically worse.
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
- In the 'minimum swaps to sort a permutation' problem, why is the answer n minus the number of cycles?
- Which statement about a monotonic deque for sliding-window minimum is correct?
- Why is prefix-sum counting of zero-sum subarrays unaffected by the choice of starting index for the prefix array?
- For the sum-at-most-K problem on a prefix-sum array with negative values, why does a balanced search structure appear in the solution?
- The shunting-yard algorithm converts the infix expression "a+bc^d^e-f^(gh)" to postfix, with ^ highest precedence and right-associative…
- What is the largest rectangular area in a histogram with bar heights 6, 2, 5, 4, 5, 1, 6 (each bar has width 1)?