Find the Second Largest Number in an Array

(Coding Clutch Challenge Series 101) – Coding Challenge #6

Finding the second largest number in an array might sound straightforward, but it’s a great way to practice array traversal, comparison logic, and edge-case handling. Whether you’re a beginner or a seasoned coder, this challenge offers something valuable for everyone.

Let’s break it down step by step and explore multiple solutions with code examples in Python, Java, C, and C++.

Coding Clutch Challenge Series 101 – All Coding Challenges


Understanding the Challenge

The task is simple: identify the second largest number in an array of integers. However, the array may contain a mix of positive and negative numbers, duplicates, or even all identical elements.

Examples:

  1. Input: [10, 20, 5, 40, 30]
    Output: 30
  2. Input: [7, 7, 7, 7]
    Output: No second largest number
  3. Input: [-10, -20, -5, -30, -15]
    Output: -10

Coding Clutch Challenge Series 101 – All Coding Challenges

Approaches to Solve the Problem


1. Naive Approach

The naive approach involves sorting the array in descending order and finding the second unique number.

Python Code Example

def second_largest(arr):
    arr = list(set(arr))  # Remove duplicates
    if len(arr) < 2:
        return "No second largest number"
    arr.sort(reverse=True)
    return arr[1]

print(second_largest([10, 20, 5, 40, 30]))  # Output: 30
print(second_largest([7, 7, 7, 7]))         # Output: No second largest number

Coding Clutch Challenge Series 101 – All Coding Challenges

C Code Example

#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return (*(int*)b - *(int*)a); // Descending order
}

void secondLargest(int arr[], int n) {
    qsort(arr, n, sizeof(int), compare);

    int largest = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] < largest) {
            printf("Second Largest: %d\n", arr[i]);
            return;
        }
    }
    printf("No second largest number\n");
}

int main() {
    int arr[] = {10, 20, 5, 40, 30};
    int n = sizeof(arr) / sizeof(arr[0]);
    secondLargest(arr, n);  // Output: 30
    return 0;
}

Coding Clutch Challenge Series 101 – All Coding Challenges

C++ Code Example

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void secondLargest(vector<int> arr) {
    sort(arr.rbegin(), arr.rend()); // Descending order
    int largest = arr[0];

    for (int i = 1; i < arr.size(); i++) {
        if (arr[i] < largest) {
            cout << "Second Largest: " << arr[i] << endl;
            return;
        }
    }
    cout << "No second largest number" << endl;
}

int main() {
    vector<int> arr = {10, 20, 5, 40, 30};
    secondLargest(arr);  // Output: 30
    return 0;
}

Coding Clutch Challenge Series 101 – All Coding Challenges

Java Code Example

import java.util.*;

public class SecondLargest {
    public static void secondLargest(int[] arr) {
        Arrays.sort(arr);
        int largest = arr[arr.length - 1];

        for (int i = arr.length - 2; i >= 0; i--) {
            if (arr[i] < largest) {
                System.out.println("Second Largest: " + arr[i]);
                return;
            }
        }
        System.out.println("No second largest number");
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 5, 40, 30};
        secondLargest(arr);  // Output: 30
    }
}

Coding Clutch Challenge Series 101 – All Coding Challenges


2. Optimized Approach Using Two Traversals

This approach finds the largest and second-largest numbers in two separate loops.

Python Code Example

def second_largest(arr):
    if len(arr) < 2:
        return "No second largest number"
    largest = max(arr)
    second_largest = float('-inf')
    for num in arr:
        if num != largest and num > second_largest:
            second_largest = num
    return second_largest if second_largest != float('-inf') else "No second largest number"

C Code Example

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

void findSecondLargest(int arr[], int n) {
    if (n < 2) {
        printf("No second largest number\n");
        return;
    }
    int largest = INT_MIN, secondLargest = INT_MIN;

    for (int i = 0; i < n; i++) {
        if (arr[i] > largest) largest = arr[i];
    }

    for (int i = 0; i < n; i++) {
        if (arr[i] > secondLargest && arr[i] < largest) {
            secondLargest = arr[i];
        }
    }

    if (secondLargest == INT_MIN)
        printf("No second largest number\n");
    else
        printf("Second Largest: %d\n", secondLargest);
}

Coding Clutch Challenge Series 101 – All Coding Challenges


3. Most Optimized Approach Using Single Traversal

This approach keeps track of the largest and second-largest numbers during a single pass through the array.

C++ Code Example

#include <iostream>
#include <climits>
using namespace std;

