FastPrepStars and Bars

Stars and Bars

TikTok logoTikTok● MediumNEW GRADOA

Problem statement

Given a string s consisting of stars "*" and bars "|", an array of starting indices startIndex, and an array of ending indices endIndex, determine the number of stars between any two bars within the substring between the two indices, inclusive. Note that in this problem, indexing starts at 1.

  • A star is represented as an asterisk ("*" = ascii decimal 42)
  • A bar is represented as a pipe ("|" = ascii decimal 124)

Function

starsAndBars(s: String, startIndex: int[], endIndex: int[]) → int[]

Complete the function starsAndBars in the editor.

starsAndBars has three parameters:

  1. 1. String s: a string to evaluate
  2. 2. int[] startIndex: the starting index for each query
  3. 3. int[] endIndex: the ending index for each query

Returns int[]: element i answers the query from startIndex[i] through endIndex[i]

Examples

Example 1

s = "|**|*|*"startIndex = [1, 1]endIndex = [5, 6]return = [2, 3]

For the first pair of indices, (1, 5), the substring is "|**|*". There are 2 stars between a pair of bars. For the second pair of indices, (1, 6), the substring is "|**|*|". There are 2 + 1 = 3 stars between bars. Both of the answers are returned in an array, [2, 3].

Example 2

s = "|*|*|"startIndex = [1]endIndex = [3]return = [1]

The substring from index = 1 to index = 3 is "|*|". Its two bars enclose one star, so the answer is [1].

Constraints

  • 1 ≤ s.length ≤ 105
  • 1 ≤ startIndex.length = endIndex.length ≤ 105
  • 1 ≤ startIndex[i] ≤ endIndex[i] ≤ s.length
  • Each character of s is either "*" or "|"

More TikTok problems

See TikTok hiring insights
Saved
public int[] starsAndBars(String s, int[] startIndex, int[] endIndex) {
    // write your code here
}
s"|**|*|*"
startIndex[1, 1]
endIndex[5, 6]
expected[2, 3]
Checking account…