"LeetCode 2460 | Apply Operations to an Array | Easy & Optimized Java Solution"
IntuitionThe problem requires us to perform two operations sequentially:Merge adjacent equal elements by doubling the first and setting the second to 0.
Shift a
# Intuition
The problem requires us to perform two operations sequentially:

Merge adjacent equal elements by doubling the first and setting the second to 0.
Shift all 0s to the end while maintaining the order of non-zero elements.

Since both operations are sequential, we can achieve the result efficiently by processing the array in a single pass without extra space.

# Approach
We iterate through the array using a single loop, applying the operations in two steps:

Merging adjacent equal elements

If nums[i] == nums[i + 1], we double nums[i] and set nums[i + 1] to 0.
Shifting non-zero elements

We maintain a pointer j to track the position of the next non-zero element.
Whenever we encounter a non-zero value, we swap it to the front.
This approach effectively merges and shifts in one traversal, optimizing performance.

# Complexity
- Time complexity:O(n)
We traverse the array once, performing both merging and shifting in-place.

- Space complexity:O(1)
We use only a few extra variables and modify the input array directly.

# Code

```java []
class Solution {
  public int[] applyOperations(int[] nums) {
    for (int i = 0, j = 0; i < nums.length; ++i) {
      if (i + 1 < nums.length && nums[i] == nums[i + 1]) {
        nums[i] *= 2;
        nums[i + 1] = 0;
      }
      if (nums[i] > 0) {
        swap(nums, i, j++);
      }
    }
    return nums;
  }
  private void swap(int[] nums, int i, int j) {
    final int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
  }
}
```
['Java']