Tutorialspoint
Problem
Solution
Submissions

Maximum Gap

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the maximum difference between successive elements in a sorted array. Given an unsorted array of integers, return the maximum gap between any two successive elements after sorting the array. The solution must achieve linear time complexity O(n) and linear space complexity O(n).

Example 1
  • Input: nums = [3, 6, 9, 1]
  • Output: 3
  • Explanation: After sorting, the array becomes [1, 3, 6, 9]. The gaps between successive elements are: 3-1=2, 6-3=3, 9-6=3. The maximum gap is 3.
Example 2
  • Input: nums = [10]
  • Output: 0
  • Explanation: Array has only one element. No successive elements exist to compare. Return 0 as there's no gap.
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • 0 ≤ nums[i] ≤ 10^9
  • Time Complexity: O(n)
  • Space Complexity: O(n)
  • Cannot use comparison-based sorting algorithms
ArraysAlgorithmsKPMGTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use bucket sort approach to achieve linear time complexity
  • Calculate the minimum possible maximum gap using pigeonhole principle
  • Create buckets with appropriate bucket size based on the gap
  • Place elements in buckets and track min/max values in each bucket
  • Calculate gaps between non-empty adjacent buckets

Steps to solve by this approach:

 Step 1: Handle edge case - if array has less than 2 elements, return 0.

 Step 2: Find minimum and maximum values in the array to determine the range.
 Step 3: Calculate bucket size using pigeonhole principle: (max-min)/(n-1) + 1.
 Step 4: Create buckets to store minimum and maximum values for each bucket.
 Step 5: Place each element in appropriate bucket and update bucket's min/max values.
 Step 6: Iterate through buckets and calculate gaps between non-empty adjacent buckets.
 Step 7: Return the maximum gap found between buckets.

Submitted Code :