#3834
Medium Algorithms Merge adjacent equal elements
Array Stack Simulation
42.0% acceptance
Mar 16, 2026
89
2
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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn merge_adjacent(nums: Vec<i32>) -> Vec<i64> {
// Use a stack-based approach: push elements one by one.
// After pushing, if top two are equal, merge them (and keep merging while top two are equal).
let mut stack: Vec<i64> = Vec::new();
for &num in &nums {
stack.push(num as i64);
// Merge while last two elements are equal
while stack.len() >= 2 {
let len = stack.len();
if stack[len - 1] == stack[len - 2] {
let val = stack.pop().unwrap();
*stack.last_mut().unwrap() = val * 2;
} else {
break;
}
}
}
stack
}
}