Problem Description
Given a circular array nums, create a new array result of the same size where for each index i:
- If nums[i] > 0, move nums[i] steps to the right (wrapping around if necessary) and set result[i] to the value at the landing index.
- If nums[i] < 0, move abs(nums[i]) steps to the left (wrapping around if necessary) and set result[i] to the value at the landing index.
- If nums[i] == 0, result[i] is simply nums[i].
Key Insights
- Each element’s target position can be computed using modular arithmetic to handle the circular behavior.
- For a right move, add nums[i] to the current index; for a left move, adding a negative number can be normalized using modulo.
- Care is needed to adjust negative indices by adding the length of the array.
- The transformation for each index is independent.
- The algorithm processes each element exactly once.
Space and Time Complexity
Time Complexity: O(n) where n is the number of elements in nums.
Space Complexity: O(n) for the result array.
Solution
We solve the problem by iterating over each index i in the array. For each element:
- If the element is 0, we copy it to result.
- Otherwise, we calculate the new index using the formula:
newIndex = (i + nums[i]) % n
To ensure a positive index, if newIndex is negative, add n. - The value at the new index in nums is then assigned to result[i].
This straightforward approach uses modular arithmetic to simulate circular movement.