Closest Numbers
Updated
Problem statement
The integer array arr holds n values, all different from each other. Find the minimum absolute difference over all pairs of elements, then collect each pair whose values differ by exactly that amount.
Return these pairs as one flat array. Inside each pair, put the lower number first. Order the pairs by that lower number, from low to high, and put them one after another. A value that belongs to two pairs appears twice in the returned array.
Function
closestNumbers(arr: int[]) → int[]Examples
Example 1
arr = [12, 3, 20, 9, 15]return = [9, 12, 12, 15]From smallest to largest the values are 3, 9, 12, 15, 20. No two of them are closer than 3, so the minimum absolute difference is 3, and two pairs reach it: (9, 12) and (12, 15). The value 12 is in both pairs, so it appears twice in the answer.
Example 2
arr = [-4, 7, 1, -10, 30]return = [-4, 1]From smallest to largest the values are -10, -4, 1, 7, 30. The minimum absolute difference is 5, and only the pair (-4, 1) has it, so the answer holds those two values.
Example 3
arr = [8, -3]return = [-3, 8]There is only one pair. Its lower number -3 goes first, so the answer is [-3, 8].
Constraints
2 <= n == arr.length <= 104-107 <= arr[i] <= 107- All values in
arrare distinct.
More Patreon interview questions
- Three SumOA · Seen Apr 2025
- Make Layer Times OddOA · Seen Oct 2024
- Sum of Subarray RegionsOA · Seen Oct 2024
- Binary Cardinality SortingOA · Seen Apr 2023
- Maximum Books From BundlesOA · Seen Apr 2023
- Professors Teaching Outside Their DepartmentOA · Seen Apr 2023
- Botany QueryOA · Seen Apr 2023
- Math with Lego BlocksOA · Seen Apr 2023
- Sliding-Window API Rate LimiterPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Employee Importance from a DictionaryPHONE SCREEN · Seen Feb 2026
Similar questions at other companies
- Build the Task HierarchyPendo · OA
- Closest NumbersHeadlands Technologies · OAHeadlands Technologies interview questions
- Macaron Order with Set DiscountsShopify · OAShopify interview questions
- Count User Mentions in Chat MessagesRamp · OARamp interview questions
- Catch Fish with Reusable BaitsSusquehanna International Group (SIG) · OASusquehanna International Group (SIG) interview questions
- Competition Winner and Runner-Up (Forward Deployed Engineer)Boston Consulting Group · OABoston Consulting Group interview questions
- Word Frequency Counts in Alphabetical OrderAbridge · OAAbridge interview questions
- Rank Football TeamsCapital One · OACapital One interview questions
- Maximum Apples That Fit in a BoxVirtu Financial · OAVirtu Financial interview questions
- Rank Football TeamsPersona · OAPersona interview questions