Elements in Array After Removing and Replacing Elements Problem
Description
LeetCode Problem 2113.
You are given a 0-indexed integer array nums. Initially on minute 0, the array is unchanged. Every minute, the leftmost element in nums is removed until no elements remain. Then, every minute, one element is appended to the end of nums, in the order they were removed in, until the original array is restored. This process repeats indefinitely.
- For example, the array
[0,1,2]would change as follows:[0,1,2] → [1,2] → [2] → [] → [0] → [0,1] → [0,1,2] → [1,2] → [2] → [] → [0] → [0,1] → [0,1,2] → ...
You are also given a 2D integer array queries of size n where queries[j] = [time_j, index_j]. The answer to the j^th query is:
nums[index_j]ifindex_j < nums.lengthat minutetime_j-1ifindex_j >= nums.lengthat minutetime_j
Return an integer array ans of size n where ans[j] is the answer to the j^th query.
Example 1:
Input: nums = [0,1,2], queries = [[0,2],[2,0],[3,2],[5,0]]
Output: [2,2,-1,0]
Explanation:
Minute 0: [0,1,2] - All elements are in the nums.
Minute 1: [1,2] - The leftmost element, 0, is removed.
Minute 2: [2] - The leftmost element, 1, is removed.
Minute 3: [] - The leftmost element, 2, is removed.
Minute 4: [0] - 0 is added to the end of nums.
Minute 5: [0,1] - 1 is added to the end of nums.
At minute 0, nums[2] is 2.
At minute 2, nums[0] is 2.
At minute 3, nums[2] does not exist.
At minute 5, nums[0] is 0.
Example 2:
Input: nums = [2], queries = [[0,0],[1,0],[2,0],[3,0]]
Output: [2,-1,2,-1]
Minute 0: [2] - All elements are in the nums.
Minute 1: [] - The leftmost element, 2, is removed.
Minute 2: [2] - 2 is added to the end of nums.
Minute 3: [] - The leftmost element, 2, is removed.
At minute 0, nums[0] is 2.
At minute 1, nums[0] does not exist.
At minute 2, nums[0] is 2.
At minute 3, nums[0] does not exist.
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 100n == queries.length1 <= n <= 10^5queries[j].length == 20 <= time_j <= 10^50 <= index_j < nums.length
Solution
Approach: Direct calculation
The array state repeats every 2n minutes, so reduce each query time t modulo 2n and look at two phases:
- If
t < n, the firsttelements have been removed, leavingn - telements:nums[t..n-1]. So wheni < n - tthe answer isnums[i + t]. - If
t >= n, elements are being restored one per minute, so the array is the firstt - nelements ofnums. So wheni < t - nthe answer isnums[i].
In every other case the index is out of range and the answer is -1.
Complexity: O(m) time for m queries, O(1) extra space besides the answer.
class Solution:
def elementInNums(self, nums: List[int], queries: List[List[int]]) -> List[int]:
n, m = len(nums), len(queries)
ans = [-1] * m
for j, (t, i) in enumerate(queries):
t %= 2 * n
if t < n and i < n - t:
ans[j] = nums[i + t]
elif t > n and i < t - n:
ans[j] = nums[i]
return ans