Given a string, the task is to count the number of special characters present in the string. A special character is any character that is not an alphabet (both uppercase and lowercase) or a digit (‘0’-‘9’).
To solve this problem, we’ll use the following steps:
Here is the Python code to solve the problem:
def count_special_characters(s: str) -> int:
special_characters_count = 0
for char in s:
if not char.isalnum():
special_characters_count += 1
return special_characters_count
# Example usage:
if __name__ == "__main__":
test_string = "Hello, World! 123"
print(count_special_characters(test_string)) # Output: 4
The time complexity of the solution is (O(n)), where (n) is the length of the string. This is because we are iterating through each character in the string once.
The space complexity is (O(1)) as we are using a constant amount of extra space regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?