The Wayback Machine - https://web.archive.org/web/20240826040134/https://www.geeksforgeeks.org/find-second-largest-element-array/
Open In App

Find Second largest element in an array

Last Updated : 20 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Basic
67.48%
3L

Given an array of integers, our task is to write a program that efficiently finds the second-largest element present in the array. 

Examples:

Input: arr[] = {12, 35, 1, 10, 34, 1}
Output: The second largest element is 34.
Explanation: The largest element of the array is 35 and the second largest element is 34

Input: arr[] = {10, 5, 10}
Output: The second largest element is 5.
Explanation: The largest element of the array is 10 and the second largest element is 5

Input: arr[] = {10, 10, 10}
Output: The second largest does not exist.
Explanation: Largest element of the array is 10 there is no second largest element

Recommended Practice

Find Second Largest element using Sorting:

The idea is to sort the array in descending order and then return the second element which is not equal to the largest element from the sorted array.

Below is the implementation of the above idea:

C++
// C++ program to find second largest element in an array

#include <bits/stdc++.h>
using namespace std;

/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
    // sort the array in descending order
    sort(arr, arr + arr_size, greater<int>());
    // start from second element as first
    // element is the largest
    for (int i = 1; i < arr_size; i++) {
        // if the element is not equal to largest element
        if (arr[i] != arr[0]) {
            printf("The second largest element is %d\n",
                   arr[i]);
            return;
        }
    }
    printf("There is no second largest element\n");
}

/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 35, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print2largest(arr, n);
    return 0;
}

// This code is contributed by Aditya Kumar (adityakumar129)
C
// C program to find second largest element in an array
#include <stdio.h>
#include <stdlib.h>

// Compare function for qsort
int cmpfunc(const void* a, const void* b)
{
    return (*(int*)b - *(int*)a);
}

/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
    // sort the array in descending order
    qsort(arr, arr_size, sizeof(int), cmpfunc);
    // start from second element as first
    // element is the largest
    for (int i = 1; i < arr_size; i++) {
        // if the element is not equal
        // to the largest element
        if (arr[i] != arr[0]) {
            printf("The second largest element is %d\n",
                   arr[i]);
            return;
        }
    }
    printf("There is no second largest element\n");
}

/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 35, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print2largest(arr, n);
    return 0;
}

// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java program to find second largest
// element in an array
import java.util.*;
class GFG {

    // Function to print the
    // second largest elements
    static void print2largest(Integer arr[], int arr_size)
    {
        // Sort the array in descending order
        Arrays.sort(arr, Collections.reverseOrder());
        // Start from second element as first
        // element is the largest
        for (int i = 1; i < arr_size; i++) {
            // If the element is not
            // equal to largest element
            if (arr[i] != arr[0]) {
                System.out.printf("The second largest "
                                      + "element is %d\n",
                                  arr[i]);
                return;
            }
        }

        System.out.printf("There is no second "
                          + "largest element\n");
    }

    // Driver code
    public static void main(String[] args)
    {
        Integer arr[] = { 12, 35, 1, 10, 34, 1 };
        int n = arr.length;
        print2largest(arr, n);
    }
}

// This code is contributed by gauravrajput1
Python3
# Python3 program to find second
# largest element in an array

# Function to print the
# second largest elements


def print2largest(arr, arr_size):

    # Sort the array in descending order
    arr.sort(reverse=True)

    # Start from second last element as first
    # element is the largest
    for i in range(1, arr_size):

        # If the element is not
        # equal to largest element
        if (arr[i] != arr[0]):
            print("The second largest element is", arr[i])
            return

    print("There is no second largest element")


# Driver code
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
print2largest(arr, n)

# This code is contributed by divyeshrabadiya07
C#
using System;
using System.Linq;

class Program
{
    // Function to print the second largest element
    static void PrintSecondLargest(int[] arr)
    {
        // Sort the array in descending order
        Array.Sort(arr);
        Array.Reverse(arr);

        int n = arr.Length;
        int largest = arr[0];
        int secondLargest = -1;

        // Find the second largest element
        for (int i = 1; i < n; i++)
        {
            if (arr[i] != largest)
            {
                secondLargest = arr[i];
                break;
            }
        }

        if (secondLargest != -1)
            Console.WriteLine($"The second largest element is {secondLargest}");
        else
            Console.WriteLine("There is no second largest element");
    }

    // Driver code to test the function
    static void Main()
    {
        int[] arr = { 12, 35, 1, 10, 34, 1 };
        PrintSecondLargest(arr);
    }
}

// This code is contributed by shivamgupta0987654321
JavaScript
<script>
 
// Javascript program to find second largest
// element in an array
  
    // Function to print the second largest elements 
    function print2largest(arr, arr_size) {
        let i;
        let largest = second = -2454635434;
  
        // There should be atleast two elements 
        if (arr_size < 2) {
            document.write(" Invalid Input ");
            return;
        }
  
        // finding the largest element 
        for (i = 0;i<arr_size;i++){
            if (arr[i]>largest){
                largest = arr[i];
            }
        }
  
        // Now find the second largest element
        for (i = 0 ;i<arr_size;i++){
            if (arr[i]>second && arr[i]<largest){
                second = arr[i];
            }
        }
 
        if (second == -2454635434){
            
        document.write("There is no second largest element<br>");
        }
        else{
            document.write("The second largest element is " + second);
                return;
            }
        }
    
  
    // Driver program to test above function 
 
    let arr= [ 12, 35, 1, 10, 34, 1 ];
    let n = arr.length;
    print2largest(arr, n);
  
</script>

Output
The second largest element is 34

Time Complexity: O(nlogn), where n is the size of input array.
Auxiliary space: O(1), as no extra space is required.

Find Second Largest element by traversing the array twice (Two Pass):

The approach is to traverse the array twice. In the first traversal, find the maximum element. In the second traversal, find the greatest element excluding the previous greatest.

Below is the implementation of the above idea:

C++
// C++ program to find the second largest element in the array
#include <iostream>
using namespace std;


int secondLargest(int arr[], int n) {
    int largest = 0, secondLargest = -1;

    // finding the largest element in the array
    for (int i = 1; i < n; i++) {
        if (arr[i] > arr[largest])
            largest = i;
    }

    // finding the largest element in the array excluding 
    // the largest element calculated above
    for (int i = 0; i < n; i++) {
        if (arr[i] != arr[largest]) {
            // first change the value of second largest 
            // as soon as the next element is found
            if (secondLargest == -1)
                secondLargest = i;
            else if (arr[i] > arr[secondLargest])
                secondLargest = i;
        }
    }
    return secondLargest;
}


int main() {
    int arr[] = { 12, 35, 1, 10, 34, 1 };
    int n = sizeof(arr)/sizeof(arr[0]);
    int second_Largest = secondLargest(arr, n);
    if (second_Largest == -1)
        cout << "Second largest didn't exit\n";
    else
        cout << "Second largest : " << arr[second_Largest];
}
Java
// Java program to find second largest
// element in an array
import java.io.*;

class GFG {

    // Function to print the second largest elements
    static void print2largest(int arr[], int arr_size)
    {
        int i, second;

        // There should be atleast two elements
        if (arr_size < 2) {
            System.out.printf(" Invalid Input ");
            return;
        }

        int largest = second = Integer.MIN_VALUE;

        // Find the largest element
        for (i = 0; i < arr_size; i++) {
            largest = Math.max(largest, arr[i]);
        }

        // Find the second largest element
        for (i = 0; i < arr_size; i++) {
            if (arr[i] != largest)
                second = Math.max(second, arr[i]);
        }
        if (second == Integer.MIN_VALUE)
            System.out.printf("There is no second "
                              + "largest element\n");
        else
            System.out.printf("The second largest "
                                  + "element is %d\n",
                              second);
    }

    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 12, 35, 1, 10, 34, 1 };
        int n = arr.length;

        print2largest(arr, n);
    }
}
Python3
# Python3 program to find 
# second largest element 
# in an array

