Problem overview
The method DropEnds receives a List<int> named nums and returns a new list with every number except the first and the last. The numbers in between keep their order. When nums has exactly two numbers, nothing is between them and the result is empty.
For [4, 8, 15, 16, 23] the ends are 4 and 23, so the result is [8, 15, 16]. For [9, 0, 9] the result is [0]. For [1, 2] it is []. The constraints say nums always has at least two numbers.
Approach
The numbers to keep form one block. It starts at index 1, right after the first number, and it is two items shorter than the list, because one item is missing at each end. So the block has nums.Count - 2 items.
GetRange(start, count) copies a block from a List<T> given its start index and its length. Together, the call is nums.GetRange(1, nums.Count - 2).
Check it on the three examples. With five numbers the count is 3, starting at index 1: the numbers at indexes 1, 2 and 3. With three numbers the count is 1. With two numbers the count is 0, which gives an empty list.
Step by step
- Copy the middle. Call
GetRangeonnumswith the start index 1 and the countnums.Count - 2. Store the new list in aList<int>namedmiddle. - Return
middle. For two numbers it is empty, which is the correct answer.
The solution in C#
class Solution {
public List<int> DropEnds(List<int> nums) {
List<int> middle = nums.GetRange(1, nums.Count - 2);
return middle;
}
}
On the three examples it produces these lists, printed as values separated by spaces (the empty list prints nothing):
8 15 16
0
The C# details worth knowing:
- The size of a list is
Count, a property with no parentheses.Lengthbelongs to arrays and strings. - A count of zero is fine.
GetRange(1, 0)on a two-item list returns an emptyList<int>. The start index 1 is allowed because it is within the list. - A new list. The original
numskeeps all its numbers, so the caller sees no change. - A shorter list would fail. On a list with a single number, the count would be -1 and
GetRangethrows anArgumentOutOfRangeException. The constraints rule that out, so the lesson's code needs no guard.
Edge cases and common mistakes
- Two numbers. The result is empty, because both are ends.
- Three numbers. Exactly one number is left, as in
[9, 0, 9]. Equal ends do not matter: the code works by position, not by value. - Count of
nums.Count - 1. With a start of 1 this runs one item past the end and throws anArgumentException. The start already skips one item, and the count has to leave out one more. - Start index 0. That keeps the first number and drops two from the end instead.
- Using the second argument as an end index.
GetRange(1, nums.Count - 1)would look like "from 1 up to the end" to a reader used to end indexes, but it is a count of items.
Testing
[4, 8, 15, 16, 23]gives[8, 15, 16].[9, 0, 9]gives[0].[1, 2]gives[].[-5, 3, 3, -5]gives[3, 3].
