2278. Percentage of Letter in String LeetCode Solution

In this guide, you will get 2278. Percentage of Letter in String LeetCode Solution with the best time and space complexity. The solution to Percentage of Letter in String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Percentage of Letter in String solution in C++
  4. Percentage of Letter in String solution in Java
  5. Percentage of Letter in String solution in Python
  6. Additional Resources
2278. Percentage of Letter in String LeetCode Solution image

Problem Statement of Percentage of Letter in 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.

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.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

2278. Percentage of Letter in String LeetCode Solution in C++

class Solution {
 public:
  int percentageLetter(string s, char letter) {
    return 100 * ranges::count(s, letter) / s.length();
  }
};
/* code provided by PROGIEZ */

2278. Percentage of Letter in String LeetCode Solution in Java

class Solution {
  public int percentageLetter(String s, char letter) {
    return 100 * (int) s.chars().filter(c -> c == letter).count() / s.length();
  }
}
// code provided by PROGIEZ

2278. Percentage of Letter in String LeetCode Solution in Python

class Solution:
  def percentageLetter(self, s: str, letter: str) -> int:
    return 100 * s.count(letter) // len(s)
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.