Open In App

Last when k numbers are Repeatedly Removed from both ends

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

There are n people from 1 to n are standing in the queue at a movie ticket counter. It is a weird ticket counter, as it distributes tickets to the first k people and then the last k people, and again the first k people, and so on. Once a person gets a ticket, they move out of the queue. The task is to find the last person to get the ticket.

Examples:

Input: n = 9, k = 3
Output: 6
Explanation: Starting queue will like [1, 2, 3, 4, 5, 6, 7, 8, 9]. After the first distribution queue will look like [4, 5, 6, 7, 8, 9]. And after the second distribution queue will look like [4, 5, 6]. The last person to get the ticket will be 6.

Input: n = 5, k = 1
Output: 3
Explanation: Queue starts as [1, 2, 3, 4, 5] -> [2, 3, 4, 5] -> [2, 3, 4] -> [3, 4] -> [3], Last person to get a ticket will be 3.

Using Deque - O(n) time and O(n) space

The given approach utilizes a deque (double-ended queue) data structure to simulate the ticket distribution process. The main idea is to pop elements from both ends of the queue in a specific pattern until only one person remains.

Follow the steps to solve the problem:

1. Iterate from i = 1 to n and add each person's number to the back of the deque using dq.push_back(i).

2. Perform the following steps until the size of the deque becomes 1:

  • Initialize a variable i to 0 to keep track of the number of elements popped from the deque.
  • Pop k elements from the front of the deque by repeatedly calling dq.pop_front() while i < k and the deque's size is not 1.
  • Reset i to 0.
  • Pop k elements from the back of the deque by repeatedly calling dq.pop_back() while i < k and the deque's size is not 1.

3. Return the element at the front of the deque using dq.front(), which represents the last person to receive a ticket.

C++
#include <deque>
#include <iostream>
using namespace std;

int distribute(int n, int k)
{
    deque<int> dq;

    for (int i = 1; i <= n; i++) {
        dq.push_back(i);
    }

    while (dq.size() > 1) {
        for (int i = 0; i < k && dq.size() > 1; i++) {
            dq.pop_front();
        }

        for (int i = 0; i < k && dq.size() > 1; i++) {
            dq.pop_back();
        }
    }

    return dq.front();
}

