Array Slicing

Array slicing involves taking a subset from an array and allocating a new array with those elements.

In C++ you can create a new vector of the elements in myVector, from startIndex to endIndex (exclusive), like this:

vector<int> slice(myVector.begin() + startIndex, myVector.begin() + endIndex);

Careful: there's a hidden time and space cost here! It's tempting to think of slicing as just "getting elements," but in reality you are:

  1. allocating a new vector
  2. copying the elements from the original vector to the new vector

This takes time and space, where n is the number of elements in the resulting vector.

That's a bit easier to see when you save the result of the slice to a variable:

vector<int> tailOfVector(myVector.begin() + 1, myVector.end());

But a bit harder to see when you don't save the result of the slice to a variable:

return vector<int>(myVector.begin() + 1, myVector.end()); // whoops, I just spent O(n) time and space!
for (int item : vector<int>(myVector.begin() + 1, myVector.end())) { // whoops, I just spent O(n) time and space! }

So keep an eye out. Slice wisely.

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .