Merge Adjacent Equal Elements

You are given an integer array nums.

You must continuously apply the following merge operation: find the leftmost pair of adjacent, equal elements and replace them with a single element equal to their sum.

Every time you merge a pair, the array shrinks by 1. Keep repeating this process until no adjacent equal elements exist. Return the final modified array.

Example 1:

Input: nums = [5, 5, 10, 20]

Output: [40]

Explanation:

The leftmost equal pair is 5, 5. Merge them into 10. Array becomes [10, 10, 20]. The next equal pair is 10, 10. Merge them into 20. Array becomes [20, 20]. Finally, merge 20, 20 into 40.

Example 2:

Input: nums = [1, 2, 3, 4]

Output: [1, 2, 3, 4]

Explanation:

There are no adjacent equal elements anywhere in the array. The array remains entirely unchanged.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [1, 1, 2, 4]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

1 <= nums.length <= 105

1 <= nums[i] <= 105

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<long long> mergeAdjacentEqual(vector<int>& nums) {
}
};
Test Case

Input:

Nums