/164. Maximum Gap

164. Maximum Gap

Medium
Arrays51.6% acceptance

Given an integer array arr, return the maximum difference between any two consecutive elements in the sorted version of arr. If arr contains fewer than two elements, return 0. The algorithm must run in linear time and use linear extra space.

Example 1

Input: [5, 2, 8, 4]

Output: 3

Explanation: Sorted array: [2, 4, 5, 8]. Maximum gap is between 5 and 8: 3.

Example 2

Input: [100]

Output: 0

Explanation: Array has less than two elements.

Example 3

Input: [7, 7, 7, 7]

Output: 0

Explanation: All elements are equal, so maximum gap is 0.

Constraints

  • 1 <= len(arr) <= 105
  • 0 <= arr[i] <= 109
  • Algorithm must run in O(n) time and use O(n) extra space
Python (current runtime)

Case 1

Input: [12, 3, 19, 7]

Expected: 8

Case 2

Input: [1, 1, 1, 1, 1]

Expected: 0

Case 3

Input: [0, 1000000000]

Expected: 1000000000

Case 4

Input: [9, 8, 7, 6, 5]

Expected: 1

Case 5

Input: [15, 22, 1, 8, 30]

Expected: 8