#2716

Minimize String Length

Easy
Hash TableStringHash MapSet
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution uses a HashSet to track unique characters efficiently, allowing us to determine the minimized string length in a single pass through the input string.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty HashSet to keep track of unique characters.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: Add each character to the HashSet (duplicates will be ignored automatically).
  4. 4Step 4: Return the size of the HashSet as the minimized string length.
solution.py2 lines
1def minimize_string_length(s):
2    return len(set(s))

Complexity note: The time complexity is O(n) because we make a single pass through the string to add characters to the HashSet. The space complexity is O(n) due to the storage of unique characters.

  • 1The minimized string will contain all distinct characters of the original string.
  • 2Using a HashSet allows for efficient duplicate checking.

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