Skip to content

ORIGINAL CODING QUESTION

Shortest distinguishing code prefixes

For each code in a list, find the shortest prefix of it that no OTHER code in the list starts with. When no such prefix exists (the code duplicates another code, or is itself the start of a longer code), use the full code length instead. Return the sum of the chosen lengths over all codes.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n codes. Each word is written as its length L followed by its L tokens.

Constraints

1 ≤ n ≤ 50; 1 ≤ L ≤ 20; every token is an integer in [1,26].

Example 1

Input

3 3 1 2 3 3 1 4 5 2 6 6

Output

5

Codes (1,2,3) and (1,4,5) need two tokens each and (6,6) needs one, totalling 5.

Example 2

Input

3 2 4 4 3 4 4 1 2 4 4

Output

7

Both copies of (4,4) fall back to length 2, and (4,4,1) needs all 3 tokens, totalling 7.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

A prefix is distinguishing when exactly one code, this one, passes through it.

Hint 2

Store pass counts in each trie node while inserting.

Hint 3

Walk each code down the trie and stop at the first node with pass count 1; fall back to its full length.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →