Skip to main content
Back to problems
Leetcode
Medium
Arrays
Greedy
Stacks
Merge Adjacent Equal Elements

Repeatedly merge neighboring equal values in an array until no such pair remains.

Acceptance 0%
Problem Statement

Problem

You are given an array of integers. You may repeatedly choose any two adjacent elements that are equal and replace them with a single element whose value is their sum.

For example, if you merge two adjacent x values, they become one value 2x.

Keep applying this operation until no adjacent equal pair exists anywhere in the array. Return the resulting array.

The final array may depend on the order of merges, but for this problem assume the standard process of scanning from left to right and merging whenever a merge becomes possible during that scan.

Goal

Transform the array according to the merge process and produce the final array after all possible adjacent merges have been performed under that rule.

Input Format

  • An integer array nums.
  • Each operation merges two adjacent equal values x and x into one value 2x.
  • Merges are applied while scanning left to right, and newly formed values can participate in later merges.

Output Format

  • Return the final array after all applicable merges are completed.

Constraints

  • 1 <= nums.length.
  • nums[i] are integers.
  • Use the merge rule only when two adjacent elements are equal.
  • Return the array in its final reduced form.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

[2, 4, 2]

Explanation

Scan left to right: merge the first two 1s into 2, then the next two 2s into 4. The last 2 remains, so the final array is [2, 4, 2].

Example 2

Input

nums = [3, 3, 3]

Output

[6, 3]

Explanation

Merge the first two 3s into 6. No further adjacent equal pair exists, so the result is [6, 3].

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.