May 2, 2022

Question 10 : Write java Program to Find Smallest and Largest Element in an Array

You are given an integer array containing 1 to n but one of the numbers from 1 to n in the array is missing. You need to provide an optimum solution to find the missing number. 

The number can not be repeated in the array.
For example
:
int[] arr1={7,5,6,1,4,2}; Missing numner : 3 int[] arr2={5,3,1,2}; Missing numner : 4

Problem:

You are given an array of numbers. You need to find smallest and largest numbers in the array.

Solution:

  • Initialize two variables largest and smallest with arr[0]
  • Iterate over array
    • If the current element is greater than the largest, then assign the current element to the largest.
    • If the current element is smaller than the smallest, then assign the current element to the smallest.
  • You will get the smallest and largest element in the end.

Java code to find the Smallest and Largest Element in an Array :

/* Java program to Find Largest and Smallest Number in an Array */ public class FindLargestSmallestNumberMain { public static void main(String[] args) { //array of 10 numbers int arr[] = new int[]{12,56,76,89,100,343,21,234}; //assign first element of an array to largest and smallest int smallest = arr[0]; int largest = arr[0]; for(int i=1; i< arr.length; i++) { if(arr[i] > largest) largest = arr[i]; else if (arr[i] < smallest) smallest = arr[i]; } System.out.println("Smallest Number is : " + smallest); System.out.println("Largest Number is : " + largest); } }

When you run the above program, you will get the below output:
:
Largest Number is : 343 Smallest Number is : 12

Python code 

def find_smallest_largest(arr): smallest = arr[0] largest = arr[0] for num in arr[1:]: if num > largest: largest = num elif num < smallest: smallest = num return smallest, largest arr = [12, 56, 76, 89, 100, 343, 21, 234] s, l = find_smallest_largest(arr) print("Smallest Number is:", s) print("Largest Number is:", l)


Approach Time Complexity Space Complexity Best Use
Single pass linear scan O(n) O(1) ⭐ Best & optimal
Sorting the array O(n log n) O(n) Simple but inefficient
Recursive divide & conquer O(n) O(log n) Not needed here

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS