Welcome to this comprehensive guide on the First Missing Positive problem, a popular algorithmic concept in the field of Data Structures and Algorithms. Let's embark on this exciting journey together, exploring real-world applications and practical examples.
The First Missing Positive problem asks us to find the first number that is missing in a given unsorted list of numbers. The numbers in the list range from 1 to n (the number of elements in the list), and there may be duplicate numbers. The goal is to find the smallest number that is not in the list.
The solution to this problem involves iterating through the list and maintaining two arrays - one to store the frequency of each number in the list, and another to mark the numbers that have been encountered. We'll then go through the numbers again and find the first number that is not marked.
Here's an outline of the algorithm:
count[] to store the frequency of each number, and present[] to mark the numbers that have been encountered.num:
count[num] if num is positive and less than or equal to n.present[num] to 1.n and do the following for each number num:
present[num] is 0 and count[num] is 0, then return num.Let's dive into some code examples to make this clearer.
def firstMissingPositive(arr, n):
# Initialize the present array with zeros
present = [0] * (n + 1)
# Iterate through the list
for num in arr:
if num > 0 and num <= n:
present[num] = 1
# Iterate through the numbers from 1 to n
for num in range(1, n + 1):
if present[num] == 0 and arr[count[num] - 1] != num:
return num
# If no missing number is found, return n+1
return n + 1public int firstMissingPositive(int[] arr, int n) {
int[] present = new int[n + 1];
for (int num : arr) {
if (num > 0 && num <= n) {
present[num] = 1;
}
}
for (int num = 1; num <= n; num++) {
if (present[num] == 0 && arr[count[num] - 1] != num) {
return num;
}
}
// If no missing number is found, return n+1
return n + 1;
}Pro Tip: You can optimize the code by using a HashSet to store the numbers instead of the present array. This will significantly improve the runtime complexity.
The First Missing Positive problem has various real-world applications, such as:
What is the goal of the First Missing Positive problem?
We hope this lesson has helped you understand the First Missing Positive problem and its applications. Keep practicing and exploring to improve your algorithmic skills! š¤š¼