Skip to content

Latest commit

 

History

History
46 lines (30 loc) · 718 Bytes

File metadata and controls

46 lines (30 loc) · 718 Bytes

Reverse First K Elements of Queue

Problem Link

Practice Problem


Pattern

  • Queue
  • Recursion

Approach

Remove the first k elements with recursion or a stack, then reinsert them in reversed order.


Time Complexity

O(n)

Space Complexity

O(k)


Java Solution

import java.util.*;
class Solution {
    public Queue<Integer> reverseFirstK(Queue<Integer> queue, int k) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < k; i++) stack.push(queue.poll());
        while (!stack.isEmpty()) queue.offer(stack.pop());
        int size = queue.size();
        for (int i = 0; i < size - k; i++) queue.offer(queue.poll());
        return queue;
    }
}