Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Reverse First K elements of Queue

Medium Acceptance 81.28% Points 30.00

Given an integer K and a queue of integers, the task is to reverse the order of the first K elements in the queue, while keeping the remaining elements in their original relative order.

The following standard queue operations are allowed:

  • enqueue(x): Adds an element x to the rear of the queue.
  • dequeue(): Removes an element from the front of the queue.
  • size(): Returns the current number of elements in the queue.
  • front(): Retrieves the element at the front of the queue.

Complete the given function modifyQueue(), which takes a queue and an integer K as input parameters, and returns the modified queue. The driver code will handle the printing of the queue automatically.

Examples
Example 1

Example 1

Input: 7 5, 1 2 3 4 5 6 7

Output: 5 4 3 2 1 6 7

Explanation: We reverse the first K = 5 elements of the queue. The first 5 elements {1, 2, 3, 4, 5} are reversed to {5, 4, 3, 2, 1}. The remaining elements {6, 7} stay in the same order. Hence, the final output is 5 4 3 2 1 6 7.

Hints
Hint 1
Expected Time Complexity: O(N)
Hint 2
Expected Auxiliary Space: O(K)
Constraints
  • 1 <= K <= N <= 10^5
Companies
Amazon Visa Goldman Sachs
Topics
Queue
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions