Leetcode 2278: Percentage of Letter in String

grid47
grid47
Exploring patterns and algorithms
Mar 24, 2024 4 min read

You are given a string s and a character letter. Your task is to determine the percentage of characters in s that are equal to letter, rounding down to the nearest whole percent.
Problem
Approach
Steps
Complexity
Input: You are given a string `s` and a character `letter` where `s` consists of lowercase English letters and `letter` is a lowercase English letter.
Example: Input: s = "hello", letter = "l"
Constraints:
• 1 <= s.length <= 100
• s consists of lowercase English letters.
• letter is a lowercase English letter.
Output: Return the percentage of characters in `s` that are equal to `letter`, rounded down to the nearest whole percent.
Example: Output: 40
Constraints:
Goal: Find the percentage of occurrences of `letter` in the string `s` and return it as an integer.
Steps:
• Count how many times `letter` appears in the string `s`.
• Calculate the percentage by dividing the count by the length of the string and multiplying by 100.
• Return the integer part of the percentage.
Goal: The solution must efficiently handle strings with lengths up to 100 characters.
Steps:
Assumptions:
• The string `s` is not empty.
• The character `letter` exists within the alphabet.
Input: Input: s = "hello", letter = "l"
Explanation: In this case, the letter 'l' appears 2 times out of 5 characters in the string 'hello'. The percentage is 2 / 5 * 100 = 40%, so the output is 40.

Input: Input: s = "abcabc", letter = "a"
Explanation: The letter 'a' appears 2 times out of 6 characters in the string 'abcabc'. The percentage is 2 / 6 * 100 = 33.33%. When rounded down, the result is 33.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus