Count Letters, Digits, Spaces and Other Characters
Solve this ProblemEasy10 min
Topics
BasicsStrings
Companies
TCSInfosysWipro
Given a string
text, return [letters, digits, spaces, others]: how many characters are English letters, how many are digits, how many are spaces, and how many are anything else.
Behind the scenes every character is a number — its character codeCharacter Code (ASCII)The number a character is stored as, e.g. 'A' = 65, 'a' = 97, '0' = 48.. Letters and digits occupy consecutive ranges of codes, which is what makes simple range checks work. Built-in tests like isalpha wrap those checks in readable names.
Test Case 1:
Input:text = "Room 42!"
Output:[4, 2, 1, 1]
Explanation:R, o, o, m are letters; 4 and 2 are digits; one space; "!" is something else.
Test Case 2:
Input:text = "abc"
Output:[3, 0, 0, 0]
Explanation:Only letters.
Constraints
- ◆
1 ≤ text.length ≤ 200 - ◆
text contains printable ASCII characters
Try the Dry Run
Approach & Solutions
Compare Character RangesGood
Characters are stored as numbers, and the codes for 'a'–'z', 'A'–'Z' and '0'–'9' are each consecutive. So a character is a letter if it lies in one of the two letter ranges, a digit if it lies in the digit range, a space if it equals ' ', and anything else otherwise.
Time
O(n)Space
O(1)Java
class Solution {
public int[] classifyCharacters(String text) {
int letters = 0, digits = 0, spaces = 0, others = 0;
for (char ch : text.toCharArray()) {
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
letters++;
} else if (ch >= '0' && ch <= '9') {
digits++;
} else if (ch == ' ') {
spaces++;
} else {
others++;
}
}
return new int[] {letters, digits, spaces, others};
}
}Built-in Character TestsOptimal
Use the ready-made tests: Character.isLetter and isDigit in Java, isalpha and isdigit in Python, C and C++, and small regular expressions in JavaScript. They read better than raw ranges and say exactly what is being checked.
Time
O(n)Space
O(1)Java
class Solution {
public int[] classifyCharacters(String text) {
int letters = 0, digits = 0, spaces = 0, others = 0;
for (char ch : text.toCharArray()) {
if (Character.isLetter(ch)) {
letters++;
} else if (Character.isDigit(ch)) {
digits++;
} else if (ch == ' ') {
spaces++;
} else {
others++;
}
}
return new int[] {letters, digits, spaces, others};
}
}