mediumArraysPattern: Mixed
Reconstruct Alternating Sequence Solution
Problem Statement
Given an array of integers `diff` representing the differences between consecutive elements in a reconstructed array, determine the original array that these differences represent, assuming the first element is 0 and differences alternate between being added and subtracted from the running total.
Examples
Example 1:
Input:[1, -2, 3, -4]
Output:[0, 1, -1, 2, -2]
Explanation: Starting with 0, add 1 to get 1, subtract 2 to get -1, add 3 to get 2, subtract 4 to get -2
Example 2:
Input:[5, -3, 2, -1]
Output:[0, 5, 2, 4, 3]
Explanation: Starting with 0, add 5 to get 5, subtract 3 to get 2, add 2 to get 4, subtract 1 to get 3
Constraints
- The length of the differences array will not exceed 10^5 elements.
- All numbers in the differences array are integers between -10^9 and 10^9.
- The input array may be empty, in which case the output is [0].
- The total sum of absolute values of differences will not exceed 10^6.
Time: O(n) Space: O(n)
The optimal approach involves initializing the result array with 0 and then iteratively applying the given differences, switching between addition and subtraction based on the pattern. This results in a linear time complexity.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
