Suppose we have a list of numbers called nums and we are placed currently at nums. 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 −
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 = 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))
[4, 8, 8, 5, 4, 6, 5]