Hard Lists and algorithms

Most frequent value

The first INPUT () is how many numbers follow (at least 1). DISPLAY the value that appears most often. If several values appear the same number of times, DISPLAY the one that comes first in the list.

Input (one value per INPUT ())Expected output
7 3 1 3 2 1 3 23
4 5 6 6 55

Check runs all 3 tests. Press Run to try the program yourself: a box asks for each INPUT ().

Output


        
        
      

Variables

Show a solution
count ← INPUT ()
nums ← []
REPEAT count TIMES
{
   APPEND (nums, INPUT ())
}
best ← nums[1]
bestCount ← 0
FOR EACH candidate IN nums
{
   times ← 0
   FOR EACH n IN nums
   {
      IF (n = candidate)
      {
         times ← times + 1
      }
   }
   IF (times > bestCount)
   {
      best ← candidate
      bestCount ← times
   }
}
DISPLAY (best)

Teachers: sign in as a teacher to add this exercise to a class, graded automatically.

Frequently asked questions

How do I solve this exercise?

Complete the starter code in the editor, press Run to try it (type values when INPUT () asks), then press Check to run every test. Step shows the program line by line with its variables.

Where is the solution?

Under the editor, in Show a solution. Try the exercise first: comparing your code with the solution afterwards is a good way to learn another approach.

AP is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this site.