#3223

Minimum Length of String After Operations

Medium
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution focuses on counting the occurrences of each character. If a character appears at least three times, we can effectively remove it. The final length of the string will be the sum of characters that appear less than three times.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each character in the string.
  2. 2Step 2: For each character, if its frequency is 3 or more, it can be removed completely.
  3. 3Step 3: Sum the lengths of characters that appear less than three times to get the minimum length.
solution.py5 lines
1from collections import Counter
2
3def min_length_optimal(s):
4    freq = Counter(s)
5    return sum(count for count in freq.values() if count < 3) + sum(1 for count in freq.values() if count >= 3)

Complexity note: The time complexity is O(n) because we only traverse the string a couple of times to count frequencies and calculate the final length.

  • 1Only characters with a frequency of 3 or more can be removed.
  • 2The final length is determined by characters that appear less than 3 times.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.