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

1 Answer

0 votes
fn can_reach_last_index(v: &Vec<i32>) -> bool {
    let size = v.len();
    let mut current_index: usize = 0;

    while current_index < size {
        // If we reach the last index, return true
        if current_index == size - 1 {
            return true;
        }

        // If jump goes out of bounds, stop
        let jump = v[current_index] as usize;
        if current_index + jump >= size {
            return false;
        }

        // Move to the next index by jumping
        current_index += jump;
    }

    false
}

fn main() {
    let v = vec![2, 3, 1, 1, 4];

    if can_reach_last_index(&v) {
        println!("Yes, we can reach the last index.");
    } else {
        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

...