Optimal Partition Of String

Solution For Optimal Partition Of String

Problem Statement:

Given a string s, divide s into some number of partitions such that every letter appears in at most one partition. Return a list of integers representing the size of these partitions.


Input: s = “ababcbacadefegdehijhklij”
Output: [9,7,8] Explanation:
The optimal partition is “ababcbaca”, “defegde”, “hijhklij”.
This is because every letter appears in at most one partition.


Treat the given string as an array of characters, and maintain a dictionary of all characters and their last occurrence in the string. Traverse through the string, and for each character encountered, put the index of its last occurrence in a variable, say ‘last_index’. Check whether this index is greater than the current index of traversal (say i). If it is, set the value of ‘last_index’ as the index of that last occurrence of the character, Otherwise, just keep traversing.

For each character encountered, keep on updating the maximum value of this ‘last_index’ for all the characters found up to the current index i. When traversing the string, if the current index ‘i’ is equal to the maximum of last_index values for the characters found upto that index say ‘j’, then the optimal partition for the sub array s[j+1:i] should be formed. Append the length of this partition to the result list.

Once the traversal is over, return the result list of partition lengths.

Pseudo Code:

  1. Initialize a dictionary to store the last occurrences of all the characters in given string s.
  2. Initialize a variable ‘last_index’ to -1 and an empty list ‘partition_lengths’.
  3. Traverse through the string s, for each index i:
    a. Find the last_index of the character currently being traversed via the dictionary constructed in step 1.
    b. Update the dictionary with the current index i as its value.
    c. If the value of last_index is less than the current index, then continue.
    d. Else, get the maximum value of last_index values for all the characters found up to index i.
    e. If the current index i is equal to the maximum index of the last occurrences of all the letters upto that index say ‘j’, then append the length of the partition s[j+1:i] to the partition_lengths list.
  4. Return the list partition_lengths.

Time Complexity: O(N), where N is the length of the input string.

Code Implementation:

def partitionLabels(s: str) -> List[int]:
# initialize variables
last_occurrence = {char: idx for idx, char in enumerate(s)}
last_index, partition_start = -1, 0
partition_lengths = []

# traverse through the string s
for i in range(len(s)):
    char = s[i]
    last_index = max(last_index, last_occurrence[char])
    if i == last_index:
        partition_lengths.append(i - partition_start + 1)
        partition_start = i + 1

return partition_lengths


Step by Step Implementation For Optimal Partition Of String

Given a string S, partition it into two parts such that every character in the first part appears before every character in the second part. Return the largest possible length of the first part.

class Solution {
    public int partition(String s) {
        // keep track of the largest possible length of the first part
        int max = 0;
        // iterate through the string
        for (int i = 0; i < s.length(); i++) {
            // set a flag to indicate whether the current character has been seen before
            boolean seen = false;
            // iterate through the string again, starting from the end
            for (int j = s.length() - 1; j > i; j--) {
                // if the current character is equal to the character at index j, set the flag to true
                if (s.charAt(i) == s.charAt(j)) {
                    seen = true;
            // if the current character has not been seen before, update the max
            if (!seen) {
                max = Math.max(max, i + 1);
        return max;
def partition(s):
    # base case: if string is empty, return empty list
    if not s:
        return []
    # initialize list of partitions
    partitions = []
    # go through each character in string
    for i in range(len(s)):
        # take out character at index i
        char = s[i]
        # take out string before index i
        left = s[:i]
        # take out string after index i
        right = s[i+1:]
        # recursively get partitions for left and right substrings
        left_partitions = partition(left)
        right_partitions = partition(right)
        # if left or right partitions are empty, initialize with empty list
        if not left_partitions:
            left_partitions = [[]]
        if not right_partitions:
            right_partitions = [[]]
        # go through each partition in left and right partitions
        for left_partition in left_partitions:
            for right_partition in right_partitions:
                # add char to each partition and append to list of partitions
                partitions.append([char] + left_partition + right_partition)
    return partitions
var optimalPartition = function(s) {
    // your code goes here
class Solution {
    int minPartitions(string s) {
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] - '0' > max) {
                max = s[i] - '0';
        return max;
using System; 

public class Solution { 

// Function to find the optimal partition of 

// the given string 

public static string optimalPartition(string s) 


// n is length of the given string 

int n = s.Length; 

// Declare a 2D array to store results of 

// subproblems 

int[,] opt = new int[n, n]; 

// Fill opt[i][j] in diagonal fashion 

for (int i = 0; i < n; i++) 


opt[i, i] = 0; 


// Consider substring of length 2 to length n 

for (int L = 2; L <= n; L++) 


// For substring of length L, set different 

// possible starting indexes 

for (int i = 0; i < n - L + 1; i++) 


int j = i + L - 1; 

// Set the default value for opt[i][j] 

opt[i, j] = int.MaxValue; 

// Consider all characters as starting 

// character and recursively call 

// for the remaining string 

for (int k = i; k <= j - 1; k++) 


// Find cost of partitioning at k and 

// recursively calculate cost for 

// remaining substring. c = cost of 

// partitioning substring from i to j 

int c = opt[i, k] + opt[k + 1, j]; 

// If partitioning at k gives us 

// minimum cost, then update min 

if (c < opt[i, j]) 


opt[i, j] = c; 



// Check if partitioning at j gives us 

// minimum cost 

if (opt[i, j] == j - i) 


opt[i, j] = 0; 




// Return the min cost stored in opt[0][n-1] 

return opt[0, n - 1].ToString(); 


// Driver code 

public static void Main() 


string str = "ababbc"; 




Scroll to Top

Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]