C++ 0164.cpp
class Solution {
public:
int maximumGap(vector<int>& nums) {
if (nums.size() == 1)
return 0;
// cheating: n log n
sort(nums.begin(), nums.end());
int result = 0;
for (int i = 1; i < nums.size(); i++)
{
auto diff = nums[i] - nums[i - 1];
if (result < diff)
result = diff;
}
return result;
}
};
Difficulty
and has an acceptance rate of about 53% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Bucket Sort
- Radix Sort
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single public method maximumGap. The method receives a mutable reference to a vector of integers and returns the largest difference between any two successive elements after the vector is ordered. The algorithm follows a straightforward three-stage process: a trivial size check, sorting the entire collection, and a linear scan to locate the maximum adjacent gap.
Size Check
The first conditional guards against the degenerate case where the input contains only one element. In such a scenario there are no pairs of distinct elements, so the function returns zero immediately.
if (nums.size() == 1)
return 0;
This early exit prevents the overhead of sorting and scanning when the result is predetermined.
Sorting Phase
The core of the algorithm relies on arranging the numbers in non-decreasing order. The standard library sort function is invoked, which employs an introspective sort combining quicksort, heapsort, and insertion sort. This choice leverages a highly tuned implementation that adapts to the data distribution and size, delivering strong practical performance.
sort(nums.begin(), nums.end());
By sorting in place, the method avoids additional memory allocations, keeping the footprint minimal.
Linear Scan for Maximum Gap
After ordering, the method iterates once over the vector, starting from the second element. For each position it computes the difference with its predecessor, updates a running maximum when a larger gap is encountered, and finally returns that maximum.
int result = 0;
for (int i = 1; i < nums.size(); i++)
{
auto diff = nums[i] - nums[i - 1];
if (result < diff)
result = diff;
}
return result;
The use of auto for the temporary diff variable lets the compiler infer the appropriate type, which can aid in generating efficient machine code. Maintaining a single result variable eliminates the need for auxiliary data structures, ensuring the scan runs with constant extra space.
Edge Cases Handled
The implementation gracefully handles several boundary conditions without explicit checks. When the input vector is empty, the size check does not trigger, but the subsequent loop body never executes because the loop condition i < nums.size() fails immediately. Consequently, result remains zero and the method returns zero, which is a sensible default for an empty collection. Duplicate values are also accommodated; the computed difference becomes zero for equal adjacent elements, and the maximum gap reflects the largest separation among distinct values, if any exist.
Performance Optimizations
The code exhibits a few deliberate choices that contribute to efficient execution. The early return for a single-element vector eliminates unnecessary work for the simplest case. Leveraging the standard sort routine provides a highly optimized sorting path that adapts to the input characteristics, reducing the number of comparisons and swaps compared to a naïve implementation. The subsequent linear scan uses a minimal set of operations: a single subtraction, a comparison, and a conditional assignment per iteration. By keeping all work within the original vector and avoiding extra containers, the method minimizes cache pressure and memory traffic, which is beneficial for large inputs. The straightforward control flow also enables the compiler to apply aggressive inlining and loop unrolling where appropriate.
ELI5 - Simplified Explanation
Imagine you have a big pile of numbered building blocks scattered all over the floor. To solve this puzzle, the first thing the code does is put all those blocks in a straight line, starting from the smallest number and ending with the biggest one. It is just like lining up your toys from shortest to tallest.
Once every block is in its correct spot, the code looks at each pair of neighbors sitting right next to each other. It measures the space between each pair, which is just the difference between the two numbers. It keeps track of the biggest gap it finds while it walks along the line. By the time it reaches the end of the blocks, it knows exactly which gap between two numbers was the largest one, just like finding the widest space in your line of toys.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | C# | Java | Go | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | |||||||||
| Progiez | C++ | Python | Java | |||||||
| github | aylei | Rust | ||||||||
| begeekmyfriend | C | |||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | Python | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| begeekmyfriend | C | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | Python | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality