C++ 1502.cpp
class Solution {
public:
bool canMakeArithmeticProgression(vector<int>& arr) {
// x = a + b*n
sort(arr.begin(), arr.end());
auto diff = arr[1] - arr[0];
for (auto i = 2; i < arr.size(); i++)
if (arr[i] - arr[i-1] != diff)
return false;
return true;
}
};
Difficulty
and has an acceptance rate of about 69% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- 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 determines whether a given integer array can be rearranged to form an arithmetic progression. It follows a straightforward strategy: sort the input, compute the common difference from the first two elements, and verify that every consecutive pair respects this difference. The function returns a Boolean result indicating success or failure.
Key Steps
The algorithm consists of three distinct operations, each reflected in a concise code fragment.
Sorting the input establishes a deterministic order that makes the progression check trivial.
sort(arr.begin(), arr.end());
After sorting, the common difference is derived from the first two elements. The use of auto lets the compiler infer the appropriate signed integer type.
auto diff = arr[1] - arr[0];
A forward scan validates the progression. The loop starts at the third element and compares each adjacent difference to the previously computed diff. An early return aborts the scan as soon as a mismatch is detected.
for (auto i = 2; i < arr.size(); i++)
if (arr[i] - arr[i-1] != diff)
return false;
If the loop completes without triggering the early exit, the function concludes that the array can indeed be arranged as an arithmetic progression.
return true;
Edge Cases Handled
The implementation gracefully accommodates several boundary conditions:
- Already Sorted Input - When the input is pre-sorted, the
sortcall incurs minimal overhead, and the subsequent difference checks operate directly on the original order. - Uniform Elements - If all elements are identical, the computed
diffequals zero, and each subsequent subtraction yields zero, satisfying the progression condition. - Negative Numbers - The subtraction logic works uniformly for negative values, allowing progressions that decrease or cross zero.
- Single-Element or Empty Arrays - Although the function accesses the first two elements, the typical problem definition guarantees at least two numbers. In contexts where the array length is one or zero, the logical definition of an arithmetic progression holds trivially, and the loop body would never execute, leading to a
trueresult.
Performance Optimizations Observed
The code leverages several language and library features that contribute to efficient execution:
- Standard Library Sort -
std::sortimplements introsort, a hybrid algorithm that combines quicksort, heapsort, and insertion sort. This choice provides fast average-case performance while guarding against pathological inputs. - Early Termination - The moment a discrepancy is found, the function returns
false. This prevents unnecessary comparisons in non-progressive arrays, especially when the violation occurs early. - Reference Parameter - The input vector is passed by non-const reference, avoiding a copy of the entire container and allowing the in-place sort to operate directly on the caller’s data.
- Type Inference with
auto- Usingautofor the loop index and the difference variable eliminates explicit type specifications, letting the compiler generate the most efficient native type for the platform.
Collectively, these choices ensure that the routine runs with minimal overhead while maintaining clear and maintainable code.
ELI5 - Simplified Explanation
Imagine you have a big pile of numbered building blocks scattered all over the floor. To solve this puzzle, the first step is to line up all those blocks from the smallest number to the biggest number, just like putting your toys in a neat row. Once they are all in order, think about the space between each block. For a sequence to be special, the distance or the number of empty spots between every single block must be exactly the same. You start by looking at the first two blocks to see how far apart they are. Then, you walk down the line and check every other pair of blocks. If you ever find a pair that is a different distance apart than the first pair, it means the pattern is broken, and it is not the special sequence you are looking for. If you make it all the way to the end and every jump between blocks is the same size, then you found the pattern.
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++ | ||||||||||
| leetcode.ca | C++ | Python | Java | JS | Go | C | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++ | ||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 1630: Arithmetic Subarrays
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
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