Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Rotate an array to the right by k steps in place, using O(1) extra space. Example: [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3].
Problem: Rotate an array to the right by k steps in place, using O(1) extra space.
Example: [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3].
def rotate(a, k):
n = len(a)
k %= n
def rev(i, j):
while i < j:
a[i], a[j] = a[j], a[i]
i += 1; j -= 1
rev(0, n - 1); rev(0, k - 1); rev(k, n - 1)
return a
print(rotate([10, 20, 30, 40, 50, 60], 8))What is printed?- A. [30, 40, 50, 60, 10, 20]
- B. [60, 10, 20, 30, 40, 50]
- C. [20, 30, 40, 50, 60, 10]
- D. [50, 60, 10, 20, 30, 40]
Correct answer: D. [50, 60, 10, 20, 30, 40]
k = 8 mod 6 = 2. Reversing the whole array, then the first k and the remaining n − k elements, rotates right by 2: [50, 60, 10, 20, 30, 40]. Forgetting k %= n would index out of range; a left rotation by 2 gives [30, 40, 50, 60, 10, 20]. O(n) time, O(1) space.
More Coding Interview Problems questions
- Problem: Every number in a list of sensor IDs appears twice except one. Find the lonely ID in O(n) time and O(1) space. python def…
- Problem: Return, for every index i, the product of all elements except a[i], without using division. Example: [1, 2, 3, 4] → [24, 12, 8…
- Problem: Given an array where values lie in 1..n, find the value that appears twice (exactly one does) without modifying the array. python…
- Problem: Given n ≤ 10⁵ integers (not sorted), find the length of the longest run of consecutive values, e.g. [100, 4, 200, 1, 3, 2] → 4…
- Problem: Group words that are anagrams of each other and report how many groups there are. python from collections import defaultdict def…
- Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative. python def countk(a, k): seen = {0: 1} p =…