Difficulty: Easy | Acceptance: 90.00% | Paid: No Topics: Array, Simulation
You are given an integer array nums. Return the alternating sum of nums.
The alternating sum is defined as nums[0] - nums[1] + nums[2] - nums[3] + ....
- Examples
- Constraints
- Iterative Simulation
- Functional Reduction
- Separate Sums
Examples
Example 1
Input:
nums = [1,3,5,7]
Output:
-4
Explanation: Elements at even indices are nums[0] = 1 and nums[2] = 5 because 0 and 2 are even numbers.
Elements at odd indices are nums[1] = 3 and nums[3] = 7 because 1 and 3 are odd numbers.
The alternating sum is nums[0] - nums[1] + nums[2] - nums[3] = 1 - 3 + 5 - 7 = -4.
Example 2
Input:
nums = [100]
Output:
100
Explanation: The only element at even indices is nums[0] = 100 because 0 is an even number.
There are no elements on odd indices.
The alternating sum is nums[0] = 100.
Constraints
1 <= nums.length <= 50
-100 <= nums[i] <= 100
Iterative Simulation
Intuition We iterate through the array once, adding the element to our total if the index is even and subtracting it if the index is odd.
Steps
- Initialize a variable
totalto 0. - Loop through the array with an index
i. - Check if
iis even (i % 2 == 0). If so, addnums[i]tototal. - If
iis odd, subtractnums[i]fromtotal. - Return
total.
class Solution:
def alternateSum(self, nums: list[int]) -> int:
total = 0
for i in range(len(nums)):
if i % 2 == 0:
total += nums[i]
else:
total -= nums[i]
return totalComplexity
- Time: O(n)
- Space: O(1)
- Notes: Most straightforward approach.
Functional Reduction
Intuition We can use the built-in reduce (or fold) functions provided by languages to accumulate the result. We pass the index to the reducer to determine the sign.
Steps
- Call the reduce function on the array.
- The accumulator starts at 0.
- In the reducer callback, check the index parity.
- Add the value if even, subtract if odd.
- Return the final accumulated value.
from functools import reduce
class Solution:
def alternateSum(self, nums: list[int]) -> int:
return reduce(lambda acc, x: acc + x[1] if x[0] % 2 == 0 else acc - x[1], enumerate(nums), 0)Complexity
- Time: O(n)
- Space: O(1)
- Notes: Concise syntax, though sometimes slightly slower than raw loops due to overhead.
Separate Sums
Intuition The alternating sum is mathematically equivalent to the sum of elements at even indices minus the sum of elements at odd indices. We can calculate these two sums separately.
Steps
- Initialize
sumEvenandsumOddto 0. - Iterate through the array.
- If index is even, add to
sumEven. - If index is odd, add to
sumOdd. - Return
sumEven - sumOdd.
class Solution:
def alternateSum(self, nums: list[int]) -> int:
sum_even = 0
sum_odd = 0
for i in range(len(nums)):
if i % 2 == 0:
sum_even += nums[i]
else:
sum_odd += nums[i]
return sum_even - sum_oddComplexity
- Time: O(n)
- Space: O(1)
- Notes: Uses two variables instead of one, but logically very clear.