Open In App

Find Largest and smallest number in an Array containing small as well as large numbers

Last Updated : 30 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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);

Output
Smallest: 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>

Output
Smallest: 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)



Next Article
Article Tags :
Practice Tags :

Similar Reads