Skip to content
Programmingoneonone
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone

HackerEarth A Game of Numbers problem solution

YASH PAL, 31 July 2024
In this HackerEarth A Game of Numbers problem solution, You are given an array A of N integers. Now, two functions F(X) and G(X) are defined:
  1. F(X) : This is the smallest number Z such that X < Z <= N and A[X] < A[Z]
  2. G(X) : This is the smallest number Z such that X < Z <= N and A[X] > A[Z]
Now, you need to find for each index i of this array G(F(i)), where 1 <= i <= N. If such a number does not exist, for particular index i, output 1 as its answer. If such a number does exist, output A[G(F(i))]
HackerEarth A Game of Numbers problem solution

HackerEarth A Game of Numbers problem solution.

#include<bits/stdc++.h>
using namespace std;

int main()
{

int n;
cin>>n;

short int a[n];
for(int i=0;i<n;i++)cin>>a[i];
short int next_greater[n], next_smaller[n];
stack<short int> s1;
for (short int i=n-1; i>=0; i--)
{
while (!s1.empty() && a[s1.top()] <= a[i] )
s1.pop();
if (!s1.empty())
next_greater[i] = s1.top();
else
next_greater[i] = -1;

s1.push(i);
}

stack<short int> s2;
for (short int i=n-1; i>=0; i--)
{
while (!s2.empty() && a[s2.top()] >= a[i])
s2.pop();
if (!s2.empty())
next_smaller[i] = s2.top();

else
next_smaller[i] = -1;

s2.push(i);
}


for (short int i=0; i< n; i++)
{

if (next_greater[i] != -1 && next_smaller[next_greater[i]] != -1)
cout << a[next_smaller[next_greater[i]]] <<" ";
else
cout<<-1<<" ";
}

return 0;
}
coding problems solutions

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes