Count Asterisks - Problem

Imagine you have a string containing text, asterisks (*), and vertical bars (|) that act as toggle switches. Your mission is to count the asterisks, but here's the twist: some asterisks are "hidden" between pairs of vertical bars!

The Rules:

  • Vertical bars (|) always come in pairs: the 1st and 2nd form a pair, the 3rd and 4th form a pair, and so on
  • Asterisks between a pair of vertical bars are hidden and should NOT be counted
  • Asterisks outside any pair should be counted

Example: In the string "l|*e*et|c**o|*de|", the asterisks between the 1st-2nd bars (*e*) and between the 3rd-4th bars (*) are hidden. Only the two asterisks in c**o should be counted, giving us 2.

Think of the vertical bars as curtains that hide the asterisks inside them!

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "l|*e*et|c**o|*de|"
โ€บ Output: 2
๐Ÿ’ก Note: The asterisks between the 1st-2nd bars (*e*) and between the 3rd-4th bars (*) are hidden. Only the two asterisks in 'c**o' are visible and counted.
example_2.py โ€” No Hidden Stars
$ Input: s = "iamprogrammer"
โ€บ Output: 0
๐Ÿ’ก Note: There are no asterisks in the string, so the count is 0.
example_3.py โ€” All Stars Visible
$ Input: s = "yo|bro|***|sis|"
โ€บ Output: 3
๐Ÿ’ก Note: All three asterisks are between the 2nd and 3rd bars (in the visible area), so all are counted.

Constraints

  • 1 โ‰ค s.length โ‰ค 1000
  • s consists of lowercase English letters, '*', and '|'
  • s contains an even number of '|'

Visualization

Tap to expand
๐ŸŽญ Theater Stage AnalogyStage View||||VISIBLECount: 2HIDDENCount: 0VISIBLECount: 3HIDDENCount: 0Total Visible Spotlights: 5๐Ÿ’ก Key Insight: Toggle state on each curtain, count only in visible areas
Understanding the Visualization
1
Curtains Open
We start with curtains open (visible=true). Any asterisks here are counted.
2
First Curtain
When we hit the first '|', the curtain closes (visible=false). Asterisks are now hidden.
3
Second Curtain
The next '|' opens the curtain again (visible=true). We can count asterisks again.
4
Continue Pattern
This pattern continues: each '|' toggles between open/closed states.
Key Takeaway
๐ŸŽฏ Key Insight: The optimal solution treats each vertical bar as a toggle switch. We maintain a single boolean state and flip it each time we encounter a bar. This elegant approach eliminates the need to track all bar positions and pair relationships, achieving O(n) time complexity.
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
22.3K Views
Medium Frequency
~5 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen