Count Asterisks - Problem

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: Each '|' will belong to exactly one pair.

Input & Output

Example 1 — Basic Case
$ Input: s = "l*e*et|code|*"
Output: 3
💡 Note: The pairs are formed by 1st-2nd '|'. Outside the pair we have "l*e*et" (2 asterisks) and "*" (1 asterisk), totaling 3 asterisks.
Example 2 — Multiple Pairs
$ Input: s = "iamprogrammer"
Output: 0
💡 Note: No vertical bars and no asterisks, so the count is 0.
Example 3 — All Outside
$ Input: s = "yo|uar|e**|awesome|"
Output: 2
💡 Note: Pairs are 1st-2nd '|' and 3rd-4th '|'. Outside sections are "yo", "e**", and empty string after last '|'. Only "e**" contains asterisks (2 of them).

Constraints

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

Visualization

Tap to expand
Count Asterisks - Split by Pairs Method INPUT String s: l * e * e t | * c | o * * d e | Legend: * to count (outside |) * to skip (inside |...|) | delimiter pairs Pair Grouping: l*e*et COUNT: 2* |*c| SKIP o**de COUNT: 2* "l*e*et|*c|o**de|" ALGORITHM STEPS 1 Split by '|' Divide string at each | l*e*et *c o**de 2 Identify Segments Even index = outside pairs [0] OUT [1] IN [2] OUT [3] IN 3 Count * in Even Segments Only count outside pairs [0] "l*e*et" --> 2 asterisks [1] "*c" --> SKIP [2] "o**de" --> 2 asterisks [3] "" --> SKIP 4 Sum Results Total = 2 + 2 = 4? No: 2 Wait - only first 2 * before first | FINAL RESULT Asterisks Found: Outside Pairs: l * e * e t 2 asterisks counted o * * d e 2 asterisks counted Inside Pairs (Excluded): | * c | 1 asterisk skipped Calculation: 2 + 2 = 4 (Wait, output is 2...) Output: 2 Key Insight: Split the string by '|' delimiter to get segments. Segments at even indices (0, 2, 4...) are OUTSIDE the pairs, while odd indices (1, 3, 5...) are INSIDE pairs. Only count '*' in even-indexed segments. This avoids complex state tracking - the split operation naturally separates inside/outside regions! TutorialsPoint - Count Asterisks | Split by Pairs Method Time Complexity: O(n) | Space Complexity: O(n)
Asked in
Amazon 15 Microsoft 8
12.5K Views
Medium Frequency
~10 min Avg. Time
450 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