
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find 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.
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]]
Let us see the following implementation to get better understanding −
Example
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))
Input
[4, 8, 8, 5, 4, 6, 5]
Output
3
Advertisements