Open In App

Find the largest three distinct elements in an array

Last Updated : 16 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array with all distinct elements, find the largest three elements.

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1). 

Examples :

Input: arr[] = {10, 4, 3, 50, 23, 90}
Output: 90, 50, 23

Input: arr[] = { 6, 8, 1, 9, 2, 1, 10, 10}
Output: 10, 10, 9

Approach:

Initialize three variables, `first`, `second`, and `third`, to store the three largest elements. We then iterate through the array and compare each element with the current values of `first`, `second`, and `third`. If an element is greater than `first`, we update `third` to `second`, `second` to `first`, and `first` to the new element. If an element is greater than `second` but not `first`, we update `third` to `second` and `second` to the new element. If an element is greater than `third` but not `second` or `first`, we update `third` to the new element. After iterating through the entire array, `first`, `second`, and `third` will contain the three largest elements, which we can then print as the result.

  • Set first, second, and third to the minimum possible integer value (INT_MIN).
  • Iterate through the Array
    • For each element arr[i]:
      • If arr[i] is greater than first:
        • Update third to second, second to first, and first to arr[i].
      • Otherwise, if arr[i] is greater than second and not equal to first:
        • Update third to second and second to arr[i].
      • Otherwise, if arr[i] is greater than third and not equal to second and first:
        • Update third to arr[i].
  • Print the values of first, second, and third as the three largest elements.

Below is the implementation of the above algorithm.

C++
// C++ program for find the largest 
// three elements in an array
#include <bits/stdc++.h> 
using namespace std;

// Function to print three largest elements 
void print3largest(int arr[], int arr_size) 
{ 
    int first, second, third; 

    // There should be atleast three elements 
    if (arr_size < 3) 
    { 
        cout << " Invalid Input "; 
        return; 
    } 

    third = first = second = INT_MIN; 
    for(int i = 0; i < arr_size; i++) 
    { 
        
        // If current element is
        // greater than first
        if (arr[i] > first)
        { 
            third = second; 
            second = first; 
            first = arr[i]; 
        } 

        // If arr[i] is in between first
        // and second then update second 
        else if (arr[i] > second && arr[i] != first)
        { 
            third = second; 
            second = arr[i]; 
        } 

        else if (arr[i] > third && arr[i] != second && arr[i] != first) 
            third = arr[i]; 
    } 

    cout << "Three largest elements are "
        << first << " " << second << " "
        << third << endl; 
} 

// Driver code
int main() 
{ 
    int arr[] = { 12, 13, 1, 10, 34, 11, 34 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    
    print3largest(arr, n); 
    return 0; 
} 

// This code is contributed by Anjali_Chauhan
C
// C program for find the largest 
// three elements in an array
#include <limits.h> /* For INT_MIN */
#include <stdio.h>

/* Function to print three largest elements */
void print3largest(int arr[], int arr_size)
{
    int i, first, second, third;

    /* There should be atleast three elements */
    if (arr_size < 3) {
        printf(" Invalid Input ");
        return;
    }

    third = first = second = INT_MIN;
    for (i = 0; i < arr_size; i++) {
        /* If current element is greater than first*/
        if (arr[i] > first) {
            third = second;
            second = first;
            first = arr[i];
        }

        /* If arr[i] is in between first and second then update second  */
        else if (arr[i] > second) {
            third = second;
            second = arr[i];
        }

        else if (arr[i] > third)
            third = arr[i];
    }

    printf("Three largest elements are %d %d %d\n", first, second, third);
}

/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 13, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print3largest(arr, n);
    return 0;
}
/*This code is edited by Ayush Singla(@ayusin51)*/
Java
// Java code to find largest three elements
// in an array

