Problem overview
The function middleElement receives an array of integers, nums, with an odd number of items, and returns the item in the middle. The middle index is the length divided by 2, rounded down.
For [1, 2, 3] the length is 3, and 3 divided by 2 rounded down is 1, so the answer is the item at index 1, which is 2. For [5, 9, 1, 8, 4] the middle index is 2 and the item there is 1: the middle is about position, not about the size of the number. For [7], 1 divided by 2 rounded down is 0, so the only item is the middle one.
Approach: halve the count
With an odd number of items, there is exactly one middle, with the same number of items on each side. Five items have indexes 0 to 4, and index 2 has two items before it and two after it. The index is the count divided by 2, dropping the remainder.
Swift does that rounding on its own. Dividing two Int values with / gives an Int and drops the fractional part, so 5 / 2 is 2. It rounds toward zero, which for a count, never negative, is the same as rounding down.
Step by step
- Compute the middle index as
nums.count / 2and store it in a constant namedmiddle, declared withletbecause it never changes. - Return the item at that index with
nums[middle].
The solution in Swift
class Solution {
func middleElement(_ nums: [Int]) -> Int {
let middle = nums.count / 2
return nums[middle]
}
}
Details worth knowing:
- Both operands are
Int.nums.countis anIntand so is the literal2, so/is integer division. No conversion orfloorcall is needed. Division by aDoublewould need a conversion and would give a fraction. - Truncation toward zero. For negative numbers, Swift's integer division truncates toward zero, so
-5 / 2is-2, not-3. A count is never negative, so this doesn't change the result here. - The type of
count. In Swiftcountis a plainInt, not an unsigned type, so no casts are needed to use it as an index. - Out of range crashes. For an empty array,
middlewould be 0 andnums[0]doesn't exist, so the program stops at run time. The lesson always gives an odd count, at least 1. - Even counts. The rule still gives an item, the upper of the two middle ones:
[1, 2, 3, 4]gives 3, and[1, 2, 3, 4, 5, 6]gives 4. The lesson doesn't use such arrays, so they are only a note.
Edge cases and common mistakes
- One item.
[7]gives 7:1 / 2is 0. - Using
count / 2 + 1orcount / 2 - 1. These point at a neighbour of the middle. For[5, 9, 1, 8, 4]the middle is index 2, so they would return 8 and 9. - Taking the middle value. The task is the middle position. For
[5, 9, 1, 8, 4]the answer is 1, even though 5 is the median of the values. - Expecting a fraction.
5 / 2is 2, not 2.5, when both numbers areInt, so the result is always a valid index. - Using the last index.
nums[nums.count - 1]is the last item, not the middle one.
Testing
[1, 2, 3]gives2.[5, 9, 1, 8, 4]gives1.[7]gives7.[-3, 0, 8, 2, 9, 4, 1]gives2.[10, 20, 30, 40, 50, 60, 70, 80, 90]gives50.
