Description
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:
i (where 0 <= i < nums.length), perform the following independent actions:
- If
nums[i] > 0: Start at indexiand movenums[i]steps to the right in the circular array. Setresult[i]to the value at the index where you land. - If
nums[i] < 0: Start at indexiand moveabs(nums[i])steps to the left in the circular array. Setresult[i]to the value at the index where you land. - If
nums[i] == 0: Setresult[i]tonums[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.
Example 1:
Input: nums = [3,-2,1,1]
Output: [1,1,1,3]
Explanation:
- For
nums[0]that is equal to 3, If we move 3 steps to right, we reachnums[3]. Soresult[0]should be 1. - For
nums[1]that is equal to -2, If we move 2 steps to left, we reachnums[3]. Soresult[1]should be 1. - For
nums[2]that is equal to 1, If we move 1 step to right, we reachnums[3]. Soresult[2]should be 1. - For
nums[3]that is equal to 1, If we move 1 step to right, we reachnums[0]. Soresult[3]should be 3.
Example 2:
Input: nums = [-1,4,-1]
Output: [-1,-1,4]
Explanation:
- For
nums[0]that is equal to -1, If we move 1 step to left, we reachnums[2]. Soresult[0]should be -1. - For
nums[1]that is equal to 4, If we move 4 steps to right, we reachnums[2]. Soresult[1]should be -1. - For
nums[2]that is equal to -1, If we move 1 step to left, we reachnums[1]. Soresult[2]should be 4.
Constraints:
1 <= nums.length <= 100-100 <= nums[i] <= 100
Solutions
This function creates a transformed array where each element is determined by following a circular offset pattern. For each position i, it takes the value nums[i], calculates how many positions to shift forward from i using (nums[i] % n), and retrieves the element at that new position (wrapping around to the start if necessary). The formula (n + i + (nums[i] % n)) % n handles the calculation safely: the nums[i] % n part normalizes the value into a valid offset (handling both positive and negative numbers by using the modulo operator), then it adds n before the final modulo to ensure the result is always positive and within array bounds. Essentially, it treats the array as a circular list and uses each element's value as an instruction for how many steps to jump forward to find the element that goes into that position of the result array.
/**
* @param {number[]} nums
* @return {number[]}
*/
var constructTransformedArray = function(nums) {
const n = nums.length;
const res = Array(n);
for (let i = 0; i < n; i++) {
res[i] = nums[(n + i + (nums[i] % n)) % n];
}
return res;
};