From 4b3ff681fe0829268cb950a974ae4a0d3f4d05fd Mon Sep 17 00:00:00 2001 From: boolpurist Date: Tue, 6 Aug 2024 11:11:43 +0200 Subject: [PATCH] Ensured correctness by using a dequeue for subsequent path walking --- src/lib.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 4b96a49..2bed49c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,8 @@ pub struct Solution; // Copy from here for submitting this solution to leet code + +use std::collections::VecDeque; impl Solution { pub fn can_jump(nums: Vec) -> bool { Solution::idiom_can_jump(&nums) @@ -30,13 +32,14 @@ impl Solution { return false; } let target_val = (nums.len() - 1) as i32; - let mut next_nodes = Vec::from([(0, nums[0])]); + // Using a dequeue ensures that every index is visited + let mut next_nodes = VecDeque::from([(0, nums[0])]); // index visited yet - let mut visted_indices = -1; + let mut greatest_visted_indices = -1; if Self::check_with_target_value(target_val, 0) { return true; } - while let Some(next_node) = next_nodes.pop() { + while let Some(next_node) = next_nodes.pop_front() { let (index, steps) = next_node; let max_jump_height = index + steps; if Self::check_with_target_value(target_val, max_jump_height) { @@ -45,12 +48,15 @@ impl Solution { // It can start at 1 because the every index was checked in previous path walking for next_to_check in 1..=steps { let to_add = index + next_to_check; - if visted_indices >= to_add { + // Going left to right and using a dequeue + // for subsequent path walking ensures that + // every index before to_add was visited. + if greatest_visted_indices >= to_add { // already visited this index continue; } - visted_indices = to_add; - next_nodes.push((to_add, nums[to_add as usize])); + greatest_visted_indices = to_add; + next_nodes.push_front((to_add, nums[to_add as usize])); } } false