Created
February 5, 2026 17:49
-
-
Save tatsuyax25/2820e54024800ab54cdbd4be8c53c92b to your computer and use it in GitHub Desktop.
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 num
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} nums | |
| * @return {number[]} | |
| */ | |
| var constructTransformedArray = function(nums) { | |
| const n = nums.length; | |
| const result = new Array(n); | |
| for (let i = 0; i < n; i++) { | |
| const steps = nums[i]; | |
| // Case 1: If the value is zero, no movement happens. | |
| if (steps === 0) { | |
| result[i] = 0; | |
| continue; | |
| } | |
| // Case 2: Movement happens. | |
| // We compute the new index using modular arithmetic. | |
| // | |
| // Why the double modulo? | |
| // JavaScript's % can return negative values, so we normalize it. | |
| // | |
| // Formula: | |
| // newIndex = (i + steps) mod n, but always positive. | |
| let newIndex = (i + steps) % n; | |
| // Normalize negative modulo results | |
| if (newIndex < 0) { | |
| newIndex += n; | |
| } | |
| // Set result[i] to the value at the landing index | |
| result[i] = nums[newIndex]; | |
| } | |
| return result; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment