Difficulty: Easy | Acceptance: 75.10% | Paid: No Topics: String
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.
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 <= 100
s consists of lowercase English letters.
letter is a lowercase English letter.
- Examples
- Constraints
- Linear Scan
- Built-in Functions
Linear Scan
Intuition We iterate through the string once to count how many times the target letter appears, then calculate the percentage based on the string’s length.
Steps
- Initialize a counter to 0.
- Loop through each character in the string.
- If the character matches the target letter, increment the counter.
- Calculate the percentage using integer arithmetic: (count * 100) / length.
- Return the result.
python
class Solution:
def percentageLetter(self, s: str, letter: str) -> int:
count = 0
for char in s:
if char == letter:
count += 1
return (count * 100) // len(s)Complexity
- Time: O(n) where n is the length of the string.
- Space: O(1) extra space.
- Notes: This is the most fundamental approach and works in any language.
Built-in Functions
Intuition Most modern languages provide optimized library functions to count occurrences of a character or substring within a string. We can leverage these to make the code concise.
Steps
- Use the language’s specific count method (e.g., count() in Python, std::count in C++) to find the frequency of the letter.
- Calculate the percentage using the formula: (frequency * 100) / length.
- Return the result.
python
class Solution:
def percentageLetter(self, s: str, letter: str) -> int:
return (s.count(letter) * 100) // len(s)Complexity
- Time: O(n) as the built-in functions must still scan the string.
- Space: O(1) or O(n) depending on implementation (e.g., spread operator in JS creates an array).
- Notes: While concise, be mindful of hidden space complexity in languages like JavaScript where strings are iterable but often converted to arrays for functional methods.