#3834
Merge Adjacent Equal Elements
MediumArrayStackSimulationStackArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a stack to efficiently manage merges. Push elements onto the stack, and if the top of the stack equals the current element, pop and merge them.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty stack.
- 2Step 2: Iterate through each element in the array.
- 3Step 3: If the stack is not empty and the top equals the current element, pop the stack and push their sum; otherwise, push the current element.
solution.py8 lines
1def merge(nums):
2 stack = []
3 for num in nums:
4 if stack and stack[-1] == num:
5 stack[-1] += num
6 else:
7 stack.append(num)
8 return stackℹ
Complexity note: Each element is processed once, leading to linear time complexity. The stack may store all elements in the worst case.
- 1Using a stack simplifies the merging process.
- 2Merging from left to right ensures we handle the earliest pairs first.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.