Skip to content

763. Partition Labels

Medium LeetCode

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 valid partition, and each letter appears in at most one part.

Example 2:

Input: s = "eccbbbbdec"
Output: [10]
Explanation: The partition is ["eccbbbbdec"]. This is a valid partition, and each letter appears in at most one part.

Constraints:

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

How to solve the problem

  • Greedy
python
class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        start = 0
        end = 0
        last = {}
        result = []
        for c in range(len(s)):
            last[s[c]] = c

        for i in range(len(s)):
            end = max(end, last[s[i]])
            if end == i:
                result.append(end - start + 1)
                start = end + 1
        return result
java
class Solution {
    public List<Integer> partitionLabels(String s) {
        int start = 0;
        int end = 0;
        Map<Character, Integer> last = new HashMap<>();
        List<Integer> result = new ArrayList<>();
        
        for (int c = 0; c < s.length(); c++) {
            last.put(s.charAt(c), c);
        }
        
        for (int i = 0; i < s.length(); i++) {
            end = Math.max(end, last.get(s.charAt(i)));
            if (end == i) {
                result.add(end - start + 1);
                start = end + 1;
            }
        }
        return result;
    }
}

Complexity

  • Greedy: Time complexity: O(n), Space complexity: O(1) - Where n is the length of the string. We traverse the string twice and use constant extra space.

Comments

No comments yet. Be the first to comment!