Problem Description
Given an array arr of n non-empty strings, for each string find the shortest substring that does not occur as a substring in any other string in arr. If multiple such substrings exist, choose the lexicographically smallest one. If no such substring exists for a string, return an empty string for that position.
Key Insights
- Generate all possible substrings for each string.
- Process substrings in order of increasing length and lexicographical order.
- For each candidate substring, check against all other strings for occurrence.
- Use early stopping once a valid substring is found.
- Although a Trie may optimize substring lookups, brute-force checking is practical given the small maximum string length (20) and array size (<=100).
Space and Time Complexity
Time Complexity: O(n * L^3) where L is the average string length (O(L^2) substrings per string and O(L) check for each substring). Space Complexity: O(n * L^2) if storing all substrings, though it can be optimized by generating substrings on the fly.
Solution
For each string in the array:
- Generate all possible substrings.
- Sort these substrings first by length and then lexicographically.
- For each substring, check if it appears in any other string within the array.
- Return the first valid substring found. If none exists, return an empty string.
This approach leverages the manageable constraint sizes with a straightforward brute-force method.