# Function to print 
# second largest elements
def print2largest(arr, arr_size):

    # There should be atleast 
    # two elements
    if (arr_size < 2):
        print(" Invalid Input ");
        return;

    largest = second = -2454635434;

    # Find the largest element
    for i in range(0, arr_size):
        largest = max(largest, arr[i]);

    # Find the second largest element
    for i in range(0, arr_size):
        if (arr[i] != largest):
            second = max(second, arr[i]);

    if (second == -2454635434):
        print("There is no second " + 
              "largest element");
    else:
        print("The second largest " + 
              "element is \n", second);

# Driver code
if __name__ == '__main__':
  
    arr = [12, 35, 1, 
           10, 34, 1];
    n = len(arr);
    print2largest(arr, n);

# This code is contributed by shikhasingrajput 
C#
// C# program to find second largest
// element in an array
using System;

class GFG{

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

    // There should be atleast two elements
    if (arr_size < 2)
    {
        Console.Write(" Invalid Input ");
        return;
    }

    int largest = second = int.MinValue;

    // Find the largest element
    for(i = 0; i < arr_size; i++)
    {
        largest = Math.Max(largest, arr[i]);
    }

    // Find the second largest element
    for(i = 0; i < arr_size; i++)
    {
        if (arr[i] != largest)
            second = Math.Max(second, arr[i]);
    }
    
    if (second == int.MinValue)
        Console.Write("There is no second " +
                      "largest element\n");
    else
        Console.Write("The second largest " +
                      "element is {0}\n", second);
}

// Driver code
public static void Main(String[] args)
{
    int []arr = { 12, 35, 1, 10, 34, 1 };
    int n = arr.Length;
    
    print2largest(arr, n);
}
} 

// This code is contributed by Amit Katiyar 
JavaScript
<script>
 
// Javascript program to find second largest
// element in an array
  
    // Function to print the second largest elements 
    function print2largest(arr, arr_size) {
        let i;
        let largest = second = -2454635434;
  
        // There should be atleast two elements 
        if (arr_size < 2) {
            document.write(" Invalid Input ");
            return;
        }
  
        // finding the largest element 
        for (i = 0;i<arr_size;i++){
            if (arr[i]>largest){
                largest = arr[i];
            }
        }
  
        // Now find the second largest element
        for (i = 0 ;i<arr_size;i++){
            if (arr[i]>second && arr[i]<largest){
                second = arr[i];
            }
        }
 
        if (second == -2454635434){
            
        document.write("There is no second largest element<br>");
        }
        else{
            document.write("The second largest element is " + second);
                return;
            }
        }
    
  
    // Driver program to test above function 
 
    let arr= [ 12, 35, 1, 10, 34, 1 ];
    let n = arr.length;
    print2largest(arr, n);
  
</script>

Output
Second largest : 34

Time Complexity: O(n), where n is the size of input array.
Auxiliary space: O(1), as no extra space is required.

Find Second Largest element by traversing the array once (One Pass):

The idea is to keep track of the largest and second largest element while traversing the array. If an element is greater than the largest element, we update the largest as well as the second largest. Else if an element is smaller than largest but greater than second largest, then we update the second largest only.

Below is the complete algorithm for doing this:  

  • Initialize the first as 0(i.e, index of arr[0] element
  • Start traversing the array from array[1],
    • If the current element in array say arr[i] is greater than first. Then update first and second as, second = first and first = arr[i]
    • If the current element is in between first and second, then update second to store the value of current variable as second = arr[i]
  • Return the value stored in second.

Below is the implementation of the above approach:

C++
// C++ program to find the second largest element

#include <iostream>
using namespace std;

// returns the index of second largest
// if second largest didn't exist return -1
int secondLargest(int arr[], int n) {
    int first = 0, second = -1;
    for (int i = 1; i < n; i++) {
        if (arr[i] > arr[first]) {
            second = first;
            first = i;
        }
        else if (arr[i] < arr[first]) {
            if (second == -1 || arr[second] < arr[i])
                second = i;
        }
    }
    return second;
}

int main() {
    int arr[] = { 12, 35, 1, 10, 34, 1 };
    int index = secondLargest(arr, sizeof(arr)/sizeof(arr[0]));
    if (index == -1)
        cout << "Second Largest didn't exist";
    else
        cout << "Second largest : " << arr[index];
}
C
// C program to find second largest
// element in an array

#include <limits.h>
#include <stdio.h>

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

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

    first = second = INT_MIN;
    for (i = 0; i < arr_size; i++) {
        /* If current element is greater than first
           then update both first and second */
        if (arr[i] > first) {
            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)
            second = arr[i];
    }
    if (second == INT_MIN)
        printf("There is no second largest element\n");
    else
        printf("The second largest element is %d", second);
}

