Find Largest and smallest number in an Array containing small as well as large numbers
Last Updated :
30 May, 2024
Given an array arr[] of N small and/or large numbers, the task is to find the largest and smallest number in this array.
Examples:
Input: N = 4, arr[] = {5677856, 657856745356587687698768, 67564, 45675645356576578564435647647}
Output: Smallest: 67564
Largest: 45675645356576578564435647647
Input: N = 5, arr[] = {56, 64, 765, 323, 4764}
Output: Smallest: 56
Largest: 4764
Input: N = 3, arr[] = {56, 56, 56}
Output: Smallest: 56
Largest: 56
Naive Approach: One easy way to solve this problem is use comparison-based sorting on all numbers, stored as strings. If the compared strings are of different length sort them on the basis of small length first. If the lengths are same, use compare function to find the first biggest non-matching character and deduce whether it belongs to first or second string and sort them whose first non-matching character’s ASCII value is smaller.
Below is the implementation of above approach:
C++
#include <algorithm> // For std::sort
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Comparator function to compare two numbers represented as
// strings
bool compareStrings(const string& a, const string& b)
{
// Compare based on length
if (a.length() != b.length()) {
return a.length() < b.length();
}
// If lengths are equal, compare lexicographically
return a < b;
}
int main()
{
vector<string> arr
= { "5677856", "657856745356587687698768", "67564",
"45675645356576578564435647647" };
// Sort the array using the custom comparator
sort(arr.begin(), arr.end(), compareStrings);
// The smallest number is at the beginning and the
// largest is at the end
string smallest = arr[0];
string largest = arr[arr.size() - 1];
// Print the results
cout << "Smallest: " << smallest << endl;
cout << "Largest: " << largest << endl;
return 0;
}
Java
import java.util.Arrays;
import java.util.Comparator;
public class Main {
// Comparator function to compare two numbers
// represented as strings
static class StringComparator
implements Comparator<String> {
public int compare(String a, String b)
{
// Compare based on length
if (a.length() != b.length()) {
return Integer.compare(a.length(),
b.length());
}
// If lengths are equal, compare
// lexicographically
return a.compareTo(b);
}
}
public static void main(String[] args)
{
String[] arr
= { "5677856", "657856745356587687698768",
"67564", "45675645356576578564435647647" };
// Sort the array using the custom comparator
Arrays.sort(arr, new StringComparator());
// The smallest number is at the beginning and the
// largest is at the end
String smallest = arr[0];
String largest = arr[arr.length - 1];
// Print the results
System.out.println("Smallest: " + smallest);
System.out.println("Largest: " + largest);
}
}
Python
class StringComparator:
@staticmethod
def compare(a, b):
# Compare based on length
if len(a) != len(b):
return len(a) - len(b)
# If lengths are equal, compare lexicographically
return (a > b) - (a < b)
if __name__ == "__main__":
arr = ["5677856", "657856745356587687698768",
"67564", "45675645356576578564435647647"]
# Sort the array using the custom comparator
arr.sort(key=lambda x: StringComparator.compare(x, ""))
# The smallest number is at the beginning and the largest is at the end
smallest = arr[0]
largest = arr[-1]
# Print the results
print("Smallest:", smallest)
print("Largest:", largest)
JavaScript
class StringComparator {
static compare(a, b) {
// Compare based on length
if (a.length !== b.length) {
return a.length - b.length;
}
// If lengths are equal, compare lexicographically
return a.localeCompare(b);
}
}
const arr = ["5677856", "657856745356587687698768", "67564", "45675645356576578564435647647"];
// Sort the array using the custom comparator
arr.sort((a, b) => StringComparator.compare(a, b));
// The smallest number is at the beginning and the largest is at the end
const smallest = arr[0];
const largest = arr[arr.length - 1];
// Print the results
console.log("Smallest:", smallest);
console.log("Largest:", largest);
OutputSmallest: 67564
Largest: 45675645356576578564435647647
This way we will get final vector which has increasingly sorted strings on the basis of its numeral representation. The first string will be smallest and last string will be largest.
Time Complexity: O(N*M*log N)
- O(N*log N) to sort the array
- O(M) to compare two numbers digit by digit when their lengths are equal
Auxiliary Space: O(1)
Efficient Approach: To solve the problem efficiently follow the below idea:
This approach is similar to finding the biggest and smallest number in a numeral vector. The only difference is that there is need to check if the length of string as well since strings with big length will always form a bigger number than one with smaller length.
For Example: “3452” with length 4 will always be greater than “345” with length 3.
Similar is the case for smallest string.
Follow the steps to solve the problem:
- Initialize minLen to maximum possible number and maxLen to minimum number possible. Here minLen and maxLen represents length of smallest number and biggest number found till now.
- Traverse all strings one by one with i.
- Find the length of current string as numLen.
- If minLen > numLen assign minLen to numLen and smallest number as numbers[i]. Similarly If maxLen < numLen assign maxLen to numLen and biggest number as numbers[i].
- If minLen == numLen and maxLen == numLen then compare smallest number and biggest number found till now with the numbers[i]. The number with first greater non-matching character will be bigger and other will be smaller.
- Return the pair of smallest and biggest number as the final answer.
Below is the implementation of the above mentioned approach:
C++14
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find biggest and
// smallest numbers
pair<string, string> findLargestAndSmallest(
vector<string>& numbers)
{
int N = numbers.size();
int maxLen = 0, minLen = INT_MAX;
// To store smallest and largest
// element respectively
pair<string, string> res;
// Traverse each number in array
for (int i = 0; i < N; i++) {
int numLen = numbers[i].length();
// Comparing current smallest
// number with current number
// If current number is smaller
if (minLen > numLen) {
minLen = numLen;
res.first = numbers[i];
}
// If current number is of same length
// Perform digitwise comparison
else if (minLen == numLen)
res.first
= res.first.compare(numbers[i]) < 0
? res.first
: numbers[i];
// Comparing current largest
// number with current number
// If current number is larger
if (maxLen < numLen) {
maxLen = numLen;
res.second = numbers[i];
}
// If current number is of same length
// Perform digitwise comparison
else if (maxLen == numLen)
res.second
= res.second.compare(numbers[i]) > 0
? res.second
: numbers[i];
}
// Returning the result
return res;
}
// Driver code
int main()
{
vector<string> numbers
= { "5677856", "657856745356587687698768", "67564",
"45675645356576578564435647647" };
// Calling the function
pair<string, string> ans
= findLargestAndSmallest(numbers);
cout << "Smallest: " << ans.first;
cout << endl;
cout << "Largest: " << ans.second;
return 0;
}
Java
// Java code for the above approach
import java.io.*;
public class GFG {
static String[] findLargestAndSmallest(String[] numbers)
{
int N = numbers.length;
int maxLen = 0, minLen = Integer.MAX_VALUE;
String[] res = { "", "" };
// To store smallest and largest
// element respectively
// Traverse each number in array
for (int i = 0; i < N; i++) {
int numLen = numbers[i].length();
// Comparing current smallest
// number with current number
// If current number is smaller
if (minLen > numLen) {
minLen = numLen;
res[0] = numbers[i];
}
// If current number is of same length
// Perform digitwise comparison
else if (minLen == numLen)
res[0] = ((res[0].length()
> numbers[i].length())
? res[0]
: numbers[i]);
// Comparing current largest
// number with current number
// If current number is larger
if (maxLen < numLen) {
maxLen = numLen;
res[1] = numbers[i];
}
// If current number is of same length
// Perform digitwise comparison
else if (maxLen == numLen)
res[1]
= (res[1].length() > numbers[i].length()
? res[1]
: numbers[i]);
}
// Returning the result
return res;
}
// driver code
public static void main(String[] args)
{
String[] numbers
= { "5677856", "657856745356587687698768",
"67564", "45675645356576578564435647647" };
// Calling the function
String[] ans = findLargestAndSmallest(numbers);
System.out.println("Smallest: " + ans[0]);
System.out.print("Largest: " + ans[1]);
}
}
// This code is contributed by phasing17
Python
# Python code for the above approach
INT_MAX = 2147483647
# Function to find biggest and
# smallest numbers
def findLargestAndSmallest(numbers):
N = len(numbers)
maxLen,minLen = 0,INT_MAX
# To store smallest and largest
# element respectively
res = ["" for i in range(2)]
# Traverse each number in array
for i in range(N):
numLen = len(numbers[i])
# Comparing current smallest
# number with current number
# If current number is smaller
if (minLen > numLen):
minLen = numLen
res[0] = numbers[i]
# If current number is of same length
# Perform digitwise comparison
elif (minLen == numLen):
res[0] = res[0] if (res[0] < numbers[i]) else numbers[i]
# Comparing current largest
# number with current number
# If current number is larger
if (maxLen < numLen):
maxLen = numLen
res[1] = numbers[i]
# If current number is of same length
# Perform digitwise comparison
elif (maxLen == numLen):
res[1] = res[1] if (res[1] > numbers[i]) else numbers[i]
# Returning the result
return res
# Driver code
numbers = ["5677856", "657856745356587687698768", "67564","45675645356576578564435647647"]
# Calling the function
ans = findLargestAndSmallest(numbers)
print(f"Smallest: {ans[0]}")
print(f"Largest: {ans[1]}")
# This code is contributed by shinjanpatra
C#
// C# code for the above approach
using System;
public class GFG {
static string[] findLargestAndSmallest(string[] numbers)
{
int N = numbers.Length;
int maxLen = 0;
int minLen = Int32.MaxValue;
string[] res = { "", "" };
// To store smallest and largest
// element respectively
// Traverse each number in array
for (int i = 0; i < N; i++) {
int numLen = numbers[i].Length;
// Comparing current smallest
// number with current number
// If current number is smaller
if (minLen > numLen) {
minLen = numLen;
res[0] = numbers[i];
}
// If current number is of same length
// Perform digitwise comparison
else if (minLen == numLen)
res[0]
= ((res[0].Length > numbers[i].Length)
? res[0]
: numbers[i]);
// Comparing current largest
// number with current number
// If current number is larger
if (maxLen < numLen) {
maxLen = numLen;
res[1] = numbers[i];
}
// If current number is of same length
// Perform digitwise comparison
else if (maxLen == numLen)
res[1] = (res[1].Length > numbers[i].Length
? res[1]
: numbers[i]);
}
// Returning the result
return res;
}
// Driver Code
public static void Main(string[] args)
{
String[] numbers
= { "5677856", "657856745356587687698768",
"67564", "45675645356576578564435647647" };
// Calling the function
String[] ans = findLargestAndSmallest(numbers);
Console.WriteLine("Smallest: " + ans[0]);
Console.WriteLine("Largest: " + ans[1]);
}
}
// this code is contributed by phasing17
JavaScript
<script>
// JavaScrip tcode for the above approach
const INT_MAX = 2147483647;
// Function to find biggest and
// smallest numbers
const findLargestAndSmallest = (numbers) => {
let N = numbers.length;
let maxLen = 0, minLen = INT_MAX;
// To store smallest and largest
// element respectively
let res = new Array(2).fill("");
// Traverse each number in array
for (let i = 0; i < N; i++) {
let numLen = numbers[i].length;
// Comparing current smallest
// number with current number
// If current number is smaller
if (minLen > numLen) {
minLen = numLen;
res[0] = numbers[i];
}
// If current number is of same length
// Perform digitwise comparison
else if (minLen == numLen)
res[0]
= res[0] < numbers[i]
? res[0]
: numbers[i];
// Comparing current largest
// number with current number
// If current number is larger
if (maxLen < numLen) {
maxLen = numLen;
res[1] = numbers[i];
}
// If current number is of same length
// Perform digitwise comparison
else if (maxLen == numLen)
res[1]
= res[1] > numbers[i]
? res[1]
: numbers[i];
}
// Returning the result
return res;
}
// Driver code
let numbers = ["5677856", "657856745356587687698768", "67564",
"45675645356576578564435647647"];
// Calling the function
let ans = findLargestAndSmallest(numbers);
document.write(`Smallest: ${ans[0]}<br/>`);
document.write(`Largest: ${ans[1]}`);
// This code is contributed by rakeshsahni
</script>
OutputSmallest: 67564
Largest: 45675645356576578564435647647
Time Complexity: O(N*M), where N is the size of array, and M is the size of largest number.
- O(N) to traverse each number of the array
- O(M) to compare two numbers digit by digit when their lengths are equal
Auxiliary Space: O(1)
Similar Reads
How to get largest and smallest number in an Array?
Given an array arr[] of length N, The task is to find the maximum and the minimum number in the array. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: Maximum is: 5Minimum is: 1Explanation: The maximum of the array is 5 and the minimum of the array is 1. Input: arr[] = {5, 3, 7, 4, 2}Output: Maximum
15 min read
Find the smallest and second smallest elements in an array
Given an array arr[] of size N, find the smallest and second smallest element in an array. Examples: Input: arr[] = {12, 13, 1, 10, 34, 1}Output: 1 10Explanation: The smallest element is 1 and second smallest element is 10. Input: arr[] = {111, 13, 25, 9, 34, 1}Output: 1 9Explanation: The smallest e
13 min read
Sum and product of k smallest and k largest composite numbers in the array
Given an integer k and an array of integers arr, the task is to find the sum and product of k smallest and k largest composite numbers in the array. Assume that there are at least k composite numbers in the array. Examples: Input: arr[] = {2, 5, 6, 8, 10, 11}, k = 2 Output: Sum of k-minimum composit
15+ min read
Sort Array such that smallest is at 0th index and next smallest it at last index and so on
Given an array, arr[] of N integers, the task is to rearrange the array elements such that the smallest element is at the 0th position, the second smallest element is at the (N-1)th position, the third smallest element at 1st position, 4th smallest element is at the (N-2)th position, and so on for a
12 min read
Nearest smaller numbers on left side in an array
Given an array of integers, find the nearest smaller number for every element such that the smaller element is on the left side. Examples: Input: arr = [1, 6, 2]Output: [-1, 1, 1,]Explanation: There is no number at the left of 1. Smaller number than 6 and 2 is 1. Input: arr = [1, 5, 0, 3, 4, 5]Outpu
8 min read
kth smallest/largest in a small range unsorted array
Find kth smallest or largest element in an unsorted array, where k<=size of array. It is given that elements of array are in small range. Examples: Input : arr[] = {3, 2, 9, 5, 7, 11, 13} k = 5 Output: 9 Input : arr[] = {16, 8, 9, 21, 43} k = 3 Output: 16 Input : arr[] = {50, 50, 40} k = 2 Output
5 min read
Smallest K digit number divisible by all numbers in given array
Given an array arr[]. The task is to create the smallest K digit number divisible by all numbers of arr[]. Examples: Input: arr[] = {2, 3, 5}, N = 3Output: 120Explanation: 120 is divisible by 2, 3 and 5 Input: arr[] = {2, 6, 7, 4, 5}, N = 5Output: 10080 Recursive approach: This problem can be solved
7 min read
Find Kth smallest number among multiples of all elements of array
Consider an array arr[] of size N consisting of prime numbers and an integer K. The task is to find the Kth smallest number among the multiples of all elements of the array. Constraints: 1 <= N <= 101 < arr[i] < 301<=K<=1e12 Examples: Input: N = 3, arr[] = {3, 5, 7}, K=5Output: 9Ex
11 min read
Arrange given numbers to form the smallest number
Given an array arr[] of integer elements, the task is to arrange them in such a way that these numbers form the smallest possible number. For example, if the given array is {5, 6, 2, 9, 21, 1} then the arrangement will be 1212569. Examples: Input: arr[] = {5, 6, 2, 9, 21, 1} Output: 1212569 Input: a
14 min read
Smallest number dividing minimum number of elements in the array | Set 2
Given an array arr[] of N integers, the task is to find the smallest number that divides the minimum number of elements from the array. Examples: Input: arr[] = {2, 12, 6} Output: 5 Here, 1 divides 3 elements 2 divides 3 elements 3 divides 2 elements 4 divides 1 element 5 divides no element 6 divide
6 min read