In this HackerEarth Help John <HSBC> problem solution you are required to collect N numbers from a bag. Initially, the bag is empty. Whenever you put a number X in the bag, then the owner of the bag asks the question.

The questions are as follows:
  1. What is the greatest integer that is smaller than X and present inside the bag?
  2. What is the smallest number that is greater than X and present inside the bag?
If you answer both the questions correctly, then you can put X inside the bag. Your task is to answers the questions that are asked by the owner of the bag.



HackerEarth Help John <HSBC> problem solution


HackerEarth Help John HSBC problem solution.

#include<bits/stdc++.h>
using namespace std;
int main()
{
  int n;
  set<int> s;
  cin >> n;
  while(n --)
  {
    int x;
    cin >> x;
    s.insert(x);
    auto it1 = s.find(x);
    auto it2 = it1, it3 = it1;
    if(it1 == s.begin())
    cout << "-1";
    else
    {
      it2 --;
      cout << *it2;
    }
    if(*it3 == * s.rbegin())
    cout << " -1" << endl;
    else
    {
      it3 ++;
      cout << " " << *it3 << endl;
    }
  }
  return 0;
}


Second solution

#include <bits/stdc++.h>
#define mod 1000000007
#define INF INT_MAX
#define max_range 1 << 20
#define ll long long
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;
ll power(ll x,ll y) {ll res=1; x =x%mod; while (y > 0) {if(y&1)res=((res*x)%mod+mod)%mod; y=y>>1; x=((x*x)%mod+mod)%mod;} return res;}
vector<vector<ll> > newdp(ll A, ll B){ vector<vector<ll> > dp; dp.resize(A+1);for(int i = 0; i < A+1; i++){dp[i].resize(B+1);for(int j = 0; j < B+1; j++)dp[i][j] = -1;} return dp;}
vector<ll> all_prime;
void prime(){ bool hash[1000000];memset(hash,false,sizeof hash); for (int p = 2; p * p < 1000000; p++)if (hash[p] == true)for (int i = p * 2; i < 1000000; i += p)hash[i] = false;
for(int i = 2;i < 1000000; i++) if(hash[i]) all_prime.push_back(i);}
vector<ll> v[max_range];

int main(int argc, char const *argv[])
{
  ll n;
  cin>>n;
  set<ll>s;

  for(int i=0,ele;i<n;i++)
  {   
    cin>>ele;
    
    if(i==0)
    cout<<"-1 -1\n";
      else{
          auto itr = s.lower_bound(ele);
          
          ll frst=-1,sec=-1;
          
          if(itr==s.begin())       {frst = -1;sec = (*itr);}
          else if(itr==s.end())    {sec  = -1;(itr--);frst = (*itr) ;}
          else                   {sec = (*itr) ; (itr--) ; frst =(*itr);}
          
          cout<<frst<<" "<<sec<<endl; 
        }
        s.insert(ele);
  }
  return 0;
}