Difficulty: Easy | Acceptance: 70.50% | Paid: No Topics: Array, Simulation
You are given a 0-indexed integer array nums. You have to transform the array into a new array result of the same length.
For each index i in the original array:
- If
nums[i] > 0, addnums[i]tonums[(i + 1) % n]. - If
nums[i] < 0, addnums[i]tonums[(i - 1 + n) % n]. - If
nums[i] == 0, do nothing.
The operations are performed based on the original values of nums. Return the transformed array.
- Examples
- Constraints
- Simulation (In-place)
- Simulation (New Array)
Examples
Example 1
Input:
nums = [1,2,3,4]
Output:
[5,3,5,7]
Explanation:
- i=0, val=1>0: add 1 to nums[1]. nums becomes [1,3,3,4].
- i=1, val=2>0: add 2 to nums[2]. nums becomes [1,3,5,4].
- i=2, val=3>0: add 3 to nums[3]. nums becomes [1,3,5,7].
- i=3, val=4>0: add 4 to nums[0]. nums becomes [5,3,5,7].
Example 2
Input:
nums = [-1,2,-3,4]
Output:
[3,-1,-1,3]
Explanation:
- i=0, val=-1<0: add -1 to nums[3]. nums becomes [-1,2,-3,3].
- i=1, val=2>0: add 2 to nums[2]. nums becomes [-1,2,-1,3].
- i=2, val=-3<0: add -3 to nums[1]. nums becomes [-1,-1,-1,3].
- i=3, val=4>0: add 4 to nums[0]. nums becomes [3,-1,-1,3].
Constraints
- 1 <= nums.length <= 100
- -100 <= nums[i] <= 100
Simulation (In-place)
Intuition We iterate through the array once. Since the transformation depends on the original values, we first create a copy of the array. Then, for each element in the copy, we update the corresponding neighbor in the original array.
Steps
- Create a copy of the input array
nums. - Iterate through the copy using index
i. - If the value is positive, add it to
nums[(i + 1) % n]. - If the value is negative, add it to
nums[(i - 1 + n) % n]. - If the value is zero, do nothing.
- Return the modified
nums.
class Solution:
def constructTransformedArray(self, nums: List[int]) -> List[int]:
n = len(nums)
original = nums[:]
for i in range(n):
val = original[i]
if val > 0:
nums[(i + 1) % n] += val
elif val < 0:
nums[(i - 1 + n) % n] += val
return numsComplexity
- Time: O(n)
- Space: O(n)
- Notes: We use O(n) space to store the copy of the array.
Simulation (New Array)
Intuition Instead of modifying the input array in-place, we create a new result array initialized with zeros. We iterate through the original array and add the values to the correct indices in the result array. This avoids modifying the input directly.
Steps
- Initialize a result array
resof sizenwith zeros. - Iterate through
numsusing indexi. - If
nums[i]is positive, add it tores[(i + 1) % n]. - If
nums[i]is negative, add it tores[(i - 1 + n) % n]. - If
nums[i]is zero, do nothing. - Return
res.
class Solution:
def constructTransformedArray(self, nums: List[int]) -> List[int]:
n = len(nums)
res = [0] * n
for i in range(n):
val = nums[i]
if val > 0:
res[(i + 1) % n] += val
elif val < 0:
res[(i - 1 + n) % n] += val
return resComplexity
- Time: O(n)
- Space: O(n)
- Notes: We use O(n) space for the result array. This approach is cleaner as it does not mutate the input.