Rotate Deque By K
JavaView on GFG
Time: O(k)
Space: O(1)
Advertisement
Intuition
Rotate a deque by k positions. Pop from front, push to back k times.
Algorithm
- 1For clockwise k rotation: move last k elements to front. Or rotate(deque, k) using deque operations.
Common Pitfalls
- •Normalize k = k % size. Deque rotation in O(k) or O(n-k) depending on direction.
Rotate Deque By K.java
Java
// Approach: Pop k elements from front and add to back (or use modular arithmetic on index).
// Time: O(k) Space: O(1)
import java.util.*;
class Solution {
public static void rotateDeque(Deque<Integer> dq, int type, int k) {
while (k-- > 0) {
if (type == 1)
dq.addFirst(dq.pollLast());
else
dq.addLast(dq.pollFirst());
}
}
}Advertisement
Was this solution helpful?