algoadvance

Leetcode 3120. Count the Number of Special Characters I

Problem Statement

You are given a string s. Count the number of special characters in the string. Special characters are defined as characters that are not alphanumeric (i.e., they are neither letters nor numbers).

Clarifying Questions

  1. Q: What characters are considered alphanumeric?
    • A: Alphanumeric characters include the uppercase letters ‘A’ to ‘Z’, lowercase letters ‘a’ to ‘z’, and the digits ‘0’ to ‘9’.
  2. Q: Should whitespace (spaces, tabs, etc.) be considered special characters?
    • A: Yes, whitespace should be considered special characters since they are not alphanumeric.
  3. Q: Is the input string guaranteed to be non-empty?
    • A: Yes, you can assume that the input string is non-empty.
  4. Q: Should I handle potential corner cases, such as strings that contain only special characters or only alphanumeric characters?
    • A: Yes, handle all possible input scenarios including those where the string contains only special characters.

Strategy

  1. Iteration: Iterate over each character of the string s.
  2. Checking: For each character, check if it is alphanumeric using the isalnum function from the C++ standard library.
  3. Counting: If the character is not alphanumeric, increment a counter by 1.
  4. Result: Return the counter as the result.

Code

Here’s the implementation in C++:

#include <iostream>
#include <cctype>

int countSpecialCharacters(const std::string& s) {
    int count = 0;
    for (char ch : s) {
        if (!isalnum(ch)) {
            count++;
        }
    }
    return count;
}

int main() {
    std::string s = "Hello, World! 123"; // Example input
    std::cout << "Number of special characters: " << countSpecialCharacters(s) << std::endl;
    return 0;
}

Explanation

Time Complexity

The time complexity of this solution is O(n), where n is the length of the input string s. This is because the algorithm involves a single pass through the string, performing a constant-time check for each character.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI