Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Interleave the First Half of the Queue with Second Half

Medium Acceptance 69.35% Points 30.00

You are given a queue Q containing N integers, where N is an even number. Rearrange the elements of the queue by interleaving the first half of the queue with the second half.

Note: Return the rearranged queue as a vector or ArrayList.

Examples
Example 1

Example 1

Input: N = 6, Q = {1, 2, 3, 4, 5, 6}

Output: {1, 4, 2, 5, 3, 6}

Explanation: The first half of the queue is {1, 2, 3}, and the second half is {4, 5, 6}. After interleaving the first half with the second half, the final queue becomes {1, 4, 2, 5, 3, 6}.

Example 2

Example 2

Input: N = 8, Q = {10, 20, 30, 40, 50, 60, 70, 80}

Output: {10, 50, 20, 60, 30, 70, 40, 80}

Explanation: The first half of the queue is {10, 20, 30, 40}, and the second half is {50, 60, 70, 80}. After interleaving the first half with the second half, the final queue becomes {10, 50, 20, 60, 30, 70, 40, 80}.

Hints
Hint 1
Expected Time Complexity: O(N)
Hint 2
Expected Auxiliary Space: O(N)
Constraints
  • 2 <= N <= 10^5
  • N is even
  • 1 <= Elements of Queue <= 10^3
  • Sum of N over all test cases doesn't exceeds 10^6
Companies
Microsoft Samsung Walmart
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