2278. Percentage of Letter in String

EasyString
Leetcode Link

Problem Description

In this problem, we are given a string s and a single character letter. Our goal is to determine what percentage of the characters in the string s are the same as the character letter. Once we have calculated this percentage, we are required to round it down to the nearest whole percent. Rounding down means that if the percentage is a decimal, we drop the decimal part and keep only the whole number part. For instance, if the percentage comes out to be 75.9, we round it down to 75.

Intuition

The process to find the solution is straightforward. To calculate the percentage of occurrences of letter in the string s, we can follow these steps:

  1. Count the number of occurrences of letter in s. In Python, this can be done using the count method of a string, which counts the number of times a substring appears in the string.

  2. To get the percentage, we divide the number of occurrences of letter by the total length of the string s. Since the length of the string represents 100%, dividing the occurrence count by the length gives us the required fraction.

  3. To convert this fraction into a percentage value, we multiply it by 100.

  4. Lastly, because we need to return the percentage rounded down to the nearest whole number, we perform integer division by using // operator in Python, which divides and then truncates the decimal part.

By following these steps, we arrive at the simple solution provided.

Solution Approach

The solution to this problem employs a very simple approach, which does not require complex algorithms or data structures. The steps taken in the implementation are a direct translation of the intuitive approach mentioned earlier, and here is how they translate into code:

  1. Use the count method on the string s to find the number of times the character letter appears. The count method iterates over the string and increments a counter every time it encounters letter. The method signature s.count(letter) performs this operation.

  2. Multiply the count obtained by 100 to convert the count into a percentage. This step involves basic arithmetic multiplication, as we want to represent the count as a percentage of the total number of characters in the string.

  3. Perform integer division using the // operator between the product obtained in the previous step and the length of the string s. Integer division will divide the two numbers and return the quotient without any fractional part, effectively rounding down to the nearest whole number. The length of the string is obtained with len(s), which is a built-in function that returns the number of characters in a string.

  4. The result of this integer division is the percentage of characters in s that are the same as letter, rounded down to the nearest whole number, which we return as the final answer.

In Python, this entire process is succinctly written in a single line as return s.count(letter) * 100 // len(s) within the percentageLetter method of the Solution class. This one-liner is an efficient way to perform the described steps due to Python's concise syntax for string manipulation and arithmetic operations.

No additional data structures are necessary for this approach, and the pattern used is a simple computation based on counting and arithmetic operations.

Ready to land your dream job?

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

Start Evaluator

Example Walkthrough

Consider the string s = "aaabbc" and the character letter = "a". We want to calculate what percentage of the characters in s are the same as letter, then round this down to the nearest whole percent.

  1. We count the number of times letter appears in s. Using s.count(letter), we find that "a" appears 3 times.

  2. Next, we determine the percentage. We multiply the count (3) by 100, giving us 300.

  3. Then, we divide this product by the total number of characters in s, which is 6 (found using len(s)). To ensure we round down to the nearest whole number, we use floor division: 300 // 6.

  4. The result is 50. Therefore, 50% of the characters in the string "aaabbc" are "a".

Using the code return s.count(letter) * 100 // len(s), this calculation is condensed into one line, and when we pass our example through this expression, it would return the integer 50, denoting that 50 percent of the letters in "aaabbc" are "a" rounded down to the nearest whole number.

Solution Implementation

1class Solution:
2    def percentageLetter(self, s: str, letter: str) -> int:
3        # Calculate the number of occurrences of the specified letter in the string
4        count_of_letter = s.count(letter)
5      
6        # Calculate the total length of the string to determine the percentage base
7        total_length = len(s)
8      
9        # Compute the percentage of the specified letter in the string
10        # The use of '//' ensures the result is an integer (floor division)
11        percentage = (count_of_letter * 100) // total_length
12      
13        # Return the computed percentage
14        return percentage
15
1class Solution {
2    public int percentageLetter(String s, char letter) {
3        // Initialize counter for occurrences of the given letter
4        int count = 0;
5
6        // Convert the string to a character array for iteration
7        char[] characters = s.toCharArray();
8
9        // Iterate over all characters in the string
10        for (char c : characters) {
11            // Check if the current character matches the target letter
12            if (c == letter) {
13                // Increment the count if it matches
14                count++;
15            }
16        }
17      
18        // Calculate the percentage of the letter in the string
19        // Multiply by 100 first to avoid integer division truncation
20        int percentage = (count * 100) / s.length();
21
22        // Return the calculated percentage
23        return percentage;
24    }
25}
26
1class Solution {
2public:
3    // Function to calculate the percentage of a specific letter in a string.
4    int percentageLetter(string s, char letter) {
5        int count = 0; // Initialize a variable to count occurrences of 'letter'.
6      
7        // Iterate over each character in the string 's'.
8        for (char& currentChar : s) {
9            // Increment count if the current character matches 'letter'.
10            count += (currentChar == letter);
11        }
12      
13        // Calculate and return the percentage of the letter in the string.
14        // Multiply count by 100 before dividing to avoid integer division issues.
15        return (count * 100) / s.size();
16    }
17};
18
1// Given a string "s" and a character "letter", this function calculates the percentage of 
2// 'letter' occurrences within "s" and returns the floor value of the percentage.
3
4// Define the function with its parameters and return type
5function percentageLetter(s: string, letter: string): number {
6    // Initialize a variable to keep track of the occurrences of "letter"
7    let letterCount = 0;
8  
9    // Store the length of the input string for later use
10    let totalCharacters = s.length;
11  
12    // Iterate over each character in the provided string
13    for (let currentChar of s) {
14        // If the current character is the same as the "letter" we're looking for, increment the count
15        if (currentChar === letter) letterCount++;
16    }
17  
18    // Calculate the percentage of the "letter" in the string
19    // flooring it to get the lower integer bound.
20    let percentage = Math.floor((letterCount / totalCharacters) * 100);
21  
22    // Return the calculated percentage
23    return percentage;
24}
25

Time and Space Complexity

Time Complexity

The time complexity of the given code is O(n), where n is the length of the string s. This is because s.count(letter) iterates over each character in the string to count the occurrences of letter, which requires a single pass through the string.

Space Complexity

The space complexity is O(1) as the space used does not depend on the size of the input string s. Only a fixed number of variables (for the count and the result of the calculation) are used, which occupy constant space.

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


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

How many times is a tree node visited in a depth first search?


Recommended Readings

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