jayati

Smallest Positive missing number

Nov 21st, 2023
1,402
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  
  6. // } Driver Code Ends
  7.  
  8. class Solution
  9. {
  10.     public:
  11.     //Function to find the smallest positive number missing from the array.
  12.     // -4 -3 -2 -2 -1 0 1 1 2
  13.     int missingNumber(int arr[], int n)
  14.     {
  15.         // Your code here
  16.        
  17.         set<int> s;
  18.         for(int i=0;i<n;i++)
  19.         {
  20.             s.insert(arr[i]);
  21.         }
  22.         int ans=*max_element(arr,arr+n);
  23.         ans+=1;
  24.         int j=1;
  25.          set<int>::iterator itr;
  26.          for (itr = s.begin();itr != s.end(); itr++)
  27.         {
  28.             if(*itr<=0)
  29.             {
  30.                 continue;
  31.             }
  32.             else
  33.             {
  34.                 if(*itr!=j)
  35.                 {
  36.                     ans=j;
  37.                     break;
  38.                 }
  39.             }
  40.             j++;
  41.         }
  42.         if(ans<0)
  43.         {
  44.             return 1;
  45.         }
  46.         return ans;
  47.     }
  48. };
  49.  
  50. //{ Driver Code Starts.
  51.  
  52. int missingNumber(int arr[], int n);
  53.  
  54. int main() {
  55.    
  56.     //taking testcases
  57.     int t;
  58.     cin>>t;
  59.     while(t--){
  60.        
  61.         //input number n
  62.         int n;
  63.         cin>>n;
  64.         int arr[n];
  65.        
  66.         //adding elements to the array
  67.         for(int i=0; i<n; i++)cin>>arr[i];
  68.        
  69.         Solution ob;
  70.         //calling missingNumber()
  71.         cout<<ob.missingNumber(arr, n)<<endl;
  72.     }
  73.     return 0;
  74. }
  75. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment