Sunday, 13 October 2019

[Arrays] [InterviewBit] [GeeksforGeeks] Maximum Consecutive Gap

Maximum Consecutive Gap

Question Statement:

Given an array, find the maximum difference between its two consecutive elements in its sorted form.

And do that in $O(n)$ space and time, just for the fun of it.

My initial solution:

InterviewBit said that the numbers are all 32 bits, so obviously radix sort was on my mind. Take counting sort for each bit, from right to left. Done in $32 \times n$ time. Then check the maximum gap. Thank God I didn't implement this, otherwise I won't be able to know how to solve this correctly. 

Actual Solution:

Remember PigeonHole principle? Yes. That is what we'll be using here, got damnitwhatthefuckpeopledothesedays.
So, initially find the maximum and the minimum of the array. Done? Now here me out, create $n-1$ buckets each of equal size. 

Now out of $n$ elements two are the minimum value and the maximum value. So, we're left with $n-2$ elements. So it is impossible that each bucket will contain an element. At best, there will be a bucket that'll be empty. And guess what, if a bucket is empty, the gap between the maximum element of the previous bucket and the minimum element of the next bucket is obviously  greater than any gap between two elements inside the same bucket. Right? So what we have to do is put elements in these buckets, and then find the gap between consecutive (alive) buckets. And boop boop we're done.

Here is my code, which you don't give a fuck about:

  

No comments:

Post a Comment

1498C - Planar reflections

1498C - Planar reflections Problem We have a set of $n$ 2D planes. A particle comes from the left, and goes through all the planes. Initiall...