55. Jump Game
Last updated
Last updated
Refer to: https://leetcode.com/problems/jump-game/description/
The solution to this problem is to start at the end and work backwards. As you move backward you want to determine if the current index can be reached by a previous (lower index) item. If it can, then you want to determine if that position can also be reached by a previous (lower index) item. This process is repeated until the start of the list is reached (or not).
The reason to work backword is it eliminates possibilites. By working forward you would potentially check multiple paths to determine if there is a solution. By working backwards only one path needs to be followed. This leads to an O(n) solution.
Given the input of: [3, 2, 1, 0, 4]
and n
is the last index of the list
Index (Element) | Result |
---|---|
No solution found. No element could jump to n
Given the input: [3,2,2,0,4]
Solution found.
Solution is O(n), O(1).
Index (Element) | Result |
---|---|
n - 1 (0)
Cannot jump to n
n - 2 (1)
Cannot jump to n (jump to n-1)
n - 3 (2)
Cannot jump to n (jump to n-1 or n-2)
n - 4 (3)
Cannot jump to n (jump to n-1 or n-2 or n-3)
n - 1 (0)
Cannot jump to n
n - 2 (2)
Can jump to n (jump to n-1 or n). Can anything jump to this position (n - 2)?
n - 3 (2)
Can jump to n - 2. Can anything jump to this position (n - 3)?
n -4 (3)
Can jump to n - 3