Post

LC 763 - Partition Labels

LC 763 - Partition Labels

Question

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:

1
2
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:

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

Constraints:

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

Question here and solution here

Solution

concept

first build a hash map to store the last index of each char in s then we iterate through s, for each char we update the end index of the current partition (imagine there is a boundary indicating the partition, but this boundary gets pushed back if there exist a char whose last index is beyond this current boundary, so this boundary has to be pushed back, to ensure all char within the current partition is included.) this is to make sure all char so far in the current partition are all included in the current partition

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        # key: char
        # val: last index of char appeared in s
        hash_map = {}
        for i, char in enumerate(s):
            hash_map[char] = i

        result = []
        # size of current partition
        curr_size = 0
        # the end index of current partition
        curr_end = 0
        for i, char in enumerate(s):
            curr_size += 1
            curr_end = max(curr_end, hash_map[char])

            if i == curr_end:
                result.append(curr_size)
                # no need reset curr_end since the max func will update in the start of the next partition
                curr_size = 0

        return result

Complexity

time: $O(n)$
space: $O(1)$

This post is licensed under CC BY 4.0 by the author.