What is the time complexity of inserting an element into an unsorted array?
a) O(n)
b) O(1)
c) O(log n)
d) O(n log n)
Answer:
b) O(1)
Explanation:
Inserting an element into an unsorted array can be done in constant time O(1) by simply placing the new element at the end of the array. This operation does not require shifting any elements or searching for a specific position.
However, if the array is full and needs to be resized, the time complexity will be O(n), as copying all elements to a new array takes linear time. Resizing typically happens in amortized constant time for dynamically sized arrays.
Although insertion is fast, searching in an unsorted array takes linear time O(n) because elements are not ordered.
Reference:
DSA (Data Structures and Algorithms) MCQ Questions and Answers