Skip to main content
Back to problems
#2899
Easy Algorithms

Last visited integers

Array Simulation
62.1% acceptance
Feb 25, 2026
165
235
Given an integer array nums where nums[i] is either a positive integer or -1. We need to find for each -1 the respective positive integer, which we call the last visited integer. To achieve this goal, let's define two empty arrays: seen and ans. Start iterating from the beginning of the array nums. If a positive integer is encountered, prepend it to the front of seen. If -1 is encountered, let k be the number of consecutive -1s seen so far (including the current -1), If k is less than or equal to the length of seen, append the k-th element of seen to ans. If k is strictly greater than the length of seen, append -1 to ans. Return the array ans.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn last_visited_integers(nums: Vec<i32>) -> Vec<i32> {
    let mut seen: Vec<i32> = vec![];
    let mut ans: Vec<i32> = vec![];
    let mut k = 0;
    for &n in &nums {
      if n == -1 {
        k += 1;
        if k <= seen.len() {
          ans.push(seen[k - 1]);
        } else {
          ans.push(-1);
        }
      } else {
        seen.insert(0, n);
        k = 0;
      }
    }
    ans
  }
}