BackmediumArraysOracle

Alternating Array Reconstruction Solution

Problem Statement

You are given an integer array nums of length n that stores the successive differences between adjacent elements of a hidden array orig. The hidden array always starts with orig[0]=0. For each index i (0‑based) the difference nums[i] is applied to the current value of orig[i] as follows: if i is even, orig[i+1]=orig[i]+nums[i]; if i is odd, orig[i+1]=orig[i]-nums[i]. Construct and return the complete array orig of length n+1. The algorithm must run in linear time.

Example 1
Input
[4,1,3]
Output
[0,4,3,6]

Explanation: Start with 0. i=0 (even): 0+4=4 → orig[1]=4. i=1 (odd): 4-1=3 → orig[2]=3. i=2 (even): 3+3=6 → orig[3]=6. Final array: [0,4,3,6].

Example 2
Input
[-2,5,-1,2]
Output
[0,-2,-7,-8,-10]

Explanation: orig[0]=0. i=0 (even): 0+(-2)=-2. i=1 (odd): -2-5=-7. i=2 (even): -7+(-1)=-8. i=3 (odd): -8-2=-10. Resulting array is [0,-2,-7,-8,-10].

Example 3
Input
[10]
Output
[0,10]

Explanation: Only one difference. i=0 (even): 0+10=10 → orig[1]=10. Output is [0,10].

Constraints

  • 1 <= nums.length <= 100000
  • -1000000000 <= nums[i] <= 1000000000
  • All calculations fit in 64‑bit signed integer range
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Alternating Array Reconstruction — Problem Statement & Solution Guide

ArraysMediumMixed
TimeO(n)
|
SpaceO(1)

Problem Description

You are given an integer array nums of length n that stores the successive differences between adjacent elements of a hidden array orig. The hidden array always starts with orig[0]=0. For each index i (0‑based) the difference nums[i] is applied to the current value of orig[i] as follows: if i is even, orig[i+1]=orig[i]+nums[i]; if i is odd, orig[i+1]=orig[i]-nums[i]. Construct and return the complete array orig of length n+1. The algorithm must run in linear time.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Alternating Array Reconstruction"

medium

WHY DOES IT MATTER?

This pattern is essential for problems involving cumulative changes, such as stock price reconstruction from daily changes or signal processing. It teaches the importance of recognizing linear dependencies and avoiding unnecessary complexity.

OPTIMIZATION CHALLENGE

The key insight is that the reconstruction is a single-pass operation. There is no need for sorting, hashing, or dynamic programming; a simple loop with a running sum suffices.

REAL-WORLD CONNECTION

Analogous to reconstructing a GPS trajectory from a series of velocity and direction changes, where each step depends on the previous position and the current movement vector.

In interviews, explicitly state that you are using a 'running sum' or 'prefix sum' approach. This demonstrates algorithmic awareness and helps the interviewer follow your logic.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem relies on the concept of prefix sums with a conditional sign flip, often referred to as an alternating prefix sum. The hidden array orig is reconstructed by iterating through the difference array nums and accumulating the values. The key theoretical insight is that the operation is deterministic and linear: each element in orig depends only on the previous element and the current difference in nums. This transforms the problem from a complex reconstruction task into a simple linear scan, avoiding any need for backtracking or complex data structures.

Interview Questions on This Problem

Q1How would you modify this algorithm if the sign flip depended on the value of `nums[i]` rather than the index `i`?

You would replace the i % 2 check with a condition on nums[i] (e.g., if nums[i] > 0). The time complexity remains O(n), but you must ensure the logic for adding or subtracting is correctly mapped to the new condition.

Q2What is the space complexity of this solution, and can it be optimized further?

The space complexity is O(1) if you modify the input array or use a single variable to track the current value, excluding the output array. If the output array is required, the space is O(n) for the result, but no auxiliary data structures are needed.

Q3How would you handle integer overflow in this problem?

Use a 64-bit integer (long) for the accumulator variable to prevent overflow during the summation process, especially if the input values are large or the array is long.

Examples

Example 1

Input

[4,1,3]

Output

[0,4,3,6]

Explanation: Start with 0. i=0 (even): 0+4=4 → orig[1]=4. i=1 (odd): 4-1=3 → orig[2]=3. i=2 (even): 3+3=6 → orig[3]=6. Final array: [0,4,3,6].

Example 2

Input

[-2,5,-1,2]

Output

[0,-2,-7,-8,-10]

Explanation: orig[0]=0. i=0 (even): 0+(-2)=-2. i=1 (odd): -2-5=-7. i=2 (even): -7+(-1)=-8. i=3 (odd): -8-2=-10. Resulting array is [0,-2,-7,-8,-10].

Example 3

Input

[10]

Output

[0,10]

Explanation: Only one difference. i=0 (even): 0+10=10 → orig[1]=10. Output is [0,10].

Constraints

  • 1 <= nums.length <= 100000
  • -1000000000 <= nums[i] <= 1000000000
  • All calculations fit in 64‑bit signed integer range

Optimal Approach & Strategy

Use a single loop to iterate through the input array, maintaining a running sum. For each index, add or subtract the current element based on whether the index is even or odd, and store the result in the output array.

Brute Force Approach

A naive approach might involve recursively trying all possible sign combinations, which is exponential and unnecessary. Another naive approach could be to store all intermediate states in a list, which is inefficient in space.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function reconstruct(nums) {
    const orig = [];
    let cur = 0;
    orig.push(cur);
    for (let i = 0; i < nums.length; ++i) {
        if (i % 2 === 0) cur += nums[i];
        else cur -= nums[i];
        orig.push(cur);
    }
    return orig;
}

function main() {
    const fs = require('fs');
    const data = fs.readFileSync(0, 'utf8').trim();
    if (data.length === 0) {
        console.log('0');
        return;
    }
    const nums = data.split(/\s+/).map(Number);
    const orig = reconstruct(nums);
    console.log(orig.join(' '));
}
main();

Asked in Top Tech Interviews

Oracle

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.