Make Selenium Easy

Java Program To Find Closest Value Of A Given Number in Unsorted Array

I have explicitly added the term “Unsorted” array but the interviewer may not say this piece of information and expect from you to ask this as a cross-question. Asking cross-questions and getting clarity on expectation or requirement is an evaluation criterion in many companies. But keep in mind – Ask valid questions. Asking more and less both are not good.

Let’s think what we understand from the above question and what needs to be asked

  1. The question says “Closest Value Of A Given Number in Unsorted Array“, it means array is an integer array and it is unsorted.
  2. Many may understand here that we need to look for a number which is lesser than the target number which is not expected. A closet number to target can be target number itself or smaller than the target or greater than the target.
  3. You need to write logic that will work for both sorted and unsorted. Do not just confuse with term unsorted here.
  4. Ask if an array contains negative numbers. I will show how this matters.
  5. You can ask for the duplicate elements in the array as well.
  6. There may be a tie. For example:- Numbers 2 & 4 both are equally closer to number 3. You can ask here which is expected. First or last. In the below examples, I have taken the first number as output.

Let’s see how negative numbers in array matters.

How many whole numbers are between 5 and 10? It is 5 numbers including 5.

How many whole numbers are between – 5 and 5? It is 10 numbers including -5.

How we can calculate it?

By taking the difference of target and number i.e. target – number or number – target. Negative or positive difference will indicate the direction to move ( left or right). For this program, we are not worrying about nature of difference so we will use absolute value. We can use Maths.abs() here.

10-5 = 5

5 – ( -5) = 10

So we need to calculate the actual distance from the target element properly. For example – If we have a target element as 10 then the actual distance of -5 to 10 is 10 while the actual distance of 5 to 10 is 5. It means 5 is closer to 10 than -5.

Logic to solve the above problem:-

You should have got some idea of logic from the above concept of “distance“. If we can get the absolute distance of all elements of the array to the target element and pick the smallest (or closest) one then we have output.

Covering edge cases

Covering edge cases is an important step and it is also a part of evaluating coding tests. Let’s think of edge cases for this problem. Only edge case I can think of if an array is empty.

Logic step by step

  1. Put a check on the length of the array. If it is zero, terminate the execution or whatever interviewer is expecting to do. We will terminate the program in this case.
  2. Let’s assume the 0th indexed element is the closest to the target element. Get the absolute distance of the 0th element to target. If the absolute distance is zero that means you got the target number itself and there is no need to check for other elements in the array. If the absolute distance is not zero, start iterating array.
  3. Start iterating array from the first index ( Not from 0th as I preassume in step 2 above). Take the absolute distance of the first indexed element to the target number. If the absolute distance is zero that means you got the target number itself and there is no need to check for other elements in the array. If the absolute distance is not zero then check if this value of the absolute distance is smaller than the 0th indexed number’s absolute distance. If it is smaller it means you got another more closest number and update assumed indexed i.e. 0th to 1st and old value of absolute distance to the new value. If it is not smaller then proceed for the next number in the array.
  4. Repeat about the process for all numbers of the array.

Why we are using Math.abs()?

Suppose we have a target element as 10 and there are two numbers -9 and 5 in array in sequence. Let’s calculate the distance with signs.

-9 – 10 = -19 & 5 – 10 = -5

When we perform step 2 above and compare both distances as -5 < -19 then we will get false and we will not update the assumed index to 1 from 0. This is not correct behavior. Obviously 5 is closer to 10 than -9. But due to negative difference out logic failed. This is the reason we need to find absolute difference i.e. |-5| < |-19|.

Java Program

Output

You can clone the GIT repo from here.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Many other topics you can navigate through the menu.

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.

Java Program To Find Closest Value Of A Given Number in Unsorted Array

by Amod Mahajan time to read: 5 min
0
%d bloggers like this: