Arrays January 17 ,2026

Find the First Missing Positive Integer

Problem Statement

You are given an unsorted integer array arr.
Find the smallest missing positive integer.

You must solve this problem in O(n) time and O(1) extra space.

Example 1

Input

arr = [1, 2, 0]

Output

3

Explanation
Positive integers present are 1 and 2.
The smallest missing positive is 3.

Example 2

Input

arr = [3, 4, -1, 1]

Output

2

Example 3

Input

arr = [7, 8, 9, 11, 12]

Output

1

Why This Problem Is Important

  • Extremely frequent interview question
  • Asked in FAANG & top product companies
  • Tests array manipulation
  • Requires index mapping logic
  • Enforces O(n) time & O(1) space
  • Strong test of in-place algorithms

Approaches Overview

ApproachTechniqueTimeSpace
Approach 1SortingO(n log n)O(1)
Approach 2HashingO(n)O(n)
Approach 3Index Mapping (Optimal)O(n)O(1)

Approach 1: Sorting

Idea

Sort the array and check the smallest missing positive sequentially.

Algorithm

  1. Sort the array
  2. Initialize expected = 1
  3. Traverse array
  4. If current element equals expected, increment it
  5. Ignore negatives & duplicates

Time & Space Complexity

  • Time: O(n log n)
  • Space: O(1)

Implementations

C

#include 
#include 

int cmp(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    int arr[] = {3,4,-1,1};
    int n = 4;
    qsort(arr, n, sizeof(int), cmp);

    int expected = 1;
    for(int i = 0; i < n; i++) {
        if(arr[i] == expected)
            expected++;
    }

    printf("%d", expected);
    return 0;
}

C++

#include 
#include 
using namespace std;

int main() {
    int arr[] = {3,4,-1,1};
    int n = 4;

    sort(arr, arr + n);

    int expected = 1;
    for(int i = 0; i < n; i++) {
        if(arr[i] == expected)
            expected++;
    }

    cout << expected;
    return 0;
}

Java

import java.util.*;

public class FirstMissingPositive {
    public static void main(String[] args) {
        int[] arr = {3,4,-1,1};
        Arrays.sort(arr);

        int expected = 1;
        for(int x : arr) {
            if(x == expected)
                expected++;
        }

        System.out.print(expected);
    }
}

Python

arr = [3,4,-1,1]
arr.sort()

expected = 1
for x in arr:
    if x == expected:
        expected += 1

print(expected)

JavaScript

let arr = [3,4,-1,1];
arr.sort((a,b) => a-b);

let expected = 1;
for (let x of arr) {
    if (x === expected)
        expected++;
}

console.log(expected);

Approach 2: Hashing

Idea

Store all positive numbers in a set and find the first missing one.

Algorithm

  1. Insert all positive numbers into a HashSet
  2. Start checking from 1 upwards
  3. First missing number is the answer

Time & Space Complexity

  • Time: O(n)
  • Space: O(n)

Implementations

C++

#include 
#include 
using namespace std;

int main() {
    int arr[] = {3,4,-1,1};
    int n = 4;

    unordered_set s;
    for(int i = 0; i < n; i++) {
        if(arr[i] > 0)
            s.insert(arr[i]);
    }

    int missing = 1;
    while(s.count(missing))
        missing++;

    cout << missing;
    return 0;
}

Java

import java.util.*;

public class FirstMissingPositive {
    public static void main(String[] args) {
        int[] arr = {3,4,-1,1};
        HashSet set = new HashSet<>();

        for(int x : arr)
            if(x > 0)
                set.add(x);

        int missing = 1;
        while(set.contains(missing))
            missing++;

        System.out.print(missing);
    }
}

Python

arr = [3,4,-1,1]
s = set(x for x in arr if x > 0)

missing = 1
while missing in s:
    missing += 1

print(missing)

JavaScript

let arr = [3,4,-1,1];
let set = new Set(arr.filter(x => x > 0));

let missing = 1;
while (set.has(missing))
    missing++;

console.log(missing);

Approach 3: Index Mapping (Optimal)

Idea

Place each number x at index x - 1.
Then find the first index where this condition fails.

Algorithm

  1. For each index i
    • While arr[i] is in range [1, n]
    • Swap it to correct position
  2. Traverse array
  3. First index i where arr[i] != i + 1
  4. Return i + 1

Time & Space Complexity

  • Time: O(n)
  • Space: O(1)

Implementations

C

#include 

void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main() {
    int arr[] = {3,4,-1,1};
    int n = 4;

    for(int i = 0; i < n; i++) {
        while(arr[i] >= 1 && arr[i] <= n && arr[arr[i] - 1] != arr[i]) {
            swap(&arr[i], &arr[arr[i] - 1]);
        }
    }

    for(int i = 0; i < n; i++) {
        if(arr[i] != i + 1) {
            printf("%d", i + 1);
            return 0;
        }
    }

    printf("%d", n + 1);
    return 0;
}

C++

#include 
using namespace std;

int main() {
    int arr[] = {3,4,-1,1};
    int n = 4;

    for(int i = 0; i < n; i++) {
        while(arr[i] >= 1 && arr[i] <= n && arr[arr[i]-1] != arr[i])
            swap(arr[i], arr[arr[i]-1]);
    }

    for(int i = 0; i < n; i++) {
        if(arr[i] != i + 1) {
            cout << i + 1;
            return 0;
        }
    }

    cout << n + 1;
    return 0;
}

Java

public class FirstMissingPositive {
    public static void main(String[] args) {
        int[] arr = {3,4,-1,1};
        int n = arr.length;

        for(int i = 0; i < n; i++) {
            while(arr[i] >= 1 && arr[i] <= n && arr[arr[i]-1] != arr[i]) {
                int temp = arr[i];
                arr[i] = arr[temp - 1];
                arr[temp - 1] = temp;
            }
        }

        for(int i = 0; i < n; i++) {
            if(arr[i] != i + 1) {
                System.out.print(i + 1);
                return;
            }
        }

        System.out.print(n + 1);
    }
}

Python

arr = [3,4,-1,1]
n = len(arr)

for i in range(n):
    while 1 <= arr[i] <= n and arr[arr[i] - 1] != arr[i]:
        arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1]

for i in range(n):
    if arr[i] != i + 1:
        print(i + 1)
        break
else:
    print(n + 1)

JavaScript

let arr = [3,4,-1,1];
let n = arr.length;

for (let i = 0; i < n; i++) {
    while (arr[i] >= 1 && arr[i] <= n && arr[arr[i] - 1] !== arr[i]) {
        [arr[i], arr[arr[i] - 1]] = [arr[arr[i] - 1], arr[i]];
    }
}

for (let i = 0; i < n; i++) {
    if (arr[i] !== i + 1) {
        console.log(i + 1);
        return;
    }
}

console.log(n + 1);

Dry Run (Optimal Approach)

Input

[3, 4, -1, 1]

After placement:

[1, -1, 3, 4]

Index 1 should contain 2 → missing is 2

Summary

  • Sorting & Hashing are intuitive but not optimal
  • Index mapping solves in O(n) time & O(1) space
  • This is the interview-preferred solution

Next Problem in the Series

Count Inversions in an Array

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com