How do you find the first missing positive integer in an unsorted array in O(n) time using cyclic index placement? | A1LabDavid to DSAEnglish • 16 hours ago

How do you find the first missing positive integer in an unsorted array in O(n) time using cyclic index placement?

message-square
0
1
How do you find the first missing positive integer in an unsorted array in O(n) time using cyclic index placement?
How do you find the first missing positive integer in an unsorted array in O(n) time using cyclic index placement? | A1LabDavid to DSAEnglish • 16 hours ago

First Missing Positive: $O(n)$ Time and $O(1)$ Space via Cyclic Sort

The First Missing Positive problem asks for the smallest positive integer ($1, 2, 3, \dots$) missing from an unsorted array of size $n$.

A hash set allows solving this in $O(n)$ time, but costs $O(n)$ memory. By treating the input array itself as an in-place direct-address hash table—placing each number $x$ at index $x - 1$ through cyclic index placement—we achieve an optimal $O(n)$ time and strictly $O(1)$ auxiliary space solution.


Key Insight: The Pigeonhole Boundary

For an array of length $n$:

  • The best-case contents containing all smallest positives is the set ${1, 2, 3, \dots, n}$.
  • In that scenario, the first missing positive is $n + 1$.
  • If any number from $1$ to $n$ is missing, the answer must lie strictly within the range $[1, n]$.

Conclusion: Any integer outside the range $[1, n]$ (such as negative numbers, zero, or values $> n$) is completely irrelevant to the outcome and can be ignored.


The Cyclic Placement Algorithm

We want to enforce the invariant: $$\text{For every valid positive } x \in [1, n], \quad \text{nums}[x - 1] == x$$

Step 1: In-Place Bucket Sort (Cyclic Swapping)

Iterate through the array with pointer i = 0 to n - 1:

  • Let $x = \text{nums}[i]$.
  • While $x$ is in the range $[1, n]$ and is not yet in its correct home slot (i.e., $\text{nums}[x - 1] \neq x$):
    • Swap $\text{nums}[i]$ with $\text{nums}[x - 1]$.
    • Re-check the new value brought into $\text{nums}[i]$ (do not increment i until $\text{nums}[i]$ holds a value that is either out of range or already at its target index).
  • If $x \le 0$, $x > n$, or $\text{nums}[x - 1] == x$ (duplicate handling), simply move to i++.

Step 2: Linear Scan for Discrepancy

Scan the array from index 0 to n - 1:

  • The first index i where $\text{nums}[i] \neq i + 1$ reveals the missing positive: return $i + 1$.
  • If all indices 0 through n - 1 satisfy $\text{nums}[i] == i + 1$, return $n + 1$.

Trace Walkthrough: nums = [3, 4, -1, 1] ($n = 4$)

  • Index 0 (num = 3): Target index is $3 - 1 = 2$.
    • Swap nums[0] with nums[2]: array becomes [-1, 4, 3, 1].
    • nums[0] = -1 is out of range $[1, 4]$. Stop and advance to index 1.
  • Index 1 (num = 4): Target index is $4 - 1 = 3$.
    • Swap nums[1] with nums[3]: array becomes [-1, 1, 3, 4].
    • New nums[1] = 1. Target index is $1 - 1 = 0$.
    • Swap nums[1] with nums[0]: array becomes [1, -1, 3, 4].
    • New nums[1] = -1 is out of range. Stop and advance to index 2.
  • Index 2 (num = 3): Already at index $3 - 1 = 2$. Advance.
  • Index 3 (num = 4): Already at index $4 - 1 = 3$. Advance.

Second Scan:

  • Index 0: nums[0] == 1 ✅
  • Index 1: nums[1] == -1 $\neq 2$ ❌ $\rightarrow$ Return 2.

Implementations (C++ & Python)

C++ Implementation

#include <vector>
#include <algorithm>

int firstMissingPositive(std::vector<int>& nums) {
    int n = nums.size();

    // Step 1: Cyclic placement
    for (int i = 0; i < n; ++i) {
        // While current element is in range [1, n] and not at its target index
        while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
            std::swap(nums[i], nums[nums[i] - 1]);
        }
    }

    // Step 2: Identify the first missing natural number
    for (int i = 0; i < n; ++i) {
        if (nums[i] != i + 1) {
            return i + 1;
        }
    }

    // If 1 through n are all present
    return n + 1;
}

Python Implementation

def first_missing_positive(nums: list[int]) -> int:
    n = len(nums)

    # Step 1: Cyclic placement
    for i in range(n):
        # Place nums[i] into index nums[i] - 1 if valid and not already there
        while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
            correct_idx = nums[i] - 1
            nums[i], nums[correct_idx] = nums[correct_idx], nums[i]

    # Step 2: Scan for first mismatch
    for i in range(n):
        if nums[i] != i + 1:
            return i + 1

    return n + 1

Complexity & Correctness Guarantees

Metric Complexity Why It Holds
Time Complexity $O(n)$ Although there is a nested while loop, every successful swap places at least one number into its permanent final position. Because there are only $n$ slots, no more than $n$ total swaps can occur across the entire loop. Thus, amortized time is strictly $O(n)$.
Auxiliary Space $O(1)$ Elements are rearranged strictly within the original buffer without allocating hash sets, maps, or auxiliary arrays.
  • Infinite Loop Prevention: The condition nums[nums[i] - 1] != nums[i] prevents infinite loops when encountering duplicate values (e.g., [1, 1]), safely ignoring redundant duplicates once one copy occupies the correct slot.