What is a Static Array?
A static array is an array with a fixed size that must be declared at the time of creation. The size cannot be changed after the array is created. Memory is allocated at compile time, which means the size must be known upfront and cannot change at runtime. Elements are stored in a contiguous block of memory, enabling efficient index-based access.Time Complexity
| Operation | Big-O | Notes |
|---|---|---|
| Access | O(1) | Direct index-to-address mapping |
| Insert / Remove End | O(1) | No shifting required |
| Insert / Remove Middle | O(n) | Subsequent elements must be shifted |
O(1) — Constant Time: The operation takes the same amount of time regardless of the size of the array, because each index maps directly to a specific memory address.
Advantages
- Simple to implement
- Efficient for accessing elements by index
Disadvantages
- Fixed size — can waste memory if under-utilized, or fail if too small
- Insertion and deletion can be costly due to element shifting
Operations
static_array = [1, 2, 3, 4, 5]
print(static_array[0]) # Output: 1
print(static_array[2]) # Output: 3
# Using index-based loop
for i in range(len(static_array)):
print(static_array[i])
# Using for-each loop
for value in static_array:
print(value)
# Using while loop
i = 0
while i < len(static_array):
print(static_array[i])
i += 1
# count = current number of elements
def remove(index: int) -> None:
if not 0 <= index < count:
raise IndexError("Index out of bounds.")
# Shift all elements from next index to the left
for i in range(index, count - 1):
static_array[i] = static_array[i + 1]
# Clear the last element and decrement count
static_array[count - 1] = 0
count -= 1
count, then increment.# count = current number of elements
# capacity = total allocated size
def insert(index: int, value: int) -> None:
if count == capacity:
raise OverflowError("Array is at full capacity.")
if not 0 <= index <= count:
raise IndexError("Index out of bounds.")
# Shift elements to the right to make space
# Example: insert 4 at index 1 in [1, 2, 3] -> [1, 4, 2, 3]
# i=3: array[3] = array[2] -> [1, 2, 3, 3]
# i=2: array[2] = array[1] -> [1, 2, 2, 3]
for i in range(count, index, -1):
static_array[i] = static_array[i - 1]
static_array[index] = value
count += 1
Static Array Class Implementation
static_array.py