Intro

Array is a DS that stores elements in contiguous memory locations and ****supports index-based access

Subarray → sequence of contiguous values

arr = [2, 3, 6, 1, 5, 4]
subarray = arr[1:4] # [3, 6, 1]

Subsequence → sequence with the order preserved, not necessarily contiguous

subsequence = [arr[i] for i in [1, 3, 4]] # [3, 1, 5]

Static Array

Dynamic Array

int arr[] =newint[10];
arr[0] =5;
arr = []
arr.append(5)

List is a DS that is mutable, ordered and a Dynamic Array

nums = [1, 2, 3]
nums.append(4) # O(1)
nums[0] = 10
nums.pop() # O(1)
nums.insert(0, 99) # O(n)
nums.remove(2) # O(n)
nums.sort() # O(n log n)
squares = [x * x for x in range(5) if x % 2 == 0] # list comprehensions 

list_empty = [] # empty list
print(list_empty) # Output: []
list_ints = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1] # list of integers
print(list_ints) # Output: [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
list_strs = ['emre', 'dot', 'me'] # list of strings
print(list_strs) # Output: ['emre', 'dot', 'me']
list_mixed = [1, 'emre.me', 5.73, True] # list of mixed data types
print(list_mixed) # Output: [1, 'emre.me', 5.73, True]
list_nested = [['emre', 'dot', 'me'], [1], 5.73, True] # nested list
print(list_nested) # Output: [['emre', 'dot', 'me'], [1], 5.73, True]

Tuple is a DS that is ordered, immutable and hashable (if elements are hashable)

t = (1, 2, 3)
coords = {(0, 0): 'origin'}

# tuple unpacking
a, b = (10, 20)
for i, val in enumerate([10, 20, 30]):
	print(i, val)

Usage

Comparison

Advantages

Disadvantages

Corner Cases

Implementation

Time Complexity
Operations Worst case
Array Sorted Array
Access / Set item by index O(1)
Access / Set item if we don’t know the index O(n) O(log n) using Binary Search
Delete item O(n)
append() O(1)
insert() O(n)
extend() O(k)
in O(n)
pop() - last O(1)
pop() - intermediate O(n)
Access slice O(n)
Set slice O(k + n)
Delete slice O(n)
sort() O(n log n)
Space Complexity
Worst case
Array/List/Tuple O(n)

n is the number of elements in the array

Algorithms

Sorting

Patterns

Problems

Code


Resources

Array Data Structure | Interview Cake

Dynamic Array Data Structure | Interview Cake