Frogs are sitting on the x-axis of the plane. The ...
Created on: July 12, 2025
Created on: July 12, 2025
Frogs are sitting on the x-axis of the plane. The x-axis is represented by a given string. represents a frog and represents a stone. The string consists of only the above-mentioned characters. You are given a start index array and end index array, and calculate the number of frogs between the two stones including the endpoint. Note-Array is 1 indexed
6018-48
Sc
Input Format
First line contains a string containing (frogs) and (stones).
Second line contains an integer n denoting the number of test cases.
Third line contains for each test case, two integers start and end (1-indexed) specifying the range on the x-axis to check for the frogs.
Output Format
b01848
x
FI
Output contains for each test case, the number of frogs (*) between the two stones (1) at the given start and end indices, including the endpoints.
code in python
Below is a concise, O(N + Q) Python solution (where N is the length of the x-axis string and Q the number of test cases).
The key idea is the same one used for the classic “plates between candles” problem:
Pre-compute
prefix[i]
– number of frogs (*
) up to and including position i.nearest_left_stone[i]
– index of the closest stone (1
) at or to the left of i (‒1 if none).nearest_right_stone[i]
– index of the closest stone (1
) at or to the right of i (‒1 if none).Answer each query [L, R]
(1-indexed):
l = L-1
, r = R-1
.left = nearest_right_stone[l]
(first stone ≥ l).right = nearest_left_stone[r]
(last stone ≤ r).left >= right
, there is no enclosing pair ⇒ answer 0.prefix[right] – prefix[left]
.pythonimport sys def preprocess(s: str): n = len(s) prefix = [0] * (n + 1) # prefix[0] = 0 nearest_left = [-1] * n nearest_right = [-1] * n # prefix sum of frogs for i, ch in enumerate(s): prefix[i + 1] = prefix[i] + (ch == '*') # nearest stone on the left last = -1 for i in range(n): if s[i] == '1': # stone last = i nearest_left[i] = last # nearest stone on the right last = -1 for i in range(n - 1, -1, -1): if s[i] == '1': last = i nearest_right[i] = last return prefix, nearest_left, nearest_right def frogs_between_stones(s: str, queries): prefix, left_stone, right_stone = preprocess(s) res = [] for L, R in queries: # both are 1-indexed l, r = L - 1, R - 1 left = right_stone[l] # first stone inside/on left bound right = left_stone[r] # last stone inside/on right bound if left == -1 or right == -1 or left >= right: res.append(0) else: res.append(prefix[right] - prefix[left]) return res def main(): data = sys.stdin.read().strip().split() s = data[0] q = int(data[1]) nums = list(map(int, data[2:])) queries = list(zip(nums[::2], nums[1::2])) answers = frogs_between_stones(s, queries) print("\n".join(map(str, answers))) if __name__ == "__main__": main()
You can run this script, provide the string, the number of test cases, and each start end
pair, and it will print one answer per line.