Maximum index a pointer can reach in N steps by avoiding a given index B
Last Updated :
29 Nov, 2023
Given two integers N and B, the task is to print the maximum index a pointer, starting from 0th index can reach in an array of natural numbers(i.e., 0, 1, 2, 3, 4, 5...), say arr[], in N steps without placing itself at index B at any point.
In each step, the pointer can move from the Current Index to a Jumping Index or can remain at the Current Index.
Jumping Index = Current Index + Step Number
Examples:
Input: N = 3, B = 2
Output: 6
Explanation:

Step 1:
Current Index = 0
Step Number = 1
Jumping Index = 0 + 1 = 1
Step 2:Current Index = 1
Step Number = 2
Jumping Index = 1 + 2 = 3
Step 3:
Current Index = 3
Step Number = 3
Jumping Index = 3 + 3 = 6
Therefore, the maximum index that can be reached is 6.
Input: N = 3, B = 1
Output: 5
Explanation:

Step 1:
Current Index = 0
Step Number = 1
Jumping Index = 0 + 1 = 1But this is bad index. So pointer remains at the Current Index.
Step 2:
Current Index = 0
Step Number = 2
Jumping Index = 0 + 2 = 2
Step 3:
Current Index = 2
Step Number = 3
Jumping Index = 2 + 3 = 5
Therefore, the maximum index that can be reached is 5.
Naive Approach: The simplest approach to solve the problem is to calculate the maximum index by considering two possibilities for every Current Index, either to move the pointer by Step Number or by remaining at the Current Index, and generate all possible combinations. Finally, print the maximum index obtained.
Algorithm
Take two integers N and B as input.
Define a recursive function that takes four arguments
Inside the function:
a. If stepNumber is equal to N, check if currentIndex is equal to B.
If it is, return -1, otherwise, return currentIndex.
b. If currentIndex is equal to B, return -1.
c. Otherwise, consider three possibilities for the next step:
move the pointer to the left (currentIndex - 1)
stay at the current index (currentIndex)
move the pointer to the right (currentIndex + 1).
return the maximum valid index among the three possibilities.
Call the function with currentIndex = 0, stepNumber = 0, N, and B as arguments.
Print the maximum index obtained.
Implementation
C++
#include <iostream>
#include <cmath> // for pow function
using namespace std;
int max_reachable_index(int N, int B) {
int max_index = 0; // initialize max_index to 0
for (int i = 0; i < N; i++) { // loop through all indices in the list
if (i != B) { // skip the index B
max_index += pow(2, N-i-1); // add 2^(N-i-1) to max_index
}
}
return max_index; // return the calculated max_index
}
int main() {
int N = 3;
int B = 2;
cout << max_reachable_index(N, B) << endl; // output the calculated max_index
return 0;
}
Java
import java.lang.Math;
public class Main {
public static int max_reachable_index(int N, int B) {
int max_index = 0;
for (int i = 0; i < N; i++) {
if (i != B) {
max_index += Math.pow(2, N-i-1);
}
}
return max_index;
}
public static void main(String[] args) {
int N = 3;
int B = 2;
System.out.println(max_reachable_index(N, B));
}
}
Python
import math
def max_reachable_index(N, B):
max_index = 0
for i in range(N):
if i != B:
max_index += math.pow(2, N-i-1)
return int(max_index)
N = 3
B = 2
print(max_reachable_index(N, B))
C#
using System;
public class Program {
public static int max_reachable_index(int N, int B) {
int max_index = 0;
for (int i = 0; i < N; i++) {
if (i != B) {
max_index += (int)Math.Pow(2, N-i-1);
}
}
return max_index;
}
public static void Main() {
int N = 3;
int B = 2;
Console.WriteLine(max_reachable_index(N, B));
}
}
JavaScript
function max_reachable_index(N, B) {
let max_index = 0;
for (let i = 0; i < N; i++) {
if (i !== B) {
max_index += Math.pow(2, N - i - 1);
}
}
return max_index;
}
const N = 3;
const B = 2;
console.log(max_reachable_index(N, B));
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach:
Calculate the maximum index that can be reached within the given steps. If the 0th Index can be reached from the maximum index by avoiding the bad index, print the result. Otherwise, repeat the procedure by decrementing the maximum index by 1.
Below are the steps:
- Calculate the maximum index that can be reached in N steps by calculating the sum of the first N natural numbers.
- Assign the value of the calculated maximum index to the Current Index.
- Keep decrementing Current Index by Step Number and Step Number by 1 until one of them becomes negative.
- After every decrement, check if the Current Index is equal to B or not. If found to be true, revert the changes made on the Current Index.
- If the Current Index reaches 0 successfully, print the current value of the maximum index as the answer.
- Otherwise, decrement the value of the maximum index by 1 and repeat from step 2.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum
// index the pointer can reach
void maximumIndex(int N, int B)
{
int max_index = 0;
// Calculate maximum possible
// index that can be reached
for (int i = 1; i <= N; i++) {
max_index += i;
}
int current_index = max_index, step = N;
while (1) {
// Check if current index and step
// both are greater than 0 or not
while (current_index > 0 && N > 0) {
// Decrement current_index by step
current_index -= N;
// Check if current index is
// equal to B or not
if (current_index == B) {
// Restore to previous index
current_index += N;
}
// Decrement step by one
N--;
}
// If it reaches the 0th index
if (current_index <= 0) {
// Print result
cout << max_index << endl;
break;
}
// If max index fails to
// reach the 0th index
else {
N = step;
// Store max_index - 1 in current index
current_index = max_index - 1;
// Decrement max index
max_index--;
// If current index is equal to B
if (current_index == B) {
current_index = max_index - 1;
// Decrement current index
max_index--;
}
}
}
}
// Driver Code
int main()
{
int N = 3, B = 2;
maximumIndex(N, B);
return 0;
}
Java
// Java program for
// the above approach
import java.util.*;
class GFG{
// Function to find the maximum
// index the pointer can reach
static void maximumIndex(int N,
int B)
{
int max_index = 0;
// Calculate maximum possible
// index that can be reached
for (int i = 1; i <= N; i++)
{
max_index += i;
}
int current_index = max_index,
step = N;
while (true)
{
// Check if current index
// and step both are greater
// than 0 or not
while (current_index > 0 &&
N > 0)
{
// Decrement current_index
// by step
current_index -= N;
// Check if current index
// is equal to B or not
if (current_index == B)
{
// Restore to previous
// index
current_index += N;
}
// Decrement step by one
N--;
}
// If it reaches the 0th index
if (current_index <= 0)
{
// Print result
System.out.print(max_index + "\n");
break;
}
// If max index fails to
// reach the 0th index
else
{
N = step;
// Store max_index - 1 in
// current index
current_index = max_index - 1;
// Decrement max index
max_index--;
// If current index is
// equal to B
if (current_index == B)
{
current_index = max_index - 1;
// Decrement current index
max_index--;
}
}
}
}
// Driver Code
public static void main(String[] args)
{
int N = 3, B = 2;
maximumIndex(N, B);
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 program for the above approach
# Function to find the maximum
# index the pointer can reach
def maximumIndex(N, B):
max_index = 0
# Calculate maximum possible
# index that can be reached
for i in range(1, N + 1):
max_index += i
current_index = max_index
step = N
while (1):
# Check if current index and step
# both are greater than 0 or not
while (current_index > 0 and N > 0):
# Decrement current_index by step
current_index -= N
# Check if current index is
# equal to B or not
if (current_index == B):
# Restore to previous index
current_index += N
# Decrement step by one
N -= 1
# If it reaches the 0th index
if (current_index <= 0):
# Print result
print(max_index)
break
# If max index fails to
# reach the 0th index
else:
N = step
# Store max_index - 1 in current index
current_index = max_index - 1
# Decrement max index
max_index -= 1
# If current index is equal to B
if (current_index == B):
current_index = max_index - 1
# Decrement current index
max_index -= 1
# Driver Code
if __name__ == '__main__':
N = 3
B = 2
maximumIndex(N, B)
# This code is contributed by mohit kumar 29
C#
// C# program for the
// above approach
using System;
class GFG{
// Function to find the maximum
// index the pointer can reach
static void maximumIndex(int N,
int B)
{
int max_index = 0;
// Calculate maximum possible
// index that can be reached
for(int i = 1; i <= N; i++)
{
max_index += i;
}
int current_index = max_index,
step = N;
while (true)
{
// Check if current index
// and step both are greater
// than 0 or not
while (current_index > 0 &&
N > 0)
{
// Decrement current_index
// by step
current_index -= N;
// Check if current index
// is equal to B or not
if (current_index == B)
{
// Restore to previous
// index
current_index += N;
}
// Decrement step by one
N--;
}
// If it reaches the 0th index
if (current_index <= 0)
{
// Print result
Console.Write(max_index + " ");
break;
}
// If max index fails to
// reach the 0th index
else
{
N = step;
// Store max_index - 1 in
// current index
current_index = max_index - 1;
// Decrement max index
max_index--;
// If current index is
// equal to B
if (current_index == B)
{
current_index = max_index - 1;
// Decrement current index
max_index--;
}
}
}
}
// Driver code
public static void Main (String[] args)
{
int N = 3, B = 2;
maximumIndex(N, B);
}
}
// This code is contributed by offbeat
JavaScript
<script>
// Javascript program for the above approach
// Function to find the maximum
// index the pointer can reach
function maximumIndex( N, B)
{
var max_index = 0;
// Calculate maximum possible
// index that can be reached
for (var i = 1; i <= N; i++) {
max_index += i;
}
var current_index = max_index, step = N;
while (1) {
// Check if current index and step
// both are greater than 0 or not
while (current_index > 0 && N > 0) {
// Decrement current_index by step
current_index -= N;
// Check if current index is
// equal to B or not
if (current_index == B) {
// Restore to previous index
current_index += N;
}
// Decrement step by one
N--;
}
// If it reaches the 0th index
if (current_index <= 0) {
// Print result
document.write(max_index + "<br>");;
break;
}
// If max index fails to
// reach the 0th index
else {
N = step;
// Store max_index - 1 in current index
current_index = max_index - 1;
// Decrement max index
max_index--;
// If current index is equal to B
if (current_index == B) {
current_index = max_index - 1;
// Decrement current index
max_index--;
}
}
}
}
// Driver Code
var N = 3, B = 2;
maximumIndex(N, B);
// This code is contributed by rrrtnx.
</script>
Time Complexity: O(N2)
Auxiliary Space: O(1)
Another Efficient Approach - Keep calculating the sum (1 + 2 + 3 + .... ). Since the elements contributing to the sum is monotonically increasing so if you get the sum equals bad index then it means answer will be (sum of natural numbers - 1) else you return the sum
C++
#include <iostream>
// Function to find the maximum index 'N' such that the sum
// of natural numbers from 1 to N is equal to 'B'.
int MaximumIndex(int N, int B) {
int s = 0; // Initialize a variable 's' to keep track of the current sum.
for (int i = 1; i <= N; i++) { // Loop through natural numbers from 1 to N.
s += i; // Add the current number 'i' to the sum 's'.
if (s == B) { // If the sum 's' equals 'B', we found the answer.
// Calculate the sum of natural numbers from 1 to N using the formula.
int sum_of_natural_nos = N * (N + 1) / 2;
return sum_of_natural_nos - 1; // Return N-1 as the maximum index.
}
}
return s; // If we didn't find a match, return the current sum 's'.
}
int main() {
int N = 3;
int B = 1;
std::cout << MaximumIndex(N, B) << std::endl; // Call the function and print the result.
return 0;
}
Java
public class Main {
// Function to find the maximum index 'N' such that the sum
// of natural numbers from 1 to N is equal to 'B'.
public static int MaximumIndex(int N, int B) {
int s = 0; // Initialize a variable 's' to keep track of the current sum.
for (int i = 1; i <= N; i++) { // Loop through natural numbers from 1 to N.
s += i; // Add the current number 'i' to the sum 's'.
if (s == B) { // If the sum 's' equals 'B', we found the answer.
// Calculate the sum of natural numbers from 1 to N using the formula.
int sum_of_natural_nos = N * (N + 1) / 2;
return sum_of_natural_nos - 1; // Return N-1 as the maximum index.
}
}
return s; // If we didn't find a match, return the current sum 's'.
}
public static void main(String[] args) {
int N = 3;
int B = 1;
System.out.println(MaximumIndex(N, B)); // Call the function and print the result.
}
}
Python3
def MaximumIndex(N, B):
s = 0
for i in range(1, N+1):
s += i
if s == B:
sum_of_natural_nos = N*(N+1)//2
return sum_of_natural_nos - 1
return s
# N = 4
# B = 6
# N = 3
# B = 2
N = 3
B = 1
print(MaximumIndex(N, B))
# This code is contributed by Swagato Chakraborty(swagatochakraborty123)
C#
using System;
class Program
{
// Function to find the maximum index 'N' such that the sum
// of natural numbers from 1 to N is equal to 'B'.
static int MaximumIndex(int N, int B)
{
int s = 0; // Initialize a variable 's' to keep track of the current sum.
for (int i = 1; i <= N; i++) // Loop through natural numbers from 1 to N.
{
s += i; // Add the current number 'i' to the sum 's'.
if (s == B) // If the sum 's' equals 'B', we found the answer.
{
// Calculate the sum of natural numbers from 1 to N using the formula.
int sum_of_natural_nos = (N * (N + 1)) / 2;
return sum_of_natural_nos - 1; // Return N-1 as the maximum index.
}
}
return s; // If we didn't find a match, return the current sum 's'.
}
static void Main()
{
int N = 3;
int B = 1;
Console.WriteLine(MaximumIndex(N, B)); // Call the function and print the result.
}
}
JavaScript
// Function to find the maximum index 'N' such that the sum
// of natural numbers from 1 to N is equal to 'B'.
function maximumIndex(N, B) {
let s = 0; // Initialize a variable 's' to keep track of the current sum.
for (let i = 1; i <= N; i++) { // Loop through natural numbers from 1 to N.
s += i; // Add the current number 'i' to the sum 's'.
if (s === B) { // If the sum 's' equals 'B', we found the answer.
// Calculate the sum of natural numbers from 1 to N using the formula.
const sumOfNaturalNos = (N * (N + 1)) / 2;
return sumOfNaturalNos - 1; // Return N-1 as the maximum index.
}
}
return s; // If we didn't find a match, return the current sum 's'.
}
const N = 3;
const B = 1;
console.log(maximumIndex(N, B)); // Call the function and print the result.
Time Complexity - O(n)
Space Complexity - 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