Problem

3834. Merge Adjacent Equal Elements

Logic

Code

#include <vector>

class Solution {
public:
    std::vector<long long> mergeAdjacent(std::vector<int>& nums) {
        // Handle empty input boundary case
        if (nums.empty()) return {}; 

        std::vector<long long> stk;
        stk.push_back(nums[0]);

        for (size_t i = 1; i < nums.size(); i++) {
            long long current = nums[i];

            // Check the adjacent element at the BACK of the stack
            while (!stk.empty() && current == stk.back()) {
                current += stk.back(); // Merge values
                stk.pop_back();        // Remove from back in O(1) time
            }

            stk.push_back(current);
        }
        
        return stk;
    }
};