#2278

Percentage of Letter in String

Easy
StringCounting occurrencesString manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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
  1. 1Step 1: Initialize a counter to zero.
  2. 2Step 2: Loop through each character in the string and increment the counter if it matches the specified letter.
  3. 3Step 3: Calculate the percentage using integer division to avoid floating-point operations.
  4. 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.