We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Transformed Array

Number: 3651

Difficulty: Easy

Paid? No

Companies: N/A


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.

Code Solutions

# Function to compute the transformed array.
def transformedArray(nums):
    n = len(nums)  # Get the length of the circular array.
    result = [0] * n  # Initialize result array of same length.
    for i in range(n):
        # If current element is 0, retain it.
        if nums[i] == 0:
            result[i] = nums[i]
        else:
            # Compute new index after moving nums[i] steps (right if positive, left if negative).
            new_index = (i + nums[i]) % n  # The modulo handles circular wrapping.
            result[i] = nums[new_index]  # Set the result at i.
    return result

# Example test case.
print(transformedArray([3, -2, 1, 1]))  # Expected output: [1, 1, 1, 3]
← Back to All Questions