Mastery Points
0

Array Rearrangement in dsa

Context & Logic

Rearranging arrays involves reordering elements based on constraints (e.g., alternating positive/negative numbers or moving zeros to the end).

Example

// Example: Move Zeros to End
function moveZeros(nums) {
    let lastNonZero = 0;
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] !== 0) {
            [nums[lastNonZero++], nums[i]] = [nums[i], nums[lastNonZero]];
        }
    }
}

Step-by-Step Logic

1

Use a pointer to track the position of the next correctly placed element.

2

Iterate through the array.

3

If the current element satisfies the target condition, swap it with the pointer position.

4

Increment the pointer.

Complexity Metrics

Time Efficiency

O(n)

Memory Footprint

O(1)