DSA Factory
Free lessonsArrays · Stage 0 · What an array is · Step 1

Positions start at 0

Read the first and last values. About 4 minutes.

Open a box by its number

An array keeps values in a row of numbered boxes. The number of a box is its index, and it starts at 0. To read a box, write the array's name with the index in square brackets: nums[0] is the first value.

That's why reading any box is instant, however long the array is. The computer doesn't search: it goes straight to box 3, the way you'd walk straight to locker 3.

The first box is box 0: the second is box 1.
Any box, instantly: no searching needed.
Step through the indices
7
0
2
1
9
2
4
3
5
4
i

Box 0 holds 7, the first value. In code that's nums[0].

Move 1 of 4

The last box is one less than the length

The length is how many boxes there are. With 5 boxes numbered from 0, the numbers are 0, 1, 2, 3 and 4. So the last box is always the length minus one.

Asking for box 5 in a row of 5 is asking for a locker that isn't there. Depending on the language you'll get an error or a strange value, so it's worth getting this right early.

Last box: the length minus one.
Box number = length: is one past the end.
In code
first = nums[0]
last = nums[len(nums) - 1]
return [first, last]
Quick check

The array holds 8, 3, 6. What's in box 2?

  1. A8
  2. B3
  3. C6
  4. DThere is no box 2
Show the answer

6. Box 2 is the third box, and it holds 6.

Your problem

First and last

You get a list with at least one number in it. Return a list of two values: the first number, then the last number.

Example
nums = [7, 2, 9, 4, 5] → [7, 5]

1 ≤ n ≤ 100 · with one number, it is both the first and the last

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding