algoadvance

Leetcode 164. Maximum Gap

Problem Statement

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Return 0 if the array contains less than 2 elements.

Clarifying Questions

Before we dive into the problem-solving approach, let me ask a few clarifying questions:

  1. Are there any constraints on the size of the array?
  2. Can the array contain negative numbers and zeros?
  3. Should the algorithm aim for a specific time complexity?

Strategy

Observations:

Approach:

  1. If the array has less than 2 elements, return 0.
  2. Calculate the minimum and maximum values in the array.
  3. Determine the bucket size based on the formula: [ \text{bucket size} = \max\left(1, \frac{\text{max} - \text{min}}{n - 1}\right) ]
  4. Create buckets and distribute the elements in these buckets. Each bucket will store the minimum and maximum value found in that bucket.
  5. Iterate through the buckets to find the maximum gap. The gap can only exist between the maximum of one bucket and the minimum of the next non-empty bucket.

Time Complexity:

Code

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>

class Solution {
public:
    int maximumGap(std::vector<int>& nums) {
        int n = nums.size();
        if (n < 2) return 0;
        
        int minVal = *min_element(nums.begin(), nums.end());
        int maxVal = *max_element(nums.begin(), nums.end());
        
        // Edge case: all elements are the same
        if (minVal == maxVal) return 0;
        
        // Calculate the size of the bucket
        int bucketSize = std::max(1, (maxVal - minVal) / (n - 1));
        int bucketCount = (maxVal - minVal) / bucketSize + 1;
        
        std::vector<int> bucketMin(bucketCount, INT_MAX);
        std::vector<int> bucketMax(bucketCount, INT_MIN);
        
        // Place each number in its corresponding bucket
        for (int num : nums) {
            int bucketIndex = (num - minVal) / bucketSize;
            bucketMin[bucketIndex] = std::min(bucketMin[bucketIndex], num);
            bucketMax[bucketIndex] = std::max(bucketMax[bucketIndex], num);
        }
        
        // Calculate the maximum gap
        int maxGap = 0, prevMax = minVal;
        for (int i = 0; i < bucketCount; ++i) {
            if (bucketMin[i] == INT_MAX) continue;  // skip empty buckets
            maxGap = std::max(maxGap, bucketMin[i] - prevMax);
            prevMax = bucketMax[i];
        }
        
        return maxGap;
    }
};

int main() {
    Solution sol;
    std::vector<int> nums = {3, 6, 9, 1};
    std::cout << sol.maximumGap(nums) << std::endl;  // Output should be 3
    return 0;
}

Explanation:

  1. Edge Case: Return 0 if the array has less than 2 elements.
  2. Calculate Min and Max Values: Determine the minimum and maximum values from the array.
  3. Bucket Initialization: Calculate bucket size and initialize each bucket’s min and max values.
  4. Distribute Values into Buckets: Each element in the array is placed into the appropriate bucket.
  5. Find Maximum Gap: Iterate over the buckets and compute the maximum gap by looking at the differences between consecutive buckets.

Time Complexity Analysis:

Hence, the overall time complexity is (O(n)).

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI