Problem overview
The method middleElement receives a list of integers, nums, with an odd number of items, and returns the item in the middle. The middle index is the length of the list divided by 2, rounded down. With 5 items the indexes run from 0 to 4, and 5 divided by 2, rounded down, is 2: two items come before index 2 and two come after it.
For [1, 2, 3] the length is 3, the middle index is 1, and the result is 2. For [5, 9, 1, 8, 4] the middle index is 2 and the result is 1: the middle is about the position, not the size of the number. For [7] the middle index is 0 and the result is 7.
Approach
Find the position first, then read the item at that position. The position comes from the length, which len(nums) gives. Dividing by 2 would give a decimal for an odd length, and a list can't be indexed with a decimal. Floor division, written //, divides and rounds down to a whole number, so 5 // 2 is 2 and 1 // 2 is 0.
It helps to see why this index is the middle. In a list of 5 items, index 2 has indexes 0 and 1 on its left and indexes 3 and 4 on its right. In a list of 7 items, index 3 has three on each side. Whenever the length is odd, the rounded-down half of the length is exactly the number of items before the middle one.
Step by step
- Find the middle index.
middle = len(nums) // 2. For[5, 9, 1, 8, 4]that is5 // 2, which is2. - Return the item at that index.
nums[middle]is1for that list.
The solution in Python
class Solution:
def middleElement(self, nums: List[int]) -> int:
middle = len(nums) // 2
return nums[middle]
Some details worth knowing:
/and//are different operators.len(nums) / 2always gives a float:5 / 2is2.5. Using it as an index raisesTypeError: list indices must be integers or slices, not float.- Floor division rounds toward negative infinity. For a length, which is never negative, that is the same as dropping the decimal part.
- For an odd length the two sides of the middle always have the same number of items, which is why the middle is well defined. A list of 7 has the middle index
7 // 2, which is 3, with three items on each side. - The variable
middleis a position, not an item. The item isnums[middle].
Edge cases and common mistakes
- One item.
1 // 2is0, so the only item is returned. - Using
/instead of//. This raises theTypeErrorabove, even though the division looks right. - Returning the index. For
[5, 9, 1, 8, 4]the middle index is2but the answer is1, the item stored there. - Looking for the middle value. The task asks for the middle position. It is not a median, so don't sort the list: for
[5, 9, 1, 8, 4], sorting first would give5, which is the wrong answer. - Even lengths. The lesson never passes them. A list of 4 would give
4 // 2, which is index 2, and the item3in[1, 2, 3, 4]. With no single middle there, the rule gives the right-hand one of the two center items.
Testing
[1, 2, 3]gives2.[5, 9, 1, 8, 4]gives1.[7]gives7.
