1345. Jump Game IV LeetCode Solution

In this guide, you will get 1345. Jump Game IV LeetCode Solution with the best time and space complexity. The solution to Jump Game IV problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Jump Game IV solution in C++
  4. Jump Game IV solution in Java
  5. Jump Game IV solution in Python
  6. Additional Resources
1345. Jump Game IV LeetCode Solution image

Problem Statement of Jump Game IV

Given an array of integers arr, you are initially positioned at the first index of the array.
In one step you can jump from index i to index:

i + 1 where: i + 1 = 0.
j where: arr[i] == arr[j] and i != j.

Return the minimum number of steps to reach the last index of the array.
Notice that you can not jump outside of the array at any time.

Example 1:

Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
Output: 3
Explanation: You need three jumps from index 0 –> 4 –> 3 –> 9. Note that index 9 is the last index of the array.

Example 2:

Input: arr = [7]
Output: 0
Explanation: Start index is the last index. You do not need to jump.

Example 3:

Input: arr = [7,6,9,6,9,6,9,7]
Output: 1
Explanation: You can jump directly from index 0 to index 7 which is last index of the array.

Constraints:

1 <= arr.length <= 5 * 104
-108 <= arr[i] <= 108

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

1345. Jump Game IV LeetCode Solution in C++

class Solution {
 public:
  int minJumps(vector<int>& arr) {
    const int n = arr.size();
    // {a: indices}
    unordered_map<int, vector<int>> graph;
    queue<int> q{{0}};
    vector<bool> seen(n);
    seen[0] = true;

    for (int i = 0; i < n; ++i)
      graph[arr[i]].push_back(i);

    for (int step = 0; !q.empty(); ++step) {
      for (int sz = q.size(); sz > 0; --sz) {
        const int i = q.front();
        q.pop();
        if (i == n - 1)
          return step;
        seen[i] = true;
        const int u = arr[i];
        if (i + 1 < n)
          graph[u].push_back(i + 1);
        if (i - 1 >= 0)
          graph[u].push_back(i - 1);
        for (const int v : graph[u]) {
          if (seen[v])
            continue;
          q.push(v);
        }
        graph[u].clear();
      }
    }

    throw;
  }
};
/* code provided by PROGIEZ */

1345. Jump Game IV LeetCode Solution in Java

class Solution {
  public int minJumps(int[] arr) {
    final int n = arr.length;
    // {a: indices}
    Map<Integer, List<Integer>> graph = new HashMap<>();
    Queue<Integer> q = new ArrayDeque<>(List.of(0));
    boolean[] seen = new boolean[n];
    seen[0] = true;

    for (int i = 0; i < n; ++i) {
      graph.putIfAbsent(arr[i], new ArrayList<>());
      graph.get(arr[i]).add(i);
    }

    for (int step = 0; !q.isEmpty(); ++step) {
      for (int sz = q.size(); sz > 0; --sz) {
        final int i = q.poll();
        if (i == n - 1)
          return step;
        seen[i] = true;
        final int u = arr[i];
        if (i + 1 < n)
          graph.get(u).add(i + 1);
        if (i - 1 >= 0)
          graph.get(u).add(i - 1);
        for (final int v : graph.get(u)) {
          if (seen[v])
            continue;
          q.offer(v);
        }
        graph.get(u).clear();
      }
    }

    throw new IllegalArgumentException();
  }
}
// code provided by PROGIEZ

1345. Jump Game IV LeetCode Solution in Python

class Solution:
  def minJumps(self, arr: list[int]) -> int:
    n = len(arr)
    # {num: indices}
    graph = collections.defaultdict(list)
    step = 0
    q = collections.deque([0])
    seen = {0}

    for i, a in enumerate(arr):
      graph[a].append(i)

    while q:
      for _ in range(len(q)):
        i = q.popleft()
        if i == n - 1:
          return step
        seen.add(i)
        u = arr[i]
        if i + 1 < n:
          graph[u].append(i + 1)
        if i - 1 >= 0:
          graph[u].append(i - 1)
        for v in graph[u]:
          if v in seen:
            continue
          q.append(v)
        graph[u].clear()
      step += 1
# code by PROGIEZ

Additional Resources

See also  2746. Decremental String Concatenation LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.