fork download
  1. // C++ program for the above approach
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // Function for finding the first
  6. // missing positive number
  7. int firstMissingPositive(int arr[], int n)
  8. {
  9.  
  10. // Loop to traverse the whole array
  11. for (int i = 0; i < n; i++) {
  12.  
  13. // Loop to check boundary
  14. // condition and for swapping
  15. while (arr[i] >= 1 && arr[i] <= n
  16. && arr[i] != arr[arr[i] - 1]) {
  17. swap(arr[i], arr[arr[i] - 1]);
  18. }
  19. }
  20.  
  21. // Checking any element which
  22. // is not equal to i+1
  23. for (int i = 0; i < n; i++) {
  24. if (arr[i] != i + 1) {
  25. return i + 1;
  26. }
  27. }
  28.  
  29. // Nothing is present return last index
  30. return n + 1;
  31. }
  32.  
  33. // Driver code
  34. int main()
  35. {
  36. int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
  37. int n = sizeof(arr) / sizeof(arr[0]);
  38.  
  39. int ans = firstMissingPositive(arr, n);
  40.  
  41. cout << ans;
  42.  
  43. return 0;
  44. }
  45. // This code is contributed by Harsh kedia
  46.  
Success #stdin #stdout 0.01s 5352KB
stdin
Standard input is empty
stdout
4