Today’s problem

https://leetcode.com/problems/minimum-length-of-string-after-operations/

Intuition

  • In this question, each character is independent. Therefore, we can deal with one character a time.
  • If one character has odd count, than we can delete from left to right and remain 1 character at the end.
  • Otherwise, we will left 2 characters at the end.

Approach

Therefore, all we need to do is the count each character, and then test whether it has odd count or even count.

Complexity

  • Time complexity: $O(N)$, N is the length of the string.

  • Space complexity: $O(N)$, I stored a counter.

Code

class Solution:
    def minimumLength(self, s: str) -> int:
        cnt = Counter([ch for ch in s])
        ans = 0
        for x,v in cnt.items():
            if v % 2 == 0:
                ans += 2
            else:
                ans += 1
        return ans