22. Smallest Positive Missing
β GFG solution to the Smallest Positive Missing Number problem: find the smallest missing positive integer using index marking technique with O(n) time and O(1) space. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an unsorted array arr[] of size N that can contain negative numbers and zeros. Your task is to find the smallest positive number missing from the array.
π Important Notes:
Positive integers start from
1.Ignore all values β€ 0 and values greater than the array size while computing the result.
The missing number must be positive and strictly greater than 0.
π Examples
Example 1
Input: arr[] = [2, -3, 4, 1, 1, 7]
Output: 3
Explanation: Smallest positive missing number is 3.
The array contains 1, 2, 4, 7 but missing 3.Example 2
Example 3
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$-10^6 \le \text{arr}[i] \le 10^6$
β
My Approach
The optimal approach uses Index Marking technique to achieve O(n) time complexity with O(1) space complexity:
Index Marking Technique
Clean Invalid Numbers:
Replace all non-positive numbers (β€ 0) with a value greater than n (array size).
This ensures all numbers are positive and within a manageable range.
Mark Presence Using Signs:
For each number
xin the array, mark its presence by makingarr[x-1]negative.Use
abs(arr[i])to get the actual value since we're modifying signs.Only mark if
xis within valid range [1, n].
Find First Unmarked Position:
Traverse the array to find the first positive number.
The index of first positive number + 1 gives the smallest missing positive.
If all numbers are negative (marked), return n+1.
Key Insight:
We use the array itself as a hash map where index represents the number.
Negative sign indicates presence, positive indicates absence.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We make three separate passes through the array: first to clean invalid numbers, second to mark presence, and third to find the first unmarked position.
Expected Auxiliary Space Complexity: O(1), as we only use the input array for marking and a few constant variables, requiring no additional space proportional to input size.
π§ Code (C)
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated