Find Second Largest Element
Fundamentals & Basic Operations DSA practice problem on Onlearn.
Difficulty: easy.
Topics: Find the second smallest and second largest element in an array, printing '-1' if either doesn't exist., Arrays, Sorting, Time Complexity, Space Complexity, Loops, Conditional Statements, edge cases, sorting algorithms, array, conditional logic, algorithm design, traversal, Array Traversal & Indexing, If-Else Statement, Edge Case Handling in Arrays, Single-Pass Algorithms.
Given an array of integers, find its second smallest and second largest elements. If an array has fewer than two unique elements, output 1 for the corresponding smallest/largest element. Input Specification: The input will consist of a single line containing space separated integers representing the elements of the array. Output Specification: Print two integers, the second smallest and second largest elements, separated by a space. If either doesn't exist (e.g., fewer than two unique elements), print 1 for that value. Examples: Example 1: Input: [1,2,4,7,7,5] Output: 2 5 Explanation: The unique elements in sorted order are 1, 2, 4, 5, 7. The second smallest is 2, and the second largest is 5. Example 2: Input: [1] Output: 1 1 Explanation: Since there is only one element in the array, it is both the largest and smallest. There is no second largest or second smallest unique element present.