Facebook Pixel

2278. Percentage of Letter in String

EasyString
Leetcode Link

Problem Description

You are given a string s and a character letter. Your task is to find what percentage of the characters in the string s are equal to the given letter.

The percentage should be calculated as: (number of times letter appears in s) × 100 / (total length of s)

The result must be rounded down to the nearest whole number (integer). This means if the calculated percentage is 33.7%, you should return 33.

For example:

  • If s = "foobar" and letter = "o", there are 2 occurrences of 'o' out of 6 total characters, giving us 2 × 100 / 6 = 33.33...%, which rounds down to 33
  • If s = "jjjj" and letter = "k", there are 0 occurrences of 'k' out of 4 total characters, giving us 0%
Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The problem is straightforward - we need to find what portion of the string consists of a specific character and express it as a percentage.

To solve this, we need two pieces of information:

  1. How many times does letter appear in the string s?
  2. What is the total length of the string s?

Once we have these two values, calculating the percentage is simply a matter of applying the percentage formula: (count / total) × 100.

Python's built-in count() method makes this particularly simple - it directly gives us the number of occurrences of letter in the string. We can then multiply this count by 100 and divide by the string's length.

The key insight here is using integer division // instead of regular division /. Since we need to round down to the nearest whole number, integer division automatically handles this for us. When we compute count * 100 // len(s), the division naturally truncates any decimal part, effectively rounding down.

This approach avoids the need for explicit rounding functions or type conversions - the integer division operator // elegantly handles the "round down" requirement in a single operation.

Solution Approach

The implementation follows a direct counting approach that leverages Python's built-in string methods for efficiency.

Step-by-step Implementation:

  1. Count the occurrences: Use the s.count(letter) method to find how many times the character letter appears in string s. This method internally traverses the string once and maintains a count.

  2. Calculate the percentage: Multiply the count by 100 first, then perform integer division by the length of the string:

    percentage = s.count(letter) * 100 // len(s)

    The order of operations is important here:

    • We multiply by 100 first: s.count(letter) * 100
    • Then divide by the string length: ... // len(s)

    This ensures we get the most accurate result before rounding down.

  3. Handle rounding down: The integer division operator // automatically rounds down to the nearest integer. For example:

    • If the calculation yields 33.7, the result is 33
    • If the calculation yields 50.0, the result is 50
    • If the calculation yields 0.9, the result is 0

Why this approach works:

The formula count * 100 // length is mathematically equivalent to calculating the percentage and then flooring it. By multiplying by 100 before dividing, we avoid potential precision issues that could arise from working with small decimal values.

Time and Space Complexity:

  • Time Complexity: O(n) where n is the length of string s, since count() needs to traverse the entire string once
  • Space Complexity: O(1) as we only use a constant amount of extra space for the calculation

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with s = "hello" and letter = "l".

Step 1: Count occurrences

  • We need to count how many times 'l' appears in "hello"
  • Going through each character: h-e-l-l-o
  • The letter 'l' appears at positions 2 and 3
  • Count = 2

Step 2: Calculate the percentage

  • We have 2 occurrences of 'l' out of 5 total characters
  • Apply the formula: count * 100 // len(s)
  • Calculation: 2 * 100 // 5
  • First multiply: 200 // 5
  • Then integer divide: 40

Step 3: Return the result

  • The percentage is 40%
  • Since we used integer division, it's already rounded down
  • Final answer: 40

Let's trace through another example where rounding down matters: s = "abbabb" and letter = "b"

Step 1: Count occurrences

  • The letter 'b' appears 4 times in "abbabb"
  • Count = 4

Step 2: Calculate the percentage

  • Formula: 4 * 100 // 6
  • First multiply: 400 // 6
  • Integer division: 66 (since 400 ÷ 6 = 66.666...)
  • The decimal part .666... is automatically discarded

Step 3: Return the result

  • Final answer: 66

The integer division operator // handles the rounding down requirement perfectly, giving us 66 instead of 67.

Solution Implementation

