Minimum steps required to reach the end of Array with a given capacity
Last Updated :
23 Jul, 2025
Given an array arr[] of size n. You will have to traverse the array from left to right deducting each element of the array from the initial capacity, such that your initial capacity should never go below 0. In case, the current capacity is less than the current element, we can traverse back to the start of the array to refill our capacity, and then start where we left off, the task is to return the minimum number of steps required to reach the end of the array, given you are initially at the start of the array or index (-1).
Examples:
Input: arr = [3, 3, 4, 4], capacity = 7
Output: 14
Explanation: Start at the index 1:
- Walk to index 0 (1 step) and subtract it, capacity = 4
- Walk to index 1 (1 step) and subtract it. capacity = 1
- Since after subtraction of element at index 2 capacity = -3 which is negative so we have to return to index -1(2 steps) and capacity becomes 7 again.
- Walk to index 2 (3 steps) and subtract it. capacity = 3
- Since after subtraction of element at index 3 capacity = -1 which is negative so we have to return to index -1(3 steps) and capacity becomes 7 again.
- Walk to index 3 (4 steps) and subtract it.capacity = 3
- Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.
Input: arr = [1, 1, 1, 4, 2, 3], capacity = 4
Output: 30
Explanation: Start at the index 1:
- subtract arr 0, 1, and 2 (3 steps). Return to index -1(3 steps).
- subtract arr 3 (4 steps). Return to index -1(4 steps).
- subtract arr 4 (5 steps). Return to index -1 (5 steps).
- subtract arr 5 (6 steps).
- Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.
Input: arr = [8, 8, 8, 8, 8], capacity = 10
Output: 25
Explanation: You have to return to index -1 after each iteration.
Steps needed = 25.
Naive Approach: The basic way to solve the problem is as follows:
We can declare a prefix array and store the results before hand of each and every arr at place. Then using binary search we could search for our specified fruit and calculate the steps in the whole iteration.
Steps that were to follow the above approach:
- Call minSteps function to return the minimum number of steps to reach the end of the array.
- Create pre array which contains the prefix sum up to that point in the input array.
- Then, loop until we reach the end of the array, and do the following:
- Binary search for the current range we can go.
- Add up to the answer, and return it ans+n, once the end is reached of the array.
Below is the code to implement the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
int minSteps(vector<int>& arr, int c)
{
int n = arr.size();
// Find the size of array
vector<int> pre(n, 0);
// Declare a prefix sum vector for
// storing the result before hand
pre[0] = arr[0];
for (int i = 1; i < n; i++)
pre[i] = pre[i - 1] + arr[i];
// Fill the prefix sum vector
int curr = 0, sc = c, ans = 0;
while (1) {
int ind = lower_bound(pre.begin(), pre.end(), sc)
- pre.begin();
// Finding the lowerbound using
// binary search and substracting
// the perviously computed value
if (ind >= n)
return ans + n;
// If index goes beyond the array
// size then return the size
// summed up with array size
else if (pre[ind] == sc) {
// If element at prefix array
// is equal to source then
// check if index has reached
// the last element
if (ind == n - 1)
return ans + n;
curr = ind;
}
else
curr = ind - 1;
sc = c + pre[curr];
// Add prefix value at current
// index to source
ans += (2 * (curr + 1));
}
return 0;
}
// Drivers code
int main()
{
vector<int> v{ 8, 8, 8, 8, 8 };
int c = 10;
// Function Call
cout << minSteps(v, c) << endl;
return 0;
}
Java
// Java code for the above approach
import java.util.*;
class GFG {
// lower_bound utility function
static int lower_bound(int n, int target,
List<Integer> pre)
{
int low = 0, high = n - 1;
int ans = n;
while (low <= high) {
int mid = (low + high) / 2;
// reduce the search space on the right
// if mid element is greater than or equal to
// target
if (pre.get(mid) >= target) {
ans = mid;
high = mid - 1;
}
// reduce the search space on the left
// if middle element is lesser than target
else {
low = mid + 1;
}
}
return ans;
}
static int minSteps(List<Integer> arr, int c)
{
// Find the size of the array
int n = arr.size();
// Declare a prefix sum List for
// storing the result before hand
List<Integer> pre = new ArrayList<>();
for (int i = 0; i < n; i++) {
pre.add(0);
}
pre.set(0, arr.get(0));
// Fill the prefix sum List
for (int i = 1; i < n; i++) {
pre.set(i, pre.get(i - 1) + arr.get(i));
}
int curr = 0, sc = c, ans = 0;
while (true) {
// Finding the lowerbound using
// binary search and substracting
// the perviously computed value
int ind = lower_bound(n, sc, pre);
// If index goes beyond the array
// size then return the size
// summed up with array size
if (ind >= n) {
return ans + n;
}
else if (pre.get(ind) == sc) {
// If element at prefix array
// is equal to source then
// check if index has reached
// the last element
if (ind == n - 1)
return ans + n;
curr = ind;
}
else
curr = ind - 1;
sc = c + pre.get(curr);
// Add prefix value at current
// index to source
ans += (2 * (curr + 1));
}
}
// Drivers code
public static void main(String[] args)
{
List<Integer> v = Arrays.asList(8, 8, 8, 8, 8);
int c = 10;
// Function Call
System.out.println(minSteps(v, c));
}
}
// This code is contributed by ragul21
Python3
# python code for the above approach:
import bisect
def minSteps(arr, c):
n = len(arr)
# Find the size of the array
pre = [0] * n
# Declare a prefix sum list for storing the result beforehand
pre[0] = arr[0]
for i in range(1, n):
pre[i] = pre[i - 1] + arr[i]
# Fill the prefix sum list
curr = 0
sc = c
ans = 0
while True:
ind = bisect.bisect_left(pre, sc)
# Finding the lower bound using binary search and subtracting
# the previously computed value
if ind >= n:
return ans + n
# If the index goes beyond the array size, then return the size
# summed up with array size
elif pre[ind] == sc:
# If the element at the prefix array is equal to the source, then
# check if the index has reached the last element
if ind == n - 1:
return ans + n
curr = ind
else:
curr = ind - 1
sc = c + pre[curr]
# Add prefix value at the current index to the source
ans += 2 * (curr + 1)
# Drivers code
if __name__ == "__main__":
v = [8, 8, 8, 8, 8]
c = 10
# Function Call
print(minSteps(v, c))
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
public class GFG {
// lower_bound utility function
static int lower_bound(int n, int target, List<int> pre)
{
int low = 0, high = n - 1;
int ans = n;
while (low <= high) {
int mid = (low + high) / 2;
// reduce the search space on the right
// if mid element is greater than or equal to
// target
if (pre[mid] >= target) {
ans = mid;
high = mid - 1;
}
// reduce the search space on the left
// if middle element is lesser than target
else {
low = mid + 1;
}
}
return ans;
}
static int minSteps(List<int> arr, int c)
{
// Find the size of array
int n = arr.Count;
// Declare a prefix sum vector for
// storing the result before hand
List<int> pre = new List<int>();
for (int i = 0; i < n; i++) {
pre.Add(0);
}
pre[0] = arr[0];
// Fill the prefix sum list
for (int i = 1; i < n; i++) {
pre[i] = pre[i - 1] + arr[i];
}
int curr = 0, sc = c, ans = 0;
while (true) {
// Finding the lowerbound using
// binary search and substracting
// the perviously computed value
int ind = lower_bound(n, sc, pre);
// If index goes beyond the array
// size then return the size
// summed up with array size
if (ind >= n) {
return ans + n;
}
else if (pre[ind] == sc) {
// If element at prefix array
// is equal to source then
// check if index has reached
// the last element
if (ind == n - 1)
return ans + n;
curr = ind;
}
else
curr = ind - 1;
sc = c + pre[curr];
// Add prefix value at current
// index to source
ans += (2 * (curr + 1));
}
// return 0;
}
// Drivers code
public static void Main()
{
List<int> v = new List<int>() { 8, 8, 8, 8, 8 };
int c = 10;
// Function Call
Console.WriteLine(minSteps(v, c));
}
}
// This code is contributed by ragul21
JavaScript
// JavaScript code for the above approach:
function minSteps(arr, c) {
const n = arr.length;
// Find the size of array
const pre = new Array(n).fill(0);
// Declare a prefix sum vector for
// storing the result beforehand
pre[0] = arr[0];
for (let i = 1; i < n; i++)
pre[i] = pre[i - 1] + arr[i];
// Fill the prefix sum vector
let curr = 0,
sc = c,
ans = 0;
while (true) {
const ind = pre.findIndex((elem) => elem >= sc);
// Finding the lower bound using
// linear search and subtracting
// the previously computed value
if (ind === -1 || ind >= n)
return ans + n;
// If index goes beyond the array
// size then return the size
// summed up with array size
else if (pre[ind] === sc) {
// If element at prefix array
// is equal to source then
// check if index has reached
// the last element
if (ind === n - 1)
return ans + n;
curr = ind;
} else
curr = ind - 1;
sc = c + pre[curr];
// Add prefix value at current
// index to source
ans += 2 * (curr + 1);
}
return 0;
}
// Drivers code
const v = [8, 8, 8, 8, 8];
const c = 10;
// Function Call
console.log(minSteps(v, c));
Time Complexity: O(n + log n), this is for prefix sum and then binary search.
Auxiliary Space: O(n), for declaring a prefix array.
Efficient Approach: To solve the problem follow the below idea:
We can substract elements going in order from left to right and get back to index -1 once capacity becomes negative and calculate the whole iteration of going to index -1 and coming back to the unsubstracted element. This will be a simple linear traversal.
Steps to implement the above approach:
- Loop over the entire array from left to right and do the following:
- If the current capacity is less than the current array element,
- increase steps for both-way movement, and add 1 to move to the next element.
- else, increment the steps and subtract the element from the total capacity left.
- Finally, return the total number of steps traveled.
Below is the code to implement the above approach:
C++
// C++ Code for the above approach:
#include <bits/stdc++.h>
using namespace std;
int subelement(vector<int>& arr, int capacity)
{
int steps = 0;
// Declare a steps variable for
// keeping the count of steps
int c = capacity;
for (int i = 0; i < arr.size(); i++) {
if (c < arr[i]) {
// If our capapcity is less
// than current array element
// increment the steps for
// bi-directional traversal
// and adding 1 to move to
// next element
steps = steps + ((i * 2) + 1);
c = capacity;
// Making the capacity element
// as it was originally
c = c - arr[i];
// Subtracting the current
// position value from
// capacity
}
else {
c = c - arr[i];
// If capacity is greater than
// current element we simply
// subtract the same from
// capacity
steps++;
// Incrementing the steps
// for each iteration
}
}
return steps;
}
// Drivers code
int main()
{
vector<int> v{ 8, 8, 8, 8, 8 };
int c = 10;
// Function Call
cout << subelement(v, c) << endl;
return 0;
}
Java
// Java code for the above approach
import java.util.*;
class Main {
public static int subelement(List<Integer> arr, int capacity) {
int steps = 0;
// Declare a steps variable for
// keeping the count of steps
int c = capacity;
for (int i = 0; i < arr.size(); i++) {
if (c < arr.get(i)) {
// If our capacity is less
// than the current array element
// increment the steps for
// bi-directional traversal
// and add 1 to move to
// next element
steps = steps + ((i * 2) + 1);
c = capacity;
// Making the capacity element
// as it was originally
c = c - arr.get(i);
// Subtracting the current
// position value from
// capacity
} else {
c = c - arr.get(i);
// If capacity is greater than
// current element, we simply
// subtract the same from
// capacity
steps++;
// Incrementing the steps
// for each iteration
}
}
return steps;
}
public static void main(String[] args) {
List<Integer> v = new ArrayList<>(Arrays.asList(8, 8, 8, 8, 8));
int c = 10;
// Function call
System.out.println(subelement(v, c));
}
}
// This code is contributed by Vaibhav Nandan
Python
# Nikunj Sonigara
def subelement(arr, capacity):
steps = 0
c = capacity
for i in range(len(arr)):
if c < arr[i]:
steps = steps + ((i * 2) + 1)
c = capacity
c = c - arr[i]
else:
c = c - arr[i]
steps += 1
return steps
# Driver code
if __name__ == "__main__":
v = [8, 8, 8, 8, 8]
c = 10
# Function Call
print(subelement(v, c))
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
public class GFG {
public static int subelement(List<int> arr,
int capacity)
{
int steps = 0;
// Declare a steps variable for
// keeping the count of steps
int c = capacity;
for (int i = 0; i < arr.Count; i++) {
if (c < arr[i]) {
// If our capacity is less
// than the current array element
// increment the steps for
// bi-directional traversal
// and add 1 to move to
// next element
steps = steps + ((i * 2) + 1);
c = capacity;
// Making the capacity element
// as it was originally
c = c - arr[i];
// Subtracting the current
// position value from
// capacity
}
else {
c = c - arr[i];
// If capacity is greater than
// current element, we simply
// subtract the same from
// capacity
steps++;
// Incrementing the steps
// for each iteration
}
}
return steps;
}
public static void Main(String[] args)
{
List<int> v = new List<int>() { 8, 8, 8, 8, 8 };
int c = 10;
// Function call
Console.WriteLine(subelement(v, c));
}
}
// This code is contributed by ragul21
JavaScript
// Javascript code for the above approach
function subelement(arr, capacity) {
let steps = 0;
// Declare a steps variable for
// keeping the count of steps
let c = capacity;
for (let i = 0; i < arr.length; i++) {
if (c < arr[i]) {
// If our capacity is less
// than the current array element
// increment the steps for
// bi-directional traversal
// and add 1 to move to
// next element
steps = steps + ((i * 2) + 1);
c = capacity;
// Making the capacity element
// as it was originally
c = c - arr[i];
// Subtracting the current
// position value from
// capacity
} else {
c = c - arr[i];
// If capacity is greater than
// current element, we simply
// subtract the same from
// capacity
steps++;
// Incrementing the steps
// for each iteration
}
}
return steps;
}
const v = [8, 8, 8, 8, 8]
const c = 10
console.log(subelement(v, c));
// This code is contributed by ragul21
Time Complexity: O(n), this is due to linear traversal.
Space Complexity: O(1), as we don't need any extra space.
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