Last Visited Integers — LeetCode 2899 Python Solution
EasyArraySimulation
- Problem
- #2899
- 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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array words |
| Space | O(n) auxiliary |
Related problems
LeetCode 495Teemo AttackingEasyLeetCode 985Sum of Even Numbers After QueriesMediumLeetCode 1389Create Target Array in the Given OrderEasyLeetCode 1409Queries on a Permutation With KeyMediumLeetCode 1503Last Moment Before All Ants Fall Out of a PlankMediumLeetCode 1535Find the Winner of an Array GameMedium
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.