![]() |
VOOZH | about |
Given an array arr[] of integers, find the smallest and second smallest distinct elements in the array. The result should be returned in ascending order, meaning the smallest element should come first, followed by the second smallest. If there is no valid second smallest (i.e., all elements are the same or the array has fewer than two elements), then return -1.
Examples:
Input: arr[] = [12, 25, 8, 55, 10, 33, 17, 11]
Output: [8, 10]
Explanation: The smallest element is 1 and second smallest element is 10.Input: arr[] = [2, 4, 3, 5, 6]
Output: [2, 3]
Explanation: 2 and 3 are respectively the smallest and second smallest elements in the array.Input: arr[] = [1, 1, 1]
Output: [-1]
Explanation: Only element is 1 which is smallest, so there is no second smallest element.
Table of Content
The Idea is to is first sorted the array in ascending order, which ensures that the smallest element is at the front. Then, the code searches for the first number that is greater than the minimum to identify the second smallest. If all elements are equal and no distinct second minimum exists, it returns
-1.
8 10
The main idea of this approach is to find the smallest and second smallest distinct elements in the array using two separate passes. In the first loop, it identifies the minimum value (mini) by comparing each element. In the second loop, it looks for the smallest element that is not equal to the minimum, which becomes the second minimum (secmini). This ensures that both values are distinct.
8 10
The main idea of this approach is to find the smallest and second smallest distinct elements by scanning the array only once. It uses two variables:
firstfor the minimum value andsecondfor the second minimum.
The values are updated based on the following conditions:
=> If the current number is less than first: Update second = first and first = current number.
=> Else if the current number is greater than first but less than second: Update second = current number.
8 10