Exchange Alphabet Leaders
Find strings that can rank first under a reordered alphabet
A stock exchange is configuring the display order of its instrument codes. Each code contains lowercase English letters.
The exchange may choose any permutation of the 26 lowercase letters as its alphabet order. Codes are then compared lexicographically using that order:
- At the first position where two codes differ, the code whose letter comes earlier in the chosen alphabet is smaller.
- If one code is a proper prefix of another, the shorter code is always smaller, regardless of the alphabet order.
- Identical codes are tied.
Given the list codes, return the zero-based indices, in increasing order, of all codes that can be tied for smallest in the entire list under some alphabet order.
Each candidate is considered independently: different returned indices may require different alphabet orders. Duplicate codes remain separate entries.
Examples
Example 1
Input: codes = ["ab","ba","aa"] Output: [1,2]
For `ab` to precede `ba`, the letter a must precede b. But for `ab` to precede `aa`, b must precede a, so that candidate is impossible. Each of the other two candidates admits a consistent alphabet order.
Example 2
Input: codes = ["arc","ar","boat","ar"] Output: [1,2,3]
The code `arc` can never lead because `ar` is its proper prefix. Either occurrence of `ar` can tie for first when a precedes b. The code `boat` can lead when b precedes a.
Example 3
Input: codes = ["zen","zen","zen"] Output: [0,1,2]
All entries are identical, so every entry is tied for smallest under every alphabet order.
Constraints
- 1 <= codes.length <= 100000
- 1 <= codes[i].length <= 30
- The sum of all code lengths is at most 200000
- Each code contains only lowercase English letters
- Duplicate codes are allowed
Let S be the total code length, n the number of codes, and A = 26. The reference solution uses O(AS + A^2n) time and O(S + A^2) auxiliary space. Since the alphabet is fixed, both bounds are linear in the input size up to fixed alphabet factors.
Hints
Show hint 1Hint 1
For one candidate, only the first differing letter against each rival matters. A trie groups rivals that impose the same comparison.
Show hint 2Hint 2
At each node on the candidate's trie path, its chosen letter must precede every sibling letter. These requirements describe a directed graph; determine when an alphabet permutation can satisfy it.
Follow-up questions
What an interviewer might ask once you have a working solution.
- For each feasible candidate, how would you construct the lexicographically smallest alphabet permutation that makes it a leader?
- How would the algorithm change if some letter-order requirements were supplied in advance?
Practice this with an AI interviewer
Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.
Start this problem