VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-reachable-index-difference/

⇱ Maximum Reachable Index Difference - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Reachable Index Difference

Last Updated : 14 Jun, 2026

Given a string s containing lowercase English letters.

  • Start from any index containing the character 'a' and perform jump operations.
  • In each jump operation, move to any index on the right side whose character is the immediate next letter of the current character in the alphabet (i.e., 'a' to 'b', 'b' to 'c', 'c' to 'd', and so on). Continue performing jumps until no further jump is possible.

Find the maximum possible difference between the starting index and the ending index. If it is not possible to choose a starting index, return -1.

Examples :

Input: s = "aaabcb"
Output: 5
Explanation: Start at index 0 ('a'), jump to index 5 ('b'). Difference = 5 - 0 = 5.

Input: s = "xynjir"
Output: -1
Explanation: The string does not contain any character 'a'. So, the answer is -1.

Input: s = "abcbzzd"
Output: 6
Explanation: Start from index 0 ('a'). Jump to index 1 ('b') because 'b' is the next alphabet character. Jump to index 2 ('c') because 'c' is the next character after 'b'. Jump to index 6 ('d') because 'd' is the next character after 'c'.

[Brute Force Approach] - Using Recursion - O(n × 2n ) Time and O(n) Space

The idea is to recursively explore all possible jump sequences starting from every index containing 'a'. For each next index, try all possible positions on the right containing the next alphabet character and continue the recursion from there.


Output
5

[Better Approach] - Using Recursion + Memoization - O(n2) Time and O(n) Space

The idea is to store the farthest reachable index from every position. For each index, recursively explore all possible jumps to the next alphabet character and store the result. This avoids recalculating the same index multiple times, but each state still scans the remaining part of the string to find possible jumps.


Output
5

[Expected Approach] - Using Dynamic Programming (Right-to-Left Traversal) - O(n) Time and O(1) Space

The idea is to process the string from right to left because every jump is only allowed towards the right side. While traversing, maintain the farthest reachable index for each character. For the current character, if the next alphabet character has already been processed, we can directly use its farthest reachable index to determine the farthest position reachable from the current index. This avoids checking all possible jumps and allows each character to be processed in constant time.


Output
5
Comment
Article Tags:
Article Tags: