We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Asterisks

Number: 2401

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given a string s, count the number of asterisks '*' that are not between paired vertical bars '|'. The vertical bars come in pairs (first with second, third with fourth, etc.), and any asterisks between a pair are ignored.


Key Insights

  • Use a flag to keep track of whether you are inside a pair of vertical bars.
  • Iterate through the string once, toggling the flag every time you encounter a '|'.
  • Count asterisks only when the flag indicates you are outside of any paired vertical bars.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string s. Space Complexity: O(1), as only a few variables are used regardless of input size.


Solution

We solve the problem by iterating through the string and maintaining a boolean variable that indicates if we are inside a pair of vertical bars. Every time we see a '|', we flip the state of the flag. If the current character is an asterisk '*' and the flag is false (indicating we are outside a paired region), we increment our counter. This simple iteration makes the solution both efficient and easy to understand.


Code Solutions

# Python solution with line-by-line comments

def countAsterisks(s: str) -> int:
    # Initialize a counter for asterisks and a flag for tracking delimited segments.
    asterisk_count = 0
    inside_bar_pair = False

    # Iterate over each character in the string.
    for char in s:
        # If the current character is a vertical bar, toggle the inside_bar_pair flag.
        if char == '|':
            inside_bar_pair = not inside_bar_pair
        # If the character is an asterisk and we are not within a bar pair, count it.
        elif char == '*' and not inside_bar_pair:
            asterisk_count += 1

    # Return the total count of asterisks outside any bar pairs.
    return asterisk_count

# Example usage:
# print(countAsterisks("l|*e*et|c**o|*de|")) would output 2
← Back to All Questions