Percentage of Letter in String

The problem is asking for the percentage of a specific letter in a given string, and the result must be rounded down to the nearest whole percent. We can accomplish this by calculating the ratio of the occurrences of the given letter to the total length of the string, and then multiplying by 100.

Approach

  1. Count Occurrences: Count the occurrences of the given letter in the string.
  2. Calculate Percentage: Calculate the percentage as (occurrences / length of the string) * 100.
  3. Round Down: Use the integer division // to round down to the nearest whole number.

Code Implementation

1
2
3
4
5
class Solution:
    def percentageLetter(self, s: str, letter: str) -> int:
        occurrences = s.count(letter)
        percentage = (occurrences * 100) // len(s)
        return percentage

Example

  • For s = "foobar" and letter = "o", the occurrences of “o” are 2, so the percentage is (2 / 6) * 100 = 33 and we return 33.
  • For s = "jjjj" and letter = "k", the occurrences of “k” are 0, so the percentage is 0 and we return 0.

Complexity

The time complexity of this solution is O(n), where n is the length of the string. This is because the count method iterates through the string to count occurrences of the specified letter. The space complexity is O(1), since we only use a constant amount of extra space.