Maximum Gap Problem

Maximum Gap Problem Statement

Given an array of n non-negative integers, find the maximum difference between 2 consecutive numbers in the sorted array of the given integers.

Example One

{
"arr": [1, 3, 7, 2]
}

Output:

4

We can see that in sorted order, the array becomes [1, 2, 3, 7], and the maximum difference is 7 – 3 = 4.

Example Two

{
"arr": [1, 1, 1]
}

Output:

0

Here the sorted array is [1, 1, 1], and so the maximum difference is 1 – 1 = 0.

Notes

  • We need a linear time solution, not n * log(n). You can use up-to linear extra space.
  • Assume input is always valid, and won’t overflow.
  • If the input has only one element, then return 0.
  • There can be duplicates elements.

Constraints:

  • 1 <= n <= 106
  • 0 <= array element <= 106

We have provided one solution for this problem.

Maximum Gap Solution: Optimal

  • First we find the minimum and maximum numbers; let’s name them, min and max respectively.
  • Now the range of the numbers is max – min + 1.
  • We create an array named buckets of this size and use it to keep frequency of occurrence of numbers in an array.
  • When we encounter the number present in the array, we increment buckets[arr[i] – max] by 1.
  • After all the numbers in the array are processed, we find the maximum number of consecutive 0’s between 2 non-zero elements of buckets array. That is the answer.

Time Complexity

O(n + range).

Auxiliary Space Used

O(range).

Space Complexity

O(n + range).

Input takes O(n) space, and we use O(range) of auxiliary space.

Code For Maximum Gap Solution: Optimal


    /*
    Asymptotic complexity in terms of `n` = length of the given array `arr` and
    `range` = max(Elements of array) – min(Elements of array):
    * Time: O(n + range).
    * Auxiliary space: O(range).
    * Total space: O(n + range).
    */

    static Integer maximum_gap(ArrayList<Integer> arr) {
        int n = arr.size();
        if(n==1) {
            return 0;
        }

        int max = 0;
        int min = 1000001;
        // Find maximum and minimum elements.
        for(int i = 0; i<n; i++) {
            min = Math.min(min,arr.get(i));
            max = Math.max(max,arr.get(i));
        }

        // Create array of size range to store the frequencies of the array elements.
        int range = max - min + 1;
        int buckets[] = new int[range + 5];
        for(int i : arr) {
            buckets[i - min]++;
        }

        // Finding maximum number of consecutive zeros between 2 non zero elements of buckets array.
        int ans = 0;
        for(int i = range-1; i>0;) {
            int cnt = 0, temp = i;
            i--;
            while(i>=0 && buckets[i]==0) {
                cnt++;
                i--;
            }
            if(i>=0) {
                ans = Math.max(ans, temp - i);
            }
        }
        return ans;
    }

We hope that these solutions to maximum gap have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Add Two Numbers Represented By Lists Problem

Binary Tree Level Order Traversal Problem with Examples

Jump Game

Zigzag Sort Problem

Boggle Solver Problem

Shortest String Transformation Using A Dictionary Problem

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC