[LeetCode] Merge Adjacent Equal Elements

3834. Merge Adjacent Equal Elements

You are given an integer array nums.

You must repeatedly apply the following merge operation until no more changes can be made:

  • If any two adjacent elements are equal, choose the leftmost such adjacent pair in the current array and replace them with a single element equal to their sum.

After each merge operation, the array size decreases by 1. Repeat the process on the updated array until no more changes can be made.

Return the final array after all possible merge operations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<long long> mergeAdjacent(vector<int>& nums) {
vector<long long> res;
for(auto& n : nums) {
if(res.size() == 0 or res.back() != n) res.push_back(n);
else {
long long x = n;
while(res.size() and res.back() == x) {
res.pop_back(); x *= 2;
}
res.push_back(x);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/merge-adjacent-equal-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.