1class Solution:
2    def percentageLetter(self, s: str, letter: str) -> int:
3        """
4        Calculate the percentage of a specific letter in a string.
5      
6        Args:
7            s: The input string to search in
8            letter: The target character to count
9          
10        Returns:
11            The percentage of occurrences of the letter in the string (floored integer)
12        """
13        # Count occurrences of the target letter in the string
14        letter_count = s.count(letter)
15      
16        # Get the total length of the string
17        total_length = len(s)
18      
19        # Calculate percentage and use integer division to floor the result
20        # Multiply by 100 first to get percentage, then integer divide by length
21        percentage = letter_count * 100 // total_length
22      
23        return percentage
24
1class Solution {
2    /**
3     * Calculates the percentage of a specific letter in a string.
4     * 
5     * @param s      The input string to search in
6     * @param letter The character to count occurrences of
7     * @return       The percentage of the letter in the string (rounded down)
8     */
9    public int percentageLetter(String s, char letter) {
10        // Initialize counter for the target letter
11        int count = 0;
12      
13        // Iterate through each character in the string
14        for (char currentChar : s.toCharArray()) {
15            // Check if current character matches the target letter
16            if (currentChar == letter) {
17                count++;
18            }
19        }
20      
21        // Calculate percentage (integer division rounds down)
22        // Formula: (occurrences * 100) / total_length
23        return count * 100 / s.length();
24    }
25}
26
1class Solution {
2public:
3    /**
4     * Calculate the percentage of a specific letter in a string
5     * @param s - the input string to search in
6     * @param letter - the target character to count
7     * @return the percentage of occurrences (rounded down to nearest integer)
8     */
9    int percentageLetter(string s, char letter) {
10        // Count occurrences of the target letter in the string
11        int letter_count = 0;
12        for (char c : s) {
13            if (c == letter) {
14                letter_count++;
15            }
16        }
17      
18        // Calculate percentage: (count * 100) / total_length
19        // Integer division automatically rounds down
20        int percentage = (letter_count * 100) / s.size();
21      
22        return percentage;
23    }
24};
25
1/**
2 * Calculates the percentage of a specific letter in a string
3 * @param s - The input string to search in
4 * @param letter - The target letter to count
5 * @returns The floor value of the percentage of the letter in the string
6 */
7function percentageLetter(s: string, letter: string): number {
8    // Count occurrences of the target letter in the string
9    const letterCount: number = s.split('').filter((char: string) => char === letter).length;
10  
11    // Calculate percentage and return the floor value
12    const percentage: number = Math.floor((100 * letterCount) / s.length);
13    return percentage;
14}
15

Time and Space Complexity

Time Complexity: O(n) where n is the length of string s. The count() method needs to traverse through the entire string once to count occurrences of the specified letter. The integer division and multiplication operations are O(1), and len(s) is also O(1) in Python as the length is stored as an attribute.

Space Complexity: O(1). The algorithm only uses a constant amount of extra space to store the count result and perform the percentage calculation. No additional data structures that scale with input size are created.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Using Regular Division Instead of Integer Division

The Pitfall: A common mistake is using regular division (/) followed by conversion to int or using math.floor():

# Incorrect approach 1
percentage = int(s.count(letter) * 100 / len(s))  # This rounds toward zero, not down

# Incorrect approach 2  
percentage = math.floor(s.count(letter) * 100 / len(s))  # Unnecessary import and overhead

Why it's problematic:

  • int() truncates toward zero, which differs from floor division for negative numbers (though not applicable in this problem since percentages are non-negative)
  • Using math.floor() requires an additional import and introduces floating-point arithmetic unnecessarily

The Solution: Use integer division (//) directly:

percentage = s.count(letter) * 100 // len(s)

2. Dividing Before Multiplying by 100

The Pitfall:

# Incorrect - loses precision
percentage = int((s.count(letter) / len(s)) * 100)

Why it's problematic: When you divide first, you get a decimal between 0 and 1. For small counts, this can lead to precision loss. For example:

  • If count = 1 and length = 3: 1/3 = 0.333..., then 0.333... * 100 = 33.333...
  • But with floating-point arithmetic, you might get slight inaccuracies

The Solution: Always multiply by 100 first to work with larger integers:

percentage = s.count(letter) * 100 // len(s)

3. Not Handling Edge Cases (Empty String)

The Pitfall: If the problem allowed empty strings, the code would crash with a ZeroDivisionError:

# This would fail if s = ""
percentage = s.count(letter) * 100 // len(s)  # Division by zero!

The Solution: Add a guard clause if empty strings are possible:

if not s:  # or if len(s) == 0:
    return 0
percentage = s.count(letter) * 100 // len(s)

4. Manual Counting Instead of Using Built-in Methods

The Pitfall:

# Unnecessarily complex and error-prone
count = 0
for char in s:
    if char == letter:
        count += 1
percentage = count * 100 // len(s)

Why it's problematic:

  • More lines of code mean more chances for bugs
  • Less readable and maintainable
  • Python's built-in count() is optimized in C and typically faster

The Solution: Leverage Python's built-in string methods:

percentage = s.count(letter) * 100 // len(s)
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which data structure is used in a depth first search?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More