How to check if the last index of a slice is reachable by jumping based on element values from index 0 in Go

1 Answer

0 votes
package main

import "fmt"

func canReachLastIndex(slice []int) bool {
    size := len(slice)
    currentIndex := 0

    for currentIndex < size {
        // If we reach the last index, return true
        if currentIndex == size-1 {
            return true
        }

        // If jump goes out of bounds, stop
        if currentIndex + slice[currentIndex] >= size {
            return false
        }

        // Move to the next index by jumping
        currentIndex += slice[currentIndex]
    }

    return false
}

func main() {
    slice := []int{2, 3, 1, 1, 4}

    if canReachLastIndex(slice) {
        fmt.Println("Yes, we can reach the last index.")
    } else {
        fmt.Println("No, we cannot reach the last index.")
    }
}



/*
run:

Yes, we can reach the last index.

*/

 



answered Dec 1, 2025 by avibootz
edited Dec 1, 2025 by avibootz

Related questions

...