Merge Adjacent Equal Elements Problem
Description
LeetCode Problem 3834.
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.
Example 1:
Input: nums = [3,1,1,2]
Output: [3,4]
Explanation:
- The middle two elements are equal and merged into 1 + 1 = 2, resulting in [3, 2, 2].
- The last two elements are equal and merged into 2 + 2 = 4, resulting in [3, 4].
- No adjacent equal elements remain. Thus, the answer is [3, 4].
Example 2:
Input: nums = [2,2,4]
Output: [8]
Explanation:
- The first two elements are equal and merged into 2 + 2 = 4, resulting in [4, 4].
- The first two elements are equal and merged into 4 + 4 = 8, resulting in [8].
Example 3:
Input: nums = [3,7,5]
Output: [3,7,5]
Explanation:
There are no adjacent equal elements in the array, so no operations are performed.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Stack
Process the array from left to right with a stack that holds the already merged prefix. Push each new element x. While the top two elements of the stack are equal, pop both and push their sum. Because the prefix had no equal neighbors before x arrived, a merge can only happen at the top, and a merged value can only create a new equal pair with the element just below it. This is exactly the leftmost-first order of the problem. At the end the stack is the answer.
Sums can reach about 10^10, so use 64-bit integers where the language needs them.
Complexity:
- Time:
O(n), since each element is pushed once and every merge removes one element. - Space:
O(n).
class Solution:
def mergeAdjacent(self, nums: List[int]) -> List[int]:
stk = []
for x in nums:
stk.append(x)
while len(stk) > 1 and stk[-1] == stk[-2]:
stk.append(stk.pop() + stk.pop())
return stk