// instantiate an array that holds 10 integersint gasPrices[]=newint[10];
gasPrices[0]=346;
gasPrices[1]=360;
gasPrices[2]=354;
Java
Inserting
If we want to insert something into an array, first we have to make space by "scooting over" everything starting at the index we're inserting into:
In the worst case we're inserting into the 0th index in the array (prepending), so we have to "scoot over" everything in the array. That's O(n) time.
Deleting
Array elements are stored adjacent to each other. So when we remove an element, we have to fill in the gap—"scooting over" all the elements that were after it:
In the worst case we're deleting the 0th item in the array, so we have to "scoot over" everything else in the array. That's O(n) time.
Why not just leave the gap? Because the quick lookup power of arrays depends on everything being sequential and uninterrupted. This lets us predict exactly how far from the start of the array the 138th or 9,203rd item is. If there are gaps, we can no longer predict exactly where each array item will be.
Data structures built on arrays
Arrays are the building blocks for lots of other, more complex data
structures.
Don't want to specify the size of your array ahead of
time? One option: use a dynamic array.
Want to look up items by something other
than an index? Use
a hash map.
of n integers sorted in ascending order. How quickly could we check if a given integer is in the array?
Solution
Start your free trial!
Log in or sign up with one click to get immediate access to 3 free mock interview questions
Actually, we don't support password-based login. Never have. Just the OAuth methods above. Why?
It's easy and quick. No "reset password" flow. No password to forget.
It lets us avoid storing passwords that hackers could access and use to try to log into our users' email or bank accounts.
It makes it harder for one person to share a paid Interview Cake account with multiple people.
“Interview Cake was instrumental in my success for interviews. I had used few other sources to prepare for technical interviews but none of them taught me the proper method of thinking and approaching a problem like Interview Cake.
—
Amir