class PrintLargest {
    /* Function to print three largest elements */
    static void print3largest(int arr[], int arr_size)
    {
        int i, first, second, third;

        /* There should be atleast three elements */
        if (arr_size < 3) {
            System.out.print(" Invalid Input ");
            return;
        }

        third = first = second = Integer.MIN_VALUE;
        for (i = 0; i < arr_size; i++) {
            /* If current element is greater than
            first*/
            if (arr[i] > first) {
                third = second;
                second = first;
                first = arr[i];
            }

            /* If arr[i] is in between first and
            second then update second  */
            else if (arr[i] > second) {
                third = second;
                second = arr[i];
            }

            else if (arr[i] > third)
                third = arr[i];
        }

        System.out.println("Three largest elements are " + first + " " + second + " " + third);
    }

    /* Driver program to test above function*/
    public static void main(String[] args)
    {
        int arr[] = { 12, 13, 1, 10, 34, 1 };
        int n = arr.length;
        print3largest(arr, n);
    }
}
/*This code is contributed by Prakriti Gupta 
and edited by Ayush Singla(@ayusin51)*/
Python
def print3largest(arr):
    arr_size = len(arr)
    
    # There should be atleast three elements
    if arr_size < 3:
        print("Invalid Input")
        return
    
    third = first = second = float('-inf')
    
    for i in range(arr_size):
        # If current element is greater than first
        if arr[i] > first:
            third = second
            second = first
            first = arr[i]
        
        # If arr[i] is in between first and second then update second
        elif arr[i] > second and arr[i] != first:
            third = second
            second = arr[i]
        
        elif arr[i] > third and arr[i] != second and arr[i] != first:
            third = arr[i]

    print("Three largest elements are", first, second, third)

# Driver code
arr = [12, 13, 1, 10, 34, 11, 34]
print3largest(arr)
C#
// C# code to find largest
// three elements in an array
using System;

class PrintLargest {

    // Function to print three
    // largest elements
    static void print3largest(int[] arr,
                              int arr_size)
    {
        int i, first, second, third;

        // There should be atleast three elements
        if (arr_size < 3) {
            Console.WriteLine("Invalid Input");
            return;
        }

        third = first = second = 000;
        for (i = 0; i < arr_size; i++) {
            // If current element is
            // greater than first
            if (arr[i] > first) {
                third = second;
                second = first;
                first = arr[i];
            }

            // If arr[i] is in between first
            // and second then update second
            else if (arr[i] > second && arr[i] != first) {
                third = second;
                second = arr[i];
            }

            else if (arr[i] > third && arr[i]!=second)
                third = arr[i];
        }

        Console.WriteLine("Three largest elements are " + first + " " + second + " " + third);
    }

    // Driver code
    public static void Main()
    {
        int[] arr = new int[] { 12, 13, 1, 10, 34, 1 };
        int n = arr.Length;
        print3largest(arr, n);
    }
}

// This code is contributed by KRV and edited by Ayush Singla(@ayusin51).
Javascript
<script>

// Javascript program for find the largest 
// three elements in an array

// Function to print three largest elements 
function print3largest(arr, arr_size) 
{ 
    let first, second, third; 

    // There should be atleast three elements 
    if (arr_size < 3) 
    { 
        document.write(" Invalid Input "); 
        return; 
    } 

    third = first = second = Number.MIN_VALUE; 
    for(let i = 0; i < arr_size; i++) 
    { 
        
        // If current element is
        // greater than first
        if (arr[i] > first)
        { 
            third = second; 
            second = first; 
            first = arr[i]; 
        } 

        // If arr[i] is in between first
        // and second then update second 
        else if (arr[i] > second)
        { 
            third = second; 
            second = arr[i]; 
        } 

        else if (arr[i] > third) 
            third = arr[i]; 
    } 

    document.write("Three largest elements are "
        + first + " " + second + " "
        + third + "<br>"); 
} 

// Driver code
    let arr = [ 12, 13, 1, 10, 34, 1 ]; 
    let n = arr.length; 
    
    print3largest(arr, n); 
    
// This is code is contributed by Mayank Tyagi

</script>
PHP
<?php
// PHP code to find largest 
// three elements in an array

