Percentage of Letter in String Problem
#2278
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2278.
Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent.
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
Approach: Counting
Count how many characters of s equal letter, then compute count * 100 / len(s) with integer division. Integer division already rounds down, which is exactly what the problem asks for.
Complexity: O(n) time and O(1) extra space, where n is the length of s.
class Solution:
def percentageLetter(self, s: str, letter: str) -> int:
return s.count(letter) * 100 // len(s)