Goldman Sachs interview question

How to get the second smallest number from an array

Interview Answers

Anonymous

26 Jan 2018

Sort the array in ascending order, get the second array value.

3

Anonymous

1 Mar 2018

You dont have to sort the entire list. Use bubble sort and run the inner loop just 2 times with if condition as below for (int i = 0; i a[j]) swap(a[j-1], a[j]); return a[1]; One needs to think about those scenarios where there are duplicates like 5,3,2,3,1,2,1. The above function will return 1. So better to ask interviewer before implementing.

Anonymous

3 Mar 2018

remove duplicates from the array, sort in asc order, and get the key second one from the beginning

Anonymous

12 Jun 2018

O(n) solution: int secondLargest(int[] nums, int n) { if (n second && num > first) { // if number is greater than both second = first; first = num; } else { second = num; // if num is between first and second } } return second; }

Anonymous

12 Jun 2018

O(n) solution: int secondLargest(int[] nums, int n) { if (n second && num > first) { second = first; first = num; } else { second = num; } } return second; }