File: apply-operations-to-an-array/solution.py

Date: 2026-06-06

Time: 15:14

apply-operations-to-an-array/solution.py

Purpose

This file is a self-contained solution to LeetCode 2460: Apply Operations to an Array. It owns both the algorithm implementation and its test suite. Within the leetcode-implementations repo, each problem directory follows this same pattern — solution.py holds the canonical solution plus inline unit tests.

Key Components

performOps(nums: list[int]) -> list[int] — The sole public function. Takes a list of non-negative integers, applies pairwise doubling operations, then moves all zeros to the end. Returns a new list (the input is not mutated, since result = nums[:] copies first).

TestPerformOps — Eight test cases covering the contract: LeetCode examples, edge cases (all zeros, no duplicates, single pair), and tricky sequential interactions (consecutive triples, all-same, zeros between values).

Patterns

The solution uses a classic two-phase in-place transformation:

1. Phase 1 (lines 16–19): Single left-to-right pass. When adjacent elements are equal, double the left one and zero the right. This is sequential and order-dependent — the result of processing index i affects what index i+1 sees.

2. Phase 2 (lines 22–27): The "move zeros to end" idiom, implemented via a write-pointer compaction. Non-zero values are packed to the front using a write index, then trailing positions are filled with zeros. This is the same algorithm as LeetCode 283 (Move Zeroes).

The file bundles tests with the solution rather than importing from a separate test file, though test_solution.py also exists and imports from here.

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The test_solution.py in this directory imports performOps. The massive "Imported By" list in the prompt is misleading — those are *other* problems' test files that follow the same structural pattern, not actual importers of this specific function.

Flow

Given input [1, 2, 2, 1, 1, 0]:

1. Copy: result = [1, 2, 2, 1, 1, 0]

2. Phase 1 iteration:

3. Phase 2 compaction: [1, 4, 2, 0, 0, 0]

Invariants

Error Handling

None — the function assumes valid input per the LeetCode contract (non-negative integers, length ≥ 1). No bounds checking or type validation. The unittest runner is the only error surface, and it uses standard assertEqual assertions.

Topics to Explore

Beliefs