Percentage of Letter in String — Problem & Solution
Percentage of Letter in String solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on strings.
Percentage of Letter in String is an easy coding problem on strings, asked in Amazon and TCS interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a string s and a single-character string letter, return the percentage of characters in s that equal letter, rounded down to the nearest whole number.
Example 1
Input: s = "foobar", letter = "o"
Output: 33
Explanation: 2 of 6 characters are o, and 200/6 truncates to 33.
Example 2
Input: s = "jjjj", letter = "k"
Output: 0
Example 3
Input: s = "vmvvvm", letter = "v"
Output: 66
Constraints
1 <= s.length <= 100letter is a single lowercase English letter.s consists of lowercase English letters.
Hints for Percentage of Letter in String
Hint 1
Count the occurrences, then scale by 100.
Hint 2
Multiply before dividing so the integer division truncates only once, at the end.
Hint 3
Integer division already rounds down for non-negative values.
How to solve Percentage of Letter in String
Count and scale. The only subtlety is doing the multiplication first so the single truncation happens on the final quotient.
Approach
- Count how many characters of
sequalletter. - Return
count * 100 / s.lengthusing integer division.
Why it works
Multiplying by 100 before dividing keeps full precision through the computation, so the floor is applied exactly once — to the true percentage.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Computing
count / s.lengthfirst yields 0 for every case in integer arithmetic. - Using floating point and then flooring is fine here but risks representation surprises; integer arithmetic is exact.
Reference solution
Python
def percentageLetter(s: str, letter: str) -> int:
return s.count(letter) * 100 // len(s)Java
public static int percentageLetter(String s, String letter) {
char target = letter.charAt(0);
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == target) count++;
}
return count * 100 / s.length();
}C++
int percentageLetter(string s, string letter) {
char target = letter[0];
int count = 0;
for (char c : s) {
if (c == target) count++;
}
return count * 100 / (int) s.size();
}JavaScript
var percentageLetter = function(s, letter) {
let count = 0;
for (let i = 0; i < s.length; i++) {
if (s.charAt(i) === letter) count++;
}
return Math.floor((count * 100) / s.length);
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings