Minimum jumps to same value or adjacent to reach end of Array
Last Updated :
23 Jul, 2025
Given an array arr[] of size N, the task is to find the minimum number of jumps to reach the last index of the array starting from index 0. In one jump you can move from current index i to index j, if arr[i] = arr[j] and i != j or you can jump to (i + 1) or (i – 1).
Note: You can not jump outside of the array at any time.
Examples:
Input: arr = {100, -23, -23, 404, 100, 23, 23, 23, 3, 404}
Output: 3
Explanation: Valid jump indices are 0 -> 4 -> 3 -> 9.
Input: arr = {7, 6, 9, 6, 9, 6, 9, 7}
Output: 1
An approach using BFS:
Here consider the elements which are at (i + 1), (i - 1), and all elements similar to arr[i] and insert them into a queue to perform BFS. Repeat the BFS in this manner and keep the track of level. When the end of array is reached return the level value.
Follow the steps below to implement the above idea:
- Initialize a map for mapping elements with the indices of their occurrence.
- Initialize a queue and an array visited[] to keep track of the elements that are visited.
- Push starting element into the queue and mark it as visited
- Initialize a variable count for counting the minimum number of valid jumps to reach the last index
- Do the following while the queue size is greater than 0:
- Iterate on all the elements of the queue
- Fetch the front element and pop out from the queue
- Check if we reach the last index or not
- If true, then return the count
- Check if curr + 1 is a valid position to visit or not
- If true, push curr + 1 into the queue and mark it as visited
- Check if curr - 1 is a valid position to visit or not
- If true, push curr - 1 into the queue and mark it as visited
- Now, Iterate over all the elements that are similar to curr
- Check if the child is in a valid position to visit or not
- If true, push the child into the queue and mark it as visited
- Erase all the occurrences of curr from the map because we already considered these elements for a valid jump in the above step
- Increment the count of jump
- Finally, return the count.
Below is the implementation of the above approach.
C++
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the
// minimum number of jumps required
int minimizeJumps(vector<int>& arr)
{
int n = arr.size();
// Initialize a map for mapping element
// with indices of all similar value
// occurrences in array
unordered_map<int, vector<int> > unmap;
// Mapping element with indices
for (int i = 0; i < n; i++) {
unmap[arr[i]].push_back(i);
}
queue<int> q;
vector<bool> visited(n, false);
// Push starting element into queue
// and mark it visited
q.push(0);
visited[0] = true;
// Initialize a variable count for
// counting the minimum number number
// of valid jump to reach at last index
int count = 0;
// Do while queue size is
// greater than 0
while (q.size() > 0) {
int size = q.size();
// Iterate on all the
// elements of queue
for (int i = 0; i < size; i++) {
// Fetch the front element and
// pop out from queue
int curr = q.front();
q.pop();
// Check if we reach at the
// last index or not if true,
// then return the count
if (curr == n - 1) {
return count;
}
// Check if curr + 1 is valid
// position to visit or not
if (curr + 1 < n
&& visited[curr + 1] == false) {
// If true, push curr + 1
// into queue and mark
// it as visited
q.push(curr + 1);
visited[curr + 1] = true;
}
// Check if curr - 1 is valid
// position to visit or not
if (curr - 1 >= 0
&& visited[curr - 1] == false) {
// If true, push curr - 1
// into queue and mark
// it as visited
q.push(curr - 1);
visited[curr - 1] = true;
}
// Now, Iterate over all the
// element that are similar
// to curr
for (auto child : unmap[arr[curr]]) {
if (curr == child)
continue;
// Check if child is valid
// position to visit or not
if (visited[child] == false) {
// If true, push child
// into queue and mark
// it as visited
q.push(child);
visited[child] = true;
}
}
// Erase all the occurrences
// of curr from map. Because
// we already considered these
// element for valid jump
// in above step
unmap.erase(arr[curr]);
}
// Increment the count of jump
count++;
}
// Finally, return the count.
return count;
}
// Driver code
int main()
{
vector<int> arr
= { 100, -23, -23, 404, 100, 23, 23, 23, 3, 404 };
// Function Call
cout << minimizeJumps(arr);
return 0;
}
Java
// Java code for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to find the minimum
// number of jumps required
static int minimizeJumps(int[] arr)
{
int n = arr.length;
// Initialize a map for mapping element
// with indices of all similar value
// occurrences in array
HashMap<Integer, List<Integer> > unmap
= new HashMap<>();
// Mapping element with indices
for (int i = 0; i < n; i++) {
if (unmap.containsKey(arr[i])) {
unmap.get(arr[i]).add(i);
}
else {
List<Integer> temp = new ArrayList<>();
temp.add(i);
unmap.put(arr[i], temp);
}
}
Queue<Integer> q = new LinkedList<>();
boolean[] visited = new boolean[n];
Arrays.fill(visited, false);
// Push starting element into queue
// and mark it visited
q.add(0);
visited[0] = true;
// Initialize a variable count for
// counting the minimum number number
// of valid jump to reach at last index
int count = 0;
// Do while queue size is
// greater than 0
while (q.size() > 0) {
int size = q.size();
// Iterate on all the
// elements of queue
for (int i = 0; i < size; i++) {
// Fetch the front element and
// pop out from queue
int curr = q.poll();
// Check if we reach at the
// last index or not if true,
// then return the count
if (curr == n - 1) {
return count / 2;
}
// Check if curr + 1 is valid
// position to visit or not
if (curr + 1 < n
&& visited[curr + 1] == false) {
// If true, push curr + 1
// into queue and mark
// it as visited
q.add(curr + 1);
visited[curr + 1] = true;
}
// Check if curr - 1 is valid
// position to visit or not
if (curr - 1 >= 0
&& visited[curr - 1] == false) {
// If true, push curr - 1
// into queue and mark
// it as visited
q.add(curr - 1);
visited[curr - 1] = true;
}
// Now, Iterate over all the
// element that are similar
// to curr
if (unmap.containsKey(arr[i])) {
for (int j = 0;
j < unmap.get(arr[curr]).size();
j++) {
int child
= unmap.get(arr[curr]).get(j);
if (curr == child) {
continue;
}
// Check if child is valid
// position to visit or not
if (visited[child] == false) {
// If true, push child
// into queue and mark
// it as visited
q.add(child);
visited[child] = true;
}
}
}
// Erase all the occurrences
// of curr from map. Because
// we already considered these
// element for valid jump
// in above step
unmap.remove(arr[curr]);
}
// Increment the count of jump
count++;
}
// Finally, return the count.
return count / 2;
}
public static void main(String[] args)
{
int[] arr = { 100, -23, -23, 404, 100,
23, 23, 23, 3, 404 };
// Function call
System.out.print(minimizeJumps(arr));
}
}
// This code is contributed by lokesh
Python
# Python code to implement the above approach
# Function to find the
# minimum number of jumps required
def minimizeJumps(arr):
n = len(arr)
# Initialize a map for mapping element
# with indices of all similar value
# occurrences in array
unmap = {}
# Mapping element with indices
for i in range(n):
if arr[i] in unmap:
unmap.get(arr[i]).append(i)
else:
unmap.update({arr[i]:[i]})
q = []
visited = [False]*n
# Push starting element into queue
# and mark it visited
q.append(0)
visited[0] = True
# Initialize a variable count for
# counting the minimum number number
# of valid jump to reach at last index
count = 0
# Do while queue size is
# greater than 0
while(len(q) > 0):
size = len(q)
# Iterate on all the
# elements of queue
for i in range(size):
# Fetch the front element and
# pop out from queue
curr = q[0]
q.pop(0)
# Check if we reach at the
# last index or not if true,
# then return the count
if(curr == n - 1):
return count//2
# Check if curr + 1 is valid
# position to visit or not
if(curr + 1 < n and visited[curr + 1] == False):
# If true, push curr + 1
# into queue and mark
# it as visited
q.append(curr + 1)
visited[curr + 1] = True
# Check if curr - 1 is valid
# position to visit or not
if(curr - 1 >= 0 and visited[curr - 1] == False):
# If true, push curr - 1
# into queue and mark
# it as visited
q.append(curr - 1)
visited[curr - 1] = True
# Now, Iterate over all the
# element that are similar
# to curr
if arr[i] in unmap:
for j in range(len(unmap[arr[curr]])):
child=unmap.get(arr[curr])[j]
if(curr==child):
continue
# Check if child is valid
# position to visit or not
if(visited[child] == False):
# If true, push child
# into queue and mark
# it as visited
q.append(child)
visited[child] = True
# Erase all the occurrences
# of curr from map. Because
# we already considered these
# element for valid jump
# in above step
if arr[curr] in unmap:
unmap.pop(arr[curr])
# Increment the count of jump
count = count + 1
# Finally, return the count.
return count//2
# Driver code
arr=[100, -23, -23, 404, 100, 23, 23, 23, 3, 404]
# Function Call
print(minimizeJumps(arr))
# This code is contributed by Pushpesh Raj.
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
public class GFG{
// Function to find the minimum
// number of jumps required
static int minimizeJumps(int[] arr)
{
int n = arr.Length;
// Initialize a map for mapping element
// with indices of all similar value
// occurrences in array
Dictionary<int,List<int>> unmap = new Dictionary<int,List<int>>();
// Mapping element with indices
for (int i = 0; i < n; i++) {
if (unmap.ContainsKey(arr[i])) {
unmap[arr[i]].Add(i);
}
else {
List<int> temp = new List<int>();
temp.Add(i);
unmap.Add(arr[i],temp);
}
}
List<int> q = new List<int>();
bool[] visited = new bool[n];
for(int i=0;i<n;i++)
{
visited[i]=false;
}
// Push starting element into queue
// and mark it visited
q.Add(0);
visited[0] = true;
// Initialize a variable count for
// counting the minimum number number
// of valid jump to reach at last index
int count = 0;
// Do while queue size is
// greater than 0
while (q.Count > 0) {
int size = q.Count;
// Iterate on all the
// elements of queue
for (int i = 0; i < size; i++) {
// Fetch the front element and
// pop out from queue
int curr = q[0];
q.RemoveAt(0);
// Check if we reach at the
// last index or not if true,
// then return the count
if (curr == n - 1) {
return count / 2;
}
// Check if curr + 1 is valid
// position to visit or not
if (curr + 1 < n
&& visited[curr + 1] == false) {
// If true, push curr + 1
// into queue and mark
// it as visited
q.Add(curr + 1);
visited[curr + 1] = true;
}
// Check if curr - 1 is valid
// position to visit or not
if (curr - 1 >= 0
&& visited[curr - 1] == false) {
// If true, push curr - 1
// into queue and mark
// it as visited
q.Add(curr - 1);
visited[curr - 1] = true;
}
// Now, Iterate over all the
// element that are similar
// to curr
if (unmap.ContainsKey(arr[i])){
for (int j = 0; j < unmap[arr[curr]].Count; j++) {
int child= unmap[arr[curr]][j];
if (curr == child) {
continue;
}
// Check if child is valid
// position to visit or not
if (visited[child] == false) {
// If true, push child
// into queue and mark
// it as visited
q.Add(child);
visited[child] = true;
}
}
}
// Erase all the occurrences
// of curr from map. Because
// we already considered these
// element for valid jump
// in above step
unmap.Remove(arr[curr]);
}
// Increment the count of jump
count++;
}
// Finally, return the count.
return count / 2;
}
static public void Main (string[] args){
int[] arr = { 100, -23, -23, 404, 100,
23, 23, 23, 3, 404 };
// Function call
Console.WriteLine(minimizeJumps(arr));
}
}
// This code is contributed by Aman Kumar
JavaScript
// Function to find the minimum number of jumps required
function minimizeJumps(arr) {
let n = arr.length;
// Initialize a map for mapping element
// with indices of all similar value occurrences in array
let unmap = new Map();
// Mapping elements with their indices
for (let i = 0; i < n; i++) {
if (unmap.has(arr[i]))
unmap.get(arr[i]).push(i);
else
unmap.set(arr[i], [i]);
}
let q = [];
let visited = new Array(n).fill(false);
// Push starting element into the queue and mark it visited
q.push(0);
visited[0] = true;
// Initialize count for the minimum jumps
let count = 0;
// Perform BFS
while (q.length > 0) {
let size = q.length;
// Process all elements at the current level
for (let i = 0; i < size; i++) {
let curr = q.shift();
// Check if we have reached the last index
if (curr == n - 1) {
return count;
}
// Jump to the adjacent index (curr + 1)
if (curr + 1 < n && !visited[curr + 1]) {
q.push(curr + 1);
visited[curr + 1] = true;
}
// Jump to the adjacent index (curr - 1)
if (curr - 1 >= 0 && !visited[curr - 1]) {
q.push(curr - 1);
visited[curr - 1] = true;
}
// Jump to all other indices with the same value
if (unmap.has(arr[curr])) {
for (let child of unmap.get(arr[curr])) {
if (!visited[child]) {
q.push(child);
visited[child] = true;
}
}
// Remove the processed value to avoid redundant jumps
unmap.delete(arr[curr]);
}
}
// Increment the count of jumps after processing the current level
count++;
}
// If no solution, return -1 (optional as input guarantees a solution)
return -1;
}
// Driver code
let arr = [100, -23, -23, 404, 100, 23, 23, 23, 3, 404];
console.log(minimizeJumps(arr)); // Output: 3
Time Complexity: O(N)
Auxiliary Space: O(N)
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