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 →

  • narayan_m
    6 years ago+ 2 comments

    one simple algorithm:
    0. get the inputs from console
    1. sort the input array as sortedInput
    2. set lowestDiff to maximum integer value
    3. set resultArray to empty array
    4. for i = 1 to length of sortedInput-1
        4a. delta = absolute value (sortedInput[i] - sortedInput[i-1])
        4b. if delta < lowestDiff, then
            -> lowestDiff = delta
            -> clear resultArray (remove all elements from array)
            -> add to resultArray sortedInpit[i-1], and then sortedInput[i]
    4c. Else, if delta == lowestDiff, then
            -> add to resultArray sortedInpit[i-1], and then sortedInput[i]
    5. print resultArray as space-separated integer on single line.

    16|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature