#2278
Percentage of Letter in String
EasyStringCounting occurrencesString manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is similar to the brute force approach but focuses on a single pass through the string to count occurrences. This ensures efficiency while maintaining clarity.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a counter to zero.
- 2Step 2: Loop through each character in the string and increment the counter if it matches the specified letter.
- 3Step 3: Calculate the percentage using integer division to avoid floating-point operations.
- 4Step 4: Return the percentage.
solution.py3 lines
1def percentage_of_letter(s, letter):
2 count = s.count(letter)
3 return (count * 100) // len(s)ℹ
Complexity note: The time complexity is O(n) because we still need to traverse the string once. The space complexity is O(1) since we are using a fixed amount of space for the counter.
- 1Counting occurrences is crucial for percentage calculations.
- 2Using built-in functions can simplify code and improve readability.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.