1

I faced this problem in a hackathon but couldn't figure out where I was going wrong.

The problem statement was

Count the number of subsequences in an array where the difference of the first and last element is <= K

Each subsequence is contiguous

Input: 11 5 2 15 25
Output: 6

Explanation: {11}, {5}, {2}, {15}, {25}, {5, 2}

I believe they were considering a single element as a valid subsequence so what I tried to return the length of the array + the count.

int getCount(int *a, int n, int k){
   sort(a, a + n);
   int c = 0;
   for(int i=0; i<n; i++){
       int j = i + 1;
       while(j < n and a[j] - a[i] <= k){
           c+=1;
           j+=1;
       }
   }
   return n + c;
}

I've tried sorting but it still timed out!

Ankit Sharma
  • 1,626
  • 1
  • 14
  • 21
  • Why you sort the input? Is that necessary? –  May 11 '19 at 05:23
  • I actually had done a similar question before on geeksforgeeks and they suggested a strategy about sorting. https://www.geeksforgeeks.org/pairs-difference-less-k/ – Ankit Sharma May 11 '19 at 05:28

2 Answers2

0

Nothing I see here is wrong with complexity, it is supposed to be O(n*n) but of course it will time out since this is an infinite loop:

while(j < n and a[j] - a[i] <= k) c += 1;

Fix:

while(j++ < n and a[j] - a[i] <= k) c += 1;

OR

while(j < n and a[j] - a[i] <= k) {
   c += 1;
   j++;
}

Also you might want to change the comparison from lower or equal to just lower

Final:

while(j < n and a[j] - a[i] < k) {
   c += 1;
   j++;
}

Cheers!

Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34
  • 1
    Thanks for pointing that out but actually I did the same thing. Sorry for that typo. It was still showing wrong answer. I've edited that code. – Ankit Sharma May 11 '19 at 07:02
  • Time outs and wrong answer. I tried first with Java and it showed TLE and when I switched to C++ it showed wrong answer for 5/10 cases – Ankit Sharma May 11 '19 at 07:04
0

you are using O(nn) approach instead use O(nlogn) approach for overcoming the TLE problem so you have sorted array so simply apply binary search for every element find the largest distance element having difference is less than or equal to k so it works on O(nlogn); hence solved !! THANKS!!!