Minimum Length of String After Operations visualization

3223: Minimum Length of String After Operations

Difficulty: Medium
Topics: String Manipulation, Frequency Counting
Companies: Amazon, Microsoft, Oracle
Pro Tip: This problem requires understanding of frequency analysis and parity. The optimal solution runs in O(n) time with O(1) space complexity.

Problem Statement

You are given a string s. You can perform the following process on s any number of times:

  1. Choose an index i where there's at least one matching character to the left and right of i
  2. Delete the closest occurrence to the left of i
  3. Delete the closest occurrence to the right of i

Return the minimum possible length of s after performing these operations.

Example 1

Input: s = "abaacbcbb"
Output: 5
Explanation:
1. Choose index 2 (first 'a'), remove at indices 0 and 3 → "bacbcbb"
2. Choose index 3 (first 'b'), remove at indices 0 and 5 → "acbcb"

Example 2

Input: s = "aa"
Output: 2
Explanation: No operations possible
Problem Link: View on LeetCode ↗

Approach 1: Frequency Analysis (Optimal)

Count character frequencies and determine minimal length based on parity.

Algorithm Steps

  1. Count frequency of each character
  2. For each character:
    • If frequency is even: Can remove all but 2
    • If frequency is odd: Can remove all but 1
  3. Sum remaining counts

Complexity Analysis

Time Complexity Space Complexity
O(n) O(1)
Optimal Solution
class Solution {
public:
    int minimumLength(string s) {
        vector<int> freq(26, 0);
        for(char c : s) freq[c-'a']++;
        
        int result = 0;
        for(int count : freq) {
            if(count == 0) continue;
            result += (count % 2 == 0) ? 2 : 1;
        }
        return result;
    }
};
class Solution {
    public int minimumLength(String s) {
        int[] freq = new int[26];
        for(char c : s.toCharArray()) freq[c-'a']++;
        
        int result = 0;
        for(int count : freq) {
            if(count == 0) continue;
            result += (count % 2 == 0) ? 2 : 1;
        }
        return result;
    }
}
class Solution:
    def minimumLength(self, s: str) -> int:
        freq = [0] * 26
        for c in s:
            freq[ord(c) - ord('a')] += 1
            
        return sum(2 if c % 2 == 0 else 1 for c in freq if c > 0)
Implementation Note: This solution leverages the observation that each operation removes two matching characters. The final length depends on whether character counts are even or odd.

Approach 2: Two Pointers

Alternative solution using two pointers to simulate the operations.

Algorithm Steps

  1. Initialize left and right pointers
  2. While characters match at both ends:
    • Move pointers inward past matching characters
    • Track remaining length
  3. Return final length

Complexity Analysis

Time Complexity Space Complexity
O(n) O(1)
Two Pointers Solution
class Solution {
public:
    int minimumLength(string s) {
        int left = 0, right = s.size() - 1;
        while(left < right && s[left] == s[right]) {
            char current = s[left];
            while(left <= right && s[left] == current) left++;
            while(left <= right && s[right] == current) right--;
        }
        return right - left + 1;
    }
};
class Solution {
    public int minimumLength(String s) {
        int left = 0, right = s.length() - 1;
        while(left < right && s.charAt(left) == s.charAt(right)) {
            char current = s.charAt(left);
            while(left <= right && s.charAt(left) == current) left++;
            while(left <= right && s.charAt(right) == current) right--;
        }
        return right - left + 1;
    }
}
class Solution:
    def minimumLength(self, s: str) -> int:
        left, right = 0, len(s) - 1
        while left < right and s[left] == s[right]:
            current = s[left]
            while left <= right and s[left] == current:
                left += 1
            while left <= right and s[right] == current:
                right -= 1
        return right - left + 1
Implementation Note: The two pointers approach simulates the actual operations by collapsing matching prefixes and suffixes. This works well for strings with matching ends.

Comparison of Approaches

Approach Time Complexity Space Complexity When to Use Pros Cons
Frequency Analysis O(n) O(1) General case Simple implementation Doesn't simulate actual operations
Two Pointers O(n) O(1) Strings with matching ends Simulates actual process Slightly more complex logic
Interview Tip: The frequency analysis approach is often sufficient for interviews, but be prepared to discuss alternative solutions like the two pointers approach.

Edge Cases and Special Considerations

When implementing solutions for this problem, consider these edge cases:

1. All Characters Same

Input: "aaaaa" → Output: 1
Explanation: Can remove all but one character

2. No Possible Operations

Input: "abc" → Output: 3
Explanation: No matching characters to perform operations

3. Alternating Characters

Input: "ababab" → Output: 6
Explanation: No operations possible due to alternation
Important: Always test your solution with these edge cases to ensure correctness. The examples demonstrate how different string patterns affect the final length.

Visualization

The frequency analysis approach works by:

  1. Counting: Calculate occurrences of each character
  2. Analyzing: Determine if counts are even or odd
  3. Summing: Add 2 for even counts, 1 for odd counts

This approach efficiently calculates the minimal possible length without simulating each operation.


Frequently Asked Questions

1. Why does the frequency approach work?

Each operation removes two matching characters. The final length depends on whether we can pair all characters (even counts leave 2, odd counts leave 1).

2. When does the two pointers approach fail?

It may fail for cases where operations could be performed in the middle of the string but not at the ends. However, the problem constraints ensure it works.

3. Can this be solved with dynamic programming?

While possible, DP would be overkill for this problem as it has O(n) solutions with better space complexity.

4. How would you handle Unicode characters?

For Unicode, replace the 26-element array with a hash map to count frequencies, increasing space to O(k) where k is number of unique characters.

5. What's the minimal possible length?

The minimal length is the number of characters with odd counts (each contributes 1) plus the number of character types with even counts (each contributes 2).

Final Thoughts: This problem demonstrates how careful analysis of operations can lead to efficient solutions without complex simulations. The frequency counting approach provides an optimal O(n) time solution.