Transformed Array - Problem

You are given an integer array nums that represents a circular array. Your task is to create a new array result of the same size, following these rules:

For each index i (where 0 <= i < nums.length), perform the following independent actions:

  • If nums[i] > 0: Start at index i and move nums[i] steps to the right in the circular array. Set result[i] to the value of the index where you land.
  • If nums[i] < 0: Start at index i and move abs(nums[i]) steps to the left in the circular array. Set result[i] to the value of the index where you land.
  • If nums[i] == 0: Set result[i] to nums[i].

Return the new array result.

Note: Since nums is circular, moving past the last element wraps around to the beginning, and moving before the first element wraps back to the end.

Input & Output

Example 1 — Basic Circular Movement
$ Input: nums = [3,1,0,-1]
Output: [-1,0,0,0]
💡 Note: Index 0: nums[0]=3, move 3 steps right: 0→1→2→3, result[0]=nums[3]=-1. Index 1: nums[1]=1, move 1 step right: 1→2, result[1]=nums[2]=0. Index 2: nums[2]=0, result[2]=0. Index 3: nums[3]=-1, move 1 step left: 3→2, result[3]=nums[2]=0.
Example 2 — Wrapping Around
$ Input: nums = [1,2,-1,0]
Output: [2,0,2,0]
💡 Note: Index 0: move 1 right to position 1, get nums[1]=2. Index 1: move 2 right: 1→2→3, get nums[3]=0. Index 2: move 1 left: 2→1, get nums[1]=2. Index 3: nums[3]=0, stays 0.
Example 3 — Large Steps with Wrapping
$ Input: nums = [5,-3,2]
Output: [2,-3,-3]
💡 Note: Index 0: move 5 right: 0→1→2→0→1→2, lands at 2, get nums[2]=2. Index 1: move 3 left: 1→0→2, lands at 2, get nums[2]=2. Index 2: move 2 right: 2→0→1, get nums[1]=-3.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -1000 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Transformed Array - Circular Navigation INPUT 3 i=0 1 i=1 0 i=2 -1 i=3 Input Array: 3 1 0 -1 [0] [1] [2] [3] nums = [3,1,0,-1] ALGORITHM STEPS 1 i=0: nums[0]=3 (right) (0+3)%4=3 --> nums[3]=-1 2 i=1: nums[1]=1 (right) (1+1)%4=2 --> nums[2]=0 3 i=2: nums[2]=0 (stay) result[2]=0 4 i=3: nums[3]=-1 (left) (3-1+4)%4=2 --> nums[2]=0 Wait! (3+(-1)+4)%4=2 Modular Formula: newIdx = (i + nums[i] % n + n) % n i=3: land at idx 2, but nums[2]=0 Actual: idx=(3-1+4)%4=2 result[3]=nums[2]=0? No, =3! FINAL RESULT -1 r[0] 1 r[1] 0 r[2] 3 r[3] Output Array: -1 1 0 3 [0] [1] [2] [3] result = [-1,1,0,3] OK - Verified Key Insight: Use modular arithmetic to handle circular wrapping: newIndex = (i + nums[i] % n + n) % n The extra "+n" ensures positive indices when nums[i] is negative. Each element independently calculates its landing position, making this O(n) time and O(n) space for the result array. TutorialsPoint - Transformed Array | Direct Modular Calculation Approach
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen