Solution: Rearrange Sorted List in Max/Min Form
This lesson gives a solution to the “Rearrange Sorted List in Max/Min Form” challenge.
We'll cover the following
Solution #1: Creating a new list
In this solution, we first create a new empty list that we will append the appropriate elements to and return. We then iterate through the list starting from the index till the middle of the list indexed as lst[length(list)/2]
. So if the length of the given list is 10, the iterator variable i
on line 4 in our solution would start from 0 and end at . Note that the starting index 0
in the example is inclusive, and the ending index 5
is exclusive. At each iteration, we first append the largest unappended element and then the smallest. So in the first iteration, i = 0
and lst[-(0+1)] = lst[-1]
corresponds to the last element of the list, which is also the largest. So the largest element in the list is appended to result
first, and then the current or element indexed by i
is appended. Next, the second largest and the second smallest are appended and so on until the end of the list.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.