2278. Percentage of Letter in String
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:
-
Count the number of occurrences of
letter
ins
. In Python, this can be done using thecount
method of a string, which counts the number of times a substring appears in the string. -
To get the percentage, we divide the number of occurrences of
letter
by the total length of the strings
. Since the length of the string represents 100%, dividing the occurrence count by the length gives us the required fraction. -
To convert this fraction into a percentage value, we multiply it by 100.
-
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:
-
Use the
count
method on the strings
to find the number of times the characterletter
appears. Thecount
method iterates over the string and increments a counter every time it encountersletter
. The method signatures.count(letter)
performs this operation. -
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.
-
Perform integer division using the
//
operator between the product obtained in the previous step and the length of the strings
. 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 withlen(s)
, which is a built-in function that returns the number of characters in a string. -
The result of this integer division is the percentage of characters in
s
that are the same asletter
, 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 EvaluatorExample 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.
-
We count the number of times
letter
appears ins
. Usings.count(letter)
, we find that "a" appears 3 times. -
Next, we determine the percentage. We multiply the count (3) by 100, giving us 300.
-
Then, we divide this product by the total number of characters in
s
, which is 6 (found usinglen(s)
). To ensure we round down to the nearest whole number, we use floor division:300 // 6
. -
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.
How many times is a tree node visited in a depth first search?
Recommended Readings
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!