Data Structures & AlgorithmsEasyInfosys · Capgemini pattern
A sorted array holds n elements and has spare capacity. What is the worst-case time to insert a new element so that the array stays sorted?
- A. O(log n)
- B. O(1)
- C. O(n log n)
- D. O(n)
Correct answer: D. O(n)
Binary search finds the position in O(log n), but every element after that position must shift one place right, which is O(n) when inserting at the front. Re-sorting (O(n log n)) is never necessary.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Counting sort on [2, 0, 2, 1, 0, 2] (values 0–2) builds count[v] and then turns it into cumulative counts, count[v] = number of elements ≤…
- Two pointers start at both ends of the sorted array [1, 3, 4, 6, 8, 11] to find pairs of DIFFERENT positions with sum 12 (move left if the…
- A hash map starts with capacity 16 and doubles its capacity whenever the number of keys EXCEEDS 0.75 × capacity. What is its capacity…
- Bubble sort (each pass compares adjacent pairs left to right and swaps if out of order) runs on [6, 2, 9, 1, 5]. What is the array after…
- The array [1, 2, 3, 4, 5, 6] is first rotated RIGHT by 2 positions and then rotated LEFT by 5 positions. What is the result?
- What is the longest common prefix of the strings interview, internet, interval and intern?