void findSecondLargest(int arr[], int n) {
    int largest = INT_MIN, secondLargest = INT_MIN;
    for (int i = 0; i < n; i++) {
        if (arr[i] > largest) {
            secondLargest = largest;
            largest = arr[i];
        } else if (arr[i] > secondLargest && arr[i] < largest) {
            secondLargest = arr[i];
        }
    }
    if (secondLargest == INT_MIN)
        cout << "No second largest number" << endl;
    else
        cout << "Second Largest: " << secondLargest << endl;
}

Coding Clutch Challenge Series 101 – All Coding Challenges


Java Code Example (Single Traversal)

import java.util.*;

public class SecondLargestSingleTraversal {
    public static void findSecondLargest(int[] arr) {
        if (arr.length < 2) {
            System.out.println("No second largest number");
            return;
        }

        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;

        for (int num : arr) {
            if (num > largest) {
                secondLargest = largest;
                largest = num;
            } else if (num > secondLargest && num < largest) {
                secondLargest = num;
            }
        }

        if (secondLargest == Integer.MIN_VALUE) {
            System.out.println("No second largest number");
        } else {
            System.out.println("Second Largest: " + secondLargest);
        }
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 5, 40, 30};
        findSecondLargest(arr);  // Output: 30
    }
}

Python Code Example (Single Traversal)

def second_largest(arr):
    if len(arr) < 2:
        return "No second largest number"
    
    largest = float('-inf')
    second_largest = float('-inf')

    for num in arr:
        if num > largest:
            second_largest = largest
            largest = num
        elif num > second_largest and num < largest:
            second_largest = num

    return second_largest if second_largest != float('-inf') else "No second largest number"

# Test cases
print(second_largest([10, 20, 5, 40, 30]))  # Output: 30
print(second_largest([7, 7, 7, 7]))         # Output: No second largest number
print(second_largest([-10, -20, -5, -30]))  # Output: -10

Coding Clutch Challenge Series 101 – All Coding Challenges

C Code Example (Single Traversal)

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

void findSecondLargest(int arr[], int n) {
    if (n < 2) {
        printf("No second largest number\n");
        return;
    }

    int largest = INT_MIN, secondLargest = INT_MIN;

    for (int i = 0; i < n; i++) {
        if (arr[i] > largest) {
            secondLargest = largest;
            largest = arr[i];
        } else if (arr[i] > secondLargest && arr[i] < largest) {
            secondLargest = arr[i];
        }
    }

    if (secondLargest == INT_MIN)
        printf("No second largest number\n");
    else
        printf("Second Largest: %d\n", secondLargest);
}

int main() {
    int arr[] = {10, 20, 5, 40, 30};
    int n = sizeof(arr) / sizeof(arr[0]);
    findSecondLargest(arr, n);  // Output: 30
    return 0;
}

C++ Code Example (Single Traversal)

#include <iostream>
#include <climits>
using namespace std;

void findSecondLargest(int arr[], int n) {
    if (n < 2) {
        cout << "No second largest number" << endl;
        return;
    }

    int largest = INT_MIN, secondLargest = INT_MIN;

    for (int i = 0; i < n; i++) {
        if (arr[i] > largest) {
            secondLargest = largest;
            largest = arr[i];
        } else if (arr[i] > secondLargest && arr[i] < largest) {
            secondLargest = arr[i];
        }
    }

    if (secondLargest == INT_MIN)
        cout << "No second largest number" << endl;
    else
        cout << "Second Largest: " << secondLargest << endl;
}

int main() {
    int arr[] = {10, 20, 5, 40, 30};
    int n = sizeof(arr) / sizeof(arr[0]);
    findSecondLargest(arr, n);  // Output: 30
    return 0;
}

Coding Clutch Challenge Series 101 – All Coding Challenges


Finding the second largest number in an array is an excellent problem to sharpen your logical reasoning and coding skills. By exploring various approaches, from sorting to optimized single traversal, you gain a deeper understanding of array manipulation.

FAQs

  1. What happens if the array has only one element?
    • The program will output that there’s no second largest number because the condition for a second largest number isn’t met.
  2. Can this handle duplicate largest values?
    • Yes! The programs are designed to skip duplicate largest values and find the next unique number.
  3. What is the best approach for large datasets?
    • The single traversal approach is the most efficient, with a time complexity of O(n).
  4. What if all elements in the array are the same?
    • The output will indicate that there’s no second largest number since all values are identical.
  5. Is this problem language-specific?
    • No, the logic applies universally, but syntax and implementation may vary based on the programming language.