Magicsheet logo

Count Asterisks

Easy
25%
Updated 8/1/2025

Asked by 1 Company

Topics

Count Asterisks

What is this problem about?

In the Count Asterisks interview question, you are given a string s that contains lowercase letters, vertical bars |, and asterisks *. The vertical bars come in pairs. You need to count the total number of asterisks in the string, but you must exclude any asterisks that are located between a pair of vertical bars.

Why is this asked in interviews?

Google uses the Count Asterisks coding problem as an "Easy" difficulty screening question. it evaluates whether you can process a string while maintaining a simple boolean state (e.g., insidePair). It tests your ability to follow logical constraints and implement a single-pass solution.

Algorithmic pattern used

This follows a State Machine / Flag pattern.

  1. Initialize a counter count = 0 and a boolean flag inside = false.
  2. Iterate through the string.
  3. If you see |, flip the inside flag.
  4. If you see * and inside is false, increment the counter.
  5. Return the count.

Example explanation

Input: s = "l|*e*et|c**o|*de|"

  1. l: Skip.
  2. |: inside = true.
  3. *: Skip (because inside is true).
  4. e: Skip.
  5. *: Skip.
  6. e, t: Skip.
  7. |: inside = false.
  8. c: Skip.
  9. *: count = 1.
  10. *: count = 2. Result: 2.

Common mistakes candidates make

  • Complex Split: Trying to use s.split('|') and then handling the logic, which can be more confusing than a simple loop.
  • Nested Flags: Over-complicating the logic with multiple flags when one boolean is enough.
  • Unpaired Bars: While the problem usually guarantees pairs, not thinking about what happens if a bar is left "open."

Interview preparation tip

This problem is a simplified version of "Parsing" (like checking for balanced parentheses). Practice using flags to track context while scanning linear data.

Similar Questions