Take a look at the nested for-loops you used. I think that makes your code O(N^2). Doesn’t it? In case I am wrong, can you explain further what you have tried to do?
Thanks dear . Yes, I used arr for that. Its just visualization. Take it as, we are at some character ‘ch’ present at index i, we can reach it in two ways, either by jumping from previous char, or jumping to this char directly from same-character checkpost. Jumping from previous same-char checkpost is already stored in arr[s[i]-‘a’], and cost to reach here from previous element is in dp[i].
For this case, imagine that we are filling a general index i , then proceed for start and end of table.
The best thing is synergy, dp[i] helps in determining arr, while arr helps in finding dp[i].
@vijju123 I have a doubt what if there is no check point of that character but it gives the smallest path i.e. acdefb.
So here a to b is shortest path Right?. But the algorithm is looking for check points which does not exist. So it will go for a-f i.e 5 then f-b that is 4. Because arr[b-‘a’] is 1000000. Can you please explain how the algo will handle this.
In the question we are starting from a, and have to reach b. We cannot reach b before we reach f, since jumping isnt possible and as given in Q, we have to go linearly from a to c, then d,e,f and finally b. Answer is same in both cases.