This problem involves simulating the described array manipulation process and answering queries about the array's state at specific times. The key to efficient solution lies in understanding the cyclical nature of the array's transformations.
Understanding the Pattern:
The array undergoes a cycle of removals and additions. The cycle length is 2 * n
, where n
is the length of the original array.
n
minutes: Elements are removed from the left, one per minute.n
minutes: Elements are added to the right, in the order they were removed.This cycle repeats infinitely. Therefore, we can determine the array's state at any minute t
by taking t modulo (2 * n)
.
Algorithm:
Initialization: Create a result array ans
to store the answers to each query. Initialize all elements to -1 (default value for an invalid index).
Query Processing: Iterate through the queries
array. For each query [time, index]
:
a. Cycle Reduction: Calculate t = time % (2 * n)
. This effectively reduces the time to its position within the current cycle.
b. Index Calculation:
t < n
: This means we are in the removal phase. The array length is n - t
. If index < n - t
, the element at index index
is the original element at index index + t
.t >= n
: This means we are in the addition phase. The array length is t - n
. If index < t - n
, the element at index index
is the original element at index index
.c. Result Update: If the index is valid within the array's current length, update ans[query_index]
with the corresponding element from the original nums
array. Otherwise, leave it as -1.
Return Result: Return the ans
array.
Time Complexity: O(m), where m is the number of queries. The algorithm iterates through each query once, performing constant-time operations for each.
Space Complexity: O(1) excluding the output array. The algorithm uses a constant amount of extra space.
Code Implementation (Python):
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, (time, index) in enumerate(queries):
t = time % (2 * n)
if t < n and index < n - t:
ans[j] = nums[index + t]
elif t >= n and index < t - n:
ans[j] = nums[index]
return ans
The implementations in other languages (Java, C++, Go, TypeScript) follow the same logic with only syntactic differences. The core algorithmic approach remains consistent across all languages.