Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Interleave the First Half of the Queue with Second Half

Medium Acceptance 69.35% Points 30

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}.

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
Hints
  • Expected Time Complexity: O(N)
  • Expected Auxiliary Space: O(N)
Topics
Queue
Companies
Microsoft Samsung Walmart
Added 27 Mar 2025 69.35% acceptance
Ln 1, Col 1Sign in to save your code
6
1 2 3 4 5 6
1 4 2 5 3 6