Problem overview
The method dropEnds receives an array of integers nums and returns a new array with every number except the first and the last. The numbers in between keep their order. The constraints say nums has 2 to 10 numbers, so there is always a first and a last number, and when there are only two of them, the answer is an empty array.
The examples:
[4, 8, 15, 16, 23]gives[8, 15, 16]. The 4 is first and the 23 is last, so both go.[9, 0, 9]gives[0]. Both 9s are ends, and only the 0 is between them.[1, 2]gives[]. Both numbers are ends, so nothing is between them.
Approach
The middle of an array starts at index 1, right after the first number, and ends just before the last number, which sits at index nums.length - 1. The slice(start, end) method copies the items from start up to, but not including, end. So the end index is the one thing that does the second half of the job for us: the last index is the end, and it is left out.
That gives nums.slice(1, nums.length - 1). Starting at 1 drops the first number. Stopping before nums.length - 1 drops the last.
Step by step
- Copy
numsfrom index 1 up tonums.length - 1withslice, and store the copy in a variable namedmiddle, declared withlet. - Return
middle.
Check the smallest case with the formula. For two numbers, the length is 2, so the call is slice(1, 1). Start and end are the same index, so the range is empty and the result is []. No special case is needed.
The solution in JavaScript
class Solution {
dropEnds(nums) {
let middle = nums.slice(1, nums.length - 1);
return middle;
}
}
Details worth knowing
The method returns a new array and leaves nums alone, because slice copies. A negative end index counts from the back, so nums.slice(1, -1) gives the same answer as the lesson's code: [8, 15, 16] for the first example and [] for [1, 2]. The lesson spells out nums.length - 1 so the end index is easy to see, and both forms are correct.
Testing
Running the method on the three examples prints:
[ 8, 15, 16 ]
[ 0 ]
[]
Try a three-number array whose numbers are all different, such as [1, 2, 3]. The answer should be [2], which shows that the one number kept is the one in the middle, not the one that equals an end.
Edge cases and common mistakes
- Ending at the length.
nums.slice(1, nums.length)drops the first number but keeps the last. The end must stop one earlier. - Starting at 0.
nums.slice(0, nums.length - 1)drops the last number but keeps the first. - Removing by value. In
[9, 0, 9]the first and last numbers are equal. Code that removes "the number 9" by value would cut the wrong things. Positions are what matter here, not values. - Changing the input. Using
shiftandpopalso removes the ends, but they changenumsitself. Slicing leaves it alone.
