algoadvance

Leetcode 2278. Percentage of Letter in String

Problem Statement

Given a string s and a character letter, return the percentage of characters in the string s that equal letter rounded down to the nearest integer.

Clarifying Questions

  1. Input Constraints:
    • What is the length of the string s? (Typically, for LeetCode problems, inputs can vary, but a common constraint could be ( 1 \leq s \leq 1000 )).
    • Is the string s guaranteed to contain only lowercase/uppercase alphabetic characters, or can there be other characters?

    • Character Case Sensitivity:
    • Should the comparison between characters be case-sensitive or case-insensitive?
  2. Output Requirements:
    • How should we handle an empty string or letter not present in the string? (Considering the given problem structure, we can assume the string will not be empty.)
    • Rounding down the percentage should be done using integer division, correct?

Code

#include <string>
#include <cmath>

int percentageLetter(std::string s, char letter) {
    int count = 0;
    int length = s.length();
    
    for (char c : s) {
        if (c == letter) {
            count++;
        }
    }
    
    // Calculate the percentage and round down
    int percentage = (count * 100) / length;
    
    return percentage;
}

Strategy

  1. Initialize Counters:
    • We need a counter count to keep track of how many times letter appears in the string s.
    • Also, keep track of the length of the string using length = s.length().
  2. Count Occurrences:
    • Iterate through each character in the string:
      • If the character matches letter, increment the count.
  3. Calculate Percentage:
    • Calculate the percentage of occurrences by (count * 100) / length.
    • Since integer division in C++ automatically floors the result towards zero, this will yield the rounded-down integer percentage directly.
  4. Return Result:
    • Return the calculated percentage.

Time Complexity

This approach ensures that the function runs efficiently even for the upper limits of string length.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI