Taro Logo

Partition Labels

#199 Most AskedMedium
0 views
Topics:
ArraysStringsGreedy Algorithms

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


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the input string, and does it contain only standard lowercase English letters?
  2. How should the function behave if the input string is empty or null?
  3. Are the partitions required to be contiguous substrings of the original string, and does their concatenation need to equal the original string?
  4. Is it guaranteed that a valid partition always exists for any given input?
  5. What should be returned if every character in the string is distinct versus if all characters are identical?

Brute Force Solution

Approach

Imagine you have a long sequence of colored beads and you want to chop it into the shortest possible segments so that no color appears in more than one segment. The brute force approach involves testing every single place you could possibly make a cut to see if it successfully traps all matching colors within their respective pieces.

Here's how the algorithm would work step-by-step:

  1. Start near the beginning of the sequence and imagine making your first cut right after the first item.
  2. Look at all the items in that newly created first piece and search the rest of the entire sequence to see if any of those exact same items show up further down the line.
  3. If you find even one matching item hiding outside your piece, that means your chosen cut was invalid because the color spilled over into another section.
  4. Because the cut failed, slide your chopping point one spot to the right to make the first piece slightly longer, and check again for any escaping colors.
  5. Keep sliding the cut one spot at a time until you reach a point where absolutely none of the items inside your current piece ever appear again anywhere to the right.
  6. Once you finally find a safe cut where all colors are securely contained, measure the length of that completed piece and remember it.
  7. Pick up where that piece ended and repeat the exact same exhaustive guessing process for the remaining sequence, piece by piece, until the entire string of items is successfully chopped up.

Code Implementation

def partition_labels(string_sequence):
    partition_sizes = []
    current_index = 0
    
    while current_index < len(string_sequence):
        end_index = current_index
        check_index = current_index
        
        # We expand the boundary whenever we encounter a character that appears later in the string
        while check_index <= end_index:
            target_character = string_sequence[check_index]
            last_seen_position = string_sequence.rfind(target_character)
            
            if last_seen_position > end_index:
                end_index = last_seen_position
                
            check_index += 1
            
        # Once no characters in our segment appear outside of it, we record the partition length
        partition_length = (end_index - current_index) + 1
        partition_sizes.append(partition_length)
        current_index = end_index + 1
        
    return partition_sizes

Big(O) Analysis

Time Complexity
O(n²) – For each potential cut position as we scan through the n characters of the string, we may need to look at the remaining sequence to check if any colors spill over. In the worst-case scenario where each segment is tested repeatedly or grows by one character at a time, we scan the remaining tail of length approximately n, n-1, n-2, down to 1. This exhaustive guessing and searching leads to approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(1) – The auxiliary space is constant because the algorithm uses a fixed-size tracking mechanism to store the last seen positions of characters, which only depends on the limited alphabet size of lowercase English letters. As the input string length N grows, no additional data structures that scale with N are created. The output list tracking segment lengths uses at most N space in the worst case, but this is typically considered part of the return value rather than auxiliary working memory. Therefore, the extra memory used beyond the input remains strictly bounded regardless of how large N becomes.

Optimal Solution

Approach

The optimal strategy works by looking ahead to find the absolute last time each letter appears in the message. Armed with this knowledge, we can slice the message into the maximum number of independent chunks where no letter appears in more than one chunk.

Here's how the algorithm would work step-by-step:

  1. Scan through the entire message from start to finish and record the very last position where every single letter shows up.
  2. Return to the very beginning of the message to start forming our first chunk.
  3. As you read through the letters of the current chunk, keep track of the furthest required stopping point dictated by the last appearance of any letter you have seen so far.
  4. Continue expanding the boundary of the current chunk whenever you encounter a letter that needs to be seen later than your current boundary.
  5. Stop expanding and finalize the chunk the moment your reading position catches up to that furthest required stopping point.
  6. Take the length of this completed chunk and set it aside as one of our segment sizes.
  7. Immediately pick up right where the previous chunk ended and repeat the entire expansion process to find the next independent segment until the entire message is fully partitioned.

Code Implementation

def partition_labels(message_string):
    last_occurrence_map = {}

    # Record the final index of every character to know how far each partition must extend.
    for index, character in enumerate(message_string):
        last_occurrence_map[character] = index

    partition_sizes_list = []
    current_partition_start = 0
    furthest_required_stop = 0

    for index, character in enumerate(message_string):
        # Expand the boundary if the current character appears later in the message string.
        if last_occurrence_map[character] > furthest_required_stop:
            furthest_required_stop = last_occurrence_map[character]

        # Finalize the partition when our scanning position reaches the required stopping boundary.
        if index == furthest_required_stop:
            partition_length = furthest_required_stop - current_partition_start + 1
            partition_sizes_list.append(partition_length)
            current_partition_start = index + 1

    return partition_sizes_list

Big(O) Analysis

Time Complexity
O(n) – First, we iterate through the entire message of size n to record the last occurrence position of every character in a hash map or array. Next, we iterate through the message a second time to dynamically expand and finalize our chunk boundaries. Since these two passes run sequentially rather than nested, the total operations scale linearly as roughly 2n, which simplifies to O(n).
Space Complexity
O(1) – To determine the last position of each letter as described in step 1, the algorithm utilizes a fixed-size auxiliary array or hash map to store the maximum index for the 26 lowercase English letters. Because the alphabet size is constant and does not scale with the input message length N, this tracking structure requires a constant amount of extra memory. The pointer variables used to track chunk boundaries and segment sizes require only a few units of primitive memory regardless of how large the input string becomes. Therefore, the auxiliary space complexity remains strictly constant at O(1).

Edge Cases

Empty string input
How to Handle:
Return an empty list immediately because no partitions can be formed from a zero-length string.
String with a single character
How to Handle:
Return a list containing the integer 1 since the single character forms a partition of size one.
String with all identical characters like aaaaa
How to Handle:
Return a list containing the total length of the string because all occurrences must fall within a single partition.
String with all unique characters like abcde
How to Handle:
Return a list of ones matching the string length because each character can be partitioned independently.
Maximum length constraints up to the problem limit
How to Handle:
Use a single-pass frequency pre-computation and a linear greedy scan to ensure optimal O(n) time complexity and prevent timeouts.
Alternating characters like ababcbacadefegde
How to Handle:
Extend the current partition boundary dynamically using the last occurrence index until the pointer catches up to the max boundary.
String containing uppercase letters or mixed types
How to Handle:
Assuming standard lowercase English per constraints, but if mixed, sanitize or map characters using a sized array of 26 or a hash map.
Memory limits during large string processing
How to Handle:
Store only the last seen indices in a fixed-size array of 26 integers to maintain O(1) auxiliary space complexity.
0/257 completed