This tutorial is a part of the Data Structures and Algorithms class:
- How data looks like (print it out!)
- How to insert/delete/access/search data
- How fast to insert/delete/access/search data
Array data structure:
- is one of the most popular data structures.
- is usually used to store a large amount of data with similar pattern.
- built-in in Javascript.
- ordered elements.
How data looks like (print it out!)
lecture-4/array-data-structure.js
// initialize
const arr = ['a', 'b', 4, 2, 'v']
// print out, see how data looks like
console.log(arr) // [ 'a', 'b', 4, 2, 'v' ]
$ node array-data-structure.js
[ 'a', 'b', 4, 2, 'v' ]
How to insert/delete/access/search data
lecture-4/array-data-structure.js
// insert
arr.push(100)
console.log(arr) // [ 'a', 'b', 4, 2, 'v', 100 ]
arr.splice(1, 0, 'Data Structure');
console.log(arr) // [ 'a', 'Data Structure', 'b', 4, 2, 'v', 100 ]
// delete
arr.splice(4,1)
console.log(arr) // [ 'a', 'Data Structure', 'b', 4, 'v', 100 ]
// access
console.log(arr[1]) // Data Structure
// search
console.log(arr.includes(100)) // true
console.log(arr.includes(200)) // false
$ node array-data-structure.js
[ 'a', 'b', 4, 2, 'v', 100 ]
[ 'a', 'Data Structure', 'b', 4, 2, 'v', 100 ]
[ 'a', 'Data Structure', 'b', 4, 'v', 100 ]
Data Structure
true
false
Make sure to checkout Array's popular methods in Javascript to know all possible operations.
How fast to insert/delete/access/search data
Data Structure | Insert | Delete | Access | Search |
---|---|---|---|---|
Array | O(1) at end: push O(n) at random: splice |
O(n): splice | O(1) with index | O(n): includes |
⬆️ Time complexity (worst case) per operation
Real life interview questions
- Do you know how your data looks like?
- What kind of information can array data structure store in real life applications?
- How do you insert/delete/access/search with array data structure?
- What is the Time Complexity of array data structure on insert/delete/access/search operation?
Find4
: Given an array of random integer, example:[2, 4, 5, 1, 6]
, and a random sum, example:13
. Write a function to return4
numbers that their combination equals to the sum, example:[2, 4, 1, 6]
.