Data Structures & AlgorithmsHardAmazon/Microsoft SDE pattern
Array [1, 2, 3, 4, 5, 6, 7, 8, 9] is left-rotated by d = 6 positions using the reversal algorithm (reverse first d, reverse rest, reverse whole). What is the result?
- A. 7, 8, 9, 1, 2, 3, 4, 5, 6
- B. 9, 8, 7, 6, 5, 4, 3, 2, 1
- C. 8, 9, 1, 2, 3, 4, 5, 6, 7
- D. 4, 5, 6, 7, 8, 9, 1, 2, 3
Correct answer: A. 7, 8, 9, 1, 2, 3, 4, 5, 6
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 [7, 8, 9, 1, 2, 3, 4, 5, 6]. Rotating right by d instead would give [4, 5, 6, 7, 8, 9, 1, 2, 3].
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
- An LRU cache of capacity 3 runs this sequence of operations in order: put(4, 40), put(2, 20), put(5, 50), put(1, 10), put(1, 10), put(2…
- What is the postfix (Reverse Polish) form of the infix expression "(i + j) d - b / h", built with the standard stack-based conversion (^…
- Array [61, 75, 77, 8, 27, 29, 31, 32, 47, 56] is a sorted array rotated at pivot 7. Using the standard O(log n) rotated-array binary…
- Using a sliding window (shrink from the left whenever more than k distinct characters are in the window), what is the length of the…
- Elevation map [2, 2, 5, 0, 2, 0, 3, 1, 1, 1] (bar width 1). Using the two-pointer / prefix-max approach for trapping rain water, how much…
- Using a sliding window of fixed size with a character-frequency count, how many substrings of "BAAAABBAACB" are anagrams of "AB"?