Back to blog
Apr 11, 2024
3 min read

Compute Alternating Sum

Calculate the alternating sum of an integer array where signs alternate between positive and negative starting with positive.

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

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 total to 0.
  • Loop through the array with an index i.
  • Check if i is even (i % 2 == 0). If so, add nums[i] to total.
  • If i is odd, subtract nums[i] from total.
  • Return total.
python
class Solution:
    def alternateSum(self, nums: list[int]) -&gt; int:
        total = 0
        for i in range(len(nums)):
            if i % 2 == 0:
                total += nums[i]
            else:
                total -= nums[i]
        return total

Complexity

  • 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.
python
from functools import reduce

class Solution:
    def alternateSum(self, nums: list[int]) -&gt; 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 sumEven and sumOdd to 0.
  • Iterate through the array.
  • If index is even, add to sumEven.
  • If index is odd, add to sumOdd.
  • Return sumEven - sumOdd.
python
class Solution:
    def alternateSum(self, nums: list[int]) -&gt; 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_odd

Complexity

  • Time: O(n)
  • Space: O(1)
  • Notes: Uses two variables instead of one, but logically very clear.