Skip to main content

Command Palette

Search for a command to run...

Maximum Number of Non-Overlapping Substrings | Java Solution | Greedy

Updated
3 min readView as Markdown
S

Ex Full Stack Developer at @WiseBoxs | Vue React Node | MERN

Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions:

  1. The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true.

  2. A substring that contains a certain character c must also contain all occurrences of c.

Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.

Notice that you can return the substrings in any order.

Example 1:

Input: s = "adefaddaccc"
Output: ["e","f","ccc"]
Explanation: The following are all the possible substrings that meet the conditions:
[
  "adefaddaccc"
  "adefadda",
  "ef",
  "e",
  "f",
  "ccc",
]
If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist.

Example 2:

Input: s = "abbaccd"
Output: ["d","bb","cc"]
Explanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.

Constraints:

  • 1 <= s.length <= 105

  • s contains only lowercase English letters.

Code

class Solution {
    public List<String> maxNumOfSubstrings(String s) {
        int n = s.length();
        int[] firstIndex = new int[26];
        int[] lastIndex = new int[26];
        Arrays.fill(firstIndex, -1);
        Arrays.fill(lastIndex, -1);
        List<String> ans = new ArrayList<>();

        for(int i=0; i<n; i++){
            char c = s.charAt(i);
            int index = c - 'a';
            if(firstIndex[index]==-1){
                firstIndex[index] = i;
            }

            lastIndex[index] = i;
        }

        ArrayList<int[]> intervals = new ArrayList<>();

        for(int c=0; c<26; c++){
            //check char exists in string or not
            if(firstIndex[c]==-1){
                continue;
            }

            int left = firstIndex[c];
            int right = lastIndex[c];
            
            //check all of other characters occurances between the range

            boolean isValid = true;

            for(int i=left; i<right; i++){
                int charIndex = s.charAt(i) - 'a';

                if(firstIndex[charIndex]<left){
                    isValid = false;
                    break;
                }

                right = Math.max(lastIndex[charIndex], right);
            }

            //I got the valid right range

            // add the range 
            if(isValid==true){
                intervals.add(new int[]{left, right});
            }
        }

        //sort the intervals on the end basis

        intervals.sort((a, b) -> Integer.compare(a[1], b[1]));
        
        int previousIndex = -1;

        for(int[] interval: intervals){

            int left = interval[0];
            int right = interval[1];
            if(left>previousIndex){
                String subStr = s.substring(left, right+1);
                ans.add(subStr);
                previousIndex = right;
            }

        }

        return ans;
    }
}

Time Complexity : O(n)