Percentage of Letter in String - Problem

Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent.

Input & Output

Example 1 — Basic Case
$ Input: s = "foobar", letter = "o"
Output: 33
💡 Note: There are 2 'o's in "foobar" out of 6 characters. Percentage = (2/6) * 100 = 33.33, floored to 33.
Example 2 — All Same Character
$ Input: s = "jjjj", letter = "k"
Output: 0
💡 Note: There are 0 'k's in "jjjj". Percentage = (0/4) * 100 = 0.
Example 3 — Perfect Match
$ Input: s = "jjjj", letter = "j"
Output: 100
💡 Note: All 4 characters are 'j'. Percentage = (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
Percentage of Letter in String INPUT String s = "foobar" f o o b a r 0 1 2 3 4 5 Letter to find: "o" Input Values s = "foobar" letter = "o" length = 6 ALGORITHM STEPS 1 Count Occurrences s.count("o") = 2 2 Get String Length len(s) = 6 3 Calculate Percentage (2 / 6) * 100 = 33.33... 4 Floor the Result floor(33.33) = 33 Formula percentage = (count / length) * 100 (2 / 6) * 100 = 33 FINAL RESULT Percentage Visualization 33% Letter Distribution 33% "o" = 2 chars (33%) Other = 4 chars (67%) Output 33 Key Insight: The built-in count() method efficiently counts character occurrences in O(n) time. Integer division (floor) ensures we round down: (count * 100) // length gives the exact result. TutorialsPoint - Percentage of Letter in String | Built-in Count Method
Asked in
Google 15 Meta 12
12.5K Views
Medium Frequency
~8 min Avg. Time
435 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