Skip to content
CodeItRaw
Sorting

Lesson 4/5

If a value fills more than half of a list, then once the list is sorted the element exactly in the middle must be it: a block longer than half covers the middle wherever it sits. Some questions come down to looking at a single index after sorting.

ordered = sorted(scores, reverse=True)
rank = 0
while rank < len(ordered) and ordered[rank] > rank:
rank += 1
return rank
Sorting from large to small and comparing "which place am I in" with "what is my value": it counts the elements whose value is larger than their place. Definitions of the form "at least h of them are at least h", like the h-index, are read this way.

Sorting is not always the fastest way, and it is nearly always the easiest correct one. Solve by sorting first and see it pass; then ask "could I do it in one pass, without sorting?". For the majority element the answer is yes: a candidate and a counter are enough.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Majority

    Function

  2. 02

    Majority

    Code reading · Break the Code

  3. 03

    H-Index

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list