LeetCode 763: Partition Labels Solution

Master LeetCode problem 763 (Partition Labels), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

763. Partition Labels

Problem Explanation

Explanation

  • We can solve this problem using a greedy approach.
  • We iterate over the string and keep track of the last occurrence of each character.
  • As we iterate, we maintain a end variable that represents the end index of the current partition.
  • When we reach the end index of the current partition, we add the length of the current partition to the result and update the start index to the next character.

Time Complexity: O(n) where n is the length of the input string s
Space Complexity: O(1)

Solution Code

import java.util.*;

class Solution {
    public List<Integer> partitionLabels(String s) {
        List<Integer> result = new ArrayList<>();
        int[] lastOccurrence = new int[26];
        for (int i = 0; i < s.length(); i++) {
            lastOccurrence[s.charAt(i) - 'a'] = i;
        }

        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            end = Math.max(end, lastOccurrence[s.charAt(i) - 'a']);
            if (i == end) {
                result.add(end - start + 1);
                start = end + 1;
            }
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 763 (Partition Labels)?

This page provides optimized solutions for LeetCode problem 763 (Partition Labels) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 763 (Partition Labels)?

The time complexity for LeetCode 763 (Partition Labels) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 763 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 763 in Java, C++, or Python.

Back to LeetCode Solutions