Ctrl K

Books Between Bookends

Medium
A library shelf is described by the string shelf: '*' is a book and '|' is a bookend. Positions are 0-based. The list ranges holds queries [left, right]. Each query looks only at the part of the shelf from left to right inclusive and asks how many books in that part are held in place, meaning they have at least one bookend to their left and at least one to their right within that part. Bookends outside the part do not count. Return the answers in the order of the queries. There can be a great many queries, so rescanning each part from scratch will be too slow.
Example 1
shelf="|**|*|**", ranges=[[0, 5], [1, 7], [4, 7]] → [3, 1, 0]

In |**|*| all three books sit between bookends. In **|*|** the bookends are at positions 3 and 5 with one book between them. *|** has only one bookend, so the answer is 0.

Example 2
shelf="*|***|*", ranges=[[0, 6], [2, 4]] → [3, 0]

Across the whole shelf three books are held between the bookends at 1 and 5; the books at the edges do not count. The segment *** has no bookends at all.

Constraints
  • 3 ≤ len(shelf) ≤ 3·10⁵
  • shelf consists only of '*' and '|'
  • 1 ≤ len(ranges) ≤ 10⁵
  • ranges[i] = [left, right], 0 ≤ left ≤ right < len(shelf)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFew Zeros or Few Ones: Range Queries HardShortest Stretch to the Goal MediumWindows With a Small Product MediumWords Hidden in a Text MediumRoll Letters by Prefix Medium
loading Python…
Input
shelf="|**|*|**", ranges=[[0, 5], [1, 7], [4, 7]]
Expected
[3, 1, 0]

Run checks the first 3 tests in your browser. Submit checks all 15 tests on the server, hidden ones included.