algoadvance

Leetcode 2278. Percentage of Letter in String

Problem Statement

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

The formula to calculate the percentage is: [ \text{percentage} = \left(\frac{\text{number of occurrences of letter}}{\text{length of s}}\right) \times 100 ]

Clarifying Questions

  1. Input Constraints:
    • What is the length range of the string s? (Typically, constraints might be 1 <= s <= 100)
    • Is the string s always non-empty?
    • Can s contain non-alphabetic characters?
  2. Case Sensitivity:
    • Should the character matching be case sensitive or insensitive? (Assuming case sensitive unless specified otherwise)
  3. Output Rounding:
    • Should the percentage be rounded down to the nearest whole number after the calculation? (Assuming yes, based on the problem statement)

Strategy

  1. Count Occurrences: Iterate through the string s to count the occurrences of letter.
  2. Calculate Percentage: Use the formula to calculate the percentage.
  3. Round Down: Use integer division to round down the percentage to the nearest whole number.

Time Complexity

Code

public class Solution {
    public int percentageLetter(String s, char letter) {
        int count = 0;
        int length = s.length();
        
        // Count the occurrences of `letter` in the string
        for (int i = 0; i < length; i++) {
            if (s.charAt(i) == letter) {
                count++;
            }
        }
        
        // Calculate the percentage and round down using integer division
        int percentage = (count * 100) / length;
        
        return percentage;
    }
    
    public static void main(String[] args) {
        Solution solution = new Solution();
        // Test cases
        System.out.println(solution.percentageLetter("foobar", 'o'));    // Expected output: 33
        System.out.println(solution.percentageLetter("jjjj", 'j'));      // Expected output: 100
        System.out.println(solution.percentageLetter("abcde", 'f'));     // Expected output: 0
    }
}

Explanation

  1. Counting Occurrences:
    • We initialize count to zero.
    • We iterate through each character of the string s and increment count whenever we find the character letter.
  2. Calculating Percentage:
    • The percentage is computed using the formula ((\text{count} \times 100) / \text{length}).
    • Since we’re using integer division, this automatically rounds down the percentage.
  3. Return Result:
    • The computed percentage is then returned as an integer.

This way, we can effectively compute the percentage of occurrences of a given character in a string, rounded down to the nearest whole percentage.

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