Java Program to Find the Smallest Positive Number Missing from an Unsorted Array

In the realm of software development, solving array-based problems efficiently is crucial, especially in technical interviews and competitive programming. One such problem is finding the smallest positive number missing from an unsorted array. This problem tests a programmer's ability to manipulate and traverse arrays, as well as their understanding of time and space complexity.

Methods

Method 1: Using Sorting

Approach:

  • Sort the array.
  • Traverse the sorted array and look for the first missing positive number.

Implementation:

  • Sort the array.
  • Iterate through the array, starting from 1, and check if each positive integer is present.

File Name: MissingPositiveNumber.java

Output:

 
2   

Time Complexity: O(nlogn) due to sorting.

Space Complexity: O(1) if in-place sorting is used

Method 2: Using Hashing

Approach:

  • Use a HashSet to store all positive numbers from the array.
  • Iterate from 1 upwards and check if each number is in the HashSet.

Implementation:

  • Traverse the array and add all positive numbers to a HashSet.
  • Start from 1 and check if it is in the HashSet. Continue until you find the missing number.

File Name: MissingPositiveNumber.java

Output:

 
2   

Time Complexity: O(n) for both insertion and search operations.

Space Complexity: O(n) for storing elements in the HashSet.

Method 3: Using Index Mapping (Optimal Solution)

Approach:

  • Use the array itself to track the presence of positive numbers by placing each number at its corresponding index (number 1 at index 0, number 2 at index 1, etc.).
  • Traverse the array again to find the first index that does not match its corresponding number.

Implementation:

  • Iterate through the array and place each number at its corresponding index.
  • Traverse the array to find the first index where the value is not equal to the index + 1.

File Name: MissingPositiveNumber.java

Output:

 
2   

Time Complexity: O(n)

Space Complexity: O(1) as the reordering is done in-place.

Conclusion

Identifying the smallest positive number missing from an unsorted array is a classic problem that can be tackled using various techniques. Through this article, we have examined three distinct methods: sorting, hashing, and index mapping. Each method has its own merits and trade-offs.

The sorting approach, while straightforward, is not optimal for large datasets. The hashing method improves time complexity but at the cost of additional space. The index mapping technique, on the other hand, achieves the best of both worlds with linear time complexity and constant space usage.

By understanding and implementing these methods, developers can enhance their problem-solving skills and prepare for complex technical challenges.