How to find largest and smallest number from integer array in Java

Today I am going to discuss one of the frequently asked programming interview questions to find the largest and smallest number from an integer array. This question is commonly asked on telephonic interviews and the first round for screening candidates. It's one the same league of other frequently asked coding question e.g. Fibonacci, Palindrome, Prime, and Power of two checks. They are easy but can feel difficult during the interview because of pressure. You can further evaluate candidate's problem-solving skill by asking him to solve the problem by a different way e.g. if he solves the problem using a loop then ask him to do it without the loop. If he knows recursion he can do it, but if he has just mugged the answer, he won't be able to do it.

Similarly, if someone finds the power of two using arithmetic logic, you can ask him to solve the problem without using an arithmetic operator, if he knows about the bitwise operator, he can solve the problem. I always ask related questions to gauge the true knowledge of the candidate, if he is genuine then he knows about those related concepts, but if he has just practiced one or two questions without really understanding them, he will fall apart.

Now, coming back to this question, you need to write a function or method which finds the maximum and minimum number in a given array of integers. For example, if given array is {1, 2, 3, 4, 5, 6} then your program should print the largest number as 6 and smallest number as 1.  You can even ask the candidate to write some unit tests and see which kind of tests he comes up.


If he is good at unit testing, he will surely write a couple of test cases for an empty array, null value, array containing all same numbers, an array containing both positive and negative number and an array containing just one number. This will really give you a good idea about the thought process and his professional attitude towards development and unit testing.

Btw, this problem is only for freshers and junior programmers. There is no point asking such questions to experienced Java developers. Instead, you should ask them about how they manage complexity, design, architecture and performance related challenges. This problem just ensures that candidates know how to implement a loop and iterate over an array, which you expect from a junior programmer or college graduate.

Solution - Logic and Errors

Now coming back to the solution, how would you solve this problem? You have an array and in order to find the maximum and minimum number, you must check all the numbers, so you need to iterate through the array. We can use a variable to keep the largest number encountered in the array and once we finish iteration, that would be the largest number in the array. Similarly, for finding out the smallest number, just store the smallest number found in the array during iteration, once you complete the loop, print the value of that variable, that would be the smallest number of the array.


One thing which is a little bit of tricky here is the initial value of the variable we are using to hold the largest and smallest number. Many programmers make mistake here by initializing these variable with zero. Let's assume, you initialize the int min = 0 and array contain all positive numbers e.g. {2, 3, 4}, now what your program will print? Your program will print zero which is not available in the array.

Similarly, many programmers initialize the max value with Integer.MAX_VALUE and min value to Integer.MIN_VALUE, this is no different then initializing with zero. If your programmer will contain all positive number then the smallest value printed by your program will be wrong. Similarly, if your program contains all negative numbers then the largest value calculated by the program will be wrong.

Some programmer will do opposite i.e. they initialize the minimum with Integer.MAX_VALUE and maximum with Integer.MIN_VALUE, because they are largest and smallest possible number in an integer array in Java, their logic will print correct output unless array contains at least one element because everything will be smaller than Integer.MIN_VALUE so minimum will always be of the value coming in the array. But, this logic fails when you pass an empty array. At the point of time, your program will print the largest value as Integer.MIN_VALUE  and smallest value as Integer.MAX_VALUE which doesn't exists in the array. Ideally, it should throw IllegalArgumentException or print an error message that array is empty as shown in below code:

How to find largest and smallest number from integer array in Java


The right way to initialize those largest and smallest variables is by using the first element of the array itself, this way, you will not only save one comparison but your output will always be correct. Though watch out, if programmer checks the length of the array before initializing these variables because, for an empty array, the logic will throw ArrayIndexOutOfBoundException.

You can also verify whether the programmer is starting comparison from the 1st element or 2nd element, the good programmer will start comparison from 2nd element because first is already been checked as part of the assignment.

I have yet to find a good book which highlights and explains common error made by programmers on these kinds of questions, but Data Structures and Algorithms Made Easy in Java by Narasimha Karumanchi is one of the best books to learn coding fundamentals in Java.



Java Program to find the largest and smallest number in Java

Here is the Java program to solve this problem. This program has two static utility methods to calculate the largest and smallest values from the given integer array. It first checks if the array is not empty and not null, after that it initialize the min and max variable with the first number in the array. It then loops over the array to compare minimum or maximum value with other numbers. If any element of the array is smaller than minimum then that value become the new minimum. At the end of the iteration, the value is the largest or smallest in the array.

import java.util.Arrays;

/**
* Java program to find the maximum and minimum number in Array. It's good
* programming exercise for beginners because you can't use API methods.
*
* @author Javin
*/

public class Pattern {

  public static void main(String args[]) {

    // normal case testing
    int[] primes = { 31, 37, 41, 43, 47, 59 };
    System.out.printf("Array: %s, Maximum: %d, Minimum: %d %n",
        Arrays.toString(primes), max(primes), min(primes));
    int[] even = { 2, 4, 14, 16, 18, 20 };
    System.out.printf("Array: %s, Maximum: %d, Minimum: %d %n",
        Arrays.toString(even), max(even), min(even));
    int[] odd = { 1, 3, 11, 15, 18, 21 };
    System.out.printf("Array: %s, Maximum: %d, Minimum: %d %n",
        Arrays.toString(odd), max(odd), min(odd));

    // testing for empty array
    try {
      int[] empty = {};
      System.out.printf("Array: %s, Largest: %d, Smallest: %d %n",
          Arrays.toString(empty), max(empty), min(empty));
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

    // testing for array with negative numbers
    int[] negative = { 1, -1, 2, -3 };
    System.out.printf("Array: %s, Maximum: %d, Minimum: %d %n",
        Arrays.toString(negative), max(negative), min(negative));

    // testing for a single element array
    int[] single = { 1 };
    System.out.printf("Array: %s, Largest: %d, Smallest: %d %n",
        Arrays.toString(single), max(single), min(single));

    // testing for a null array
    try {
      int[] nullInput = null;
      System.out.printf("Array: %s, Maximum: %d, Minimum: %d %n",
          Arrays.toString(nullInput), max(nullInput), min(nullInput));
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

  }

  /**
   * Method to find maximum number of Array in Java
   *
   * @param numbers
   * @return maximum number from given array
   */
  public static int max(int[] numbers) {
    if (numbers == null || numbers.length == 0) {
      throw new IllegalArgumentException("Invalid input: "
          + Arrays.toString(numbers));
    }
    int max = numbers[0];
    for (int i = 1; i < numbers.length; i++) {
      if (numbers[i] > max) {
        max = numbers[i];
      }
    }
    return max;
  }

  /**
   * Method to calculate minimum of an Array in Java
   *
   * @param numbers
   * @return minimum number from array
   */
  public static int min(int[] numbers) {
    if (numbers == null || numbers.length == 0) {
      throw new IllegalArgumentException("Invalid input: "
          + Arrays.toString(numbers));
    }
    int min = numbers[0];
    for (int i = 1; i < numbers.length; i++) {
      if (numbers[i] < min) {
        min = numbers[i];
      }
    }
    return min;
  }
}

Output
Array: [31, 37, 41, 43, 47, 59], Maximum: 59, Minimum: 31 
Array: [2, 4, 14, 16, 18, 20], Maximum: 20, Minimum: 2 
Array: [1, 3, 11, 15, 18, 21], Maximum: 21, Minimum: 1 
Invalid input: []
Array: [1, -1, 2, -3], Maximum: 2, Minimum: -3 
Array: [1], Largest: 1, Smallest: 1 
Invalid input: null

You can see that our program is behaving correctly on different scenarios e.g. it prints invalid input when you pass an empty array and null value. It correctly printed maximum and minimum values even if the array contains both positive and negative number and a single element, but there is still some scope of improvement. You can convert those tests into JUnit tests because that's the standard way to write tests in Java world. You can also calculate largest and smallest number in one iteration by merging the code into one method, it's an exercise for you do.

That's all about how to find the largest and smallest numbers of a given integer array in Java. No doubt it is one of the simplest problems you will see on the real interview but the point is that programmers make mistakes even with easiest of problems and these small things separate good programmers with the averages programmers.

Another important point I want to make here is that you should always ask the candidate to write code, or SQL query, or shell scripts etc. You can find a lot more about a candidate by just looking at their code, instead of asking so many questions. The code will tell you about his thought process, coding prowess, error handling, the quest for performance etc. If he knows his stuff and he is mindful of them while writing code then he is a definite hire, even if he can't answer some theoretical question.

Other arrays related coding Interview Questions for practice:
  • How to find all pairs on integer array whose sum is equal to given number? [solution]
  • Write a program to find top two numbers from an integer array? [solution]
  • How to remove duplicates from an array in Java? [solution]
  • How to check if an array contains a number in Java? [solution]
  • How do you remove duplicates from an array in place? [solution]
  • Write a program to find the missing number in integer array of 1 to 100? [solution]
  • How do you reverse an array in place in Java? [solution]
  • How to find the maximum and minimum number in a unsorted array? [solution]
  • How to sort an array in place using QuickSort algorithm? [solution]
  • How do you print all duplicate elements from the array in Java? [solution]

Thanks for reading this article. If you like this question and explanation then please share with your friends and colleagues. If you have any suggestion, feedback or you want to add anything to this article, please drop a comment. You can even share with us any coding/programming interview questions you have seen on interviews and you have yet to find the answer.

Further Reading



2 comments :

SARAL SAXENA said...

Hi Javin ,

Just to simplify tell me your views on the below approach

1,3,2,5

for this finding min,max will take 6 comparisons

but divide them

1,3 ---> will give min 1 and max 3 in one comparison 2,5 ---> will give min 2 and max 5 in one comparison

now we can compare two mins (1,2) --> will give the final min as 1 ( one comparison) likewise two max(3,5) ---> will give the final max as 5( one comparison)

so totally four comparisons

many m@ny said...

Why don' use Stream API ?

Post a Comment