Closest Numbers

Sort by

recency

|

107 Discussions

|

  • + 0 comments

    Python 3 solution:

    from itertools import pairwise
    
    
    def closestNumbers(arr: list[int]) -> list[int]:
        pairs = []
        min_diff = float("inf")
        arr.sort()
        for i, j in pairwise(arr):
            if (diff := abs(i - j)) == min_diff:
                pairs += [i, j]
                continue
            if diff < min_diff:
                min_diff = diff
                pairs = [i, j]
        return pairs
    
  • + 0 comments

    using Ruby

      arr.sort!
      min_diff = 10000000
      result = {}
      
      (0..(arr.size - 2)).each do |i|
        diff = (arr[i+1] - arr[i]).abs
        if diff <= min_diff
          min_diff = diff
          result[diff] ||= []
          result[diff] << [arr[i], arr[i+1]]
        end
      end
      result[min_diff]
    
  • + 0 comments

    python 3 simple solution

    def closestNumbers(arr):
            arr.sort()
            _min = min([arr[i+1]-arr[i] for i in range(len(arr)-1)])
            pairs = [(arr[i], arr[i+1]) for i in range(len(arr)-1) if arr[i+1]-arr[i] == _min ]
            return reduce(lambda a, b: a+b, pairs)
    
  • + 0 comments

    My rust solution:

    fn closestNumbers(arr: &[i32]) -> Vec<i32> {
        let mut arr = Vec::from(arr);
        arr.sort();
    
        let mut pairs: Vec<(i32, i32)> = arr
            .windows(2)
            .map(|window| (window[0], window[1]))
            .collect();
    
        pairs.sort_by(|a, b| (a.1 - a.0).cmp(&(b.1 - b.0)));
    
        let closest_pair = pairs[0];
    
        pairs
            .iter()
            .take_while(|pair| pair.1 - pair.0 == closest_pair.1 - closest_pair.0)
            .flat_map(|pair| [pair.0, pair.1])
            .collect()
    }
    
  • + 0 comments

    Solution using dictionary

    def closestNumbers(arr):
        # Write your code 
        arr.sort()
        result = {}
        for index in range(len(arr)):
            if (index +1 < len(arr)):
                current_dif = abs(arr[index] - arr[index + 1])
                if (current_dif in result):
                    result[current_dif].append((arr[index], arr[index + 1]))
                else:
                    result[current_dif] = [(arr[index], arr[index + 1])]
        
        min_key = min(list(result.keys()))
        arr_result = result[min_key]
        final_result = []
        for item in arr_result:
            final_result.extend(item)
        return final_result