Ctrl K

Shrink and Regrow

Medium
You are given an array values. At minute 0 it is complete. Then, every minute, its leftmost element is removed until the array is empty. After that, every minute one element is put back at the end, in the order they were removed, until the original array is restored. The whole cycle then repeats forever. For example, [4, 8] goes [4, 8] → [8] → [] → [4] → [4, 8] → [8] → ... You are also given queries, where queries[j] = [time, index]. The answer to a query is the element at position index (0-based) at minute time, or -1 if the array has fewer than index + 1 elements at that moment. Return the answers to all queries, in order.
Example 1
values=[7, 3, 9], queries=[[1, 1], [3, 0], [4, 0], [7, 0]] → [9, -1, 7, 3]

Minute 1: [3, 9], position 1 holds 9. Minute 3: the array is empty, so -1. Minute 4: [7], the answer is 7. A cycle lasts 6 minutes, so minute 7 looks like minute 1: [3, 9], position 0 holds 3.

Example 2
values=[5, 1], queries=[[0, 1], [2, 0], [3, 1], [5, 1]] → [1, -1, -1, -1]

Minute by minute: [5, 1] → [1] → [] → [5] → [5, 1] → [1] → ... At minute 3 only position 0 exists, and at minute 5 the array again has a single element.

Constraints
  • 1 ≤ len(values) ≤ 100
  • 0 ≤ values[i] ≤ 100
  • 1 ≤ len(queries) ≤ 10⁵
  • 0 ≤ time ≤ 10⁵
  • 0 ≤ index < len(values)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumZero-Sum Triples MediumTriple Sum Nearest the Target MediumFour Numbers to a Target MediumNext Arrangement in Order Medium
loading Python…
Input
values=[7, 3, 9], queries=[[1, 1], [3, 0], [4, 0], [7, 0]]
Expected
[9, -1, 7, 3]

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