Count Asterisks — Easy Problem & Solution
s is divided into pairs of vertical bars: the 1st and 2nd '|' form a pair, the 3rd and 4th another, and so on. s always holds an even number of bars.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, Google, Accenture
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
s is divided into pairs of vertical bars: the 1st and 2nd '|' form a pair, the 3rd and 4th another, and so on. s always holds an even number of bars.
Return the number of '*' characters that lie outside every such pair.
Example 1
Input: s = "code|*kai*|ro**"
Output: 2
Explanation: The two stars inside the bar pair are excluded; the trailing `**` counts.
Example 2
Input: s = "codekairo"
Output: 0
Explanation: No stars at all.
Example 3
Input: s = "yo|uar|e**|b|e***au|tifu|l"
Output: 5
Explanation: The segments outside the pairs are `yo`, `e**`, `e***au` and `l`.
Constraints
1 <= s.length <= 1000s consists of lowercase English letters, vertical bars '|' and asterisks '*'.s contains an even number of vertical bars '|'.
How to solve Count Asterisks
One pass with a single inside flag. Each bar toggles it; a star counts only when the flag is off.
Approach
- Start with
inside = falseandcount = 0. - For each character: a
'|'flipsinside; a'*'withinsidefalse incrementscount. - Return
count.
Why it works
Because the bar count is guaranteed even, a single toggling flag is enough — there is no nesting to track and no unbalanced bar to recover from. Splitting the string on '|' and summing the stars in the even-indexed pieces is the same idea written differently.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- The bars themselves are never counted, only the asterisks.
- A star sitting immediately after an opening bar is inside, not outside.
- The flag must toggle on every bar, including the closing one.
Reference solution
Python
def countAsterisks(s: str) -> int:
count = 0
inside = False
for c in s:
if c == "|":
inside = not inside
elif c == "*" and not inside:
count += 1
return countJavaScript
var countAsterisks = function(s) {
var count = 0, inside = false;
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
if (c === "|") inside = !inside;
else if (c === "*" && !inside) count++;
}
return count;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.