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 arrayqueries of size n where queries[j] = [timej, indexj]. The answer to the jth query is:
nums[indexj] if indexj < nums.length at minute timej
-1 if indexj >= nums.length at minute timej
Return an integer array ans of size n where ans[j] is the answer to the jth query.
Input & Output
Example 1 — Basic Cycle
$Input:nums = [0,1,2], queries = [[3,1],[4,2]]
›Output:[-1,-1]
💡 Note:At time 3: array is [], so index 1 doesn't exist → -1. At time 4: array is [0], so index 2 doesn't exist → -1
Example 2 — Removal Phase
$Input:nums = [2], queries = [[0,0],[1,0]]
›Output:[2,-1]
💡 Note:At time 0: array is [2], index 0 exists → 2. At time 1: array is [], index 0 doesn't exist → -1
Example 3 — Multiple Cycles
$Input:nums = [1,2], queries = [[4,0],[6,1]]
›Output:[1,2]
💡 Note:Cycle length is 4. At time 4 (4%4=0): back to original [1,2], index 0 → 1. At time 6 (6%4=2): restoration phase → 2
Elements in Array After Removing and Replacing Elements — Solution
The key insight is recognizing the array follows a predictable 2n-minute cycle: n minutes of removal followed by n minutes of restoration. Best approach uses modular arithmetic to directly calculate array state without simulation. Time: O(m), Space: O(1)
Common Approaches
✓
Hash Map
⏱️ Time: N/A
Space: N/A
Brute Force Simulation
⏱️ Time: O(m × t)
Space: O(n)
For each query, simulate the array transformations minute by minute until reaching the target time. Remove elements from left during removal phase, add elements back during restoration phase.
Mathematical Pattern Recognition
⏱️ Time: O(m)
Space: O(1)
Recognize that the array follows a predictable cycle of 2n minutes. Use modular arithmetic to determine the exact state of the array at any given time without simulating each step.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int nums[5000];
static int queries[5000][2];
static int result[5000];
int parseArray(char* str, int* arr) {
if (strcmp(str, "[]") == 0) return 0;
int count = 0;
char* ptr = str + 1; // Skip '['
while (*ptr && *ptr != ']') {
while (*ptr && (*ptr == ' ' || *ptr == ',')) ptr++;
if (*ptr && *ptr != ']') {
arr[count++] = (int)strtol(ptr, &ptr, 10);
}
}
return count;
}
int parseQueries(char* str, int queries[][2]) {
if (strcmp(str, "[]") == 0) return 0;
int count = 0;
char* ptr = str + 1; // Skip outer '['
while (*ptr && *ptr != ']') {
// Find start of query
while (*ptr && *ptr != '[') ptr++;
if (!*ptr || *ptr == ']') break;
ptr++; // Skip '['
// Parse time
queries[count][0] = (int)strtol(ptr, &ptr, 10);
// Skip comma
while (*ptr && *ptr != ',') ptr++;
if (*ptr) ptr++;
// Parse index
queries[count][1] = (int)strtol(ptr, &ptr, 10);
count++;
// Skip to next query
while (*ptr && *ptr != ']') ptr++;
if (*ptr) ptr++; // Skip ']'
}
return count;
}
void solution(int* nums, int numsSize, int queries[][2], int queriesSize, int* result) {
for (int i = 0; i < queriesSize; i++) {
int time = queries[i][0];
int index = queries[i][1];
// Calculate effective time within cycle
int cycleLength = 2 * numsSize;
int effectiveTime = time % cycleLength;
if (effectiveTime < numsSize) {
// Removal phase: array has (numsSize - effectiveTime) elements
int currentLength = numsSize - effectiveTime;
if (index >= currentLength) {
result[i] = -1;
} else {
// Element at index corresponds to nums[effectiveTime + index]
result[i] = nums[effectiveTime + index];
}
} else {
// Restoration phase: array has (effectiveTime - numsSize) elements
int restoredCount = effectiveTime - numsSize;
if (index >= restoredCount) {
result[i] = -1;
} else {
// Element at index corresponds to nums[index]
result[i] = nums[index];
}
}
}
}
int main() {
char numsStr[50000], queriesStr[50000];
fgets(numsStr, sizeof(numsStr), stdin);
fgets(queriesStr, sizeof(queriesStr), stdin);
// Remove newlines
numsStr[strcspn(numsStr, "\n")] = 0;
queriesStr[strcspn(queriesStr, "\n")] = 0;
int numsSize = parseArray(numsStr, nums);
int queriesSize = parseQueries(queriesStr, queries);
solution(nums, numsSize, queries, queriesSize, result);
printf("[");
for (int i = 0; i < queriesSize; i++) {
printf("%d", result[i]);
if (i < queriesSize - 1) printf(",");
}
printf("]\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
⚡ Linearithmic Space
8.5K Views
MediumFrequency
~25 minAvg. Time
284 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.