Skip to main content
Back to problems
Leetcode
Medium
Arrays
Simulation
Apply Operations To An Array

Apply a set of simple transformation rules to an array, then compact the result by moving zeros to the end.

Acceptance 0%
Problem Statement

Problem

You are given an integer array nums. Perform the following operation on the array from left to right:

  • If nums[i] == nums[i + 1], replace nums[i] with 2 * nums[i] and replace nums[i + 1] with 0.
  • Otherwise, leave the pair unchanged.

After processing all adjacent pairs once, shift all zeros to the end of the array while preserving the relative order of the non-zero elements.

Return the transformed array.

Notes

  • Each adjacent pair is considered once from left to right.
  • When a value is doubled, the next element in that pair becomes 0.
  • The final zero-shifting step is part of the required output.

Input Format

  • An integer array nums of length n.

The array is processed in-place conceptually, but return the final transformed array.

Output Format

  • Return an integer array representing the result after applying the adjacent-pair transformation and then moving all zeros to the end.

Constraints

  • 1 <= n
  • Elements are integers.
  • Exact official constraints are not provided in the source metadata; assume standard interview-scale array sizes.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,2,2,1,1,0]

Output

[1,4,2,0,0,0]

Explanation

  • 2 and 2 become 4 and 0.
  • 1 and 1 become 2 and 0.
  • After moving all zeros to the end, the array becomes [1,4,2,0,0,0].

Example 2

Input

nums = [0,0,3,3]

Output

[6,0,0,0]

Explanation

  • 0 and 0 are equal, so the first becomes 0 and the second becomes 0.
  • 3 and 3 become 6 and 0.
  • After compacting non-zero values, the result is [6,0,0,0].

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.