Percentage of Letter in String
EasyUpdated: Oct 13, 2025
Practice on:
Problem
Given a string s and a character letter, return _thepercentage of characters in _s that equalletter rounded down to the nearest whole percent.
Examples
Example 1
Input: s = "foobar", letter = "o"
Output: 33
Explanation:
The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.
Example 2
Input: s = "jjjj", letter = "k"
Output: 0
Explanation:
The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.
Constraints
1 <= s.length <= 100sconsists of lowercase English letters.letteris a lowercase English letter.
Solution
Method 1 - Count & Percentage
Intuition
Count the number of times letter appears in s, compute the percentage, and round down to the nearest integer.
Approach
Use a simple loop or built-in count to compute cnt = occurrences of letter in s, let n = len(s), then return cnt * 100 // n (integer division to get the floored percentage).
Code
C++
#include <string>
using namespace std;
class Solution {
public:
int percentageLetter(string s, char letter) {
int cnt = 0, n = s.size();
for (char c : s) if (c == letter) cnt++;
return cnt * 100 / n;
}
};
Go
func percentageLetter(s string, letter byte) int {
cnt := 0
for i := 0; i < len(s); i++ {
if s[i] == letter { cnt++ }
}
return cnt * 100 / len(s)
}
Java
class Solution {
public int percentageLetter(String s, char letter) {
int cnt = 0, n = s.length();
for (char c : s.toCharArray()) if (c == letter) cnt++;
return cnt * 100 / n;
}
}
Kotlin
class Solution {
fun percentageLetter(s: String, letter: Char): Int {
val cnt = s.count { it == letter }
return cnt * 100 / s.length
}
}
Python
def percentageLetter(s: str, letter: str) -> int:
return s.count(letter) * 100 // len(s)
Rust
fn percentage_letter(s: &str, letter: char) -> i32 {
let cnt = s.chars().filter(|&c| c == letter).count();
(cnt * 100 / s.len()) as i32
}
TypeScript
function percentageLetter(s: string, letter: string): number {
let cnt = 0;
for (const c of s) if (c === letter) cnt++;
return Math.floor(cnt * 100 / s.length);
}
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)