Find First Positive Missing Number in Unsorted Array

The given array has positive and negative unsorted jumbled elements, We need to find the first minimum positive element missing from the array.

For Example

In arr {3, 4, -1, 1} the first minimum positive missing element is 2.

{1, 1, 0, -1, -2} the first minimum positive missing element is 2.

2, 3, 7, 6, 8, -1, -10, 15} the first minimum positive missing element is 1.

{1, 2, 3, 4, 5, 6, 7, 8, 9} there is no minimum positive missing element hence answer is -1.

{0, 10, 2, -10, -20} the first minimum positive missing element is 1.

{1, 2, 0} the first minimum positive missing element is 3.

package org.wesome.dsalgo;

import java.util.HashSet;
import java.util.Set;

public class FirstMissingPositive {
    public static int firstMissingPositive(int[] nums) {
        int result = -1;
        if (nums.length < 1) {
            return result;
        }
        Set<Integer> intSet = new HashSet<>();
        for (int num : nums) {
            intSet.add(num);
        }
        if (!intSet.contains(1)) {
            return 1;
        }
        for (int i = 2; i <= nums.length; i++) {
            if (!intSet.contains(i)) {
                result = i;
                break;
            }
        }
        return result;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.FirstMissingPositive.firstMissingPositive;

public class FirstMissingPositiveTest {
    @Test
    void firstMissingPositiveTest1() {
        int[] arr = new int[]{3, 4, -1, 1};
        Assertions.assertEquals(2, firstMissingPositive(arr));
    }

    @Test
    void firstMissingPositiveTest2() {
        int[] arr = new int[]{1, 1, 0, -1, -2};
        Assertions.assertEquals(2, firstMissingPositive(arr));
    }

    @Test
    void firstMissingPositiveTest3() {
        int[] arr = new int[]{2, 3, 7, 6, 8, -1, -10, 15};
        Assertions.assertEquals(1, firstMissingPositive(arr));
    }

    @Test
    void firstMissingPositiveTest4() {
        int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
        Assertions.assertEquals(-1, firstMissingPositive(arr));
    }

    @Test
    void firstMissingPositiveTest5() {
        int[] arr = new int[]{0, 10, 2, -10, -20};
        Assertions.assertEquals(1, firstMissingPositive(arr));
    }

    @Test
    void firstMissingPositiveTest6() {
        int[] arr = new int[]{1, 2, 0};
        Assertions.assertEquals(3, firstMissingPositive(arr));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on