How to insert into an Array

Jonathan Rasmusson
A free video tutorial from Jonathan Rasmusson
Ex-Spotify Engineer, The Agile Samurai
4.5 instructor rating • 6 courses • 45,342 students

Learn more from the full course

Data Structures and Algorithms Bootcamp

How to ace your Silicon Valley style coding interview

06:27:06 of on-demand video • Updated April 2021

  • How to answer commonly asked Silicon Valley style interview questions
  • Demonstrate knowledge and mastery of data structures and algorithms
  • How to pass Silicon Valley style technical interviews
  • Interview confidently
  • Land your dream job
English All right let's talk about Insert when we insert an element into an array, What we're really talking about is adding a new element while retaining all the other elements already in there. When we insert usually we're specifying an index that we'd like to insert insert something at along with its value. But basically when we insert what we're really doing in this case for example if we wanted to insert a value of B at this index of one, there's basically three steps we need to go through here first. First thing we need to do is we need to take all the elements at the given index where we're doing the insertion and copy or shift them up one space that's in order to make room or free up the space for the new element that we like to insert there. We then insert the new value just copy it right in and then we increase the size of our array by 1. In this case we started with three elements and now we have four. Now one thing to be careful of is these two notions of sizes that we can talk about when we look at arrays. The first notion is capacity. That's how many slots or how much room does the array have to hold data. In this case for example we have a capacity of 10. That's one notion of size. The other one is the number of elements. For example in this case we started with three. And once we've done our insertion we needed to bump it up to four. It's this size that I'm talking about the number of elements that I'm referring to and we need to increment or increase our count by one. Now we're going to see later on why keeping track of the number of elements is important. But that's basically how insert works we copy up we insert and then we increment our counter. And because of all this shifting and copying insert is actually a linear operation. When it comes to arrays because in the worst case if we had all 10 elements of array full we'd have to copy and shift every element of that array up which means the bigger our array gets the more time it's going to take. That's why insertion is a linear operation O to the N and that's insert. All right. Next let's take a look at delete.