Junior — Middle
When is it preferable to use an array and when a singly linked list for storing data?
sobes.tech AI
Answer from AI
An array is preferred when quick access to elements by index (O(1)) is needed and the data size is fixed or small. It is memory-efficient and easy to use.
A singly linked list is better to use if:
- Elements are frequently added or removed from the middle or beginning of the list (insertion/deletion operations O(1) with a reference to the node).
- The data size is dynamic and unknown in advance.
However, access to elements by index in a singly linked list is slow (O(n)), as it requires sequential traversal.
Example in Python:
# Array (list) for quick access
arr = [1, 2, 3, 4]
print(arr[2]) # Quick access to element at index 2
# Singly linked list (simplified example)
class Node:
def __init__(self, val):
self.val = val
self.next = None
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
# Adding a new node at the beginning
new_node = Node(0)
new_node.next = head
head = new_node