Arrays vs Other Data Structures When to Choose Arrays in DSA Python - Complexity Comparison
Choosing the right data structure affects how fast your program runs.
We want to see how arrays perform compared to others when doing common tasks.
Analyze the time complexity of accessing and inserting elements in an array.
arr = [10, 20, 30, 40, 50]
# Access element at index 2
value = arr[2]
# Insert element at the end
arr.append(60)
# Insert element at the start
arr.insert(0, 5)
This code shows accessing and inserting elements in an array at different positions.
Look at what repeats and costs time in arrays.
- Primary operation: Accessing by index and inserting elements.
- How many times: Access is done once here; insertion at end once; insertion at start once.
- Insertion at start requires shifting all elements, which repeats for each element after the insertion point.
Accessing an element stays fast no matter the size, but inserting at the start gets slower as array grows.
| Input Size (n) | Approx. Operations for Insertion at Start |
|---|---|
| 10 | 10 shifts |
| 100 | 100 shifts |
| 1000 | 1000 shifts |
Pattern observation: Insertion at start grows linearly with input size; accessing stays constant.
Time Complexity: O(1) for access and append, O(n) for insertion at start
This means accessing or adding at the end is fast and does not slow down with size, but inserting at the start slows down as the array grows.
[X] Wrong: "Inserting anywhere in an array is always fast like accessing by index."
[OK] Correct: Inserting at the start or middle requires moving many elements, which takes more time as the array grows.
Understanding when arrays are fast or slow helps you pick the right tool and explain your choices clearly in interviews.
"What if we used a linked list instead of an array? How would the time complexity for insertion at the start change?"