
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)
Editorial
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. |
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)