Problem overview
The method firstN gets a vector<int> named nums and a number n. It returns a new vector holding the first n numbers of nums, in the same order. The constraints say n is between 0 and the length of nums.
With nums = [3, 8, 1, 9, 4] and n = 3, the answer is [3, 8, 1]: the 9 and the 4 are left out. With n = 0 the answer is the empty vector, and when n equals the length, every number is kept.
Approach
This is a slice: a copy of a range of the vector. In C++ you make one by building a vector from two positions. The vector copies everything from the first position up to, but not including, the second.
The first position is nums.begin(), the place of index 0. The second is nums.begin() + n, the place of index n. The items copied are the ones at indexes 0 to n - 1, which is exactly n items.
Step by step
- Create a
vector<int>namedresultfromnums.begin()andnums.begin() + n. Whennis 0, both positions are the same, soresultis empty with no special case. - Return
result. It is a copy, sonumsstays as it was.
The solution in C++
class Solution {
public:
vector<int> firstN(vector<int> &nums, int n) {
vector<int> result(nums.begin(), nums.begin() + n);
return result;
}
};
The parameter vector<int> &nums is passed by reference, so calling the method does not copy the input. The copy happens only in the line that builds result. The vector is returned by value; the compiler moves it out, so the return does not copy it again.
Running it on the statement's examples, with a small helper that prints a vector in bracket notation:
[3, 8, 1]
[]
[2, 4]
These are the results for ([3, 8, 1, 9, 4], 3), ([5, 6, 7], 0) and ([2, 4], 2). Calling it with n = 5 on the first vector returns all five numbers, and afterwards nums still holds [3, 8, 1, 9, 4].
Trying more inputs
Some small inputs are worth running. For nums = [7] and n = 1 the answer is [7], and for the same vector with n = 0 it is []. The first case checks that the whole vector can be taken, and the second that nothing is taken. For [-5, 0, 5] with n = 2, negative numbers copy like any other: the answer is [-5, 0].
When you test, also print nums after the call. A correct solution never changes it, and seeing it intact confirms that the result really is an independent copy.
Complexity
Time is O(n): the constructor copies n numbers. Space is O(n) for the new vector.
Edge cases and common mistakes
- Off by one. Using
nums.begin() + n - 1as the second position gives one item too few, because the second position is not included. - Using the first position wrongly. The first position is the start, not
n.nums.begin() + ngoes second. - Passing a number instead of positions.
vector<int> result(nums, n)does not mean "the firstnitems". It needs two positions. - Asking for more than exists. C++ does not check the positions. An
nbigger thannums.size()can crash the program. The lesson's constraints keepnin range, so no extra check is needed here.
