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

1 Answer

0 votes
def can_reach_last_index(lst):
    size = len(lst)
    current_index = 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
        if current_index + lst[current_index] >= size:
            return False

        # Move to the next index by jumping
        current_index += lst[current_index]

    return False


def main():
    lst = [2, 3, 1, 1, 4]

    if can_reach_last_index(lst):
        print("Yes, we can reach the last index.")
    else:
        print("No, we cannot reach the last index.")


if __name__ == "__main__":
    main()




'''
run:

Yes, we can reach the last index.

'''

 



answered Dec 1, 2025 by avibootz

Related questions

...