Repeatedly merge neighboring equal values in an array until no such pair remains.
Problem
You are given an array of integers. You may repeatedly choose any two adjacent elements that are equal and replace them with a single element whose value is their sum.
For example, if you merge two adjacent x values, they become one value 2x.
Keep applying this operation until no adjacent equal pair exists anywhere in the array. Return the resulting array.
The final array may depend on the order of merges, but for this problem assume the standard process of scanning from left to right and merging whenever a merge becomes possible during that scan.
Goal
Transform the array according to the merge process and produce the final array after all possible adjacent merges have been performed under that rule.
Input Format
- An integer array
nums. - Each operation merges two adjacent equal values
xandxinto one value2x. - Merges are applied while scanning left to right, and newly formed values can participate in later merges.
Output Format
- Return the final array after all applicable merges are completed.
Constraints
1 <= nums.length.nums[i]are integers.- Use the merge rule only when two adjacent elements are equal.
- Return the array in its final reduced form.
Example 1
Input
nums = [1, 1, 2, 2, 2]
Output
[2, 4, 2]
Explanation
Scan left to right: merge the first two 1s into 2, then the next two 2s into 4. The last 2 remains, so the final array is [2, 4, 2].
Example 2
Input
nums = [3, 3, 3]
Output
[6, 3]
Explanation
Merge the first two 3s into 6. No further adjacent equal pair exists, so the result is [6, 3].
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.