Solved LeetCode Problem 268: First Missing Positive

Problem 23 : LeetCode LeetCode Problem(268) Solved: First Missing Positive (Optimal In-Place Solution) 🤯 Problem: Given an unsorted array of integers, find the smallest positive integer that is not present in the array. This must be solved in O(n) time and O(1) extra space. My Approach: I solved this challenging problem using the Cyclic Sort algorithm for an optimal in-place solution. In-Place Hashing: I iterated through the array, ensuring that every number x (where 1≤x≤n) is placed at its correct index, which is x−1. For example, the number 3 belongs at index 2. Swapping: I repeatedly swapped elements that were out of place until they met the condition or were outside the valid range [1,n]. This effectively uses the array itself as a hash map. Final Scan: After the sorting phase, a final linear scan of the array quickly identified the first index i where arr[i] is not equal to i+1. The missing positive number is then i+1. Key Achievements: Time Complexity: Achieved an O(n) time complexity with a runtime of 1 ms, beating 31.66% of other Java submissions. Space Complexity: Achieved O(1) extra space, utilizing the array in-place. Memory: The solution used 47.56 MB of memory, beating 5.17% of other submissions. Link : https://lnkd.in/dJShvfwn

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories