algoadvance

Leetcode 2315. Count Asterisks

Problem Statement

You have a string s that consists of lower case English letters and symbols. The symbols are "*" and "|". We call a pair of bars a “barrier”. A pair of barriers divides the string into parts. Asterisks between consecutive bars are ignored, whereas those outside any barrier are counted.

You need to implement a function countAsterisks that accepts a string s and returns the total number of asterisks outside all the barriers.

Clarifying Questions

  1. What is the range of length for the string s?
    • The length can range from 1 to 1000.
  2. Does the string always contain an even number of bars |?
    • Yes, barriers will always be balanced, meaning every | has a corresponding closing |.
  3. Are empty parts between barriers allowed?
    • Yes, there may be no characters between a pair of bars.
  4. Can the string contain no barriers?
    • Yes, the string can have no | symbols.

Strategy

  1. Initialize Counters: Initialize a counter to keep track of the asterisks outside barriers and a flag to indicate whether we are inside a barrier section or not.

  2. Iterate Through the String:
    • Toggle the barrier flag when encountering a |.
    • Count asterisks only when the barrier flag is not active.
  3. Return the Counter: Finally, return the counter of asterisks outside barriers.

Code

public class Solution {
    public int countAsterisks(String s) {
        int asteriskCount = 0;
        boolean insideBarrier = false;

        for (char c : s.toCharArray()) {
            if (c == '|') {
                insideBarrier = !insideBarrier;
            } else if (c == '*' && !insideBarrier) {
                asteriskCount += 1;
            }
        }

        return asteriskCount;
    }
}

Time Complexity

This solution is efficient given the constraints and handles all edge cases specified in the problem.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI