Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find number of minimum steps to reach last index in Python
Suppose we have a list of numbers called nums and we are placed currently at nums[0]. On each step, we can either jump from the current index i to i + 1 or i - 1 or j where nums[i] == nums[j]. We have to find the minimum number of steps required to reach the final index.
So, if the input is like nums = [4, 8, 8, 5, 4, 6, 5], then the output will be 3, as we can jump from index 0 to index 4 as their values are both 4. And then we jump back to index 3. Finally, we can jump from index 3 to 6 since both of their values are 5.
Algorithm
To solve this, we will follow these steps ?
- pos := an empty map
- for each index i, and value n in nums, do
- insert i at the end of pos[n]
- n := size of nums
- visited := make a list of size n, and fill this with False
- visited[0] := True
- while q is not empty, do
- (u, d) := left element of q, and delete left element
- if u is same as n - 1, then
- return d
- for each v in the lists pos[nums[u]] and [u - 1, u + 1], do
- if 0 <= v < n and visited[v] is false, then
- visited[v] := True
- insert pair (v, d + 1) at the end of q
- if 0 <= v < n and visited[v] is false, then
- remove pos[nums[u]]
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, nums):
from collections import defaultdict, deque
pos = defaultdict(list)
for i, n in enumerate(nums):
pos[n].append(i)
q = deque([(0, 0)])
n = len(nums)
visited = [False] * n
visited[0] = True
while q:
u, d = q.popleft()
if u == n - 1:
return d
for v in pos[nums[u]] + [u - 1, u + 1]:
if 0 <= v < n and not visited[v]:
visited[v] = True
q.append((v, d + 1))
del pos[nums[u]]
ob = Solution()
nums = [4, 8, 8, 5, 4, 6, 5]
print(ob.solve(nums))
3
How It Works
The solution uses Breadth-First Search (BFS) to find the minimum steps. We create a position map that stores all indices for each value. Starting from index 0, we explore all reachable positions: adjacent indices (i±1) and indices with the same value. The BFS guarantees we find the shortest path to the last index.
Key Points
- BFS ensures minimum steps due to level-by-level exploration
- Position map allows quick access to all indices with same value
- Deleting used positions prevents revisiting same value indices
- Time complexity: O(n), Space complexity: O(n)
Conclusion
This BFS approach efficiently finds the minimum steps to reach the last index by exploring all possible jumps. The key insight is using a position map to quickly jump between indices with equal values.
