In this post, we will solve the Closest Numbers Jumps HackerRank Solution. This problem (Number Line Jumps) is a part of the HackerRank Problem Solving series.
Sorting is useful as the first step in many different tasks. The most common task is to make finding things easier, but there are other uses as well. In this case, it will make it easier to determine which pair or pairs of elements have the smallest absolute difference between them.
Closest Numbers Hacker Rank Solution
Problem solution in Python programming:
def closestNumbers(arr): arr.sort() res = arr[0:2] min_diff = abs(res[0]-res[1]) for i in range(1,len(arr)-1): if abs(arr[i] - arr[i+1]) < min_diff: res = [arr[i],arr[i+1]] min_diff = abs(arr[i] - arr[i+1]) elif abs(arr[i] - arr[i+1]) == min_diff: res.append(arr[i]) res.append(arr[i+1]) return res
Problem solution in JavaScript programming:
function closestNumbers(arr) { const arrOrd = arr.sort((a,b)=>a-b) let arrPairs = []; let minDif = 200000; for (let pos = 0; pos < arrOrd.length; pos++) { const dif = arrOrd[pos+1] - arrOrd[pos]; if( dif <= minDif){ if( dif < minDif) arrPairs = []; minDif = dif; arrPairs.push( arrOrd[pos], arrOrd[pos+1] ); } } return arrPairs }
Problem solution in C# programming:
public static List<int> closestNumbers(List<int> arr) { arr.Sort(); var pairs=new List<int>(); var minDiff=int.MaxValue; for (var i=1;i<arr.Count;i++) { var d=Math.Abs(arr[i]-arr[i-1]); if (d<=minDiff) { if (d<minDiff) { pairs.Clear(); minDiff=d; } pairs.Add(arr[i-1]); pairs.Add(arr[i]); } } return pairs; } }
Leave a Reply