/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 35, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print2largest(arr, n);
    return 0;
}
Java
// JAVA Code for Find Second largest
// element in an array
import java.io.*;

class GFG {

    /* Function to print the second largest
    elements */
    public static void print2largest(int arr[],
                                     int arr_size)
    {
        int i, first, second;

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

        first = second = Integer.MIN_VALUE;
        for (i = 0; i < arr_size; i++) {
            /* If current element is greater than 
            first then update both first and second */
            if (arr[i] > first) {
                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)
                second = arr[i];
        }

        if (second == Integer.MIN_VALUE)
            System.out.print("There is no second largest"
                             + " element\n");
        else
            System.out.print("The second largest element"
                             + " is " + second);
    }

    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = { 12, 35, 1, 10, 34, 1 };
        int n = arr.length;
        print2largest(arr, n);
    }
}
// This code is contributed by Arnav Kr. Mandal.
Python3
# Python program to
# find second largest 
# element in an array


# Function to print the
# second largest elements 
def print2largest(arr, arr_size):

    # There should be atleast
        # two elements 
    if (arr_size < 2):
    
        print(" Invalid Input ")
        return
    

    first = second = -2147483648
    for i in range(arr_size):
    
        # If current element is
                # greater than first
        # then update both
                # first and second 
        if (arr[i] > first):
        
            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):
            second = arr[i]
    
    if (second == -2147483648):
        print("There is no second largest element")
    else:
        print("The second largest element is", second)


# Driver program to test
# above function 
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)

print2largest(arr, n)

# This code is contributed
# by Anant Agarwal.
C#
// C# Code for Find Second largest
// element in an array
using System;

class GFG {

    // Function to print the
    // second largest elements
    public static void print2largest(int[] arr,
                                     int arr_size)
    {
        int i, first, second;

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

        first = second = int.MinValue;
        for (i = 0; i < arr_size; i++) {
            // If current element is greater than
            // first then update both first and second
            if (arr[i] > first) {
                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)
                second = arr[i];
        }

        if (second == int.MinValue)
            Console.Write("There is no second largest"
                          + " element\n");
        else
            Console.Write("The second largest element"
                          + " is " + second);
    }

    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 12, 35, 1, 10, 34, 1 };
        int n = arr.Length;
        print2largest(arr, n);
    }
}

// This code is contributed by Parashar.
JavaScript
<script> 
 
// Javascript program to find second largest
// element in an array
  
    // Function to print the second largest elements 
    function print2largest(arr, arr_size) {
        let i;
        let largest = second = -2454635434;
  
        // There should be atleast two elements 
        if (arr_size < 2) {
            document.write(" Invalid Input ");
            return;
        }
  
        // finding the largest element 
        
        for (i = 0 ;i<arr_size;i++){
            if (arr[i]>largest){
                second = largest ;
                largest = arr[i]
            }

            else if (arr[i]!=largest && arr[i]>second ){
                second = arr[i];
            }
        }
 
        if (second == -2454635434){
            
        document.write("There is no second largest element<br>");
        }
        else{
            document.write("The second largest element is " + second);
                return;
            }
        }
    

    // Driver program to test above function 
 
    let arr= [ 12, 35, 1, 10, 34, 1 ];
    let n = arr.length;
    print2largest(arr, n);
    
 // This code is contributed by Shaswat Singh 
 
</script>
PHP
<?php
// PHP program to find second largest 
// element in an array

