Code Logo

Count Uppercase and Lowercase

Published at25 Jul 2026
Easy 0 views
Like0

Given a string, count the number of uppercase letters and lowercase letters separately. Return the counts as a tuple or two values: (uppercase count, lowercase count). Non-alphabetic characters are ignored.

For example, "Hello World" has 2 uppercase (H, W) and 8 lowercase letters. "ABC" has 3 uppercase and 0 lowercase. "123" has 0 and 0. An empty string returns (0, 0).

Character case counting teaches character classification using comparison operators. Uppercase letters are in the range 'A' to 'Z', and lowercase letters are in the range 'a' to 'z'. This skill is used in text normalization, password validation, and data cleaning.

The solution iterates through each character, checks if it is an uppercase letter (between 'A' and 'Z'), a lowercase letter (between 'a' and 'z'), and increments the appropriate counter.

Edge cases include an empty string (0, 0), a string with no letters (0, 0), a string with mixed cases and numbers (only letters are counted), and Unicode characters (only standard ASCII letters are considered).

Example Input & Output

Example 1
Input
"abc"
Output
[0,3]
Explanation

All lowercase

Example 2
Input
""
Output
[0,0]
Explanation

Empty string

Example 3
Input
"123!@#"
Output
[0,0]
Explanation

No letters

Example 4
Input
"Hello World"
Output
[2,8]
Explanation

2 uppercase, 8 lowercase (including space)

Example 5
Input
"ABC"
Output
[3,0]
Explanation

All uppercase

Algorithm Flow

Recommendation Algorithm Flow for Count Uppercase and Lowercase
Recommendation Algorithm Flow for Count Uppercase and Lowercase

Solution Approach

Iterate through the string and classify each character as uppercase or lowercase using range comparisons.

function countCase(s)
  upper = 0, lower = 0
  for i = 0 to length(s) - 1
    c = s[i]
    if c >= 'A' and c <= 'Z' then upper = upper + 1
    if c >= 'a' and c <= 'z' then lower = lower + 1
  return (upper, lower)

Initialize both counters to 0. Loop through each character. If it falls within the uppercase ASCII range ('A' to 'Z'), increment the uppercase counter. If it falls within the lowercase ASCII range ('a' to 'z'), increment the lowercase counter. Non-letter characters are ignored.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
class Solution {
    public int[] solution(String s) {
        int u=0,l=0;
        for(int i=0;i<s.length();i++){char c=s.charAt(i);
            if(Character.isUpperCase(c))u++;
            else if(Character.isLowerCase(c))l++;
        }return new int[]{u,l};
    }
}