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.
The length is 7, so indices run from 0 to 6.
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.
middle = len(nums) // 2 return nums[middle]
An array has 9 values. Which box is in the middle?
- ABox 4
- BBox 5
- 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.
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.
nums = [4, 8, 15, 16, 23] → 15
1 ≤ n ≤ 99 · n is odd