Last when k numbers are Repeatedly Removed from both ends
Last Updated :
23 Jul, 2025
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));
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));
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));
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem