I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1200. Minimum Absolute Difference, the solution in this repository is mainly a greedy solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: greedy.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The solution is organized around the main LeetCode entry point and a few local helpers.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 120 ms, faster than 60.62% of C++ online submissions for Minimum Absolute Difference.
02//Memory Usage: 17 MB, less than 100.00% of C++ online submissions for Minimum Absolute Difference.
03
04class Solution {
05public:
06 vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
07 sort(arr.begin(), arr.end());
08
09 int dist = INT_MAX;
10 vector<vector<int>> ans;
11
12 for(int i = 0; i < arr.size() - 1; i++){
13 if(arr[i+1] - arr[i] < dist){
14 dist = arr[i+1] - arr[i];
15 ans.clear();
16 ans.push_back({arr[i], arr[i+1]});
17 }else if(arr[i+1] - arr[i] == dist){
18 ans.push_back({arr[i], arr[i+1]});
19 }
20 }
21
22 return ans;
23 }
24};
Cost