10. Split a String Into the Max Number of Unique Substrings

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.

Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.

Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].


Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.

Solution: (Backtracking)

Approach: Try each possible split and check the max

class Solution
{
public:
    void split(string s, int count, int &maxCount, unordered_set<string> st)
    {
        
        int n = s.length();
        if (n == 0)
        {
            maxCount = max(maxCount, count);
            return;
        }

        for (int i = 1; i <= n; i++)
        {
            string k = s.substr(0, i);
            string res = s.substr(i, n - i);

            if (st.find(k) == st.end())
            {
                st.insert(k);            
                split(res, count + 1, maxCount, st);
                st.erase(st.find(k));
            }
        }

        return;
    }

    int maxUniqueSplit(string s)
    {
        int maxCount = INT_MIN;
        unordered_set<string> st;
        split(s, 0, maxCount, st);
        return maxCount;
    }
};

Time Complexity: O(n !)

Last updated