Q#52: Largest elements in an array

Given an array with k distinct elements, write a function to return all elements that have at least two elements greater than themselves in the same array:

For example:

#Given the following:
array = [2,3,9,7,6]
#Your function should return:
[2,3,6]

TRY IT YOURSELF

ANSWER

This question tests our problem solving skills in Python and our understanding of the array data structure.

Since we are tasked with finding numbers that are less than at least two numbers, lets make it easy for ourselves by sorting the list. This way the last two elements will always be the two largest. Now, we can simply take every element but the last two, if the array is longer than 3 elements.

def greater_elems(array):
array.sort()
if len(array) <3:
return []
elif len(array) == 3:
return array[:1]
else:
return array[:-2]

--

--