easy
0 views

Second Largest Integer – Greater than X

Find the second largest integer from a list that is greater than a given threshold X

Understand the Problem

Problem Statement

Given N integers and a threshold X, find the second largest integer that is strictly greater than X.

It is guaranteed that at least two integers in the list are greater than X.

Constraints

  • 3 ≤ N ≤ 100
  • 1 ≤ Each integer value, X ≤ 1000
  • At least two integers are always greater than X

Examples

Example 1
Input
8
18 11 13 9 6 25 36 2
15
Output
25
Explanation

Integers greater than 15 are [18, 25, 36]. When sorted in descending order: [36, 25, 18]. The second largest is 25.

Example 2
Input
6
10 10 20 30 40 50
9
Output
20
Explanation

All integers are greater than 9: [10, 10, 20, 30, 40, 50]. After removing duplicates and sorting: [50, 40, 30, 20, 10]. The second largest is 20.

Solution

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

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

int main() {
    int n;
    scanf("%d", &n);
    
    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    int x;
    scanf("%d", &x);
    
    // Filter integers greater than x
    int filtered[100];
    int count = 0;
    
    for (int i = 0; i < n; i++) {
        if (arr[i] > x) {
            filtered[count++] = arr[i];
        }
    }
    
    // Sort in descending order
    qsort(filtered, count, sizeof(int), compare);
    
    // Print second largest (index 1)
    printf("%d\n", filtered[1]);
    
    return 0;
}
Time:O(N log N) - due to sorting operation
Space:O(N) - for storing filtered integers
Approach:

The C solution:

  1. Reads N integers into an array
  2. Reads the threshold X
  3. Filters integers greater than X into a separate array
  4. Uses qsort() with a custom comparator to sort in descending order
  5. Prints the element at index 1 (second largest)

Visual Explanation

Loading diagram...