Shortest Uncommon Substring in an Array Problem
#3076
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3076.
You are given an array arr of size n consisting of non-empty strings.
Find a string array answer of size n such that:
answer[i]is the shortest substring ofarr[i]that does not occur as a substring in any other string inarr. If multiple such substrings exist,answer[i]should be the lexicographically smallest. And if no such substring exists,answer[i]should be an empty string.
Return the array answer.
Example 1:
Input: arr = ["cab","ad","bad","c"]
Output: ["ab","","ba",""]
Explanation: We have the following:
- For the string "cab", the shortest substring that does not occur in any other string is either "ca" or "ab", we choose the lexicographically smaller substring, which is "ab".
- For the string "ad", there is no substring that does not occur in any other string.
- For the string "bad", the shortest substring that does not occur in any other string is "ba".
- For the string "c", there is no substring that does not occur in any other string.
Example 2:
Input: arr = ["abc","bcd","abcd"]
Output: ["","","abcd"]
Explanation: We have the following:
- For the string "abc", there is no substring that does not occur in any other string.
- For the string "bcd", there is no substring that does not occur in any other string.
- For the string "abcd", the shortest substring that does not occur in any other string is "abcd".
Constraints:
n == arr.length2 <= n <= 1001 <= arr[i].length <= 20arr[i]consists only of lowercase English letters.
Solution
Approach: Enumeration
The limits are small, so we try every substring. For each string, go through the substring lengths from short to long and, for each length, every start position. A substring is accepted when no other string contains it; among accepted substrings of the same length keep the lexicographically smallest. Stop at the first length that has one.
Complexity: O(n^2 m^4) time and O(m) extra space, where n is the number of strings and m <= 20 is the maximum length.
class Solution:
def shortestSubstrings(self, arr: List[str]) -> List[str]:
ans = [""] * len(arr)
for i, s in enumerate(arr):
m = len(s)
for j in range(1, m + 1):
for l in range(m - j + 1):
sub = s[l : l + j]
if not ans[i] or ans[i] > sub:
if all(k == i or sub not in t for k, t in enumerate(arr)):
ans[i] = sub
if ans[i]:
break
return ans