Given a string s, return every distinct substring of s.
A substring is a contiguous, non-empty sequence of characters within the string. A substring that occurs at several positions appears only once in the result. Return the result as a list of strings.
Function Signature
def unique_substrings(s: str) -> list[str]:
...
Rules
-
Return the substrings sorted in ascending lexicographic order (Python's default string order). A string that is a prefix of a longer string comes before it, so
"a"
precedes
"aa"
, which precedes
"ab"
.
-
Each distinct substring appears exactly once. The empty string is not included.
Constraints
-
1 <= len(s) <= 100
-
s
consists of lowercase English letters.
Examples
Input: s = "abc"
Output: ["a", "ab", "abc", "b", "bc", "c"]
The six substrings "a", "b", "c", "ab", "bc" and "abc" are all different, so all six are returned in sorted order.
Input: s = "aab"
Output: ["a", "aa", "aab", "ab", "b"]
The substrings are "a", "a", "b", "aa", "ab" and "aab". The two copies of "a" collapse into one, which leaves 5 distinct substrings.
Input: s = "abab"
Output: ["a", "ab", "aba", "abab", "b", "ba", "bab"]
By length there are 2 distinct substrings of length 1 ("a", "b"), 2 of length 2 ("ab", "ba"), 2 of length 3 ("aba", "bab") and 1 of length 4, for 7 in total.