KatInterview

Bracket the Shortest Exclusive Fragment in Every Menu Entry

StringsAuto-graded · 21 test cases
MediumAuto-gradedStringsstringshash-mapsubstrings

Last updated

Find, for each string, its shortest substring that occurs in no other string (case-insensitive), with leftmost tie-break, and wrap it in brackets while keeping original casing.

Bracket the Shortest Exclusive Fragment

A menu shows a list of entry names. To let users jump to an entry by typing a short fragment, each entry must have a highlighted fragment that identifies it and no other entry.

You are given a list of strings entries. Return a new list in which, for each entry, one fragment has been wrapped in square brackets [ and ].

Definitions

A fragment of entries[i] is a contiguous run of characters (a substring). It is exclusive to entries[i] if its lowercase form does not occur as a substring of the lowercase form of any other entry entries[j] with j != i.

Rules for each entry

  1. Pick the shortest exclusive fragment.
  2. If several exclusive fragments share that shortest length, pick the one that starts earliest in the entry.
  3. Exclusivity is checked case-insensitively, but the returned string must keep the original letter casing of the entry. Only the brackets are added.
  4. If the entry has no exclusive fragment, return it unchanged.

Each entry is handled independently, and the output list has the same length and order as the input.

Notes

  • Two entries that are equal ignoring case, or an entry that is contained in another entry (ignoring case), have no exclusive fragment, so the contained or duplicated entry is left unchanged.
  • Spaces and digits are ordinary characters and may be part of a fragment.

Constraints

  • 1 <= len(entries) <= 100
  • 1 <= len(entry) <= 50 for every entry
  • Entries consist of English letters, digits, and spaces.

Examples

Example 1

Input: bracket_exclusive_fragments(['apple', 'banana', 'cat'])

Output: ['a[p]ple', '[b]anana', '[c]at']

Example 2

Input: bracket_exclusive_fragments(['pull', 'push', 'pullet'])

Output: ['pull', 'pu[s]h', 'pull[e]t']

Example 3

Input: bracket_exclusive_fragments(['File', 'FILTER'])

Output: ['Fi[le]', 'FIL[T]ER']

Hints

Hint 1

For a fragment to be exclusive to entry i, entry i must be the only entry containing it. Think about precomputing, for every lowercase substring, which entries contain it.

Hint 2

Build a dictionary from lowercase substring to the set (or bitmask) of entry indices that contain it. Count each entry only once per distinct substring.

Hint 3

For each entry, scan lengths 1, 2, ... and within each length scan start positions left to right; the first fragment owned only by this entry is the answer. Use the found indices on the original-case string to insert the brackets.