int main()
{
    int n = 9, k = 3;
    cout << distribute(n, k) << endl;
    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;

public class GfG {
    public static int distribute(int n, int k) {
        Queue<Integer> queue = new LinkedList<>();

        for (int i = 1; i <= n; i++) {
            queue.add(i);
        }

        while (queue.size() > 1) {
            for (int i = 0; i < k && queue.size() > 1; i++) {
                queue.poll();
            }

            for (int i = 0; i < k && queue.size() > 1; i++) {
                queue.poll();
            }
        }

        return queue.peek();
    }

    public static void main(String[] args) {
        int n = 9, k = 3;
        System.out.println(distribute(n, k));
    }
}
Python
from collections import deque


def distribute(n, k):
    dq = deque()

    for i in range(1, n + 1):
        dq.append(i)

    while len(dq) > 1:
        for _ in range(k):
            if len(dq) > 1:
                dq.popleft()

        for _ in range(k):
            if len(dq) > 1:
                dq.pop()

    return dq[0]


if __name__ == '__main__':
    n = 9
    k = 3
    print(distribute(n, k))
C#
// C# version of the distribute function
using System;
using System.Collections.Generic;

class GfG
{
    static int distribute(int n, int k)
    {
        LinkedList<int> dq = new LinkedList<int>();

        for (int i = 1; i <= n; i++)
        {
            dq.AddLast(i);
        }

        while (dq.Count > 1)
        {
            for (int i = 0; i < k && dq.Count > 1; i++)
            {
                dq.RemoveFirst();
            }

            for (int i = 0; i < k && dq.Count > 1; i++)
            {
                dq.RemoveLast();
            }
        }

        return dq.First.Value;
    }

    static void Main()
    {
        int n = 9, k = 3;
        Console.WriteLine(distribute(n, k));
    }
}
JavaScript
// JavaScript version of the distribute function
function distribute(n, k) {
    let dq = [];

    for (let i = 1; i <= n; i++) {
        dq.push(i);
    }

    while (dq.length > 1) {
        for (let i = 0; i < k && dq.length > 1; i++) {
            dq.shift();
        }

        for (let i = 0; i < k && dq.length > 1; i++) {
            dq.pop();
        }
    }

    return dq[0];
}

let n = 9, k = 3;
console.log(distribute(n, k));

Output
6

Two-Pointer Approach - O(n) time and O(1) space

The given approach utilizes a two-pointer approach to find the last person to receive a ticket. It maintains two pointers, left and right, which represent the leftmost and rightmost positions in the queue, respectively.

Follow the steps to solve the problem:

1. Initialize left to 1 (representing the leftmost position in the queue) and right to n (representing the rightmost position in the queue).

2. Initialize firstDistribution to true, indicating the first distribution of tickets.

3. While the left is less than or equal to right, repeat the following steps:

  • If firstDistribution is true (indicating the first distribution):
    • If left + k is less than right, update left to left + k (moving k positions forward).
    • Otherwise, return right as the last person to receive a ticket.
  • If firstDistribution is false (indicating the last distribution):
    • If right - k is greater than left, update right to right - k (moving k positions backward).
    • Otherwise, return left as the last person to receive a ticket.
  • Toggle the value of firstDistribution (alternate between the first and last distribution).

4. If the while loop condition is not satisfied, return 0 as an error value.

C++
#include <iostream>
using namespace std;

int distribute(int n, int k) {
    int left = 1, right = n;
    bool firstDist = true;

    while (left <= right) {
        if (firstDist) {
            if (left + k < right) left += k;
            else return right;
        } else {
            if (right - k > left) right -= k;
            else return left;
        }
        firstDist = !firstDist;
    }

    return 0;
}

int main() {
    int n = 9, k = 3;
    cout << distribute(n, k) << endl;
    return 0;
}
Java
import java.util.Scanner;

public class GfG {
    public static int distribute(int n, int k) {
        int left = 1, right = n;
        boolean firstDist = true;

        while (left <= right) {
            if (firstDist) {
                if (left + k < right) left += k;
                else return right;
            } else {
                if (right - k > left) right -= k;
                else return left;
            }
            firstDist = !firstDist;
        }

        return 0;
    }

    public static void main(String[] args) {
        int n = 9, k = 3;
        System.out.println(distribute(n, k));
    }
}
Python
def distribute(n, k):
    left = 1
    right = n
    firstDist = True

    while left <= right:
        if firstDist:
            if left + k < right:
                left += k
            else:
                return right
        else:
            if right - k > left:
                right -= k
            else:
                return left
        firstDist = not firstDist

if __name__ == '__main__':
    n = 9
    k = 3
    print(distribute(n, k))
C#
// C# implementation
using System;

class GfG {
    static int Distribute(int n, int k) {
        int left = 1, right = n;
        bool firstDist = true;

        while (left <= right) {
            if (firstDist) {
                if (left + k < right) left += k;
                else return right;
            } else {
                if (right - k > left) right -= k;
                else return left;
            }
            firstDist = !firstDist;
        }

        return 0;
    }

    static void Main() {
        int n = 9, k = 3;
        Console.WriteLine(Distribute(n, k));
    }
}
JavaScript
// JavaScript implementation
function distribute(n, k) {
    let left = 1, right = n;
    let firstDist = true;

    while (left <= right) {
        if (firstDist) {
            if (left + k < right) left += k;
            else return right;
        } else {
            if (right - k > left) right -= k;
            else return left;
        }
        firstDist = !firstDist;
    }

    return 0;
}

const n = 9, k = 3;
console.log(distribute(n, k));

Output
6

Mathematical Approach - O(1) Time and O(1) Soace

The given approach uses a calculation-based approach to determine the last person to receive a ticket. It avoids explicitly simulating the distribution process and directly computes the result based on the values of n and k.

Follow the steps to solve the problem:

Perform the following checks in order to determine the last person to receive a ticket:

  • If m is even and r is non-zero, return k * (m/2) + r. This means that there are an even number of complete distributions, and there are some remaining people after that.
  • If m is odd and r is zero, return k * (m/2 + 1). This means that there are an odd number of complete distributions and no remaining people.
  • If m is odd and r is non-zero, return k * (m/2 + 1) + 1. This means that there are an odd number of complete distributions, and there are some remaining people after that.
  • If m is even and r is zero, return k * (m/2) + 1. This means that there are an even number of complete distributions and no remaining people.

If none of the above conditions are satisfied, return an appropriate error value.

C++
#include <iostream>
using namespace std;

int distribute(int n, int k) {
    int m = n / k;
    int r = n % k;

    if (m % 2 == 0 && r)
        return k * (m / 2) + r;
    if (m % 2 && !r)
        return k * (m / 2 + 1);
    if (m % 2 && r)
        return k * (m / 2 + 1) + 1;
    if (m % 2 == 0 && !r)
        return k * (m / 2) + 1;

    return 0;
}

int main() {
    int n = 9, k = 3;
    cout << distribute(n, k) << endl;
    return 0;
}
Java
import java.util.*;

public class GfG {
    public static int distribute(int n, int k) {
        int m = n / k;
        int r = n % k;

        if (m % 2 == 0 && r != 0)
            return k * (m / 2) + r;
        if (m % 2 != 0 && r == 0)
            return k * (m / 2 + 1);
        if (m % 2 != 0 && r != 0)
            return k * (m / 2 + 1) + 1;
        if (m % 2 == 0 && r == 0)
            return k * (m / 2) + 1;

        return 0;
    }

    public static void main(String[] args) {
        int n = 9, k = 3;
        System.out.println(distribute(n, k));
    }
}
Python
def distribute(n, k):
    m = n // k
    r = n % k

    if m % 2 == 0 and r:
        return k * (m // 2) + r
    if m % 2 and not r:
        return k * (m // 2 + 1)
    if m % 2 and r:
        return k * (m // 2 + 1) + 1
    if m % 2 == 0 and not r:
        return k * (m // 2) + 1

    return 0

n = 9
k = 3
print(distribute(n, k))
C#
// C# implementation
using System;

class GfG {
    static int Distribute(int n, int k) {
        int m = n / k;
        int r = n % k;

        if (m % 2 == 0 && r != 0)
            return k * (m / 2) + r;
        if (m % 2 != 0 && r == 0)
            return k * (m / 2 + 1);
        if (m % 2 != 0 && r != 0)
            return k * (m / 2 + 1) + 1;
        if (m % 2 == 0 && r == 0)
            return k * (m / 2) + 1;

        return 0;
    }

    static void Main() {
        int n = 9, k = 3;
        Console.WriteLine(Distribute(n, k));
    }
}
JavaScript
// JavaScript implementation
function distribute(n, k) {
    let m = Math.floor(n / k);
    let r = n % k;

    if (m % 2 === 0 && r !== 0)
        return k * (m / 2) + r;
    if (m % 2 !== 0 && r === 0)
        return k * (Math.floor(m / 2) + 1);
    if (m % 2 !== 0 && r !== 0)
        return k * (Math.floor(m / 2) + 1) + 1;
    if (m % 2 === 0 && r === 0)
        return k * (m / 2) + 1;

    return 0;
}

let n = 9, k = 3;
console.log(distribute(n, k));

Output
6

Time complexity: O(1), because the calculations and checks performed are constant time operations. 
Auxiliary space: O(1), as there is constant space used.


Similar Reads