Merge Adjacent Equal Elements

medium stack array simulation

Problem

Given an integer array nums, repeatedly apply this merge until no change is possible: find the leftmost pair of adjacent equal elements and replace the two of them with a single element equal to their sum. Each merge shrinks the array by one. Return the final array once no adjacent equal elements remain.

Inputnums = [3, 1, 1, 2]
Output[3, 4]
Merge 1+1 → [3, 2, 2], then merge 2+2 → [3, 4]. No adjacent equals remain.

def mergeAdjacent(nums):
    stack = []
    for x in nums:
        cur = x
        # absorb every equal neighbour now on top
        while stack and stack[-1] == cur:
            cur += stack.pop()
        stack.append(cur)
    return stack
function mergeAdjacent(nums) {
  const stack = [];
  for (const x of nums) {
    let cur = x;
    // absorb every equal neighbour now on top
    while (stack.length && stack[stack.length - 1] === cur) {
      cur += stack.pop();
    }
    stack.push(cur);
  }
  return stack;
}
List<Long> mergeAdjacent(int[] nums) {
    Deque<Long> stack = new ArrayDeque<>();
    for (int x : nums) {
        long cur = x;
        // absorb every equal neighbour now on top
        while (!stack.isEmpty() && stack.peekLast() == cur) {
            cur += stack.pollLast();
        }
        stack.addLast(cur);
    }
    return new ArrayList<>(stack);
}
vector<long long> mergeAdjacent(vector<int>& nums) {
    vector<long long> stack;
    for (int x : nums) {
        long long cur = x;
        // absorb every equal neighbour now on top
        while (!stack.empty() && stack.back() == cur) {
            cur += stack.back();
            stack.pop_back();
        }
        stack.push_back(cur);
    }
    return stack;
}
Time: O(n) Space: O(n)