// Function to print the 
// second largest elements
function print2largest($arr, $arr_size)
{

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

    $first = $second = PHP_INT_MIN;
    for ($i = 0; $i < $arr_size ; $i++)
    {
        
        // If current element is
        // greater than first
        // then update both 
        // first and second 
        if ($arr[$i] > $first)
        {
            $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)
            $second = $arr[$i];
    }
    if ($second == PHP_INT_MIN)
        echo("There is no second largest element\n");
    else
        echo("The second largest element is " . $second . "\n");
}

// Driver Code
$arr = array(12, 35, 1, 10, 34, 1);
$n = sizeof($arr);
print2largest($arr, $n);

// This code is contributed by Ajit.
?>

Output
Second largest : 34

Time Complexity: O(n), where n is the size of input array.
Auxiliary space: O(1), as no extra space is required.

Related Article: Smallest and second smallest element in an array

This article is contributed by Harsh Agarwal.  



Previous Article
Next Article

Similar Reads

Make all array elements equal by repeatedly replacing largest array element with the second smallest element
Given an array arr[] of size N, the task is to count the number of operations required to make all array elements equal by replacing the largest array element with the second-largest array element, which is strictly smaller than the largest array element. Examples: Input: arr[ ] = {1, 1, 2, 2, 3}Output: 4Explanation: A total of 4 operations are req
6 min read
Find Second largest element in an array | Set 2
Given an array arr[] consisting of N integers, the task is to find the second largest element in the given array using N+log2(N) - 2 comparisons. Examples: Input : arr[] = {22, 33, 14, 55, 100, 12}Output : 55 Input : arr[] = {35, 23, 12, 35, 19, 100}Output : 35 Sorting and Two-Traversal Approach: Refer to Find Second largest element in an array for
9 min read
Find just strictly greater element from first array for each element in second array
Given two arrays A[] and B[] containing N elements, the task is to find, for every element in the array B[], the element which is just strictly greater than that element which is present in the array A[]. If no value is present, then print 'null'. Note: The value from the array A[] can only be used once. Examples: Input: A[] = {0, 1, 2, 3, 4}, B[]
10 min read
Find the Second Largest Element in a Linked List
Given a Linked list of integer data. The task is to write a program that efficiently finds the second largest element present in the Linked List. Examples: Input : List = 12 -&gt; 35 -&gt; 1 -&gt; 10 -&gt; 34 -&gt; 1 Output : The second largest element is 34. Input : List = 10 -&gt; 5 -&gt; 10 Output : The second largest element is 5. A Simple Solu
9 min read
Find Array formed by adding each element of given array with largest element in new array to its left
Given an array A of size N, the task is to find the resultant array formed by adding each element of the given array with the largest element in the new array to its left.Examples: Input: arr[] = {5, 1, 6, -3, 2} Output: {5, 6, 12, 9, 14} Element A0: No element if present at its left. Hence the element at 0th index of the resultant array = 5 Elemen
6 min read
Find last element after deleting every second element in array of n integers
Given a circular array of size n containing integers from 1 to n. Find the last element that would remain in the list after erasing every second element starting from the first element. Example: Input: 5 Output: 3 Explanation Element in circular array are: 1 2 3 4 5 Starting from first element i.e, '1' delete every second element like this, 1 0 3 4
7 min read
Find a pair in Array with second largest product
Given an array arr[] of N integers, where N &gt; 2, the task is to find the second largest product pair from the given array. Examples: Input: arr[] = {10, 20, 12, 40, 50}Output: 20 50Explanation:A pair of array elements = [(10, 20), (10, 12), (10, 40), (10, 50), (20, 12), (20, 40), (20, 50), (12, 40), (12, 50), (40, 50)]If do product of each pair
15+ min read
Second Largest element in n-ary tree
Given an N-ary tree, find and return the node with second largest value in the given tree. Return NULL if no node with required value is present.For example, in the given tree Second largest node is 20. A simple solution is to traverse the array twice. In the first traversal find the maximum value node. In the second traversal find the greatest ele
9 min read
Second largest element in BST
Given a Binary Search Tree (BST), find the second largest element. Example: Input: Root of below BST 10 /5 Output: 5 Input: Root of below BST 10 / \ 5 20 \ 30 Output: 20 Source: Microsoft Interview The idea is similar to below post. K’th Largest Element in BST when modification to BST is not allowedThe second largest element is second last element
9 min read
Find the last element after repeatedly removing every second element from either end alternately
Given an array arr[] consisting of N integers, the task is to find the last remaining array element after removing every second element, starting from the first and last alternately. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}Output: 8Explanation: Elements in the list are: 1 2 3 4 5 6 7 8 9 10Starting from first array element, removing
8 min read
Largest element smaller than current element on left for every element in Array
Given an array arr[] of the positive integers of size N, the task is to find the largest element on the left side of each index which is smaller than the element present at that index. Note: If no such element is found then print -1. Examples: Input: arr[] = {2, 5, 10} Output: -1 2 5 Explanation : Index 0: There are no elements before it So Print -
11 min read
Longest subsequence from an array of pairs having first element increasing and second element decreasing.
Given an array of pairs A[][] of size N, the task is to find the longest subsequences where the first element is increasing and the second element is decreasing. Examples: Input: A[]={{1, 2}, {2, 2}, {3, 1}}, N = 3Output: 2Explanation: The longest subsequence satisfying the conditions is of length 2 and consists of {1, 2} and {3, 1}; Input: A[] = {
10 min read
Find Kth largest element from right of every element in the array
Given an array arr[] of size N and an integer K. The task is to find the Kth largest element from the right of every element in the array. If there are not enough elements to the right then print the same element. Examples: Input: N = 6, K = 3, arr[] = {4, 5, 3, 6, 7, 2}Output: 5 3 2 6 7 2Explanation: The elements right to 4 are {5, 3, 6, 7, 2}. So
14 min read
Split array into K subsets to maximize sum of their second largest elements
Given an array arr[] consisting of N integers and an integer K, the task is to split the array into K subsets (N % K = 0) such that the sum of second largest elements of all subsets is maximized. Examples: Input: arr[] = {1, 3, 1, 5, 1, 3}, K = 2Output: 4Explanation: Splitting the array into the subsets {1, 1, 3} and {1, 3, 5} maximizes the sum of
5 min read
Find extra element in the second array
Given two arrays A[] and B[]. The second array B[] contains all the elements of A[] except for 1 extra element. The task is to find that extra element.Examples: Input: A[] = { 1, 2, 3 }, B[] = {1, 2, 3, 4} Output: 4 Element 4 is not present in arrayInput: A[] = {10, 15, 5}, B[] = {10, 100, 15, 5} Output: 100 Naive approach: Run nested loops and fin
10 min read
Array formed from difference of each element from the largest element in the given array
Given an array arr[], the task is to find the array formed from the difference of each element from the largest element in the given array. Example: Input: arr[] = {3, 6, 9, 2,6} Output: {6, 3, 0, 7, 3} Explanation: Largest element of the array = 9 Therefore difference of arr[i] from 9: Element 1: 9 - 3 = 6 Element 2: 9 - 6 = 3 Element 3: 9 - 9 = 0
5 min read
Count of elements in first Array greater than second Array with each element considered only once
Given two sorted array of size N. The task is to find the maximum number of elements in the first array which are strictly greater than the elements of the second array such that an element can be considered only once. Examples: Input: arr1[] = { 20, 30, 50 }, arr2[] = { 25, 40, 60 } Output: 2 Explanation: Maximum 2 elements 30 (30 &gt; 25) and 50
5 min read
Count elements in first Array with absolute difference greater than K with an element in second Array
Given two arrays arr1[] and arr2[] and an integer K, our task is to find the number elements in the first array, for an element x, in arr1[], there exists at least one element y, in arr2[] such that absolute difference of x and y is greater than the integer K. Examples: Input: arr1 = {3, 1, 4}, arr2 = {5, 1, 2}, K = 2 Output: 2 Explanation: Such el
7 min read
Count distinct elements after adding each element of First Array with Second Array
Given two arrays arr1[] and arr2[]. We can generate another array arr3[] by adding each element of the array arr1[] to each element arr2[]. The task is to find the count of distinct element in the array arr3[]. Examples: Input: Arr1[] = {1, 2}, Arr2[] = {3, 4}, MAX = 4 Output: 4 -&gt; 1 5 -&gt; 2 6 -&gt; 1 Explanation: Here the third array will be
15+ min read
Maximize count of pairs (i, j) from two arrays having element from first array not exceeding that from second array
Given two arrays arr1[] and arr2[] of lengths N and M respectively, the task is to find the maximum number of pairs (i, j) such that 2 * arr1[i] ≤ arr2[j] (1 ≤ i ≤ N and 1 ≤ j ≤ M). Note: Any array element can be part of a single pair. Examples: Input: N = 3, arr1[] = {3, 2, 1}, M = 4, arr2[] = {3, 4, 2, 1}Output: 2Explanation:Only two pairs can be
7 min read
Probability of obtaining pairs from two arrays such that element from the first array is smaller than that of the second array
Given two arrays arr1[] and arr2[] consisting of N and M integers respectively, the task is to find the probability of randomly selecting the two numbers from arr1[] and arr2[] respectively, such that the first selected element is strictly less than the second selected element. Examples: Input: arr1[] = {3, 2, 1, 1}, arr2[] = {1, 2, 5, 2}Output: 0.
15+ min read
Number of indices pair such that element pair sum from first Array is greater than second Array
Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] &gt; B[i] + B[j] and i &lt; j.Examples: Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3} Output: 7 Explanation: There are a total of 7 pairs of indices {i, j} in the array following the condition. The
15+ min read
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
Count of subarrays with largest element at least twice the largest of remaining elements
Given an array arr[] consisting of N positive integers, the task is to find the count of subarrays such that the maximum element of the subarray is greater than twice the maximum of all other elements of the array. Examples: Input: arr[] = {1, 6, 10, 9, 7, 3}Output: 4Explanation:Below are the subarrays satisfying the given condition: Consider the s
14 min read
Sum of all second largest divisors after splitting a number into one or more parts
Given an integer N( 2 &lt;= N &lt;= 10^9 ), split the number into one or more parts(possibly none), where each part must be greater than 1. The task is to find the minimum possible sum of the second largest divisor of all the splitting numbers.Examples: Input : N = 27 Output : 3 Explanation : Split the given number into 19, 5, 3. Second largest div
6 min read
Find numbers which are multiples of first array and factors of second array
Given two arrays A[] and B[], the task is to find the integers which are divisible by all the elements of array A[] and divide all the elements of array B[]. Examples: Input: A[] = {1, 2, 2, 4}, B[] = {16, 32, 64} Output: 4 8 16 4, 8 and 16 are the only numbers that are multiples of all the elements of array A[] and divide all the elements of array
7 min read
Largest possible Subset from an Array such that no element is K times any other element in the Subset
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n = m * K). Examples: Input: arr[] = {2, 8, 6, 5, 3},
7 min read
Split array into K-length subsets to minimize sum of second smallest element of each subset
Given an array arr[] of size N and an integer K (N % K = 0), the task is to split array into subarrays of size K such that the sum of 2nd smallest elements of each subarray is the minimum possible. Examples: Input: arr[] = {11, 20, 5, 7, 8, 14, 2, 17, 16, 10}, K = 5Output: 13Explanation: Splitting array into subsets {11, 5, 14, 2, 10} and {20, 7, 8
5 min read
Rearrange an array in order - smallest, largest, 2nd smallest, 2nd largest, ..
Given an array of integers, the task is to print the array in the order - smallest number, the Largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number, and so on..... Examples: Input : arr[] = [5, 8, 1, 4, 2, 9, 3, 7, 6] Output :arr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5} Input : arr[] = [1, 2, 3, 4] Output :arr[] =
7 min read
Find largest element from array without using conditional operator
Given an array of n-elements, we have to find the largest element among them without using any conditional operator like greater than or less than.Examples: Input : arr[] = {5, 7, 2, 9} Output : Largest element = 9 Input : arr[] = {15, 0, 2, 15} Output : Largest element = 15 First Approach (Use of Hashing) : To find the largest element from the arr
8 min read