EasyNo. 2899
Last Visited Integers — LeetCode 2899 Python Solution
- Topics
- Array, Simulation
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
- Time
- O(n)where n is the length of the array words
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0495 | Teemo Attacking | Easy |
| 0985 | Sum of Even Numbers After Queries | Medium |
| 1389 | Create Target Array in the Given Order | Easy |
| 1409 | Queries on a Permutation With Key | Medium |
| 1503 | Last Moment Before All Ants Fall Out of a Plank | Medium |
| 1535 | Find the Winner of an Array Game | Medium |
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.