Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Percentage of Letter in String

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2278" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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.

Explanation

  • Iterate through the input string s and count the occurrences of the target character letter.
    • Calculate the percentage of letter in s by dividing the count by the length of s and multiplying by 100.
    • Return the integer part of the calculated percentage (rounding down).
  • Runtime Complexity: O(n), where n is the length of the string s. Storage Complexity: O(1).

Code

    def percentageLetter(s: str, letter: str) -> int:
    """
    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.
    """
    count = 0
    for char in s:
        if char == letter:
            count += 1
    return (count * 100) // len(s)

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Percentage of Letter in String