LeetCode 2297: Jump Game VIII Solution

Master LeetCode problem 2297 (Jump Game VIII), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

The problem asks us to determine if it is possible to reach the end of an array from the start by selecting elements based on a given constraint. We are allowed to jump k steps to the right from the current index where k is the maximum value of the nums[i] element within the range [i+1, i+k]. We need to return true if we can reach the end index, otherwise false.

To solve this problem, we can use a deque (double-ended queue) to store the indices we can reach from the current index. We start by adding the first index to the deque. We then iterate through the array and at each step, we remove the indices that are out of the current range (greater than or equal to the current index minus k). For each index, we update the maximum reachable index based on the current element value. If the current index is the end index or beyond it, we return true. If we finish iterating through the array and cannot reach the end index, we return false.

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

: :

Solution Code

import java.util.*;

class Solution {
    public boolean canReach(int[] nums, int k) {
        Deque<Integer> deque = new LinkedList<>();
        deque.offer(0);

        for (int i = 1; i < nums.length; i++) {
            while (!deque.isEmpty() && deque.peekFirst() < i - k) {
                deque.pollFirst();
            }

            if (!deque.isEmpty()) {
                int maxIndex = deque.stream().map(j -> nums[j]).max(Integer::compare).get();
                if (maxIndex + i >= nums.length) {
                    return true;
                }
            }

            while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[i]) {
                deque.pollLast();
            }

            deque.offerLast(i);
        }

        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2297 (Jump Game VIII)?

This page provides optimized solutions for LeetCode problem 2297 (Jump Game VIII) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2297 (Jump Game VIII)?

The time complexity for LeetCode 2297 (Jump Game VIII) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2297 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2297 in Java, C++, or Python.

Back to LeetCode Solutions