Lexicographically Largest String From Repeated Pick-and-Discard-One-Side Moves
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: Starting from a lowercase string, repeatedly pick a character from the current interval, append it to an identifier, and keep only the left or right remainder. Return the lexicographically largest identifier possible. Tests careful reasoning about lexicographic order and reachable choices on inputs up to 100,000 characters.
Read the full Amazon Software Engineer interview experience this question came from
Constraints
- 1 <= len(key) <= 10^5
- key contains only lowercase English letters 'a' to 'z'.
Examples
Input: ('a',)
Expected Output: 'a'
Explanation: Minimum valid key: the single character is picked and the interval becomes empty.
Input: ('abc',)
Expected Output: 'cba'
Explanation: Source example 1, strictly increasing: every character is used, largest first.
Hints
- Identifiers are compared from their first character, so first ask which character can come first and how many times it can be repeated at the start.
- After a pick, every later pick lies on one side of it. Once several picks have been made, which stretch of the key can the remaining interval be?
- A longer string beats its own prefix, so compare candidate continuations in full, not only by their first letter or by their length.