Find the smallest and second smallest elements in an array | GeeksforGeeks

preview_player
Показать описание


This video is contributed by Harshit Verma

Please Like, Comment and Share the Video among your friends.

Also, Subscribe if you haven't already! :)
Рекомендации по теме
Комментарии
Автор

was asked the same question in an interview.. Thank you soo much, now I can solve in the much better way....

nishantgarg
Автор

My way of doing it


int [] arr = {10, 20, 3, 2, 2, 4, 5, 50};

int Min = 21313; // Random value that exceeds all the number in array
int secMin = 0;
Arrays.sort(arr);
for(int i=0;i<arr.length;i++) {

if (arr[i] < Min) {
Min = arr[i];
secMin=Min;
}
if(arr[i]!=arr[i+1]){
secMin=arr[i+1];
break;
}

}
System.out.println("Minimum number: "+Min);
System.out.println("Second minimum "+secMin);


Prints 2 as smallest and 3 as second smallest

vansh
Автор

thank you for sharing this tutorial sir, keep it up 👍👍🙂🙂

SmartProgramming
Автор

Great! Answered my question. thank you so much..

caypanganiban
Автор

what if the input array is like {0, 0, 0, 0, Integer.MAX_VALUE}?

junchen
Автор

Thanks for sharing this. you have already put time and effort to make this video why you make it low quality by moving so fast and not explaining everything. it would only take 30 seconds more if you had explained your code and algorithm in a slower pace.

maslam
Автор

what if the array is { 1, 2147483647 }, does the INT_MAX count as the second smallest in this array? The smallest will become 1 but the second smallest won't update and therefore print out no second smallest.

Simeon