1136. Slide and Merge Row

Easy1.5 points estimatedArrayTwo PointersSimulation

A sliding-tile game uses a single row of tiles. The array row holds the tiles: 0 is an empty cell and any other value is a power of two.

One move to the left works like this. First slide every non-zero tile as far left as it can go, keeping their order. Then scan from left to right and merge two equal adjacent tiles into one tile of double value. A tile created by a merge cannot merge again in the same move, so [2,2,2,2] becomes [4,4,0,0] and [4,2,2] becomes [4,4,0]. Modify row in place so it holds the result, padded with zeros on the right; the method returns nothing. One pass with a pending tile gives O(n) time.

Example 1

Input:
row = [2,2,2,2,0]
Output:
[4,4,0,0,0]
Explanation:

The first two 2s merge into a 4 and the next two 2s merge into another 4; a merged tile cannot merge again in the same move.

Example 2

Input:
row = [4,2,2]
Output:
[4,4,0]
Explanation:

The two 2s merge into a 4, which then sits next to the first 4 but does not merge with it during this move.

Example 3

Input:
row = [0,2,0,4]
Output:
[2,4,0,0]
Explanation:

Sliding left gives 2 and 4 in the first two cells with no equal neighbours, so nothing merges.

Constraints

1 ≤ n ≤ 1000, where n is the length of row

Each row[i] is 0 or a power of two not above 220

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Graded
Your answer is read from row after your method returns.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…