Get the First, Middle and Last Elements

Solve this Problem
Easy5 min
Topics
Companies
Given an array nums, return [first, middle, last], where the middle element is at index length / 2 (integer division). This is the textbook example of O(1)Constant Time O(1)The work stays the same no matter how large the input is. work. Because array elements are stored next to each other, reading any index takes the same time whether the array has five elements or five million. Walking the array to reach those positions also works, but its cost grows with the length — O(n) work for an O(1) job.

Test Case 1:

Input:nums = [4, 8, 15, 16, 23]
Output:[4, 15, 23]
Explanation:Length 5, so the middle index is 5 / 2 = 2.

Test Case 2:

Input:nums = [1, 2, 3, 4]
Output:[1, 3, 4]
Explanation:Length 4: the middle index 4 / 2 = 2 picks the right one of the two middle values.

Constraints

  • ◆1 ≤ nums.length ≤ 1000
  • ◆-1000000 ≤ nums[i] ≤ 1000000

Try the Dry Run

Approach & Solutions

Walk the Array to Each PositionBrute

Treat the array like a list you can only read from the start: walk through every element, note the value when you reach index 0 and index length / 2, and keep overwriting "last" until the walk ends. Correct, but it visits every element to read just three.

TimeO(n)
SpaceO(1)
class Solution { public int[] endsAndMiddle(int[] nums) { int first = 0, middle = 0, last = 0; for (int i = 0; i < nums.length; i++) { if (i == 0) { first = nums[i]; } if (i == nums.length / 2) { middle = nums[i]; } last = nums[i]; } return new int[] {first, middle, last}; } }
Index DirectlyOptimal

An array stores its elements side by side in memory, so the computer can jump to any index immediately — reading nums[0], the middle nums[length / 2] and the last nums[length − 1] each takes the same tiny amount of time, no matter how long the array is.

TimeO(1)
SpaceO(1)
class Solution { public int[] endsAndMiddle(int[] nums) { int first = nums[0]; int middle = nums[nums.length / 2]; int last = nums[nums.length - 1]; return new int[] {first, middle, last}; } }

Related Problems