Microsoft interview question

Find two smallest elements in an unsorted array using only one pass i.e. O(n)

Interview Answers

Anonymous

27 Oct 2015

Initialize two variables which will the first and second elements in the array respectively. As you loop, if current value is less than both then update both, if it's between the two then only update second.

1

Anonymous

31 Oct 2015

Here is my python code solution def TwoSmallest(lst): tmp_list = [lst[0],lst[1]] for i in xrange(2,len(lst)): maxi=max(tmp_list[0],tmp_list[1]) if lst[i] < maxi : tmp_list.remove(maxi) tmp_list.append(lst[i]) return tmp_list

Anonymous

12 June 2016

If currVal < smallest, 2ndSmallest = smallest and smallest = currVal else if currVal < 2ndSmallest, 2ndSmallest = currVal