BFS using vectors & queue as per the algorithm of CLRS Last Updated : 25 Jan, 2023 Comments Improve Suggest changes Like Article Like Report Breadth-first search traversal of a graph using the algorithm given in CLRS book. BFS is one of the ways to traverse a graph. It is named so because it expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. What it means is that the algorithm first discovers all the vertices connected to "u" at a distance of k before discovering the vertices at a distance of k+1 from u. The algorithm given in CLRS uses the concept of "colour" to check if a vertex is discovered fully or partially or undiscovered. It also keeps a track of the distance a vertex u is from the source s. BFS(G,s) 1 for each vertex u in G.V - {s} 2 u.color = white 3 u.d = INF 4 u.p = NIL 5 s.color = green 6 s.d = 0 7 s.p = NIL 8 Q = NULL 9 ENQUEUE(Q,s) 10 while Q != NULL 11 u = DEQUEUE(Q) 12 for each v in G.Adj[u] 13 if v.color == white 14 v.color = green 15 v.d = u.d + 1 16 v.p = u 17 ENQUEUE(Q,v) 18 u.color = dark_green It produces a "breadth-first tree" with root s that contains all reachable vertices. Let's take a simple directed graph and see how BFS traverses it. The graph Starting of traversal 1st traversal 1st traversal completes Implementation: C++ // CPP program to implement BFS as per CLRS // algorithm. #include <bits/stdc++.h> using namespace std; // Declaring the vectors to store color, distance // and parent vector<string> colour; vector<int> d; vector<int> p; /* This function adds an edge to the graph. It is an undirected graph. So edges are added for both the nodes. */ void addEdge(vector <int> g[], int u, int v) { g[u].push_back(v); g[v].push_back(u); } /* This function does the Breadth First Search*/ void BFSSingleSource(vector <int> g[], int s) { // The Queue used for the BFS operation queue<int> q; // Pushing the root node inside the queue q.push(s); /* Distance of root node is 0 & colour is gray as it is visited partially now */ d[s] = 0; colour[s] = "green"; /* Loop to traverse the graph. Traversal will happen traverse until the queue is not empty.*/ while (!q.empty()) { /* Extracting the front element(node) and popping it out of queue. */ int u = q.front(); q.pop(); cout << u << " "; /* This loop traverses all the child nodes of u */ for (auto i = g[u].begin(); i != g[u].end(); i++) { /* If the colour is white then the said node is not traversed. */ if (colour[*i] == "white") { colour[*i] = "green"; d[*i] = d[u] + 1; p[*i] = u; /* Pushing the node inside queue to traverse its children. */ q.push(*i); } } /* Now the node u is completely traversed and colour is changed to black. */ colour[u] = "dark_green"; } } void BFSFull(vector <int> g[], int n) { /* Initially all nodes are not traversed. Therefore, the colour is white. */ colour.assign(n, "white"); d.assign(n, 0); p.assign(n, -1); // Calling BFSSingleSource() for all white // vertices. for (int i = 0; i < n; i++) if (colour[i] == "white") BFSSingleSource(g, i); } // Driver Function int main() { // Graph with 7 nodes and 6 edges. int n = 7; // The Graph vector vector <int> g[n]; addEdge(g, 0, 1); addEdge(g, 0, 2); addEdge(g, 1, 3); addEdge(g, 1, 4); addEdge(g, 2, 5); addEdge(g, 2, 6); BFSFull(g, n); return 0; } Java // Java program to implement BFS as per CLRS // algorithm. import java.io.*; import java.util.*; public class Graph { private int V; private LinkedList<Integer>[] g; // Declaring the arrays to store color, distance // and parent String[] colour; int[] d, p; // Constructor @SuppressWarnings("unchecked") Graph(int v) { V = v; g = new LinkedList[v]; for (int i = 0; i < v; i++) g[i] = new LinkedList<Integer>(); } // Function to add an edge into the graph void addEdge(int u, int v) { g[u].add(v); g[v].add(u); } // This function does the Breadth First Search void BFSSingleSource(int s) { // The Queue used for the BFS operation Queue<Integer> q = new LinkedList<>(); // Pushing the root node inside the queue q.add(s); /* Distance of root node is 0 & colour is gray as it is visited partially now */ d[s] = 0; colour[s] = "green"; /* Loop to traverse the graph. Traversal will happen traverse until the queue is not empty.*/ while (!q.isEmpty()) { /* Extracting the front element(node) and popping it out of queue. */ int u = q.poll(); System.out.print(u + " "); /* This loop traverses all the child nodes of u */ for (int i : g[u]) { /* If the colour is white then the said node is not traversed. */ if (colour[i] == "white") { colour[i] = "green"; d[i] = d[u] + 1; p[i] = u; /* Pushing the node inside queue to traverse its children. */ q.add(i); } } /* Now the node u is completely traversed and colour is changed to black. */ colour[u] = "dark_green"; } System.out.println(); } void BFSFull(int n) { /* Initially all nodes are not traversed. Therefore, the colour is white. */ colour = new String[n]; d = new int[n]; p = new int[n]; Arrays.fill(colour, "white"); Arrays.fill(d, 0); Arrays.fill(p, -1); // Calling BFSSingleSource() for all white // vertices. for (int i = 0; i < n; i++) { if (colour[i] == "white") BFSSingleSource(i); } } // Driver method public static void main(String[] args) { int n = 7; Graph g = new Graph(n); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(1, 4); g.addEdge(2, 5); g.addEdge(2, 6); g.BFSFull(n); } } // This code is contributed by cavi4762. Python3 # Python3 program to implement BFS as # per CLRS algorithm. import queue # This function adds an edge to the graph. # It is an undirected graph. So edges # are added for both the nodes. def addEdge(g, u, v): g[u].append(v) g[v].append(u) # This function does the Breadth # First Search def BFSSingleSource(g, s): # The Queue used for the BFS operation q = queue.Queue() # Pushing the root node inside # the queue q.put(s) # Distance of root node is 0 & colour is # gray as it is visited partially now d[s] = 0 colour[s] = "green" # Loop to traverse the graph. Traversal # will happen traverse until the queue # is not empty. while (not q.empty()): # Extracting the front element(node) # and popping it out of queue. u = q.get() print(u, end = " ") # This loop traverses all the child # nodes of u i = 0 while i < len(g[u]): # If the colour is white then # the said node is not traversed. if (colour[g[u][i]] == "white"): colour[g[u][i]] = "green" d[g[u][i]] = d[u] + 1 p[g[u][i]] = u # Pushing the node inside queue # to traverse its children. q.put(g[u][i]) i += 1 # Now the node u is completely traversed # and colour is changed to black. colour[u] = "dark_green" def BFSFull(g, n): # Initially all nodes are not traversed. # Therefore, the colour is white. colour = ["white"] * n d = [0] * n p = [-1] * n # Calling BFSSingleSource() for all # white vertices for i in range(n): if (colour[i] == "white"): BFSSingleSource(g, i) # Driver Code # Graph with 7 nodes and 6 edges. n = 7 # Declaring the vectors to store color, # distance and parent colour = [None] * n d = [None] * n p = [None] * n # The Graph vector g = [[] for i in range(n)] addEdge(g, 0, 1) addEdge(g, 0, 2) addEdge(g, 1, 3) addEdge(g, 1, 4) addEdge(g, 2, 5) addEdge(g, 2, 6) BFSFull(g, n) # This code is contributed by Pranchalk C# using System; using System.Collections.Generic; namespace GraphTraversal { public class Graph { private int V; private List<int>[] g; // Declaring the arrays to store color, distance // and parent string[] colour; int[] d, p; // Constructor Graph(int v) { V = v; g = new List<int>[ v ]; for (int i = 0; i < v; i++) g[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int u, int v) { g[u].Add(v); g[v].Add(u); } // This function does the Breadth First Search void BFSSingleSource(int s) { // The Queue used for the BFS operation Queue<int> q = new Queue<int>(); // Pushing the root node inside the queue q.Enqueue(s); /* Distance of root node is 0 & colour is gray as it is visited partially now */ d[s] = 0; colour[s] = "green"; /* Loop to traverse the graph. Traversal will happen traverse until the queue is not empty.*/ while (q.Count != 0) { /* Extracting the front element(node) and popping it out of queue. */ int u = q.Dequeue(); Console.Write(u + " "); /* This loop traverses all the child nodes of u */ foreach(int i in g[u]) { /* If the colour is white then the said node is not traversed. */ if (colour[i] == "white") { colour[i] = "green"; d[i] = d[u] + 1; p[i] = u; /* Pushing the node inside queue to traverse its children. */ q.Enqueue(i); } } /* Now the node u is completely traversed and colour is changed to black. */ colour[u] = "dark_green"; } Console.WriteLine(); } void BFSFull(int n) { /* Initially all nodes are not traversed. Therefore, the colour is white. */ colour = new string[n]; d = new int[n]; p = new int[n]; Array.Fill(colour, "white"); Array.Fill(d, 0); Array.Fill(p, -1); // Calling BFSSingleSource() for all white // vertices. for (int i = 0; i < n; i++) { if (colour[i] == "white") BFSSingleSource(i); } } // Driver method static void Main(string[] args) { int n = 7; Graph g = new Graph(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(1, 4); g.addEdge(2, 5); g.addEdge(2, 6); g.BFSFull(n); } } } // This code is contributed by ishankhandelwals. JavaScript <script> // Javascript program to implement BFS as per CLRS // algorithm. // Declaring the vectors to store color, distance // and parent var colour = []; var d = []; var p = []; /* This function adds an edge to the graph. It is an undirected graph. So edges are added for both the nodes. */ function addEdge(g, u, v) { g[u].push(v); g[v].push(u); } /* This function does the Breadth First Search*/ function BFSSingleSource(g, s) { // The Queue used for the BFS operation var q = []; // Pushing the root node inside the queue q.push(s); /* Distance of root node is 0 & colour is gray as it is visited partially now */ d[s] = 0; colour[s] = "green"; /* Loop to traverse the graph. Traversal will happen traverse until the queue is not empty.*/ while (q.length!=0) { /* Extracting the front element(node) and popping it out of queue. */ var u = q[0]; q.shift(); document.write( u + " "); /* This loop traverses all the child nodes of u */ for(var i of g[u]) { /* If the colour is white then the said node is not traversed. */ if (colour[i] == "white") { colour[i] = "green"; d[i] = d[u] + 1; p[i] = u; /* Pushing the node inside queue to traverse its children. */ q.push(i); } } /* Now the node u is completely traversed and colour is changed to black. */ colour[u] = "dark_green"; } } function BFSFull(g, n) { /* Initially all nodes are not traversed. Therefore, the colour is white. */ colour = Array(n).fill("white"); d = Array(n).fill(0); p = Array(n).fill(0); // Calling BFSSingleSource() for all white // vertices. for (var i = 0; i < n; i++) if (colour[i] == "white") BFSSingleSource(g, i); } // Driver Function // Graph with 7 nodes and 6 edges. var n = 7; // The Graph vector var g = Array.from(Array(n), ()=>Array()); addEdge(g, 0, 1); addEdge(g, 0, 2); addEdge(g, 1, 3); addEdge(g, 1, 4); addEdge(g, 2, 5); addEdge(g, 2, 6); BFSFull(g, n); // This code is contributed by rutvik_56. </script> Output0 1 2 3 4 5 6 Time Complexity: O(V+E) - we traverse all vertices at least once and check every edge.Auxiliary Space: O(V) - for using a queue to store vertices. Comment More infoAdvertise with us Next Article Find if there is a path between two vertices in a directed graph S shubhamrath Follow Improve Article Tags : Graph Algorithms Advanced Data Structure Technical Scripter Competitive Programming DSA BFS +3 More Practice Tags : Advanced Data StructureAlgorithmsBFSGraph Similar Reads Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read BFS in different languageC Program for Breadth First Search or BFS for a GraphThe Breadth First Search (BFS) algorithm is used to search a graph data structure for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at the current depth level before moving on to the nodes at the next depth level. Relation between BFS for Graph and Tree 3 min read Java Program for Breadth First Search or BFS for a GraphThe Breadth First Search (BFS) algorithm is used to search a graph data structure for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at the current depth level before moving on to the nodes at the next depth level. Relation between BFS for Graph and Tree 3 min read Breadth First Search or BFS for a Graph in PythonBreadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent nodes. Once all adjacent are visited, then their adjacent are traversed. BFS is different from DFS in a way that closest vertices are visited before others. We mainly t 4 min read BFS for Disconnected Graph In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s 14 min read Applications, Advantages and Disadvantages of Breadth First Search (BFS) We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight 4 min read Breadth First Traversal ( BFS ) on a 2D array Given a matrix of size M x N consisting of integers, the task is to print the matrix elements using Breadth-First Search traversal. Examples: Input: grid[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Input: grid[][] = {{-1, 0, 0, 9 min read 0-1 BFS (Shortest Path in a Binary Weight Graph) Given an undirected graph where every edge has a weight as either 0 or 1. The task is to find the shortest path from the source vertex to all other vertices in the graph.Example: Input: Source Vertex = 0 and below graph Having vertices like (u, v, w): edges: [[0,1,0], [0, 7, 1], [1,2,1], [1, 7, 1], 10 min read Variations of BFS implementationsImplementation of BFS using adjacency matrixBreadth First Search (BFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph.Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n ( 7 min read BFS using STL for competitive codingA STL based simple implementation of BFS using queue and vector in STL. The adjacency list is represented using vectors of vector. In BFS, we start with a node. Create a queue and enqueue source into it. Mark source as visited.While queue is not empty, do followingDequeue a vertex from queue. Let t 5 min read Breadth First Search without using QueueBreadth-first search is a graph traversal algorithm which traverse a graph or tree level by level. In this article, BFS for a Graph is implemented using Adjacency list without using a Queue.Examples: Input: Output: BFS traversal = 2, 0, 3, 1 Explanation: In the following graph, we start traversal fr 8 min read BFS using vectors & queue as per the algorithm of CLRSBreadth-first search traversal of a graph using the algorithm given in CLRS book. BFS is one of the ways to traverse a graph. It is named so because it expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. What it means is that the algorithm 11 min read Easy problems on BFSFind if there is a path between two vertices in a directed graphGiven a Directed Graph and two vertices src and dest, check whether there is a path from src to dest.Example: Consider the following Graph: adj[][] = [ [], [0, 2], [0, 3], [], [2] ]Input : src = 1, dest = 3Output: YesExplanation: There is a path from 1 to 3, 1 -> 2 -> 3Input : src = 0, dest = 11 min read Find if there is a path between two vertices in an undirected graphGiven an undirected graph with N vertices and E edges and two vertices (U, V) from the graph, the task is to detect if a path exists between these two vertices. Print "Yes" if a path exists and "No" otherwise. Examples: U = 1, V = 2 Output: No Explanation: There is no edge between the two points and 15+ min read Print all the levels with odd and even number of nodes in it | Set-2Given an N-ary tree, print all the levels with odd and even number of nodes in it. Examples: For example consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4 The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2 No 12 min read Finding the path from one vertex to rest using BFSGiven an adjacency list representation of a directed graph, the task is to find the path from source to every other node in the graph using BFS. Examples: Input: Output: 0 <- 2 1 <- 0 <- 2 2 3 <- 1 <- 0 <- 2 4 <- 5 <- 2 5 <- 2 6 <- 2 Approach: In the images shown below: 14 min read Find all reachable nodes from every node present in a given setGiven an undirected graph and a set of vertices, find all reachable nodes from every vertex present in the given set.Consider below undirected graph with 2 disconnected components.  arr[] = {1 , 2 , 5}Reachable nodes from 1 are 1, 2, 3, 4Reachable nodes from 2 are 1, 2, 3, 4Reachable nodes from 5 ar 12 min read Program to print all the non-reachable nodes | Using BFSGiven an undirected graph and a set of vertices, we have to print all the non-reachable nodes from the given head node using a breadth-first search. For example: Consider below undirected graph with two disconnected components: In this graph, if we consider 0 as a head node, then the node 0, 1 and 2 8 min read Check whether a given graph is Bipartite or notGiven a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not.Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex i 8 min read Print all paths from a given source to a destination using BFSGiven a directed graph, a source vertex âsrcâ and a destination vertex âdstâ, print all paths from given âsrcâ to âdstâ. Please note that in the cases, we have cycles in the graph, we need not to consider paths have cycles as in case of cycles, there can by infinitely many by doing multiple iteratio 9 min read Minimum steps to reach target by a Knight | Set 1Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position.Examples: Input: KnightknightPosition: (1, 3) , targetPosition: (5, 0)Output: 3Explanation: In above diagr 9 min read Intermediate problems on BFSTraversal of a Graph in lexicographical order using BFSC++ // C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to traverse the graph in // lexicographical order using BFS void LexiBFS(map<char, set<char> >& G, char S, map<char, bool>& vis) { // Stores nodes of the gr 8 min read Detect cycle in an undirected graph using BFSGiven an undirected graph, the task is to determine if cycle is present in it or not.Examples:Input: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]]Undirected Graph with 5 NodeOutput: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 1 â 0.Input: V = 4, edges[][] = [[0, 1], [1, 6 min read Detect Cycle in a Directed Graph using BFSGiven a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0->1->2->3->0 and 2->4->2, so your function must return 11 min read Minimum number of edges between two vertices of a GraphYou are given an undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v). Examples: Input: For given graph G. Find minimum number of edges between (1, 5). Output: 2Explanation: (1, 2) and (2, 5) are the only edges resu 8 min read Word Ladder - Shortest Chain To Reach Target WordGiven an array of strings arr[], and two different strings start and target, representing two words. The task is to find the length of the smallest chain from string start to target, such that only one character of the adjacent words differs and each word exists in arr[].Note: Print 0 if it is not p 15 min read Print the lexicographically smallest BFS of the graph starting from 1Given a connected graph with N vertices and M edges. The task is to print the lexicographically smallest BFS traversal of the graph starting from 1. Note: The vertices are numbered from 1 to N.Examples: Input: N = 5, M = 5 Edges: 1 4 3 4 5 4 3 2 1 5 Output: 1 4 3 2 5 Start from 1, go to 4, then to 3 7 min read Shortest path in an unweighted graphGiven an unweighted, undirected graph of V nodes and E edges, a source node S, and a destination node D, we need to find the shortest path from node S to node D in the graph. Input: V = 8, E = 10, S = 0, D = 7, edges[][] = {{0, 1}, {1, 2}, {0, 3}, {3, 4}, {4, 7}, {3, 7}, {6, 7}, {4, 5}, {4, 6}, {5, 11 min read Number of shortest paths in an unweighted and directed graphGiven an unweighted directed graph, can be cyclic or acyclic. Print the number of shortest paths from a given vertex to each of the vertices. For example consider the below graph. There is one shortest path vertex 0 to vertex 0 (from each vertex there is a single shortest path to itself), one shorte 11 min read Distance of nearest cell having 1 in a binary matrixGiven a binary grid of n*m. Find the distance of the nearest 1 in the grid for each cell.The distance is calculated as |i1 - i2| + |j1 - j2|, where i1, j1 are the row number and column number of the current cell, and i2, j2 are the row number and column number of the nearest cell having value 1. Th 15+ min read Hard Problems on BFSIslands in a graph using BFSGiven an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in 15+ min read Print all shortest paths between given source and destination in an undirected graphGiven an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: Input: source = 0, destination = 5 Output: 0 -> 1 -> 3 -> 50 -> 2 -> 3 -> 50 -> 1 -> 13 min read Count Number of Ways to Reach Destination in a Maze using BFSGiven a maze of dimensions n x m represented by the matrix mat, where mat[i][j] = -1 represents a blocked cell and mat[i][j] = 0 represents an unblocked cell, the task is to count the number of ways to reach the bottom-right cell starting from the top-left cell by moving right (i, j+1) or down (i+1, 8 min read Coin Change | BFS ApproachGiven an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: Input: X = 7, arr[] = {3, 5, 4} 6 min read Water Jug problem using BFSGiven two empty jugs of m and n litres respectively. The jugs don't have markings to allow measuring smaller quantities. You have to use the jugs to measure d litres of water. The task is to find the minimum number of operations to be performed to obtain d litres of water in one of the jugs. In case 12 min read Word Ladder - Set 2 ( Bi-directional BFS )Given a dictionary, and two words start and target (both of the same length). Find length of the smallest chain from start to target if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may b 15+ min read Implementing Water Supply Problem using Breadth First SearchGiven N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are b 10 min read Minimum Cost Path in a directed graph via given set of intermediate nodesGiven a weighted, directed graph G, an array V[] consisting of vertices, the task is to find the Minimum Cost Path passing through all the vertices of the set V, from a given source S to a destination D. Examples: Input: V = {7}, S = 0, D = 6 Output: 11 Explanation: Minimum path 0->7->5->6. 10 min read Shortest path in a Binary MazeGiven an M x N matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.Note: You can move into an adjacent cell in one of the four directions, Up, Down, Left, and 15+ min read Minimum cost to traverse from one index to another in the StringGiven a string S of length N consisting of lower case character, the task is to find the minimum cost to reach from index i to index j. At any index k, the cost to jump to the index k+1 and k-1(without going out of bounds) is 1. Additionally, the cost to jump to any index m such that S[m] = S[k] is 10 min read Like