Tools
Tools: π Beginner-Friendly Guide 'Minimum Absolute Difference' - Problem 1200 (C++, Python, JavaScript)
2026-01-26
0 views
admin
You're given: ## Your goal: ## Intuition: The Power of Sorting ## Walkthrough: Understanding the Examples ## C++ Solution ## Python Solution ## JavaScript Solution ## Key Takeaways ## Final Thoughts Finding the closest relationship between numbers is a fundamental task in data analysis and pattern recognition. This problem challenges you to efficiently identify pairs of numbers that sit nearest to each other on a number line. If we look at a random pile of numbers, finding the two closest ones requires comparing every single number with every other number. This would take time. However, if we line the numbers up in order (sorting), the closest neighbors must be physically next to each other. By sorting the array first: Example 1: arr = [4, 2, 1, 3] This problem is a classic example of how changing the state of data (sorting) makes an impossible-looking task simple. In real-world systems, this logic is used in Recommendation Engines to find items with the most similar attributes or in Signal Processing to find the closest frequency peaks. Mastering these "sorting-first" patterns is a major milestone in your interview preparation journey. Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well For further actions, you may consider blocking this person and/or reporting abuse COMMAND_BLOCK:
class Solution {
public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { vector<vector<int>> res; sort(arr.begin(), arr.end()); // Initialize with a large value or the first possible difference int minDiff = arr[1] - arr[0]; for (int i = 0; i < arr.size() - 1; i++) { int currDiff = arr[i+1] - arr[i]; if (currDiff < minDiff) { // Found a new smaller gap: reset the list minDiff = currDiff; res.clear(); res.push_back({arr[i], arr[i+1]}); } else if (currDiff == minDiff) { // Matches the current smallest gap: add to list res.push_back({arr[i], arr[i+1]}); } } return res; }
}; Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
class Solution {
public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { vector<vector<int>> res; sort(arr.begin(), arr.end()); // Initialize with a large value or the first possible difference int minDiff = arr[1] - arr[0]; for (int i = 0; i < arr.size() - 1; i++) { int currDiff = arr[i+1] - arr[i]; if (currDiff < minDiff) { // Found a new smaller gap: reset the list minDiff = currDiff; res.clear(); res.push_back({arr[i], arr[i+1]}); } else if (currDiff == minDiff) { // Matches the current smallest gap: add to list res.push_back({arr[i], arr[i+1]}); } } return res; }
}; COMMAND_BLOCK:
class Solution {
public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { vector<vector<int>> res; sort(arr.begin(), arr.end()); // Initialize with a large value or the first possible difference int minDiff = arr[1] - arr[0]; for (int i = 0; i < arr.size() - 1; i++) { int currDiff = arr[i+1] - arr[i]; if (currDiff < minDiff) { // Found a new smaller gap: reset the list minDiff = currDiff; res.clear(); res.push_back({arr[i], arr[i+1]}); } else if (currDiff == minDiff) { // Matches the current smallest gap: add to list res.push_back({arr[i], arr[i+1]}); } } return res; }
}; COMMAND_BLOCK:
class Solution: def minimumAbsDifference(self, arr: list[int]) -> list[list[int]]: arr.sort() res = [] min_diff = float('inf') for i in range(len(arr) - 1): curr_diff = arr[i+1] - arr[i] if curr_diff < min_diff: # Update minimum and start a new results list min_diff = curr_diff res = [[arr[i], arr[i+1]]] elif curr_diff == min_diff: # Add to existing results res.append([arr[i], arr[i+1]]) return res Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
class Solution: def minimumAbsDifference(self, arr: list[int]) -> list[list[int]]: arr.sort() res = [] min_diff = float('inf') for i in range(len(arr) - 1): curr_diff = arr[i+1] - arr[i] if curr_diff < min_diff: # Update minimum and start a new results list min_diff = curr_diff res = [[arr[i], arr[i+1]]] elif curr_diff == min_diff: # Add to existing results res.append([arr[i], arr[i+1]]) return res COMMAND_BLOCK:
class Solution: def minimumAbsDifference(self, arr: list[int]) -> list[list[int]]: arr.sort() res = [] min_diff = float('inf') for i in range(len(arr) - 1): curr_diff = arr[i+1] - arr[i] if curr_diff < min_diff: # Update minimum and start a new results list min_diff = curr_diff res = [[arr[i], arr[i+1]]] elif curr_diff == min_diff: # Add to existing results res.append([arr[i], arr[i+1]]) return res COMMAND_BLOCK:
/** * @param {number[]} arr * @return {number[][]} */
var minimumAbsDifference = function(arr) { // Sort numerically in ascending order arr.sort((a, b) => a - b); let res = []; let minDiff = Infinity; for (let i = 0; i < arr.length - 1; i++) { let currDiff = arr[i+1] - arr[i]; if (currDiff < minDiff) { minDiff = currDiff; res = [[arr[i], arr[i+1]]]; } else if (currDiff === minDiff) { res.push([arr[i], arr[i+1]]); } } return res;
}; Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
/** * @param {number[]} arr * @return {number[][]} */
var minimumAbsDifference = function(arr) { // Sort numerically in ascending order arr.sort((a, b) => a - b); let res = []; let minDiff = Infinity; for (let i = 0; i < arr.length - 1; i++) { let currDiff = arr[i+1] - arr[i]; if (currDiff < minDiff) { minDiff = currDiff; res = [[arr[i], arr[i+1]]]; } else if (currDiff === minDiff) { res.push([arr[i], arr[i+1]]); } } return res;
}; COMMAND_BLOCK:
/** * @param {number[]} arr * @return {number[][]} */
var minimumAbsDifference = function(arr) { // Sort numerically in ascending order arr.sort((a, b) => a - b); let res = []; let minDiff = Infinity; for (let i = 0; i < arr.length - 1; i++) { let currDiff = arr[i+1] - arr[i]; if (currDiff < minDiff) { minDiff = currDiff; res = [[arr[i], arr[i+1]]]; } else if (currDiff === minDiff) { res.push([arr[i], arr[i+1]]); } } return res;
}; - An array of distinct integers named arr. - Find all pairs of elements that have the minimum absolute difference of any two elements in the array.
- Return these pairs in ascending order, where each pair satisfies . - We only need to check the difference between adjacent elements: arr[i] and arr[i+1].
- As we iterate through the sorted list, we track the smallest difference found so far.
- If we find a new, smaller difference, we throw away our old results and start a new list.
- If we find a difference equal to our current minimum, we add that pair to our collection. - Sort the array: [1, 2, 3, 4].
- First gap: (2 - 1) = 1. Current minDiff is 1. Results: [[1, 2]].
- Second gap: (3 - 2) = 1. Matches minDiff. Results: [[1, 2], [2, 3]].
- Third gap: (4 - 3) = 1. Matches minDiff. Results: [[1, 2], [2, 3], [3, 4]].
- Final Output: [[1, 2], [2, 3], [3, 4]]. - Sorting for Proximity: Sorting is the most efficient way to bring "closest" values together, reducing our search space significantly.
- Greedy Refinement: By clearing the result list when a smaller difference is found, we use a greedy approach to ensure only the global minimums are kept.
- Time Complexity: The performance is dominated by the sorting step, resulting in time complexity.
how-totutorialguidedev.toaipythonjavascript