Sunday, June 23, 2024

How to find smallest number from int array in Java, Python, JavaScript and Golang? [Solved]

This is the second part on this array interview question. In the first part, I have showed you how to find the largest element in array, and in this part, you will learn how to find the smallest number from an integer array. We will solve this problem on Java programming language but you are free to solve in any other programming language like Python or JavaScript. Most interviewer doesn't care much about which programming language you are solving the question, if you can provide working solution. This one is also a popular Java programming exercise which is taught in school and colleges and give in homework to teach programming to kids and engineering graduates. 

Problem : You have given an int array, return the smallest number from it. The array may contain both positive and negative number. For example, if given array is {1, 2, 3} then your program should return 1 and if input is {-1, -2, -3} then your program should return -3

Btw, sorting of array is not allowed. You need to solve this problem in O(n) time without additional space, except couple of variables. 

Solution : You can solve this problem in the same we found the highest number from array. All you need to do is iterate over int array and compare each element with the smallest one, which is initialized with first element in array. 

If current element is lower than smallest than it become the new smallest number. 

At the end of iteration, you have your smallest number from int array. 

Steps:
1) Create an int variable smallest.
2) Assign the first element to smallest.
3) loop over array and compare each element with smallest, if current element is smaller than smallest, swap.
4) End of iteration, you have the answer

How to find the smallest number from Array in Java?

Here is the solution coded in Java :

public class SmallestNumber {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 9, 1, 6, 2};

        int smallest = findSmallest(numbers);
        System.out.println("The smallest number is: " + smallest);
    }

    public static int findSmallest(int[] array) {
        int smallest = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] < smallest) {
                smallest = array[i];
            }
        }
        return smallest;
    }
}
When you run this program it will print the "The smallest number is: 1" because the array you are passing has 6 numbers and 1 is the smallest of all of them. 

How to find the smallest number from Array in Python?

If you need a solution in Python, here is the python code also for your reference, its shorter than Java:
def find_smallest(array):
    smallest = array[0]
    for number in array[1:]:
        if number < smallest:
            smallest = number
    return smallest

numbers = [5, 3, 9, 1, 6, 2]
smallest = find_smallest(numbers)
print("The smallest number is:", smallest)
This program will also print the same output because the input array is same but you can play around with input like you can even check with negative numbers whether this logic is working fine or not. 


How to find the smallest number from Array in JavaScript?

And, if you need solution in JavaScript, here is the code for that:

function findSmallest(array) {
    let smallest = array[0];
    for (let i = 1; i < array.length; i++) {
        if (array[i] < smallest) {
            smallest = array[i];
        }
    }
    return smallest;
}

const numbers = [5, 3, 9, 1, 6, 2];
const smallest = findSmallest(numbers);
console.log("The smallest number is:", smallest);

This program print the smallest number in console. We have used the same input so this program will also print the same output, I mean "The smallest number is: 1"

How to find the smallest number from Array in Golang?

A couple of you also asked me solution of this problem in Golang, so here is how to find smallest number from a given array in Golang:

package main

import "fmt"

func findSmallest(array []int) int {
    smallest := array[0]
    for _, value := range array[1:] {
        if value < smallest {
            smallest = value
        }
    }
    return smallest
}

func main() {
    numbers := []int{5, 3, 9, 1, 6, 2}
    smallest := findSmallest(numbers)
    fmt.Println("The smallest number is:", smallest)
}
The logic is same in all program. You loop over array and compare each number with others and swap when the new number is smaller than old one. 

Also, here is the flow chart to understand the logic better:

How to find smallest number from int array i


That's all about how to find the smallest number in array. This is too trivial to be asked on interviews but you never know. Sometime you may be lucky to get this question. Well, to be frank I did ask this question to many graduates before and not all of them know the answer. They get confused, once they hear that they cannot sort the array.

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]

1 comment :

Anonymous said...

will this program work for negative number including zero?

Post a Comment