I was solving the problem and came up with the logic, and applied binary search, but still got TLE.
Now I looked up the solution and found that they came up with the same logic, just that they applied lower_bound to find the index.
Here’s is my code :
#include <bits/stdc++.h>
using namespace std;
#define int long long int
int binSearch(int k, vector<int> smaller)
{
int n = smaller.size();
int lo = 0, hi = n, mid;
while (lo < hi)
{
mid = lo + (hi - lo) / 2;
if (k <= smaller[mid])
{
hi = mid;
}
else
{
lo = mid + 1;
}
}
return hi;
}
int32_t main()
{
int t;
cin >> t;
while (t--)
{
int n, q;
cin >> n >> q;
vector<int> a(n);
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a.begin(), a.end());
vector<int> smaller(n);
for (int i = 0; i < n; i++)
{
int l = n - i - 1;
if (l > 1)
{
smaller[i] = l * (l - 1) / 2;
if (i > 0)
smaller[i] += smaller[i - 1];
}
else
{
smaller[i] = smaller[i - 1];
}
}
for (int i = 0; i < q; i++)
{
int k;
cin >> k;
int index = binSearch(k, smaller);
cout << a[index] << endl;
}
}
return 0;
}
Now, time complexity for binary search, as well as lower_bound, is O(logn). Then why am I getting TLE using Binary Search??
Do suggest some correction in my binSearch function.