KatInterview

768. Partition Labels

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of the problem is to partition a string s into the maximum possible number of substrings. The constraint is that each letter must appear in at most one substring. This implies that if a character appears in a certain partition, all of its occurrences throughout the entire original string s must also lie within that same partition.

Solution

Partition Labels in Python

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        # Create a dictionary to store the last occurrence index of each character.
        # This can be done in one line with a dictionary comprehension.
        last_indices = {char: i for i, char in enumerate(s)}

        result = []
        start = 0  # The start of the current partition.
        end = 0    # The end of the current partition.

        # Iterate through the string with index `i` to find partitions.
        for i, char in enumerate(s):
            # Update the end of the current partition to be the farthest
            # last occurrence of a character seen so far.
            end = max(end, last_indices[char])

            # If the current index `i` is the end of the partition,
            # it means all characters in s[start...i] appear only in this partition.
            if i == end:
                # Add the size of the partition to the result.
                result.append(end - start + 1)
                # Move the start to the beginning of the next partition.
                start = i + 1

        return result

Partition Labels in Java

class Solution {
    public List<Integer> partitionLabels(String s) {
        // Create an array to store the last occurrence index of each character.
        int[] last = new int[26];
        for (int i = 0; i < s.length(); ++i) {
            last[s.charAt(i) - 'a'] = i;
        }

        List<Integer> result = new ArrayList<>();
        int start = 0; // The start of the current partition.
        int end = 0;   // The end of the current partition.

        // Iterate through the string to find partitions.
        for (int i = 0; i < s.length(); ++i) {
            // Update the end of the current partition to be the farthest
            // last occurrence of a character seen so far.
            end = Math.max(end, last[s.charAt(i) - 'a']);

            // If the current index 'i' is the end of the partition,
            // it means all characters in s[start...i] appear only in this partition.
            if (i == end) {
                // Add the size of the partition to the result.
                result.add(end - start + 1);
                // Move the start to the beginning of the next partition.
                start = i + 1;
            }
        }

        return result;
    }
}

Partition Labels in C++

class Solution {
public:
    vector<int> partitionLabels(string s) {
        // Create an array to store the last occurrence index of each character.
        vector<int> last(26, 0);
        for (int i = 0; i < s.length(); ++i) {
            last[s[i] - 'a'] = i;
        }

        vector<int> result;
        int start = 0; // The start of the current partition.
        int end = 0;   // The end of the current partition.

        // Iterate through the string to find partitions.
        for (int i = 0; i < s.length(); ++i) {
            // Update the end of the current partition to be the farthest
            // last occurrence of a character seen so far.
            end = max(end, last[s[i] - 'a']);

            // If the current index 'i' is the end of the partition, 
            // it means all characters in s[start...i] appear only in this partition.
            if (i == end) {
                // Add the size of the partition to the result.
                result.push_back(end - start + 1);
                // Move the start to the beginning of the next partition.
                start = i + 1;
            }
        }

        return result;
    }
};

Partition Labels in TypeScript

function partitionLabels(s: string): number[] {
    // Create an array to store the last occurrence index of each character.
    const last = new Array(26).fill(0);
    const aCharCode = 'a'.charCodeAt(0);

    for (let i = 0; i < s.length; ++i) {
        last[s.charCodeAt(i) - aCharCode] = i;
    }

    const result: number[] = [];
    let start = 0; // The start of the current partition.
    let end = 0;   // The end of the current partition.

    // Iterate through the string to find partitions.
    for (let i = 0; i < s.length; ++i) {
        // Update the end of the current partition to be the farthest
        // last occurrence of a character seen so far.
        end = Math.max(end, last[s.charCodeAt(i) - aCharCode]);

        // If the current index 'i' is the end of the partition,
        // it means all characters in s[start...i] appear only in this partition.
        if (i === end) {
            // Add the size of the partition to the result.
            result.push(end - start + 1);
            // Move the start to the beginning of the next partition.
            start = i + 1;
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.