#2315
Count Asterisks
EasyStringTwo PointersString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution efficiently counts asterisks by using a single pass through the string, toggling a flag when encountering vertical bars, and counting asterisks only when not between bars.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a counter for asterisks and a boolean flag to track if we are inside a pair of '|'.
- 2Step 2: Loop through each character in the string.
- 3Step 3: If the character is '|', toggle the boolean flag.
- 4Step 4: If the character is '*', check the boolean flag; if it's false, increment the counter.
- 5Step 5: Continue until the end of the string.
- 6Step 6: Return the total count of asterisks.
solution.py9 lines
1def countAsterisks(s):
2 count = 0
3 in_bar = False
4 for char in s:
5 if char == '|':
6 in_bar = not in_bar
7 elif char == '*' and not in_bar:
8 count += 1
9 return countℹ
Complexity note: The complexity is O(n) because we only traverse the string once, making it efficient for larger inputs.
- 1Only count asterisks when not between pairs of '|'.
- 2Efficiently toggle a flag to track whether we are inside a pair of bars.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.