Skip to content

768. Partition Labels

Difficulty: Medium

LeetCode Problem View on GitHub


768. Partition Labels

Medium


You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string "ababcc" can be partitioned into ["abab", "cc"], but partitions such as ["aba", "bcc"] or ["ab", "ab", "cc"] are invalid.

Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.

Return a list of integers representing the size of these parts.

 

Example 1:

Input: s = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.

Example 2:

Input: s = "eccbbbbdec"
Output: [10]

 

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

Solution

class Solution {
    public  List<Integer> partitionLabels(String s) {
        int n = s.length();
        List<Integer> res = new ArrayList<>();
        int first[] = new int[30];
        int last[] = new int[30];
        Arrays.fill(first, -1); Arrays.fill(last, -1);
        for(int i = 0; i < n; i++) {
            if(first[s.charAt(i) - 'a'] == -1) first[s.charAt(i) - 'a'] = i;
            else last[s.charAt(i) - 'a'] = i;
        }
        for(int i = n - 1; i >= 0; i--) {
            if(last[s.charAt(i) - 'a'] == -1) last[s.charAt(i) - 'a'] = i;
        }
        int start = 0;
        while(true) {
            int j = last[s.charAt(start) - 'a'];
            int lastj = start;
            while(start < j) {
                start++;
                j = Math.max(j , last[s.charAt(start) - 'a']);
            }
            res.add(j - lastj + 1);
            start = j + 1;
            if(start >= n) break;
        }
        return res;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here