Largest Gap in Python

In this problem, we need to find the largest difference between two consecutive numbers in a sorted list. This is commonly known as finding the "largest gap" in a dataset.

For example, if we have the list [5, 2, 3, 9, 10, 11], after sorting it becomes [2, 3, 5, 9, 10, 11]. The consecutive differences are: 1, 2, 4, 1, 1. The largest gap is 4 (between 5 and 9).

Algorithm Steps

To solve this problem, we follow these steps:

  • Sort the input list in ascending order
  • Calculate the difference between each pair of consecutive elements
  • Return the maximum difference found

Method 1: Using a List to Store Differences

This approach stores all consecutive differences in a list and then finds the maximum ?

def find_largest_gap(nums):
    if len(nums) < 2:
        return 0
    
    sorted_nums = sorted(nums)
    gaps = []
    
    for i in range(len(sorted_nums) - 1):
        gaps.append(sorted_nums[i + 1] - sorted_nums[i])
    
    return max(gaps)

# Test the function
nums = [5, 2, 3, 9, 10, 11]
result = find_largest_gap(nums)
print(f"Input: {nums}")
print(f"Largest gap: {result}")
Input: [5, 2, 3, 9, 10, 11]
Largest gap: 4

Method 2: Direct Maximum Calculation

This optimized approach finds the maximum difference without storing all gaps ?

def find_largest_gap_optimized(nums):
    if len(nums) < 2:
        return 0
    
    sorted_nums = sorted(nums)
    max_gap = 0
    
    for i in range(len(sorted_nums) - 1):
        gap = sorted_nums[i + 1] - sorted_nums[i]
        max_gap = max(max_gap, gap)
    
    return max_gap

# Test with multiple examples
test_cases = [
    [5, 2, 3, 9, 10, 11],
    [1, 3, 6, 10, 15],
    [4, 4, 4, 4],
    [10, 5]
]

for nums in test_cases:
    result = find_largest_gap_optimized(nums)
    sorted_nums = sorted(nums)
    print(f"Original: {nums}")
    print(f"Sorted: {sorted_nums}")
    print(f"Largest gap: {result}")
    print()
Original: [5, 2, 3, 9, 10, 11]
Sorted: [2, 3, 5, 9, 10, 11]
Largest gap: 4

Original: [1, 3, 6, 10, 15]
Sorted: [1, 3, 6, 10, 15]
Largest gap: 5

Original: [4, 4, 4, 4]
Sorted: [4, 4, 4, 4]
Largest gap: 0

Original: [10, 5]
Sorted: [5, 10]
Largest gap: 5

Comparison

Method Space Complexity Time Complexity Best For
List Storage O(n) O(n log n) Debugging, seeing all gaps
Direct Maximum O(1) O(n log n) Memory efficiency

Key Points

  • Always sort the input list first to get consecutive elements
  • Handle edge cases like lists with fewer than 2 elements
  • The time complexity is dominated by the sorting operation O(n log n)
  • Space complexity can be optimized to O(1) by not storing all differences

Conclusion

Finding the largest gap involves sorting the list and calculating consecutive differences. The optimized approach using direct maximum calculation is more memory-efficient while maintaining the same time complexity.

Updated on: 2026-03-25T10:27:35+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements