No result illustrationNo result illustration

DevLoom

search

Lets Connect

chevron right
Menu
Home

Home

Community

Community

Blog Posts

Blog Posts

Programming

Programming

Tech Topics

Tech Topics

Explore

Explore

Find Jobs

Find Jobs

Tags

Tags

DevLoomPerfect Place for devs
    profile

    Jubair

    upvoteupvote

    1

    downvote

    0

    star

    Interleave 1st and 2nd half of queue

    clock icon

    Asked 10 months ago

    message

    0Comments

    eye

    2 Views

    Problem Statement:

    You are given a queue of integers. The task is to interleave the first half of the queue with the second half, meaning that the first element from the first half should be followed by the first element from the second half, the second element from the first half should be followed by the second element from the second half, and so on. If the queue has an odd number of elements, the last element should remain at the end of the queue.

    Example:

    • Input: queue = [10, 20, 30, 40, 50, 60]
    • Output: queue = [10, 40, 20, 50, 30, 60]

    If the queue has an odd number of elements:

    • Input: queue = [10, 20, 30, 40, 50, 60, 70]
    • Output: queue = [10, 40, 20, 50, 30, 60, 70]

    Approach:

    The main idea is to split the queue into two halves, interleave the elements of these two halves, and then handle the case where the number of elements is odd.

    Step-by-Step Explanation:

    1. Edge Case Check:

      • If the queue is empty, there's nothing to interleave, so we return immediately.
    2. Split the Queue into Two Halves:

      • We calculate k, which is half the size of the queue.
      • We create a new queue (q2) and move the first k elements from the original queue (q) to this new queue.
    3. Interleave the Two Halves:

      • We now have two queues:
        • q2 contains the first half.
        • q contains the second half.
      • We interleave by alternately taking elements from q2 and q, and pushing them back to the original queue.
    4. Handle the Odd Case:

      • If the queue has an odd number of elements, the last element in the queue needs to remain at the end.

    Code Implementation with Detailed Comments:

    #include <queue>
    #include <iostream>
    using namespace std;
    
    // Function to interleave the first half of the queue with the second half
    void interleaveQueue(queue<int>& q) {
        int n = q.size();
    
        // If the queue is empty or has only one element, no interleaving is needed
        if (n <= 1) return;
    
        int k = n / 2;  // Determine the halfway point
        queue<int> q2;  // Queue to hold the first half of the original queue
        int count = 0;
    
        // Step 1: Move the first k elements to q2
        while (count < k) {
            int temp = q.front();
            q.pop();
            q2.push(temp);
            count++;
        }
    
        // Step 2: Interleave elements from q2 and the remaining elements in q
        while (!q2.empty()) {
            int first = q2.front(); // First element from the first half
            q2.pop();
            q.push(first); // Place it in the interleaved queue
    
            if (!q.empty()) { // Check to prevent empty queue access
                int second = q.front(); // Next element from the second half
                q.pop();
                q.push(second); // Place it in the interleaved queue
            }
        }
    
        // Step 3: Handle odd number of elements
        if (n % 2 == 1) {
            int lastElement = q.front(); // The last element if n is odd
            q.pop();
            q.push(lastElement); // Push it back to maintain its position
        }
    }
    
    // Helper function to print the elements of the queue
    void printQueue(queue<int> q) {
        while (!q.empty()) {
            cout << q.front() << " ";
            q.pop();
        }
        cout << endl;
    }
    
    int main() {
        queue<int> q;
        q.push(10);
        q.push(20);
        q.push(30);
        q.push(40);
        q.push(50);
        q.push(60);
        q.push(70);  
    
        cout << "Original Queue: ";
        printQueue(q);
    
        interleaveQueue(q);
    
        cout << "Queue after Interleaving: ";
        printQueue(q);
    
        return 0;
    }
    

    Confused ! ? Lets Dry Run with an Example! :

    Lets have a Problem Recap:

    We are given a queue of integers. The goal is to interleave the first half of the queue with the second half. If the number of elements in the queue is odd, the last element should remain at the end after interleaving.

    Assume we have a Queue : [10, 20, 30, 40, 50, 60, 70]. 

    Step 2: Split the Queue into Two Halves

    We split the queue into two halves:

    • k = 3 (since 7/2 = 3.5, we take the floor value, which is 3).
    • We create a new queue q2 and move the first 3 elements to q2.

    After splitting:

    q2 (First Half): [10, 20, 30]
    q (Second Half): [40, 50, 60, 70]
    

    Step 3: Interleave the Two Halves

    We interleave elements from q2 (first half) and q (second half), pushing them back into the original queue.

    Let's go through the interleaving steps:

        First Pair:

      • Take 10 from q2 and push it to q.
      • Then take 40 from q and push it to q. 
    Queue after first pair: [50, 60, 70, 10, 40]

        Second Pair:

    • Take 20 from q2 and push it to q.
    • Then take 50 from q and push it to q.
    Queue after second pair: [60, 70, 10, 40, 20, 50]

       Third Pair:

    • Take 30 from q2 and push it to q.
    • Then take 60 from q and push it to q.
    Queue after third pair: [70, 10, 40, 20, 50, 30, 60]
    

    Note: After this step, all elements from q2 have been interleaved with elements from 

    the original q. The q now contains the interleaved elements plus the leftover elements from the second half.

    Step 4: Handle the Odd Case

    Since the queue has an odd number of elements, there is one leftover element (70). This element should stay at the end of the queue.

    Thus, the final state of the queue is:

    Final Queue: [10, 40, 20, 50, 30, 60, 70]

    Why Not [40, 20, 50, 30, 60]?

    You might have expected the output to be [40, 20, 50, 30, 60], but that would mean the original first half of the queue is not considered at all. The purpose of interleaving is to merge the two halves, so both halves are represented in the final queue, with each element from the first half followed by a corresponding element from the second half.

    Final Clarification:

    The process ensures that:

    • The first element from the first half (q2) is followed by the first element from the second half (q).
    • This pattern continues until all elements from the first half (q2) are exhausted.
    • If there's an odd number of elements, the last element in the second half (q) is simply placed at the end of the final queue.

    Conclusion:

    • Time Complexity: O(n), where n is the number of elements in the queue.
    • Space Complexity: O(k), where k is half the number of elements in the queue (for the temporary queue q2).

    This method effectively interleaves the two halves of the queue, ensuring that the elements are alternated correctly, with special handling for odd-sized queues.

     

    Queue
    Approch
    medium

    Share

    Write your comment here !

    0 Responses