Geeksforgeeks question doubt

Here is the link to the question (Question). And I will give my function’s code below.

I am using an iterative approach. But I am getting TLE when submitting. Please help in identifying the error. Even though the given example test cases are working.

int findFloor(vector<long long> a, long long n, long long x){
if(a[0]>x)
{
    return -1;
}
else if(x>a[n-1])
{
    return n-1;
}
else
{
    int i=0,j=n-1;
    while(i<=j)
    {
        int m=i+j / 2;
        if(a[m]==x || (a[m]<x && a[m+1]>x))
        {
            return m;
        }
        else if(a[m]<x)
        {
            i=m+1;
        }
        else
        {
            j=m-1;
        }
    }
}
// Your code here

}

maybe try changing
vector<long long> a to const vector<long long> &a
Expected time complexity is O(\log{n}) and passing the vector itself is taking O(n)

1 Like

That didn’t work. Actually the function parameters were predefined so something is wrong with the working of code.
But I matched it with given recursive solution on the website. I can’t figure out what’s the problem.

  1. Stop sync with stdio. ios_base::sync_with_stdio(false); cin.tie(NULL);
  2. Use pass by reference.
  3. Add parentheses at m=(i+j)/2.
1 Like

Sorry for the late reply. I have some internet issues. The parentheses addition fixed it. I forgot that it will calculate the expression by BODMAS.