Problem
3834. Merge Adjacent Equal Elements
Logic
- Simulates the merging process using a vector as a stack (
stk) to process numbers sequentially. - If the input array is empty, handle boundary case early by returning
{}. - Push the first element onto the stack.
- For each subsequent element
current:- Continuously check if the stack is non-empty and
current == stk.back(). - While equal, merge
stk.back()intocurrent(current += stk.back()) and pop from the stack (stk.pop_back()). - Push the fully merged
currentontostk.
- Continuously check if the stack is non-empty and
- Using
long longprevents potential integer overflow as values double upon merging.
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;
}
};