Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2899: Last Visited Integers

In this guide, we solve Leetcode #2899 Last Visited Integers in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Easy
  • Premium: No
  • Tags: Array, Simulation

Intuition

The rules are explicit, so simulating the process step by step is safest.

Careful state updates prevent subtle bugs.

Approach

Translate the rules into state updates and apply them in order.

Track the final state or aggregate as required.

Steps:

  • Translate rules into state updates.
  • Iterate for each step.
  • Return the final state.

Python Solution

class Solution: def lastVisitedIntegers(self, words: List[str]) -> List[int]: nums = [] ans = [] k = 0 for w in words: if w == "prev": k += 1 i = len(nums) - k ans.append(-1 if i < 0 else nums[i]) else: k = 0 nums.append(int(w)) return ans

Complexity

The time complexity is O(n)O(n)O(n), where nnn is the length of the array wordswordswords. The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy