DSA Factory
Free lessonsArrays · Stage 0 · What an array is · Step 2

The length tells you where things are

Find the middle from the length. About 5 minutes.

The middle of a queue

Seven people stand in a queue. Who's in the middle? The one with three people in front and three behind: the fourth person. Counting from 0, that's box 3.

Notice where 3 comes from: 7 halved is 3.5, rounded down to 3. That works for any odd length. Halve the length, round down, and you land on the box with the same number of values on each side.

Middle box: the length halved, rounded down.
Find the middle of 7 boxes
4
0
8
1
15
2
16
3
23
4
42
5
7
6
i

The length is 7, so indices run from 0 to 6.

Move 1 of 3

Why rounding down is the right way

With 9 boxes, halving gives 4.5. Round down to 4: boxes 0 to 3 sit on the left and boxes 5 to 8 on the right, four on each side. Rounding up to 5 would leave five before it and only three after.

Counting from 0 is what makes rounding down land in exactly the right place.

Divide with rounding down: a plain / gives a fraction in Python.
In code
middle = len(nums) // 2
return nums[middle]
Quick check

An array has 9 values. Which box is in the middle?

  1. ABox 4
  2. BBox 5
  3. CBox 4.5
Show the answer

Box 4. 9 halved is 4.5, rounded down to 4. Boxes 0 to 3 are on the left and 5 to 8 on the right.

Your problem

Middle value

You get a list with an odd number of values. Return the value in the middle: the one with as many values before it as after it.

Example
nums = [4, 8, 15, 16, 23] → 15

1 ≤ n ≤ 99 · n is odd

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding