Back to DSA Topics

Arrays

Arrays are contiguous memory locations that store elements of the same type.

Animated Visualization

Step 1 of 4
10
0
20
1
30
2
40
3
50
4
Initial array: Access elements using indices (O(1))
javascript
← Scroll →
// Array Declaration and Initialization
let arr = [10, 20, 30, 40, 50];
// Accessing Elements
console.log(arr[0]); // 10
console.log(arr[2]); // 30
// Inserting at End
arr.push(60); // [10, 20, 30, 40, 50, 60]
// Removing from End
arr.pop(); // [10, 20, 30, 40, 50]
// Inserting at Beginning
arr.unshift(5); // [5, 10, 20, 30, 40, 50]
// Removing from Beginning
arr.shift(); // [10, 20, 30, 40, 50]
// Finding Element
let index = arr.indexOf(30); // 2
// Time Complexity:
// Access: O(1)
// Search: O(n)
// Insertion: O(n)
// Deletion: O(n)
Swipe horizontally to view full code

Explanation

Arrays are the most basic data structure. They store elements in contiguous memory locations, allowing for O(1) access time. However, insertion and deletion operations can be expensive (O(n)) as elements may need to be shifted.

Operations & Complexity

AccessO(1)

Direct access using index

SearchO(n)

Linear search through elements

InsertionO(n)

May require shifting elements

DeletionO(n)

May require shifting elements

Time Complexity

AccessO(1)

Direct access using index

SearchO(n)

Linear search through elements

InsertionO(n)

May require shifting elements

DeletionO(n)

May require shifting elements