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 the nodes will be connected to adjacent nodes with an edge of weight of ‘1’ and nodes with same characters with an edge with weight ‘0’.
- In this setup, 0-1 BFS can be run to find 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:
- Minimum cost to modify a string
- Minimum cost to construct a string
- Minimum cost to convert string into palindrome
- Minimum cost to make a string free of a subsequence
- Find the character in first string that is present at minimum index in second string
- Minimum initial vertices to traverse whole matrix with given conditions
- Minimum Cost Graph
- Connect n ropes with minimum cost
- Minimum cost to make two strings same
- Minimum cost to connect all cities
- Minimum possible travel cost among N cities
- Minimum odd cost path in a matrix
- Minimum spanning tree cost of given Graphs
- Find the minimum cost to cross the River
- Minimum Cost To Make Two Strings Identical
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.