Data Structures & AlgorithmsHardProduct Company SDE · array manipulation
Problem: Rotate the array [1, 2, 3, 4, 5, 6, 7] to the right by k = 3 using the three-reversal method. What is printed?
Problem: Rotate the array [1, 2, 3, 4, 5, 6, 7] to the right by k = 3 using the three-reversal method. What is printed?
a = [1, 2, 3, 4, 5, 6, 7] k = 3 % len(a) a.reverse() a[:k] = reversed(a[:k]) a[k:] = reversed(a[k:]) print(a)What is printed?
- A. [5, 6, 7, 4, 3, 2, 1]
- B. [5, 6, 7, 1, 2, 3, 4]
- C. [4, 5, 6, 7, 1, 2, 3]
- D. [7, 6, 5, 4, 3, 2, 1]
Correct answer: B. [5, 6, 7, 1, 2, 3, 4]
Reversing the whole array, then each part, gives the right rotation by k. Reversing only the first k elements is the trap that yields [5, 6, 7, 4, 3, 2, 1].
More Coding Interview Problems questions
- Problem: How many unordered pairs of distinct elements of [1, 5, 3, 9, 7, 2] have absolute difference exactly 2? Run the code. python a =…
- Problem: Minimum cost to climb stairs where cost[i] is paid when standing on step i and you may take one or two steps. Starting positions…
- Problem: Houses in a circle hold the amounts [2, 3, 2]. You may not rob two adjacent houses, and the first and last are adjacent. Run the…
- Problem: What is the length of the longest common subsequence of 'ABCBDAB' and 'BDCABA'? python a, b = 'ABCBDAB', 'BDCABA' dp = [[0]…
- Problem: The number of structurally distinct binary search trees on 5 keys is the Catalan number. What does this code print? python dp =…
- Problem: What is the sum over all pairs (i < j) of the Hamming distances (number of differing bits) between the values in [1, 3, 5]? Run…