Split a String Into the Max Number of Unique Substrings - Problem

Given a string s, return the maximum number of unique substrings that the given string can be split into.

You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.

A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "ababccc"
Output: 5
💡 Note: One optimal split: ["a", "b", "ab", "c", "cc"] - all 5 substrings are unique
Example 2 — Short String
$ Input: s = "aba"
Output: 2
💡 Note: Best split: ["ab", "a"] - 2 unique substrings (better than ["a", "ba"] which also gives 2)
Example 3 — All Same Characters
$ Input: s = "aa"
Output: 1
💡 Note: Only one way: ["aa"] - cannot split into ["a", "a"] as both substrings would be identical

Constraints

  • 1 ≤ s.length ≤ 16
  • s contains only lowercase English letters

Visualization

Tap to expand
Split String Into Max Unique Substrings INPUT String s = "ababccc" a b a b c c c 0 1 2 3 4 5 6 Goal: Split into maximum unique substrings HashSet (to track unique) { } Initially empty Input: s = "ababccc" ALGORITHM STEPS 1 Backtracking Setup Use HashSet to store substrings 2 Try All Splits At each position, try different substring lengths 3 Check Uniqueness If substring not in HashSet, add it and recurse 4 Track Maximum Update max count when reaching end of string Optimal Split Found: a b ab c cc "a" + "b" + "ab" + "c" + "cc" FINAL RESULT Maximum Unique Substrings: 5 Final HashSet: "a" "b" "ab" "c" "cc" 5 unique substrings Output: 5 OK Key Insight: Use backtracking with a HashSet to explore all possible ways to split the string. At each position, try all possible substring lengths. The HashSet ensures O(1) lookup for checking uniqueness. Time Complexity: O(2^n) in worst case, Space: O(n) for recursion stack and HashSet. TutorialsPoint - Split a String Into the Max Number of Unique Substrings | Hash + Backtracking Approach
Asked in
Google 15 Amazon 12
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen