Wednesday, September 27, 2023

How to find the largest and smallest number in given Array in Java? Example Tutorial

Hello guys, 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. This coding problem is in the same league of other frequently asked algorithmic questions like Fibonacci, Palindrome, Prime, and Power of two checks. They are easy but you will find them difficult during the interview because of the pressure, particularly if you have not solved them before. Sometimes even if you have solved the problem one time, you tend to do mistakes because you haven't understood them properly. So, always take your time to understand the question.

Many interviewers further evaluate a candidate's problem-solving skill by asking him to solve the problem in different ways as if he solves the problem using a loop then asking him to do it without the loop. If you know the Recursion you can do it, but if you have just mugged the answer, you won't be able to do it and that's where this technique helps you.

Similarly, if someone solves the power of two using arithmetic logic easily, Interviewer can ask him to solve the problem without using an arithmetic operator, if you know about the bitwise operator, you can solve the problem.

I always ask related questions to gauge the true knowledge of the candidate, if he is a good programmer then he knows about those related concepts, but if he has just practiced one or two questions without really understanding them, he will struggle. So, you should not fall apart on that trap and always lead the interviewer to the question you know well.

Btw, if you are not familiar with the array  data structure and essential programming techniques like Iteration and Recursion, it's better to first go through a  good data structure and algorithm course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to learn more about basic data structure and Programming techniques in Java.





Problem - Find the largest and smallest number in given Array

Now, coming back to this question, you need to write a Java program or method which finds the maximum and minimum number in a given array of integers.

For example, if the given array is {1, 2, 3, 4, 5, 6} then your program should print the largest number as 6 and the smallest number as 1.  This problem ensures that candidates know how to implement a loop and iterate over an array, which you expect from a junior programmer or college graduate.

You also need to write some unit tests, that's a decisive factor in selecting a candidate nowadays, so make sure you write good tests and cover all possible scenarios like a positive test, negative test, corner cases, missing arguments, etc.

For example, you can write unit test cases for an empty array, null value, array containing all same numbers, an array containing both positive and negative numbers, and an array containing just one number.

This will not only show your thought process but also proves that you have a professional attitude towards the development and unit testing.

This problem is generally asked, freshers and junior programmers.  Experienced Java Developers are generally asked about how to manage complexity, design, architecture, and performance-related challenges. 

Btw, the data structure is an integral part of all kind of programming job interviews and you should prepare well. You can also take help from courses like Data Structures in Java: An Interview Refresher to cover essential topics in a quick time.

How to find largest and smallest number in given Integer Array in Java



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 variables with zero

Let's assume, you initialize the int min = 0 and array contain all positive numbers like {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 programmers will do the opposite like they initialize the minimum with Integer.MAX_VALUE and maximum with Integer.MIN_VALUE, because they are the largest and smallest possible number in an integer array in Java, their logic will print correct output unless array contains at least one element (non-empty array) 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 the 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 a comparison from the 1st element or 2nd element, the good programmer will start comparison from the 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 Algorithms and Data Structures - Part 1 and 2  on Pluralsight are one of the best course to learn algorithms fundamentals in Java.





Java Program to find the Maximum and Minimum Number in Given Array 

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 initializes 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 the minimum then that value becomes 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 numbers 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 the 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 the 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 Array related coding Interview Questions for practice:
  • How to find all pairs on integer array whose sum is equal to a given number? [solution]
  • Write a program to find the top two numbers from an integer array? [solution]
  • 10 Courses to learn Data Structure and Algorithms in Java (courses)
  • How to remove duplicates from an array in Java? [solution]
  • 7 Free Books to learn Data Structure and Algorithms (books)
  • 30+ Array-based Coding Problems from Interviews (questions)
  • How to check if an array contains a number in Java? [solution]
  • 7 Best Courses to learn Data Structure and Algorithms (courses)
  • How do you remove duplicates from an array in place? [solution]
  • 10 Free Data Structure and Algorithms Courses for Programmers [courses]
  • Write a program to find the missing number in an 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 an 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]
  • 50+ Data Structure and Algorithms Coding Problems from Interviews (questions)
  • 10 Algorithms courses to Crack Coding Interviews [courses]
  • 10 Algorithms Books Every Programmer should read [books]
Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you. As always suggestions, comments, innovative and better answers are most welcome.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the these best free Data Structures courses on Udemy.

And, lastly one question for you? What is your favorite data structure? Array, LinkedList, Hash table, Stack, Queue, Heap, Bloom Filter or anything else?

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

Unknown said...

Why don' use Stream API ?

Post a Comment