Easy and Beginner Friendly Solution💯. Apply Operations to an Array (Optimized Solution 🚀)
IntuitionThe problem requires modifying the array based on adjacent values and then rearranging it efficiently.The key steps involve merging adjacent equal elem

# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

The problem requires modifying the array based on adjacent values and then rearranging it efficiently.

The key steps involve merging adjacent equal elements and shifting non-zero elements to the front while pushing zeros to the end.

A simple two-pass approach (first pass for merging, second pass for shifting) is sufficient.


# Approach
<!-- Describe your approach to solving the problem. -->

1. First Pass (Modify the Array)

Iterate through the array.

If two adjacent elements are equal, double the first and set the 
second to zero.

2. Second Pass (Rearrange Elements)

Traverse the array again to collect all non-zero elements into a new array.
Append the required number of zeros at the end.

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

Merging step: O(n)

Shifting non-zero elements: O(n)

Total: O(n)

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

Using extra vector v: O(n)

# Code
```cpp []
class Solution {
public:
    vector<int> applyOperations(vector<int>& nums) {
        int n= nums.size();
        vector<int> v;
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                nums[i] = nums[i]*2;
                nums[i+1]=0;
            }
        }
        for (int i = 0; i < n; i++) {
            if (nums[i]!=0) {
                v.push_back(nums[i]);
            }
        }
        for (int i = 0; i < n; i++) {
            if (nums[i]==0) {
                v.push_back(nums[i]);
            }
        }
        return v;

    }
};
```
If You Like Solution, Just Click On Upvote.

![image.png](https://assets.leetcode.com/users/images/5fee76f2-9539-48e4-a370-48e3be61786e_1740803067.193718.png)






['C++']