Last Visited Integers — LeetCode 2899 Python Solution

EasyArraySimulation
Problem
#2899
Reading time
2 min

The problem

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.

Python solution

Python
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

MeasureComplexity
TimeO(n), where n is the length of the array words
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2899. Last Visited Integers?
LeetCode 2899. Last Visited Integers is rated Easy on LeetCode.
What is the time complexity of LeetCode 2899. Last Visited Integers?
The Python solution on this page runs in O(n), where n is the length of the array words.
What is the space complexity of LeetCode 2899. Last Visited Integers?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2899. Last Visited Integers cover?
LeetCode 2899. Last Visited Integers is tagged Array and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview