πŸ“˜ LeetCode 283: Move Zeroes

πŸ“Œ Problem Overview

  • Problem Number: 283
  • Problem Name: Move Zeroes
  • Difficulty: Easy
  • Category: Two Pointers
  • Runnable Source: Program.cs

πŸ’‘ Algorithmic Approach & Pattern

This problem is solved using the Two Pointers algorithmic pattern.

Key Insights & Invariants:

  1. Identify the input constraints and edge conditions.
  2. Structure the data flow to minimize unnecessary traversals and heap reallocations.
  3. Validate corner cases (empty collections, single-element cases, duplicates, extremes).

πŸ’» Verified C# Implementation (.NET 9)

The solution is verified and executable via the companion project in src/283.Move-Zeroes/:

System.Console.WriteLine(MoveZeroes([1, 1, 2, 0]));
System.Console.WriteLine(MoveZeroes([0, 1, 0, 3, 12]));
System.Console.WriteLine(MoveZeroes([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]));
int MoveZeroes(int[] nums)
{
    int i = -1;
    for (int j = 0; j < nums.Length; j++)
    {
        if (nums[j] != 0)
        {
            i++;
            int temp = nums[j];
            nums[j] = nums[i];
            nums[i] = temp;
        }
    }
    System.Console.WriteLine(string.Join(",", nums));
    return i;
}

πŸ“Š Complexity Analysis

MetricComplexityNotes
Time Complexity (or optimal for pattern)Single or bounded passes over the input
Space Complexity or Minimal auxiliary memory overhead

🚨 Edge Cases & Interview Traps

  • Empty / Null Input: Ensure null safety and guard clauses.
  • Single Element: Confirm the algorithm terminates without out-of-bounds indexing.
  • Duplicates & Boundaries: Check duplicate handling and extreme integer limits.