Problem overview
The function middleElement receives a slice of integers, nums, with an odd number of items, and returns the item in the middle. Every number is between -1000 and 1000.
For [1, 2, 3] the result is 2. For [5, 9, 1, 8, 4] it is 1: the middle is about the position, not the size of the number. For [7] the only item is the middle one, so the result is 7.
Approach
With an odd number of items, one item has the same number of neighbours on both sides. Its index is the length divided by 2, rounded down. Five items have the indexes 0 to 4, and 5 divided by 2, rounded down, is 2: two items come before index 2 and two come after it.
Go does the rounding for you. When both operands of / are integers, the result is an integer and the fractional part is dropped, so 5 / 2 is 2, not 2.5. That means len(nums) / 2 is exactly the middle index.
Step by step
- Compute the middle index as
len(nums) / 2and store it in a variable namedmiddle, declared with:=. - Return the item at that index:
nums[middle].
The solution in Go
func middleElement(nums []int) int {
middle := len(nums) / 2
return nums[middle]
}
Running it on the three examples gives these results:
[1 2 3] -> 2
[5 9 1 8 4] -> 1
[7] -> 7
Details worth knowing:
- Integer division truncates.
lenreturns anintand2is an untyped constant that becomes anint, so/is integer division. With 7 items,7 / 2is 3. There is no need formath.Floor. :=declares and infers the type.middlegets the typeintfromlen(nums) / 2, which is also the type that a slice index accepts.- The result is an
int. The slice holdsintvalues, sonums[middle]matches the function's return type. - The variable is optional.
return nums[len(nums)/2]does the same. The lesson names the index first so that each step is visible.
Edge cases and common mistakes
- A single item.
1 / 2is 0, somiddleis 0 and the only item is returned. - Subtracting 1 by habit. The last index is
len(nums)-1, but the middle islen(nums) / 2, with no subtraction. Writingnums[len(nums)-1 / 2]is a trap:/binds tighter than-, so Go reads it aslen(nums) - (1 / 2). Since1 / 2is 0, the index becomeslen(nums), one past the end. - Expecting a fraction. In Go,
5 / 2with integers is 2. If you ever need2.5, convert tofloat64first; this lesson doesn't. - An even number of items. The constraints rule it out. With 4 items,
4 / 2is 2, which is the upper of the two middle items; the lesson never asks for it. - An empty slice. It has an even length, 0, so it isn't a valid input.
nums[0]on an empty slice stops the program with an "index out of range" panic.
Testing
Besides the examples, try a longer slice to see that the position decides the answer, not the values:
[1, 2, 3]gives 2.[5, 9, 1, 8, 4]gives 1.[7]gives 7.[10, 20, 30, 40, 50, 60, 70]gives 40.
