When to use Array over Linked List and vice versa?
An array is a linear data structure that is a collection of homogeneous elements. Arrays are stored in contiguous memory locations. An array is a static data structure that combines data of similar types.
A linked list is a linear data structure that contains nodes and pointers. Each node contains data and pointers to another node. It is an ordered collection of data elements called nodes and the linear order is maintained by pointers. Like an array, a linked list also contains elements of homogeneous data types.
Scenarios in which we use Linked Lists:
- Linked Lists are used when the number of elements is not known in advance i.e. size is not known as linked lists support dynamic memory allocation.
- Linked lists are simple and can be used to implement other data structures like stack, queue, and tree.
- Linked Lists can be used for the manipulation of polynomials.
- Linked lists are used for performing arithmetic operations on long integers.
- Linked List can be used in cases when faster insertion and deletion are required. Linked takes O(1) time complexity for insertion and deletion while array takes O(N).
Scenarios in which we use Arrays:
- Arrays are used when we require random access to elements.
- Arrays are used as the base of all sorting algorithms.
- Arrays are used when the number of elements(size of an array) is known in advance as the array supports static memory allocation.
- Arrays are used to implement matrices.
- Arrays can be used to implement various data structures like stacks, queues, and trees.