EasyNo. 2899

Last Visited Integers — LeetCode 2899 Python Solution

Topics
Array, Simulation
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

PythonSolution
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

Time
O(n)where n is the length of the array words
Space · auxiliary
O(n)

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.

Free to download. Check it runs on your machine, then pick a plan.