KatInterview

164. Maximum Gap

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation: Bucket Sort (Pigeonhole Principle)

The problem asks for the maximum difference between successive elements in a sorted array, but with a constraint of O(n) time and O(n) space complexity. A standard sorting algorithm would take O(n log n) time, which is too slow. This suggests a non-comparison-based sorting method or a distribution-based approach like bucket sort.

Solution

Maximum Gap in Python

class Solution:
    def maximumGap(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 2:
            return 0

        # Find the minimum and maximum elements in the array.
        min_val = min(nums)
        max_val = max(nums)

        if min_val == max_val:
            return 0

        # Calculate bucket size and count.
        # The gap will be at least (max_val - min_val) / (n - 1).
        bucket_size = max(1, (max_val - min_val) // (n - 1))
        bucket_count = (max_val - min_val) // bucket_size + 1

        # Create buckets and store min/max for each non-empty bucket.
        # A sentinel value of -1 for max works since nums[i] >= 0.
        buckets_min = [float('inf')] * bucket_count
        buckets_max = [-1] * bucket_count

        for num in nums:
            bucket_idx = (num - min_val) // bucket_size
            buckets_min[bucket_idx] = min(buckets_min[bucket_idx], num)
            buckets_max[bucket_idx] = max(buckets_max[bucket_idx], num)

        # Calculate the maximum gap by checking gaps between adjacent non-empty buckets.
        max_gap = 0
        prev_max = min_val

        for i in range(bucket_count):
            # Skip empty buckets.
            if buckets_max[i] == -1:
                continue
            
            # Calculate gap with the previous bucket's max.
            max_gap = max(max_gap, buckets_min[i] - prev_max)
            # Update prev_max to the current bucket's max.
            prev_max = buckets_max[i]

        return max_gap

Maximum Gap in Java

class Solution {
    public int maximumGap(int[] nums) {
        int n = nums.length;
        if (n < 2) {
            return 0;
        }

        // Find the minimum and maximum elements in the array.
        int minVal = nums[0];
        int maxVal = nums[0];
        for (int i = 1; i < n; i++) {
            minVal = Math.min(minVal, nums[i]);
            maxVal = Math.max(maxVal, nums[i]);
        }

        if (minVal == maxVal) {
            return 0;
        }

        // Calculate bucket size and count.
        // The gap will be at least (maxVal - minVal) / (n - 1).
        int bucketSize = (maxVal - minVal) / (n - 1);
        if (bucketSize == 0) {
            bucketSize = 1;
        }
        int bucketCount = (maxVal - minVal) / bucketSize + 1;

        // Create buckets and store min/max for each non-empty bucket.
        int[] bucketsMin = new int[bucketCount];
        int[] bucketsMax = new int[bucketCount];
        Arrays.fill(bucketsMin, Integer.MAX_VALUE);
        Arrays.fill(bucketsMax, Integer.MIN_VALUE);

        for (int num : nums) {
            int bucketIdx = (num - minVal) / bucketSize;
            bucketsMin[bucketIdx] = Math.min(bucketsMin[bucketIdx], num);
            bucketsMax[bucketIdx] = Math.max(bucketsMax[bucketIdx], num);
        }

        // Calculate the maximum gap by checking gaps between adjacent non-empty buckets.
        int maxGap = 0;
        int prevMax = minVal;

        for (int i = 0; i < bucketCount; i++) {
            // Skip empty buckets.
            if (bucketsMax[i] == Integer.MIN_VALUE) {
                continue;
            }
            
            // Calculate gap with the previous bucket's max.
            maxGap = Math.max(maxGap, bucketsMin[i] - prevMax);
            // Update prevMax to the current bucket's max.
            prevMax = bucketsMax[i];
        }

        return maxGap;
    }
}

Maximum Gap in C++

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        int n = nums.size();
        if (n < 2) {
            return 0;
        }

        // Find the minimum and maximum elements in the array.
        int minVal = nums[0];
        int maxVal = nums[0];
        for (int i = 1; i < n; ++i) {
            minVal = min(minVal, nums[i]);
            maxVal = max(maxVal, nums[i]);
        }

        if (minVal == maxVal) {
            return 0;
        }

        // Calculate bucket size and count.
        // The gap will be at least (maxVal - minVal) / (n - 1).
        int bucketSize = (maxVal - minVal) / (n - 1);
        if (bucketSize == 0) {
            bucketSize = 1;
        }
        int bucketCount = (maxVal - minVal) / bucketSize + 1;

        // Create buckets and store min/max for each non-empty bucket.
        vector<int> bucketsMin(bucketCount, INT_MAX);
        vector<int> bucketsMax(bucketCount, INT_MIN);

        for (int num : nums) {
            int bucketIdx = (num - minVal) / bucketSize;
            bucketsMin[bucketIdx] = min(bucketsMin[bucketIdx], num);
            bucketsMax[bucketIdx] = max(bucketsMax[bucketIdx], num);
        }

        // Calculate the maximum gap by checking gaps between adjacent non-empty buckets.
        int maxGap = 0;
        int prevMax = minVal;

        for (int i = 0; i < bucketCount; ++i) {
            // Skip empty buckets.
            if (bucketsMax[i] == INT_MIN) {
                continue;
            }
            
            // Calculate gap with the previous bucket's max.
            maxGap = max(maxGap, bucketsMin[i] - prevMax);
            // Update prevMax to the current bucket's max.
            prevMax = bucketsMax[i];
        }

        return maxGap;
    }
};

Maximum Gap in TypeScript

function maximumGap(nums: number[]): number {
    const n = nums.length;
    if (n < 2) {
        return 0;
    }

    // Find the minimum and maximum elements in the array.
    let minVal = nums[0];
    let maxVal = nums[0];
    for (let i = 1; i < n; i++) {
        minVal = Math.min(minVal, nums[i]);
        maxVal = Math.max(maxVal, nums[i]);
    }

    if (minVal === maxVal) {
        return 0;
    }

    // Calculate bucket size and count.
    // The gap will be at least (maxVal - minVal) / (n - 1).
    let bucketSize = Math.floor((maxVal - minVal) / (n - 1));
    if (bucketSize === 0) {
        bucketSize = 1;
    }
    const bucketCount = Math.floor((maxVal - minVal) / bucketSize) + 1;

    // Create buckets and store min/max for each non-empty bucket.
    const bucketsMin = new Array(bucketCount).fill(Infinity);
    const bucketsMax = new Array(bucketCount).fill(-1);

    for (const num of nums) {
        const bucketIdx = Math.floor((num - minVal) / bucketSize);
        bucketsMin[bucketIdx] = Math.min(bucketsMin[bucketIdx], num);
        bucketsMax[bucketIdx] = Math.max(bucketsMax[bucketIdx], num);
    }

    // Calculate the maximum gap by checking gaps between adjacent non-empty buckets.
    let maxGap = 0;
    let prevMax = minVal;

    for (let i = 0; i < bucketCount; i++) {
        // Skip empty buckets.
        if (bucketsMax[i] === -1) {
            continue;
        }
        
        // Calculate gap with the previous bucket's max.
        maxGap = Math.max(maxGap, bucketsMin[i] - prevMax);
        // Update prevMax to the current bucket's max.
        prevMax = bucketsMax[i];
    }

    return maxGap;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.