Minimum time required to fill given N slots
Last Updated :
23 Jul, 2025
Given an integer N which denotes the number of slots, and an array arr[] consisting of K integers in the range [1, N] . Each element of the array are in the range [1, N] which represents the indices of the filled slots. At each unit of time, the index with filled slot fills the adjacent empty slots. The task is to find the minimum time taken to fill all the N slots.
Examples:
Input: N = 6, K = 2, arr[] = {2, 6}
Output: 2
Explanation:
Initially there are 6 slots and the indices of the filled slots are slots[] = {0, 2, 0, 0, 0, 6}, where 0 represents unfilled.
After 1 unit of time, slots[] = {1, 2, 3, 0, 5, 6}
After 2 units of time, slots[] = {1, 2, 3, 4, 5, 6}
Therefore, the minimum time required is 2.
Input: N = 5, K = 5, arr[] = {1, 2, 3, 4, 5}
Output: 0
Minimum time required to fill given N slots using Level Order Traversal:
To solve the given problem, the idea is to perform Level Order Traversal on the given N slots using a Queue. Follow the steps below to solve the problem:
- Initialize a variable, say time as 0, and an auxiliary array visited[] to mark the filled indices in each iteration.
- Now, push the indices of filled slots given in array arr[] in a queue and mark them as visited.
- Now, iterate until the queue is not empty and perform the following steps:
- Remove the front index i from the queue and if the adjacent slots (i - 1) and (i + 1) are in the range [1, N] and are unvisited, then mark them as visited and push them into the queue.
- If any of the non visited index becomes visited in the current process Increment the time by 1 .
- After completing the above steps, print the value of (time - 1) as the minimum time required to fill all the slots.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum
// time to fill all the slots
void minTime(vector<int> arr, int N, int K)
{
// Stores visited slots
queue<int> q;
// Checks if a slot is visited or not
vector<bool> vis(N + 1, false);
int time = 0;
// Insert all filled slots
for (int i = 0; i < K; i++) {
q.push(arr[i]);
vis[arr[i]] = true;
}
// Iterate until queue is
// not empty
while (q.size() > 0) {
// Iterate through all slots
// in the queue
bool op = false;
for (int i = 0; i < q.size(); i++) {
// Front index
int curr = q.front();
q.pop();
// If previous slot is
// present and not visited
if (curr - 1 >= 1 &&
!vis[curr - 1]) {
op = true;
vis[curr - 1] = true;
q.push(curr - 1);
}
// If next slot is present
// and not visited
if (curr + 1 <= N &&
!vis[curr + 1]) {
op = true;
vis[curr + 1] = true;
q.push(curr + 1);
}
}
// Increment the time
// at each level
time+=op;
}
// Print the answer
cout << (time);
}
// Driver Code
int main()
{
int N = 6;
vector<int> arr = { 2,6 };
int K = arr.size();
// Function Call
minTime(arr, N, K);
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to return the minimum
// time to fill all the slots
public static void minTime(int arr[],
int N, int K)
{
// Stores visited slots
Queue<Integer> q = new LinkedList<>();
// Checks if a slot is visited or not
boolean vis[] = new boolean[N + 1];
int time = 0;
// Insert all filled slots
for (int i = 0; i < K; i++) {
q.add(arr[i]);
vis[arr[i]] = true;
}
// Iterate until queue is
// not empty
while (q.size() > 0) {
// Iterate through all slots
// in the queue
for (int i = 0; i < q.size(); i++) {
// Front index
int curr = q.poll();
// If previous slot is
// present and not visited
if (curr - 1 >= 1 &&
!vis[curr - 1]) {
vis[curr - 1] = true;
q.add(curr - 1);
}
// If next slot is present
// and not visited
if (curr + 1 <= N &&
!vis[curr + 1]) {
vis[curr + 1] = true;
q.add(curr + 1);
}
}
// Increment the time
// at each level
time++;
}
// Print the answer
System.out.println(time - 1);
}
// Driver Code
public static void main(String[] args)
{
int N = 6;
int arr[] = { 2, 6 };
int K = arr.length;
// Function Call
minTime(arr, N, K);
}
}
Python3
# Python3 program for the above approach
# Function to return the minimum
# time to fill all the slots
def minTime(arr, N, K):
# Stores visited slots
q = []
# Checks if a slot is visited or not
vis = [False] * (N + 1)
time = 0
# Insert all filled slots
for i in range(K):
q.append(arr[i])
vis[arr[i]] = True
# Iterate until queue is
# not empty
while (len(q) > 0):
# Iterate through all slots
# in the queue
for i in range(len(q)):
# Front index
curr = q[0]
q.pop(0)
# If previous slot is
# present and not visited
if (curr - 1 >= 1 and vis[curr - 1] == 0):
vis[curr - 1] = True
q.append(curr - 1)
# If next slot is present
# and not visited
if (curr + 1 <= N and vis[curr + 1] == 0):
vis[curr + 1] = True
q.append(curr + 1)
# Increment the time
# at each level
time += 1
# Print the answer
print(time - 1)
# Driver Code
N = 6
arr = [ 2, 6 ]
K = len(arr)
# Function Call
minTime(arr, N, K)
# This code is contributed by susmitakundugoaldanga
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to return the minimum
// time to fill all the slots
static void minTime(List<int> arr, int N, int K)
{
// Stores visited slots
Queue<int> q = new Queue<int>();
// Checks if a slot is visited or not
int []vis = new int[N + 1];
Array.Clear(vis, 0, vis.Length);
int time = 0;
// Insert all filled slots
for (int i = 0; i < K; i++)
{
q.Enqueue(arr[i]);
vis[arr[i]] = 1;
}
// Iterate until queue is
// not empty
while (q.Count > 0)
{
// Iterate through all slots
// in the queue
for (int i = 0; i < q.Count; i++)
{
// Front index
int curr = q.Peek();
q.Dequeue();
// If previous slot is
// present and not visited
if (curr - 1 >= 1 &&
vis[curr - 1]==0)
{
vis[curr - 1] = 1;
q.Enqueue(curr - 1);
}
// If next slot is present
// and not visited
if (curr + 1 <= N &&
vis[curr + 1] == 0)
{
vis[curr + 1] = 1;
q.Enqueue(curr + 1);
}
}
// Increment the time
// at each level
time++;
}
// Print the answer
Console.WriteLine(time-1);
}
// Driver Code
public static void Main()
{
int N = 6;
List<int> arr = new List<int>() { 2, 6 };
int K = arr.Count;
// Function Call
minTime(arr, N, K);
}
}
// THIS CODE IS CONTRIBUTED BY SURENDRA_GANGWAR.
JavaScript
<script>
// Javascript program for the above approach
// Function to return the minimum
// time to fill all the slots
function minTime(arr, N, K)
{
// Stores visited slots
var q = [];
// Checks if a slot is visited or not
var vis = Array(N + 1).fill(false);
var time = 0;
// Insert all filled slots
for (var i = 0; i < K; i++) {
q.push(arr[i]);
vis[arr[i]] = true;
}
// Iterate until queue is
// not empty
while (q.length > 0) {
// Iterate through all slots
// in the queue
for (var i = 0; i < q.length; i++) {
// Front index
var curr = q[0];
q.pop();
// If previous slot is
// present and not visited
if (curr - 1 >= 1 &&
!vis[curr - 1]) {
vis[curr - 1] = true;
q.push(curr - 1);
}
// If next slot is present
// and not visited
if (curr + 1 <= N &&
!vis[curr + 1]) {
vis[curr + 1] = true;
q.push(curr + 1);
}
}
// Increment the time
// at each level
time++;
}
// Print the answer
document.write(time - 1);
}
// Driver Code
var N = 6;
var arr = [2, 6];
var K = arr.length;
// Function Call
minTime(arr, N, K);
// This code is contributed by noob2000.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Minimum time required to fill given N slots using Sorting:
Another approach to solve this problem can be done by sorting the array of filled slots and then iterating through the array to find the maximum distance between adjacent filled slots. The minimum time required to fill all the slots would be equal to the maximum distance between adjacent filled slots.
- Declare a function minTime() which takes three arguments: vector of integers arr, integer N, and integer K.
- Sort the vector arr[] using the sort function from STL.
- Declare an integer variable maxDist and initialize it to zero.
- Traverse the sorted array arr and find the maximum distance between adjacent slots, store this distance in the maxDist variable.
- Check the distance from the first and last slot to the closest filled slot and store the maximum of these two distances in the maxDist variable.
- Subtract 1 from maxDist to account for the time it takes to fill each slot.
- Print the value of maxDist.
Below is the implementation of this approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum
// time to fill all the slots
void minTime(vector<int> arr, int N, int K)
{
// Sort the array
sort(arr.begin(), arr.end());
int maxDist = 0;
// Find maximum distance
// between adjacent slots
for (int i = 1; i < K; i++) {
maxDist = max(maxDist, arr[i] - arr[i - 1] - 1);
}
// an area is being filled with both sides it will take
// half time to fill that area
maxDist = (maxDist + 1) / 2;
// Check the distance from the
// first and last slot to the
// closest filled slot
maxDist = max(maxDist, arr[0] - 1);
maxDist = max(maxDist, N - arr[K - 1]);
// Print the answer
cout << maxDist;
}
// Driver Code
int main()
{
int N = 6;
vector<int> arr = { 2, 6 };
int K = arr.size();
// Function Call
minTime(arr, N, K);
}
Java
import java.util.*;
public class Main {
// Function to return the minimum
// time to fill all the slots
static void minTime(List<Integer> arr, int N, int K) {
// Sort the array
Collections.sort(arr);
int maxDist = 0;
// Find maximum distance
// between adjacent slots
for (int i = 1; i < K; i++) {
maxDist = Math.max(maxDist, arr.get(i) - arr.get(i - 1) - 1);
}
// Check the distance from the
// first and last slot to the
// closest filled slot
maxDist = Math.max(maxDist, arr.get(0) - 1);
maxDist = Math.max(maxDist, N - arr.get(K - 1));
// Subtract 1 from maxDist to
// account for the time it takes
// to fill each slot
maxDist--;
// Print the answer
System.out.println(maxDist);
}
// Driver Code
public static void main(String[] args) {
int N = 6;
List<Integer> arr = new ArrayList<Integer>();
arr.add(2);
arr.add(6);
int K = arr.size();
// Function Call
minTime(arr, N, K);
}
}
Python
# Function to return the minimum
# time to fill all the slots
def minTime(arr, N, K):
# Sort the array
arr.sort()
maxDist = 0
# Find maximum distance
# between adjacent slots
for i in range(1, K):
maxDist = max(maxDist, arr[i] - arr[i - 1] - 1)
# Check the distance from the
# first and last slot to the
# closest filled slot
maxDist = max(maxDist, arr[0] - 1)
maxDist = max(maxDist, N - arr[K - 1])
# Subtract 1 from maxDist to
# account for the time it takes
# to fill each slot
maxDist -= 1
# Print the answer
print(maxDist)
# Driver Code
if __name__ == "__main__":
N = 6
arr = [2, 6]
K = len(arr)
# Function Call
minTime(arr, N, K)
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
// Function to return the minimum
// time to fill all the slots
public static void MinTime(List<int> arr, int N, int K)
{
// Sort the array
arr.Sort();
int maxDist = 0;
// Find maximum distance
// between adjacent slots
for (int i = 1; i < K; i++)
{
maxDist = Math.Max(maxDist, arr[i] - arr[i - 1] - 1);
}
// Check the distance from the
// first and last slot to the
// closest filled slot
maxDist = Math.Max(maxDist, arr[0] - 1);
maxDist = Math.Max(maxDist, N - arr[K - 1]);
// Subtract 1 from maxDist to
// account for the time it takes
// to fill each slot
maxDist--;
// Print the answer
Console.WriteLine(maxDist);
}
public static void Main()
{
int N = 6;
List<int> arr = new List<int> { 2, 6 };
int K = arr.Count;
// Function Call
MinTime(arr, N, K);
}
}
JavaScript
// Function to calculate the minimum time to fill all slots
function minTime(arr, N, K) {
// Sort the array of slots in ascending order
arr.sort((a, b) => a - b);
let maxDist = 0;
// Calculate the maximum distance between adjacent slots
for (let i = 1; i < K; i++) {
maxDist = Math.max(maxDist, arr[i] - arr[i - 1] - 1);
}
// Check the distance from the first and last slot to the closest filled slot
maxDist = Math.max(maxDist, arr[0] - 1);
maxDist = Math.max(maxDist, N - arr[K - 1]);
// Subtract 1 from maxDist to account for the time it takes to fill each slot
maxDist--;
// Print the calculated minimum time
console.log(maxDist);
}
//Driver code
// Total number of slots
const N = 6;
// Array representing filled slots
const arr = [2, 6];
// Number of filled slots (K)
const K = arr.length;
// Call the minTime function with the given inputs
minTime(arr, N, K);
Output:-
2
Time Complexity: O(KlogK), then it loops through the vector once to calculate the maximum distance between adjacent slots and twice to calculate the distance from the first and last slot to the closest filled slot, which takes O(K) time. Therefore, the overall time complexity is O(KlogK).
Auxiliary Space: O(1).
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