Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count Asterisks

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2315" 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

You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth. Return the number of '' in s, excluding the '' between each pair of '|'. Note that each '|' will belong to exactly one pair. Example 1: Input: s = "l|eet|co|de|" Output: 2 Explanation: The considered characters are underlined: "l|e*et|co|de|". The characters between the first and second '|' are excluded from the answer. Also, the characters between the third and fourth '|' are excluded from the answer. There are 2 asterisks considered. Therefore, we return 2. Example 2: Input: s = "iamprogrammer" Output: 0 Explanation: In this example, there are no asterisks in s. Therefore, we return 0. Example 3: Input: s = "yo|uar|e|b|eau|tifu|l" Output: 5 Explanation: The considered characters are underlined: "yo|uar|e|b|e*au|tifu|l". There are 5 asterisks considered. Therefore, we return 5. Constraints: 1 <= s.length <= 1000 s consists of lowercase English letters, vertical bars '|', and asterisks '*'. s contains an even number of vertical bars '|'.

Explanation

Here's the solution:

  • Iterate through the string. Maintain a boolean variable to track whether we are currently "inside" a pair of vertical bars.
  • If we encounter a vertical bar, flip the boolean. If we are not inside a pair, and we encounter an asterisk, increment the counter.
  • Return the final count.

  • Runtime Complexity: O(n), where n is the length of the string. Storage Complexity: O(1).

Code

    def countAsterisks(s: str) -> int:
    """
    Counts the number of asterisks in the string s, excluding the asterisks between pairs of vertical bars.

    Args:
        s: The input string.

    Returns:
        The number of asterisks outside the vertical bar pairs.
    """

    count = 0
    inside_bars = False
    for char in s:
        if char == '|':
            inside_bars = not inside_bars
        elif char == '*' and not inside_bars:
            count += 1
    return count

More from this blog

C

Chatmagic blog

2894 posts