Shortest Uncommon Substring in an Array
Problem
You are given an array of strings arr.
For each string arr[i], you must find its shortest distinguishing substring: the shortest non-empty substring of arr[i] that does not appear as a substring of any other string in arr (that is, of arr[j] for every j != i). Occurrences within arr[i] itself do not disqualify a substring — only appearances inside the other strings matter.
Among all substrings of arr[i] that satisfy this uniqueness condition, pick the shortest one. If several substrings share that minimal length, pick the lexicographically smallest among them. If no substring of arr[i] is unique to it (every possible substring also occurs in some other string), the answer for that index is the empty string "".
Return an array answer where answer[i] is the shortest distinguishing substring for arr[i], following the rules above.
Examples
Example 1:
Input: arr = ["cab", "ad", "bad"]
Output: ["c","","ba"]
Explanation:
"cab"contains letterc, which never appears in"ad"or"bad", so the shortest distinguishing substring is"c".- Every substring of
"ad"(a,d,ad) also appears inside"bad", so no distinguishing substring exists and the answer is"". - For
"bad", single lettersb,a,dall appear in"cab"or"ad", but"ba"appears in neither of the other strings, giving"ba".
Example 2:
Input: arr = ["aaa", "aa", "a"]
Output: ["aaa","",""]
Explanation:
- Substrings of
"aaa"area,aa,aaa; bothaandaaoccur inside"aa"or"a", butaaadoes not, so the answer is"aaa". - All substrings of
"aa"(a,aa) occur inside"aaa", so there is no distinguishing substring. - The only substring of
"a"isa, which also occurs in"aaa"and"aa", so the answer is"".
Example 3:
Input: arr = ["xy", "yz", "zx"]
Output: ["xy","yz","zx"]
Explanation:
Each two-letter string uses a letter pair that never occurs together in either of the other two strings, so each whole string is already its own shortest distinguishing substring.
Constraints
2 <= arr.length <= 1001 <= arr[i].length <= 20arr[i]consists of lowercase English letters only.
Solution
Sign in to get AI feedback on your answer. Your work is saved while you do.
Sign in to evaluate