DEV Community

shipra Shankhwar
shipra Shankhwar

Posted on

Leetcode QOTD:- 3120. Count the Number of Special Characters I

  1. Use two integers as bit masks:
    • lower stores lowercase letters present.
    • upper stores uppercase letters present.
  2. Traverse each character in the string:
    • If lowercase, set its corresponding bit in lower.
    • If uppercase, set its corresponding bit in upper.
  3. Perform lower & upper:
    • Common set bits represent characters present in both lowercase and uppercase forms.
  4. Use Integer.bitCount() to count total common bits and return the answer.
class Solution {
    public int numberOfSpecialChars(String word) {
        int lower = 0, upper = 0;

        for (char c : word.toCharArray()) {
            if (Character.isLowerCase(c))
                lower |= 1 << (c - 'a');
            else
                upper |= 1 << (c - 'A');
        }

        return Integer.bitCount(lower & upper);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
prachub profile image
PracHub

The bit manipulation trick is clever for counting characters in both cases. How would it handle non-alphabetic characters or mixed content? It seems like a limited solution. If you're getting into DSA, prachub.com has been helpful for banks that reflect what I'm asked in technical screens. Just using LeetCode can sometimes leave gaps, especially with oddly specific questions.