We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Sorting
  4. Closest Numbers
  5. Discussions

Closest Numbers

Problem
Submissions
Leaderboard
Discussions
Editorial
Topics

    You are viewing a single comment's thread. Return to all comments →

  • Coder_AMiT
    5 years ago+ 15 comments

    sort and then check the diff of two adjecent numbers.. keep tracking the min value, update the both pairs in a list, if the new pair is having less than last min value, then delete the list, update with new pairs,, if the new pair is having exact value, add them in list too.

    n =  input()
    nums = list(map(int,input().strip().split()))
    nums.sort()
    lowestDiff = nums[1]-nums[0]
    res = [nums[0],nums[1]]
    for i in range(1,len(nums)-1):            
        if nums[i+1]-nums[i] < lowestDiff:
            res = []   
            res.append(nums[i])
            res.append(nums[i+1])
            lowestDiff = abs(nums[i+1]-nums[i])
        elif nums[i+1]-nums[i] == lowestDiff:
            res.append(nums[i])
            res.append(nums[i+1])
    
    print(*res)
    
    41|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature