Second Smallest Element
easySave
Array
Given an unsorted array of integers, write a function to find the second smallest element in the array. If such an element does not exist, the function should return -1.
Example 1
Input
[ 4, 2, 7, 3, 1 ]
Output
2
Explanation. The smallest element is 1 and the second smallest is 2.
Example 2
Input
[ 5, 5 ]
Output
-1
Explanation. All elements are the same so there is no second smallest element.
Example 3
Input
[ 9 ]
Output
-1
Explanation. There is only one element, so there cannot be a second smallest.
Example 4
Input
[ 13, 21, 13, 21, 13 ]
Output
21
Explanation. The smallest element is 13 repeated, and the second smallest is 21.
Follow-up: How would your solution change if you were asked to find the second largest element?
Constraints:
The input array will contain at least one integer, but may contain duplicates. All elements are integers.
- Views
- 3