Given 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 0.
Input : S = “abcde”, i = 0, j = 4
Output : 4
The shortest path will be:
Thus, the answer will be 4.
Input : S = “abcdefb”, i = 0, j = 5
Output : 2
0->1 edge weight is 1, 1->6 edge weight is 0, and 6->5 edge weight is 1.
Thus, the answer will be 2
- One approach to solve this problem is 0-1 BFS.
- The setup can be visualized as a graph with N nodes.
- All the nodes will be connected to adjacent nodes with an edge of weight of ‘1’ and nodes with the same characters with an edge with weight ‘0’.
- In this setup, 0-1 BFS can be run to find the shortest path from index ‘i’ to index ‘j’.
Time complexity: O(N^2) – As number of vertices would be of O(N^2)
- For each character X, all the characters are found for which it is adjacent to.
- A graph is created with number of nodes as number of distinct characters in the string, each representing a character.
- Each node X, will have an edge of weight 1 with all the nodes representing characters adjacent to character X.
- Then BFS can be run from nodes representing S[i] to nodes representing S[j] in this new graph
Time complexity: O(N)
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Minimum cost to modify a string
- Minimum cost to construct a string
- Minimum cost to convert string into palindrome
- Find the character in first string that is present at minimum index in second string
- Minimum cost to convert given string to consist of only vowels
- Minimum cost to make a string free of a subsequence
- Minimum Cost of deletions such that string does not contains same consecutive characters
- Minimum Cost using Dijkstra by reducing cost of an Edge
- Minimum initial vertices to traverse whole matrix with given conditions
- Minimum Cost Graph
- Connect n ropes with minimum cost
- Minimum cost to merge numbers from 1 to N
- Minimum cost to make two strings same
- Minimum cost to connect all cities
- Minimum odd cost path in a matrix
- Minimum possible travel cost among N cities
- Minimum Cost To Make Two Strings Identical
- Minimum spanning tree cost of given Graphs
- Find the minimum cost to cross the River
- Minimum cost to reach the top of the floor by climbing stairs
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.