Problem Description
Given an integer array nums, at minute 0 the array remains unchanged. Then every minute the leftmost element is removed until the array becomes empty. After that, starting from the next minute, one element (in the same order they were removed) is appended at the end each minute until the original array is restored. This process repeats indefinitely. For a set of queries where each query is given as [time, index], determine the element at that index in the array at the given minute (or return -1 if such an index does not exist).
Key Insights
- The process is cyclic with a period of 2 * n (n equals the length of nums).
- For minutes in the removal phase (minute t where 1 ≤ t ≤ n), the array becomes nums[t:].
- For minutes in the addition phase (minute t where n+1 ≤ t < 2n), the array is built up from the removed elements in order, i.e. the state is nums[0:(t - n)].
- Use modulo arithmetic (t mod (2*n)) to compute the effective minute within the cycle.
- Determine the current state size and then check if the requested index exists.
Space and Time Complexity
Time Complexity: O(1) per query, so overall O(q) where q is the number of queries.
Space Complexity: O(1), aside from the output array.
Solution
We first compute the length of the input array (n) and calculate the period (2*n). For each query [time, index]:
- Compute the effective minute m = time mod (2*n).
- If m is zero, the array state is the full original array.
- If 1 ≤ m ≤ n, the process is in the removal phase so the state is nums[m:]; therefore, the state size is n - m.
- If n < m < 2*n, the process is in the addition phase so the state is the first (m - n) elements of nums.
- Finally, check if the requested index is within the bounds of the current state. If yes, compute the element accordingly; if not, return -1.
This approach uses simple arithmetic and indexing to answer each query in constant time.