We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Percentage of Letter in String

Number: 2365

Difficulty: Easy

Paid? No

Companies: American Express


Problem Description

Given a string s and a character letter, determine the percentage of characters in s that match letter. The percentage should be computed by taking (number of matching characters / total number of characters) * 100 and then rounding down to the nearest whole number.


Key Insights

  • Count the occurrences of the character letter in the string s.
  • Compute the percentage by dividing the count by the length of s and multiplying by 100.
  • Use integer division (or floor operation) to round down to the nearest whole percent.
  • The string length is small (max 100), so a linear scan is efficient.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string s because we iterate through each character once. Space Complexity: O(1), as we use only a few integer variables for counting and calculation.


Solution

This problem is solved by using a simple iteration through the string. We count every occurrence of the specific character letter. Once the count is obtained, we calculate the percentage by using the formula: floor((count / length of string) * 100). The data structures used include primitive variables to store the count and to perform the arithmetic operations. No additional complex data structures are required given the small input constraints.


Code Solutions

# Python solution with line-by-line comments

def percentageLetter(s: str, letter: str) -> int:
    # Initialize a counter to count occurrences of letter in s
    count = 0
    # Iterate over each character in the string s
    for char in s:
        # If the current character matches 'letter', increment the count
        if char == letter:
            count += 1
    # Calculate the percentage by multiplying count by 100 and dividing by the length of s (using floor division)
    result = (count * 100) // len(s)
    # Return the computed percentage
    return result

# Example usage:
print(percentageLetter("foobar", "o"))  # Expected output: 33
← Back to All Questions