Data Structures & AlgorithmsVery hardTCS NQT · Infosys pattern
Array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] is left-rotated by d = 2 positions using the reversal algorithm (reverse first d, reverse rest, reverse whole). What is the result?
- A. 9, 10, 1, 2, 3, 4, 5, 6, 7, 8
- B. 3, 4, 5, 6, 7, 8, 9, 10, 1, 2
- C. 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- D. 4, 5, 6, 7, 8, 9, 10, 1, 2, 3
Correct answer: B. 3, 4, 5, 6, 7, 8, 9, 10, 1, 2
Left-rotating by d moves the first d elements to the end in order: reversing the first d elements, then the remaining n−d, then the whole array achieves this in O(n) time with O(1) extra space, giving [3, 4, 5, 6, 7, 8, 9, 10, 1, 2]. Rotating right by d instead would give [9, 10, 1, 2, 3, 4, 5, 6, 7, 8].
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
- Two sorted linked lists [9 → 14 → 35 → 36 → 37] and [27 → 29 → 31 → 32] are merged with the standard O(n+m) two-pointer merge (always take…
- Kadane's algorithm runs on the array [-9, 3, 3, -2, 6, 4, -4, 6, 9] to find the maximum sum of a contiguous subarray. What sum does it…
- Elevation map [4, 6, 0, 2, 6, 6, 6, 2] (bar width 1). Using the two-pointer / prefix-max approach for trapping rain water, how much water…
- Using a sliding window (shrink from the left whenever more than k distinct characters are in the window), what is the length of the…
- The Dutch National Flag algorithm (single pass, three pointers low/mid/high) partitions [1, 2, 0, 0, 2, 1, 0, 2, 0] (values 0, 1, 2 only)…
- Using a sliding window (shrink from the left whenever more than k distinct characters are in the window), what is the length of the…