What is the time complexity of inserting an element at the beginning of an array?
a) O(1)
b) O(n)
c) O(log n)
d) O(n^2)
Answer:
b) O(n)
Explanation:
Inserting an element at the beginning of an array requires shifting all existing elements one position to the right to make space for the new element, resulting in a time complexity of O(n), where n is the number of elements in the array.
This operation is inefficient compared to inserting at the end of the array, which can be done in O(1) time. For frequent insertions at the beginning, data structures like linked lists are more efficient.
Array operations that involve shifting elements, such as insertion at the start or deletion from the start, have linear time complexity due to the need to move all other elements.
Reference:
DSA (Data Structures and Algorithms) MCQ Questions and Answers