Visa OA SDE1 Question
Anonymous User
197

You are given a array of heights of hills
a hiker can see the hills ahead of him after a certain gap distance x

i.e
if x = 2,
He can see the hills ahead of him after 2 indexes
like if on i = 1 then he can see from 3 , 4, ...n;

We need to find the minimum gap he can see from any hill

Ex:

  1. heights = [ 2, 4 , 9, 10], gap = 2

ans:
at i = 0
he can see i = 2 and i =3
minimum differance = 7

at i = 1
minimum differance = 6

from 2 nd 3 no hill is visible

So final answer is 6.

This was my approach:

int minimumDiff( vectorheights, int gap){
set s;
int ans = INT_MAX;
for(int i = gap; i < heights.size() ; i++){
s.insert(heights[i-gap]);
int x = heights[i];
auto it = lower_bound(s.begin(),s.end(),x);
if(it != s.end()){
ans = min(ans , abs(heights[i] - *it));
}
if(it != s.begin()){
it--;
ans = min(ans,abs(heights[i]- *it));
}
}
return ans;
}

But this gave me TLE after 13 test cases(out of 20)
Any alternate approach

Only regret i have is of not putting a multi before the set
and submitting again

Comments (1)