// Function to print 
// three largest elements
function print3largest($arr, $arr_size)
{
    $i; $first; $second; $third;

    // There should be atleast
    // three elements 
    if ($arr_size < 3)
    {
        echo " Invalid Input ";
        return;
    }

    $third = $first = $second = PHP_INT_MIN;
    for ($i = 0; $i < $arr_size ; $i ++)
    {
        // If current element is
        // greater than first
        if ($arr[$i] > $first)
        {
            $third = $second;
            $second = $first;
            $first = $arr[$i];
        }

        // If arr[i] is in between first 
        // and second then update second 
        else if ($arr[$i] > $second)
        {
            $third = $second;
            $second = $arr[$i];
        }

        else if ($arr[$i] > $third)
            $third = $arr[$i];
    }

    echo "Three largest elements are ", 
       $first, " ", $second, " ", $third;
}


// Driver Code
$arr = array(12, 13, 1, 
             10, 34, 1);
$n = count($arr);
print3largest($arr, $n);

// This code is contributed by anuj_67 and edited by Ayush Singla(@ayusin51).
?>

Output
Three largest elements are 34 13 12

Time Complexity: O(n)
Auxiliary Space: O(1)




Previous Article
Next Article

Similar Reads

Find three closest elements from given three sorted arrays
Given three sorted arrays A[], B[] and C[], find 3 elements i, j and k from A, B and C respectively such that max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])) is minimized. Here abs() indicates absolute value. Example : Input : A[] = {1, 4, 10} B[] = {2, 15, 20} C[] = {10, 12} Output: 10 15 10Explanation: 10 from A, 15 from B and 10 from C
15+ min read
Find the lexicographically largest array containing all distinct elements from each prefix of the given array
Given an array arr[] of length N. The task is to find a lexicographically largest array res[] of the same length such that each prefix of res[] includes all distinct elements present in the corresponding prefix of array arr[]. Examples: Input: N = 6, arr[] = {2, 5, 3, 2, 6, 5}Output: res[] = {2, 5, 3, 6, 6, 6}Explanation: This can be verified that
7 min read
Find three element from given three arrays such that their sum is X | Set 2
Given three sorted integer arrays A[], B[] and C[], the task is to find three integers, one from each array such that they sum up to a given target value X. Print Yes or No depending on whether such triplet exists or not.Examples: Input: A[] = {2}, B[] = {1, 6, 7}, C[] = {4, 5}, X = 12 Output: Yes A[0] + B[1] + C[0] = 2 + 6 + 4 = 12Input: A[] = {2}
9 min read
Find three element from different three arrays such that a + b + c = sum
Given three integer arrays and a "sum", the task is to check if there are three elements a, b, c such that a + b + c = sum and a, b and c belong to three different arrays. Examples : Input : a1[] = { 1 , 2 , 3 , 4 , 5 }; a2[] = { 2 , 3 , 6 , 1 , 2 }; a3[] = { 3 , 2 , 4 , 5 , 6 }; sum = 9 Output : Yes 1 + 2 + 6 = 9 here 1 from a1[] and 2 from a2[] a
15+ min read
Find all distinct three digit numbers from given array of digits
Given an array containing digits[], where each element is a single digit integer. The array may contain duplicates. The task is to find all the unique integers that follow the given requirements: The integer consists of the concatenation of three elements from digits in any arbitrary order.The integer does not have leading zeros. Examples: Input: d
6 min read
Php Program for Third largest element in an array of distinct elements
Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example :   Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 14 Input: arr[] = {19, -10, 20, 14, 2, 16, 10} Outp
5 min read
C++ Program for Third largest element in an array of distinct elements
Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example :   Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 14 Input: arr[] = {19, -10, 20, 14, 2, 16, 10} Outp
5 min read
Java Program for Third largest element in an array of distinct elements
Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example :   Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 14 Input: arr[] = {19, -10, 20, 14, 2, 16, 10} Outp
5 min read
Python Program for Third largest element in an array of distinct elements
Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example: Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 14 Input: arr[] = {19, -10, 20, 14, 2, 16, 10} Output:
6 min read
Javascript Program for Third largest element in an array of distinct elements
Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example : Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 14 Input: arr[] = {19, -10, 20, 14, 2, 16, 10} Output
6 min read
Practice Tags :