Taro Logo

First Missing Positive

#10 Most AskedHard
0 views
Topics:
Arrays

Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums.

You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.

Example 1:

Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.

Example 2:

Input: nums = [3,4,-1,1]
Output: 2
Explanation: 1 is in the array but 2 is missing.

Example 3:

Input: nums = [7,8,9,11,12]
Output: 1
Explanation: The smallest positive integer 1 is missing.

Constraints:

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input array is empty or null?
  2. Can the array contain negative numbers and zeros, and should those be ignored?
  3. Are duplicate values allowed in the input array, and how should they be handled?
  4. Is the input array allowed to be modified in-place, or must it remain read-only?
  5. What is the maximum possible size of the array and the range of values inside it to avoid integer overflow concerns?

Brute Force Solution

Approach

To find the very first positive number that is missing from a collection, the brute force strategy is to test numbers starting from the absolute beginning and check if each one is present.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the number one.
  2. Check the entire collection to see if your current number is hiding somewhere inside.
  3. If you discover that your number is missing, you have found your answer immediately and can stop right there.
  4. If you find that your number is indeed present in the collection, simply move on to the next positive number.
  5. Repeat this checking process for two, then three, then four, and keep going upward one by one.
  6. Eventually, you will hit a number that is not in the collection, and that will be your final answer.

Code Implementation

def first_missing_positive(number_collection):    # We must check every positive integer starting from one to find the first absent value    current_target = 1    while True:        # We assume the target is missing until we find evidence of it in the collection        is_target_present = False        for current_number in number_collection:            if current_number == current_target:                is_target_present = True                break        # If the target was never found during our scan, we have located our missing positive        if not is_target_present:            return current_target        current_target += 1

Big(O) Analysis

Time Complexity
O(n²) – To find the first missing positive, this strategy checks each integer starting from one and scans the entire collection of size n to see if that integer is present. In the worst-case scenario, we might need to check up to n + 1 numbers, and for each number tested, we iterate through all n elements of the collection. This means we perform a full scan of n elements repeatedly for roughly n different candidate numbers. Consequently, the total operations approximate n multiplied by n, which simplifies to the final Big O time complexity of O(n²).
Space Complexity
O(1) – The provided plain English explanation describes an in-place checking strategy that uses only a few primitive variables to iterate through numbers starting from one. No auxiliary data structures, temporary lists, or hash maps are created, meaning the extra memory remains constant regardless of the input size N. Therefore, the auxiliary space complexity is O(1).

Optimal Solution

Approach

The optimal strategy is like playing a game of musical chairs where every positive number gets its own rightful seat based on its value. By rearranging the numbers so that each positive number sits in the position matching its value, the missing number will immediately reveal itself by sitting in the wrong spot.

Here's how the algorithm would work step-by-step:

  1. Look through all the items and ignore anything that is zero or negative because we only care about positive counting numbers.
  2. For every valid positive number you find, pick it up and place it into the exact position that matches its numerical value.
  3. If the number you are trying to place is too large to fit in the available seating, or if its target seat is already occupied by the correct number, just leave it alone for now.
  4. Whenever you swap a number into its correct seat, take the number that was displaced and repeat the placement process for it until you land on something you cannot use.
  5. After everyone has been shifted around as much as possible, walk down the line from the very beginning.
  6. Stop at the first spot where the number sitting there does not match the position's number.
  7. That mismatched spot represents the smallest missing positive number you were looking for.

Code Implementation

def first_missing_positive(input_numbers):    array_length = len(input_numbers)    index_pointer = 0    while index_pointer < array_length:        target_index = input_numbers[index_pointer] - 1                # We must place positive numbers in their exact index matching value minus one to enable O(1) space tracking.        if 0 <= target_index < array_length and input_numbers[index_pointer] != input_numbers[target_index]:            input_numbers[index_pointer], input_numbers[target_index] = input_numbers[target_index], input_numbers[index_pointer]        else:            index_pointer += 1    scan_pointer = 0    while scan_pointer < array_length:                # The first position whose value does not match the expected sequence reveals the missing positive integer.        if input_numbers[scan_pointer] != scan_pointer + 1:            return scan_pointer + 1        scan_pointer += 1    # If all positions contain their expected values, the missing positive is the next integer after the array length.    return array_length + 1

Big(O) Analysis

Time Complexity
O(n) – Although the solution contains a while loop nested inside a for loop, each positive number is placed into its correct seat at most once and never visited again by the inner swap mechanism. Walking down the array of size n to rearrange elements takes linear time, and the final check to find the first mismatched position also scans the array in a single pass. This results in at most a constant number of operations per element, meaning the total operations scale linearly with n and simplify to O(n).
Space Complexity
O(1) – The algorithm performs all rearrangements and swaps directly in place within the input array without allocating any auxiliary data structures, temporary lists, or hash maps. A few primitive integer variables are used to maintain loop indices and temporary values during the swapping process, which require a constant amount of memory regardless of the input size. Therefore, as the input size N grows, the extra memory usage remains entirely fixed, resulting in an optimal auxiliary space complexity.

Edge Cases

Empty array or null input
How to Handle:
Return 1 immediately since the smallest missing positive integer in an empty set is always 1.
Array with a single element like 1 or 2
How to Handle:
If the element is 1, return 2; otherwise, return 1 as the smallest positive integer.
Array containing only negative numbers and zeros
How to Handle:
The algorithm will ignore these non-positive values and correctly return 1 as the first missing positive.
Array already containing a continuous sequence starting from 1 up to N
How to Handle:
The in-place cyclic sort will place each number in its correct bucket, leading to N + 1 as the output.
Array with large positive numbers far exceeding the array length
How to Handle:
Values greater than the array length are ignored during placement because they cannot affect the smallest missing positive within range 1 to N + 1.
Array containing duplicate numbers
How to Handle:
The cyclic placement handles duplicates gracefully by ignoring redundant values once the correct position is already occupied.
Maximum-sized inputs up to integer limits
How to Handle:
The linear time O(N) and constant space O(1) in-place modification ensures the solution scales efficiently without exceeding memory constraints.
Inputs with extreme boundary values including Integer.MAX_VALUE and Integer.MIN_VALUE
How to Handle:
Out-of-bound values are filtered out safely so they do not cause array index out of bounds exceptions.
0/13 completed