algoadvance

You are given a string s and a character letter. You need to return the percentage of characters in s that are equal to letter rounded down to the nearest whole percent.

Clarifying Questions

  1. Input Constraints:
    • What is the maximum length of the string s?
    • Can s contain non-alphabetic characters?
    • Is the comparison case-sensitive?
  2. Output Details:
    • Should the result be an integer?

Strategy

  1. Count Occurrences:
    • Traverse the string s and count how many times the character letter appears.
  2. Calculate the Percentage:
    • Compute the percentage by dividing the count of letter by the length of the string s, multiplying by 100, and then using integer division to round down to the nearest whole number.
  3. Edge Cases:
    • If the string s is empty, the function should handle it appropriately, although typically this edge case may not be needed if input constraints guarantee a non-empty string.

Code

def percentageLetter(s: str, letter: str) -> int:
    # Count occurrences of the specified letter in the string
    count = s.count(letter)
    
    # Calculate the percentage and round down to the nearest integer
    percentage = (count * 100) // len(s)
    
    return percentage

Time Complexity

This strategy effectively counts the number of occurrences and calculates the percentage in a straightforward manner, ensuring both efficiency and simplicity.

Try our interview co-pilot at AlgoAdvance.com