Tutorialspoint
Problem
Solution
Submissions

Maximum Gap using Bucket Sort

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Write a Java program to find the maximum gap between two adjacent elements in an array after the array is sorted. If the array contains fewer than 2 elements, return 0. You must solve this in linear time and space complexity using the bucket sort technique.

Example 1
  • Input: nums = [3, 6, 9, 1]
  • Output: 3
  • Explanation: When sorted, the array becomes [1, 3, 6, 9]. The gaps between adjacent elements are: (3-1)=2, (6-3)=3, (9-6)=3. The maximum gap is 3.
Example 2
  • Input: nums = [10, 7, 1, 20, 15]
  • Output: 6
  • Explanation: When sorted, the array becomes [1, 7, 10, 15, 20]. The gaps between adjacent elements are: (7-1)=6, (10-7)=3, (15-10)=5, (20-15)=5. The maximum gap is 6.
Constraints
  • 0 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9
  • Time Complexity: O(n)
  • Space Complexity: O(n)
AlgorithmsMicrosoftTCS (Tata Consultancy Services)
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
  • Find the minimum and maximum values in the array
  • Create n-1 buckets, where n is the array length
  • Calculate the bucket size as (max-min)/(n-1)
  • Place each number in its corresponding bucket
  • For each bucket, keep track of the minimum and maximum values
  • The maximum gap will be the maximum of (min value of current bucket - max value of previous non-empty bucket)

Steps to solve by this approach:

 Step 1: Check if the array has fewer than 2 elements, return 0 if true.

 Step 2: Find the minimum and maximum values in the array.
 Step 3: Calculate the bucket size as (max-min)/(n-1) and determine the number of buckets needed.
 Step 4: Create buckets and initialize each with min value as MAX_VALUE and max value as MIN_VALUE.
 Step 5: Place each number in its corresponding bucket and update the min and max values for that bucket.
 Step 6: Iterate through non-empty buckets to find the maximum gap between the min value of current bucket and max value of previous non-empty bucket.
 Step 7: Return the maximum gap found.

Submitted Code :