Given an array of integers nums, return the second-largest element in the array. If the second-largest element does not exist, return -1.
Input: nums = [8, 8, 7, 6, 5]
Output: 7
Explanation: The largest value in nums is 8, the second largest is 7
Input: nums = [10, 10, 10, 10, 10]
Output: -1
Explanation: The only value in nums is 10, so there is no second largest value, thus -1 is returned
Input: nums = [7, 7, 2, 2, 10, 10, 10]
There would not be any second largest element for this case, so returned value will be -1.
largest
, and secondLargest
. Initialize secondLargest
to -1
as initially there shall be no second largest element.largest
with last element of array.largest
, update secondLargest
to that element and break out once secondLargest is updated. Return the value stored in secondLargest
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to find the second largest element
int secondLargestElement(vector<int>& nums) {
int n = nums.size();
// Check if the array has less than 2 elements
if (n < 2) {
// Indicating no second largest element is possible
return -1;
}
// Sort the vector in ascending order
sort(nums.begin(), nums.end());
// Largest element will be at last index
int largest = nums.back();
int secondLargest = -1;
// Traverse the sorted vector from right to left
for (int i = n-2; i >= 0; i--) {
/* If the current element is not
equal to the largest element*/
if (nums[i] != largest) {
/* Assign the current element
as the second largest and break*/
secondLargest = nums[i];
break;
}
}
// Return the second largest element
return secondLargest ;
}
};
int main() {
vector nums = {1, 2, 4, 6, 7, 5};
//Create an instance of the Solution class
Solution sol;
/* Function call to find
the second largest element*/
int ans = sol.secondLargestElement(nums);
cout << "The second largest element is: " << ans << endl;
return 0;
}
import java.util.*;
class Solution {
// Function to find the second largest element
public int secondLargestElement(int[] nums) {
int n = nums.length;
// Check if the array has less than 2 elements
if (n < 2) {
// Indicating no second largest element is possible
return -1;
}
// Sort the array in ascending order
Arrays.sort(nums);
// Largest element will be at last index
int largest = nums[n - 1];
int secondLargest = -1;
// Traverse the sorted array from right to left
for (int i = n - 2; i >= 0; i--) {
/* If the current element is not
equal to the largest element*/
if (nums[i] != largest) {
/* Assign the current element
as the second largest and break*/
secondLargest = nums[i];
break;
}
}
// Return the second largest element
return secondLargest;
}
}
class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 4, 6, 7, 5};
// Create an instance of the Solution class
Solution sol = new Solution();
/* Call the method to find
the second largest element */
int ans = sol.secondLargestElement(nums);
System.out.println("The second largest element is: " + ans);
}
}
class Solution:
# Function to find the second largest element
def secondLargestElement(self, nums):
n = len(nums)
# Check if the array has less than 2 elements
if n < 2:
# Indicating no second largest element is possible
return -1
# Sort the list in ascending order
nums.sort()
# Largest element will be at last index
largest = nums[-1]
secondLargest = -1
# Traverse the sorted list from right to left
for i in range(n-2, -1, -1):
''' If the current element is not
equal to the largest element'''
if nums[i] != largest:
''' Assign the current element
as the second largest and break'''
secondLargest = nums[i]
break
# Return the second largest element
return secondLargest
# Example usage
nums = [1, 2, 4, 6, 7, 5]
# Create an instance of the Solution class
sol = Solution()
''' Call the method to find
the second largest element'''
ans = sol.secondLargestElement(nums)
print("The second largest element is:", ans)
class Solution {
// Function to find the second largest element
secondLargestElement(nums) {
let n = nums.length;
// Check if the array has less than 2 elements
if (n < 2) {
// Indicating no second largest element is possible
return -1;
}
// Sort the array in ascending order
nums.sort((a, b) => a - b);
// Largest element will be at last index
let largest = nums[n - 1];
let secondLargest = -1;
// Traverse the sorted array from right to left
for (let i = n - 2; i >= 0; i--) {
/* If the current element is not
equal to the largest element */
if (nums[i] != largest) {
/* Assign the current element
as the second largest and break */
secondLargest = nums[i];
break;
}
}
// Return the second largest element
return secondLargest;
}
}
// Example usage
let nums = [1, 2, 4, 6, 7, 5];
// Create an instance of the Solution class
let sol = new Solution();
/* Call the method to find
the second largest element */
let ans = sol.secondLargestElement(nums);
console.log("Second largest element is:", ans);
To optimise the solution further the idea is to eliminate sorting. Traverse the array once to find the largest element. Perform a second traversal to find the largest element that is smaller than the largest element found.
When there are fewer than 2 elements in an array, there would not be any second largest element, so return -1.
largest
, and secondLargest
to INT_MIN
.largest
element.secondLargest
and also not equal to largest then update the secondLargest
. Return secondLargest
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Method for the second largest element in the vector
int secondLargestElement(vector<int>& nums) {
int n = nums.size();
// Check if the vector has less than 2 elements
if (n < 2) {
/* If true, return -1 indicating there
is no second largest element*/
return -1;
}
/* Initialize variables to store the
largest and second largest elements*/
int largest = INT_MIN, secondLargest = INT_MIN;
// First traversal to find the largest element
for (int i = 0; i < n; i++) {
largest = max(largest, nums[i]);
}
// Second traversal to find second largest element
for (int i = 0; i < n; i++) {
if (nums[i] > secondLargest && nums[i] != largest) {
secondLargest = nums[i];
}
}
// Return the second largest element
return secondLargest == INT_MIN ? -1 : secondLargest;
}
};
int main() {
vector nums = {1, 2, 4, 6, 7, 5};
//Create an instance of Solution class
Solution sol;
// Call the method to find second largest element
int result = sol.getSecondLargest(nums, n);
cout << "Second largest is " << result << endl;
return 0;
}
import java.util.*;
class Solution {
public int secondLargestElement(int[] nums) {
int n = nums.length;
// Check if the array has less than 2 elements
if (n < 2) {
// If true, return -1
// Exit the method
return -1;
}
/*Initialize variables to store the
largest and second largest elements*/
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
// First traversal to find the largest element
for (int i = 0; i < n; i++) {
largest = Math.max(largest, nums[i]);
}
// Second traversal to find second largest element
for (int i = 0; i < n; i++) {
if (nums[i] > secondLargest && nums[i] != largest) {
secondLargest = nums[i];
}
}
// Return the second largest element
return secondLargest == Integer.MIN_VALUE ? -1 : secondLargest;
}
public static void main(String[] args) {
int[] nums = {1, 2, 4, 6, 7, 5};
//Create Instance of Solution Class
Solution sol = new Solution();
/* Call the method to find the second
largest element and store the result*/
int result = sol.getSecondLargest(nums);
System.out.println("Second largest is " + result);
}
}
class Solution:
def secondLargestElement(self, nums):
# Get the length of the array
n = len(nums)
# Check if the array has less than 2 elements
if n < 2:
# If true, return -1 indicating there is no second largest element
return -1
# Initialize variables to store the largest and second largest elements
largest = float('-inf')
secondLargest = float('-inf')
# First traversal to find the largest element
for i in range(n):
largest = max(largest, nums[i])
# Second traversal to find second largest element
for i in range(n):
if nums[i] > secondLargest and nums[i] != largest:
secondLargest = nums[i]
# Return the second largest element
return -1 if secondLargest == float('-inf') else secondLargest
nums = [1, 2, 4, 6, 7, 5]
# Create an instance of the Solution class
sol = Solution()
"""Call the method to find the second
largest element and store the result"""
result = sol.getSecondLargest(nums)
print("Second largest is", result)
class Solution {
secondLargestElement(nums) {
// Get the length of the array
let n = nums.length;
// Check if the array has less than 2 elements
if (n < 2) {
/*If true, return -1 indicating there
is no second largest element*/
return -1;
}
/*Initialize variables to store the
largest and second largest elements*/
let largest = Number.MIN_VALUE;
let secondLargest = Number.MIN_VALUE;
// First traversal to find the largest element
for (let i = 0; i < n; i++) {
largest = Math.max(largest, nums[i]);
}
// Second traversal to find second largest element
for (let i = 0; i < n; i++) {
if (nums[i] > secondLargest && nums[i] != largest) {
secondLargest = nums[i];
}
}
// Return the second largest element
return secondLargest == Number.MIN_VALUE ? -1 : secondLargest;
}
}
let nums = [1, 2, 4, 6, 7, 5];
// Create an instance of the Solution class
let sol = new Solution();
/*Call the method to find the second
largest element and store the result*/
let result = sol.getSecondLargest(nums);
console.log("Second largest is " + result);
To find the second-largest element in an array more efficiently, the idea is to perform the operation in a single traversal by making smart comparisons. This approach uses two variables to keep track of the largest and the second-largest elements while iterating through the array. This will help to find the second-largest element with just one pass throughout the array.
When there are fewer than 2 elements in an array, there would not be any second largest element, so return -1.
largest
, and secondLargest
. Initialize largest
and secondLargest
to INT_MIN
as initially none of them should be holding any values.largest
, update secondLargest
and largest
.secondLargest
and not equal to largest
, update secondLargest
.secondLargest
.#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Method for second largest element in the vector
int secondLargestElement(vector<int>& nums) {
// Check if the vector has less than 2 elements
if (nums.size() < 2) {
/* If true, return -1 indicating there
is no second largest element*/
return -1;
}
/*Initialize variables to store the
largest and second largest elements*/
int large = INT_MIN;
int second_large = INT_MIN;
/* Single traversal to find the
largest and second largest elements*/
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > large) {
second_large = large;
large = nums[i];
}
else if (nums[i] > second_large && nums[i] != large) {
second_large = nums[i];
}
}
// Return the second largest element
return second_large == INT_MIN ? -1 : second_large;
}
};
int main() {
vector nums = {1, 2, 4, 7, 7, 5};
//Create an instance of the Solution class
Solution sol;
/Call the method to find
the second largest element*/
int sL = sol.secondLargestElement(nums);
cout << "Second largest is " << sL << endl;
return 0;
}
import java.io.*;
class Solution {
// Method for second largest element in the array
public int secondLargestElement(int[] nums) {
// Check if the array has less than 2 elements
if (nums.length < 2) {
// If true, return -1 there is no second largest element
return -1;
}
/* Initialize variables to store the
largest and second largest elements */
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
/*Single traversal to find thelargest
and second largest elements*/
for (int i = 0; i < nums.length; i++) {
if (nums[i] > largest) {
secondLargest = largest;
largest = nums[i];
}
else if (nums[i] > secondLargest && nums[i] != largest) {
secondLargest = nums[i];
}
}
// Return the second largest element
return secondLargest == Integer.MIN_VALUE ? -1 : secondLargest;
}
public static void main(String[] args) {
int[] nums = {1, 2, 4, 7, 7, 5};
//Creating the instance of the Solution class
Solution sol=new Solution();
int n = nums.length;
/* Call the method to find
the second largest element*/
int sL = sol.secondLargestElement(nums);
System.out.println("Second largest is " + sL);
}
}
from typing import List
class Solution:
def secondLargestElement(self, nums: List[int]) -> int:
if len(nums) < 2:
return -1
largest = float('-inf')
second_largest = float('-inf')
for num in nums:
if num > largest:
second_largest = largest
largest = num
elif num > second_largest and num != largest:
second_largest = num
return -1 if second_largest == float('-inf') else second_largest
# Main function
if __name__ == "__main__":
nums = [1, 2, 4, 6, 7, 5]
#Creating an instance of the Solution class
sol = Solution()
result = sol.secondLargestElement(nums)
print("Second largest is:", result)
class Solution {
secondLargestElement(nums) {
// Get the length of the array
let n = nums.length;
// Check if the array has less than 2 elements
if (n < 2) {
/*If true, return -1 indicating there
is no second largest element*/
return -1;
}
/* Initialize variables to store the
largest and second largest elements*/
let largest = Number.MIN_VALUE;
let secondLargest = Number.MIN_VALUE;
/*Single traversal to find the largest
and second largest elements*/
for (let i = 0; i < n; i++) {
if (nums[i] > largest) {
secondLargest = largest;
largest = nums[i];
}
else if (nums[i] > secondLargest && nums[i] != largest) {
secondLargest = nums[i];
}
}
// Return the second largest element
return secondLargest == Number.MIN_VALUE ? -1 : secondLargest;
}
}
let nums = [1, 2, 4, 7, 7, 5];
// Create an instance of the Solution class
let sol = new Solution();
// Call the method to find second largest element
let sL = sol.secondLargestElement(nums);
console.log("Second largest is " + sL);
Q: What happens if the array has fewer than two elements?
A: If the array has fewer than two elements, there is no second-largest element. Return -1 to indicate this scenario. Example: Input: nums = [7] Output: -1
Q: How does the algorithm handle arrays with identical elements?
A: If all elements are identical, there is no second-largest distinct value. Return -1 in this case. Example: Input: nums = [4, 4, 4] Output: -1
Q: How would you handle finding the second-largest element in a stream of data?
A: For a stream of data (where elements arrive one at a time): Maintain two variables, largest and second_largest, initialized to -∞.Update these variables dynamically as new elements arrive. Example: Stream: [2, 5, 1, 8, 3] Process: Start with largest = −∞, second_largest = −∞. After processing the stream: largest = 8, second_largest = 5.
Q: Can you solve this problem using a different approach, such as heap data structures?
A: Yes, a min-heap of size 2 can be used to maintain the two largest elements: Insert the first two elements into the heap. For each new element, compare it with the smallest element in the heap. If it is larger, replace the smallest element. At the end, the heap will contain the two largest elements. Example: Input: nums = [3, 1, 4, 2] Heap after processing: [3, 4] Output: 3 (second-largest element).