Samsung Electronics Interview Question

How to find the 3rd smallest element of an array? Write (on paper) a pseudo code for the algorithm.

Interview Answer

Anonymous

Oct 17, 2023

Given an array 'a' Create another array 'b' of size = 3 (sorted) that stores the elements b = {a[0],a[1],a[2]}, but in sorted order. Notice these elements are lowest three elements of a[0..2] (obviously). Now if we have stored lowest three elements of a[0..k] in b[0],b[1],b[2] then updating b to store lowest 3 elements in a[0...k+1] would require inserting a[k + 1] in 'b' at right position. In 3 comparisons we can find position of a[k + 1] in 'b', insert at that position. Then the smallest three elements are first 3 elements of 'b'. Keep doing this updates until we have top 3 elements of a[0...n-1] in b, then b[2] is the required answer. Time : O(n) Space : O(1)