Problem overview
The function middleElement receives a list of integers, nums, with an odd number of items, and returns the item in the middle.
For [1, 2, 3] the answer is 2. For [5, 9, 1, 8, 4] it is 1: the middle is a position, not the largest or the median value. For [7] it is 7.
Approach
With an odd count of items, one item has the same number of neighbors on each side. Five items have indexes 0 to 4, and the middle is index 2: two items before it and two after. The index is the size divided by 2, rounded down.
In Kotlin, dividing two Int values with / already drops the fraction, so 5 / 2 is 2 and no extra step is needed.
Step by step
- Find the middle index. Divide
nums.sizeby 2 and store the result in avalnamedmiddle. - Return the item at that index:
nums[middle].
The solution in Kotlin
class Solution {
fun middleElement(nums: List<Int>): Int {
val middle = nums.size / 2
return nums[middle]
}
}
Details worth knowing:
- Integer division truncates.
7 / 2is 3, while7 / 2.0is 3.5, because one operand is aDouble. Here both operands areInt, so the result is anInt, which is what an index must be. For negative values truncation goes toward zero:-7 / 2is -3. The size is never negative, so that doesn't matter here. List<Int>is enough. The function only reads, so a read-onlyListworks. AMutableListor anArrayListcan be passed in, because both are lists.size, notlength. Lists report their length withsize. Strings uselength.- Combining the steps.
return nums[nums.size / 2]does the same in one line. The lesson keeps the index in a namedvalso the idea is visible.
Tracing the examples
For [1, 2, 3]: the size is 3 and middle is 1. The item at index 1 is 2.
For [5, 9, 1, 8, 4]: the size is 5 and middle is 2. The item at index 2 is 1.
For [7]: the size is 1 and middle is 0, so the only item is returned.
Position, not value
Don't confuse the middle item with the median. The median is the middle value after sorting, while this exercise reads the item that sits in the middle position of the list as it is given. For [5, 9, 1, 8, 4] the item at index 2 is 1, but sorting the list first would put 5 at index 2. The function never sorts, so it runs in constant time: reading by index doesn't depend on the size of the list.
Edge cases and common mistakes
- Even sizes. The lesson only gives odd sizes. For
[1, 2, 3, 4]the same code returns 3, the second of the two middle items, because4 / 2is 2. - Using
nums.size / 2 + 1ornums.size / 2 - 1. Those are off by one. Indexes start at 0, which is why the rounded-down half is already the middle. - An empty list. The size is 0,
middleis 0, andnums[0]throws anIndexOutOfBoundsException. The lesson guarantees at least one item. - Expecting the middle value. The function returns the item at the middle position. It doesn't sort the list.
Testing
[1, 2, 3]gives 2.[5, 9, 1, 8, 4]gives 1.[7]gives 7.
