Bracket the Shortest Exclusive Fragment in Every Menu Entry
StringsAuto-graded · 21 test casesLast 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
- Pick the shortest exclusive fragment.
- If several exclusive fragments share that shortest length, pick the one that starts earliest in the entry.
- Exclusivity is checked case-insensitively, but the returned string must keep the original letter casing of the entry. Only the brackets are added.
- 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) <= 1001 <= len(entry) <= 50for 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A fragment is exclusive to entry i exactly when entry i is the only entry that contains it (ignoring case). So we work in two passes.
- Build an ownership index. Lowercase each entry and enumerate its distinct substrings. For each substring, keep a bitmask of the entries that contain it (
owners[sub] |= 1 << i). A per-entryseenset ensures each entry contributes once per substring. - Search in tie-break order. For entry
i, loop over lengths1..L, and for each length over start positions from left to right. The first substring whose mask equals exactly1 << iis the answer. This loop order enforces "shortest first, then earliest start" with no extra comparison logic. - Insert the brackets into the original (not lowercased) string at the found indices. Lowercasing does not change string length or positions for the allowed characters, so casing is preserved.
If no substring qualifies, the entry is returned unchanged.
Why it is correct
owners[sub] == 1 << imeans entryicontainssuband no other entry does, which is the definition of exclusive.- All substrings of a given length are examined before any longer one, and starts are scanned in increasing order, so the first hit is the shortest and, among those, the leftmost.
- When an entry is contained in another one (or duplicates one ignoring case), even its full text is owned by at least two entries, so nothing is found and it stays unchanged.
Complexity
Let N be the number of entries and L the maximum entry length.
- Time:
O(N * L^3), since there areO(L^2)substrings per entry and each slice/hash costsO(L). WithN = 100,L = 50this is small. - Space:
O(N * L^3)characters for the dictionary keys, plus up toN-bit masks per key.
Reference solution
from typing import List
def bracket_exclusive_fragments(entries: List[str]) -> List[str]:
owners = {} # lowercase substring -> bitmask of entries containing it
for i, entry in enumerate(entries):
text = entry.lower()
seen = set()
for start in range(len(text)):
for end in range(start + 1, len(text) + 1):
sub = text[start:end]
if sub not in seen:
seen.add(sub)
owners[sub] = owners.get(sub, 0) | (1 << i)
result = []
for i, entry in enumerate(entries):
text = entry.lower()
chosen = None
for length in range(1, len(text) + 1):
for start in range(0, len(text) - length + 1):
sub = text[start:start + length]
if owners.get(sub, 0) == (1 << i):
chosen = (start, start + length)
break
if chosen is not None:
break
if chosen is None:
result.append(entry)
else:
s, e = chosen
result.append(entry[:s] + "[" + entry[s:e] + "]" + entry[e:])
return result