Taro Logo

Percentage of Letter in String

Easy
American Express logo
American Express
0 views
Topics:
Strings

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.

Example 1:

Input: s = "foobar", letter = "o"
Output: 33
Explanation:
The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.

Example 2:

Input: s = "jjjj", letter = "k"
Output: 0
Explanation:
The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.

Constraints:

  • 1 <= s.length <= 100
  • s consists of lowercase English letters.
  • letter is a lowercase English letter.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Is the input string `s` case-sensitive? For example, should 'A' be considered the same as 'a' for the character `letter`?
  2. Can the input string `s` be empty? If so, what should I return?
  3. Can the input character `letter` be an empty string or null character? If so, what should I return?
  4. Are there any constraints on the character set used in the input string `s` (e.g., ASCII, Unicode)?
  5. Should I handle potential floating point precision issues when calculating the percentage before rounding down?

Brute Force Solution

Approach

The brute-force approach calculates the percentage of a specific letter in a string by examining each character individually. It's like counting how many times you see that letter and then figuring out what percentage that number is of the total number of characters. We will go through the string one character at a time to solve this.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the first character in the string.
  2. Check if that character is the letter we're interested in counting.
  3. If it is, increase our count by one. If not, do nothing.
  4. Move on to the next character and repeat the checking and counting process.
  5. Continue checking and counting each character until you have reached the end of the string.
  6. Once you've gone through the whole string, divide the number of times you found the specific letter by the total number of characters in the string.
  7. Multiply that result by 100 to get the percentage of that letter in the string.

Code Implementation

def percentage_of_letter_in_string(input_string, target_letter):
    letter_count = 0
    string_length = len(input_string)

    # Iterate through the input string to count target letter occurrences.
    for char in input_string:
        if char == target_letter:

            # Increment the counter when the current char matches target.
            letter_count += 1

    # Calculate percentage only if the string is not empty to avoid division by zero.
    if string_length > 0:
        percentage = (letter_count / string_length) * 100

        return percentage
    else:
        return 0

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through the input string once, examining each character individually. The input size is the length of the string, denoted as 'n'. For each of the 'n' characters, a constant-time comparison is performed to check if it matches the target letter. Therefore, the time complexity is directly proportional to the length of the string, resulting in O(n).
Space Complexity
O(1)The algorithm uses a single counter variable to track the occurrences of the target letter. The plain English explanation states it only increments a count and calculates the percentage, which involves only simple arithmetic operations. The space required for this counter and intermediate calculations is constant and does not depend on the length of the string. Therefore, the auxiliary space complexity is O(1).

Optimal Solution

Approach

The goal is to calculate the percentage of a specific letter within a given string. The optimal solution efficiently counts the occurrences of the letter and then uses a simple formula to determine the percentage, avoiding unnecessary computations or data structures.

Here's how the algorithm would work step-by-step:

  1. First, go through the string and count how many times the specific letter appears.
  2. Next, find the total number of letters in the whole string.
  3. Then, divide the number of times the letter appears by the total number of letters in the string.
  4. Finally, multiply the result by 100 to get the percentage.

Code Implementation

def percentage_of_letter(string, letter):
    letter_count = 0

    # Need to count the occurances of the target letter.
    for character in string:
        if character == letter:
            letter_count += 1

    string_length = len(string)

    # Avoid division by zero if the string is empty.
    if string_length == 0:
        return 0.0

    # Calculate the percentage of the target letter.
    percentage = (letter_count / string_length) * 100

    return percentage

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through the string once to count the occurrences of the specified letter. This single loop is directly proportional to the length of the string, denoted as n. The subsequent calculations (division and multiplication) are constant time operations. Therefore, the overall time complexity is determined by the single linear pass through the string, resulting in O(n).
Space Complexity
O(1)The provided solution calculates the percentage of a letter in a string by counting the occurrences of the letter and dividing by the total length of the string. The algorithm uses only a few constant space variables to store the count of the letter and potentially the length of the string. No auxiliary data structures, like arrays or hash maps, are created that scale with the input size. Therefore, the space complexity is constant and does not depend on the length of the input string (N).

Edge Cases

CaseHow to Handle
Empty string sReturn 0 since the percentage of any character in an empty string is 0.
Null string sThrow IllegalArgumentException or return 0 (depending on requirements) to handle the invalid input.
Null character letterThrow IllegalArgumentException to indicate invalid input.
Empty character letterTreat it as a space or throw IllegalArgumentException based on requirements.
String s with length 1 and letter not equal to s[0]Return 0 since the letter does not appear in the string.
String s with length 1 and letter equal to s[0]Return 100 since the letter makes up 100% of the string.
Very long string s to test scalabilityThe solution iterates through the string once, which scales linearly with string length O(n).
String s consists entirely of the letter characterReturn 100, indicating that the letter accounts for 100% of the string.