Percentage of Letter in String - Problem

You're analyzing text data and need to calculate character frequencies! Given a string s and a specific character letter, determine what percentage of the string is made up of that character.

Your task is to return the percentage of characters in s that equal letter, rounded down to the nearest whole percent.

Example: In the string "programming" with letter 'g', there are 2 'g's out of 11 total characters. That's 18.18%, which rounds down to 18%.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "foobar", letter = "o"
โ€บ Output: 33
๐Ÿ’ก Note: The letter 'o' appears 2 times in "foobar" which has 6 characters. (2/6) * 100 = 33.33%, rounded down to 33%.
example_2.py โ€” No Matches
$ Input: s = "jjjj", letter = "k"
โ€บ Output: 0
๐Ÿ’ก Note: The letter 'k' does not appear in "jjjj", so the percentage is 0%.
example_3.py โ€” All Matches
$ Input: s = "aaaa", letter = "a"
โ€บ Output: 100
๐Ÿ’ก Note: All 4 characters are 'a', so the percentage is (4/4) * 100 = 100%.

Constraints

  • 1 โ‰ค s.length โ‰ค 1000
  • s consists of lowercase English letters
  • letter is a lowercase English letter

Visualization

Tap to expand
Character Percentage CalculatorExample: s = "hello", letter = 'l'helloNot 'l'Not 'l'Match!Match!Not 'l'Calculation๐Ÿ“Š Total characters: 5โœ… Target letter 'l' count: 2๐Ÿงฎ Raw percentage: (2 รท 5) ร— 100 = 40.0%โฌ‡๏ธ Floor to whole number: 40%Result: 40Time Complexity: O(n) - single passSpace Complexity: O(1) - only counter
Understanding the Visualization
1
Scan Survey
Go through each response (character) in the dataset (string)
2
Count Target
Keep track of how many chose our specific option (target letter)
3
Calculate Rate
Divide count by total responses and multiply by 100 for percentage
4
Floor Result
Round down to nearest whole percent as required
Key Takeaway
๐ŸŽฏ Key Insight: This problem only requires counting one specific character and applying a simple percentage formula. The integer division automatically handles the floor operation, making the solution both elegant and efficient.
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 5
28.4K Views
Medium Frequency
~5 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen