Last Visited Integers - Solution & Explanation
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.
To achieve this goal, let's define two empty arrays: seen and ans.
Start iterating from the beginning of the array nums.
- If a positive integer is encountered, prepend it to the front of
seen. - If
-1is encountered, letkbe the number of consecutive-1s seen so far (including the current-1),- If
kis less than or equal to the length ofseen, append thek-th element ofseentoans. - If
kis strictly greater than the length ofseen, append-1toans.
- If
Return the array ans.
Example 1:
Input: nums = [1,2,-1,-1,-1]
Output: [2,1,-1]
Explanation:
Start with seen = [] and ans = [].
- Process
nums[0]: The first element in nums is1. We prepend it to the front ofseen. Now,seen == [1]. - Process
nums[1]: The next element is2. We prepend it to the front ofseen. Now,seen == [2, 1]. - Process
nums[2]: The next element is-1. This is the first occurrence of-1, sok == 1. We look for the first element in seen. We append2toans. Now,ans == [2]. - Process
nums[3]: Another-1. This is the second consecutive-1, sok == 2. The second element inseenis1, so we append1toans. Now,ans == [2, 1]. - Process
nums[4]: Another-1, the third in a row, makingk = 3. However,seenonly has two elements ([2, 1]). Sincekis greater than the number of elements inseen, we append-1toans. Finally,ans == [2, 1, -1].
Example 2:
Input: nums = [1,-1,2,-1,-1]
Output: [1,2,1]
Explanation:
Start with seen = [] and ans = [].
- Process
nums[0]: The first element in nums is1. We prepend it to the front ofseen. Now,seen == [1]. - Process
nums[1]: The next element is-1. This is the first occurrence of-1, sok == 1. We look for the first element inseen, which is1. Append1toans. Now,ans == [1]. - Process
nums[2]: The next element is2. Prepend this to the front ofseen. Now,seen == [2, 1]. - Process
nums[3]: The next element is-1. This-1is not consecutive to the first-1since2was in between. Thus,kresets to1. The first element inseenis2, so append2toans. Now,ans == [1, 2]. - Process
nums[4]: Another-1. This is consecutive to the previous-1, sok == 2. The second element inseenis1, append1toans. Finally,ans == [1, 2, 1].
Constraints:
1 <= nums.length <= 100nums[i] == -1or1 <= nums[i] <= 100
Approach Overview
Problem Overview: You receive a list of strings representing operations. A value can either be an integer or the string "prev". Every integer is recorded as a visited number. When you encounter "prev", return the k-th most recently visited integer where k equals how many consecutive "prev" operations have occurred since the last integer. If fewer than k integers exist, return -1. The task is essentially a stream simulation problem.
Approach 1: Using Two Stacks (O(n) time, O(n) space)
This approach explicitly models the operation history using two stacks. The first stack stores all integers seen so far. The second stack tracks results produced by consecutive "prev" calls. When a number appears, push it to the integer stack and clear the prev stack because the sequence of "prev" queries resets. When a "prev" operation appears, compute which previous element should be returned by referencing the integer stack index len(stack) - k. Push the returned value into the prev stack so the next "prev" automatically refers to the next older element. This method closely mirrors how the problem statement describes the behavior and is easy to reason about during interviews. Since each element is processed once, the total time complexity is O(n) with O(n) space to store visited integers. This technique fits naturally with problems involving history traversal and stack-like access patterns.
Approach 2: Using a Deque for Seen (O(n) time, O(n) space)
A cleaner simulation keeps all visited integers in a deque (or list) and tracks the current k value representing how many consecutive "prev" operations occurred. When an integer appears, append it to the deque and reset k = 0. When "prev" appears, increment k and check if the deque has at least k elements. If it does, return the element at index size - k; otherwise return -1. This approach avoids maintaining a second stack and relies on simple index lookup. The operations are constant time, so the full scan of the input array still runs in O(n) time with O(n) memory for the stored integers. It is a straightforward example of Array and Simulation working together with deque-style access patterns similar to a Stack.
Recommended for interviews: The deque/list simulation is typically the expected answer. It uses minimal state (a container plus a counter) and directly models the k-th previous lookup in constant time. Showing the stack-based reasoning first demonstrates understanding of the history behavior, while the optimized simulation highlights clean implementation skills.
Approach 1: Approach 1: Using Two Stacks
In this approach, we utilize two data structures: a stack to maintain the current viewed positive integers and another to handle queries simulated by -1. While iterating through the array, maintain the stack for positive integers. For each -1 encountered, manage a counter to handle consecutive -1s and respond accordingly by peeking into the positive stack.
The function last_visited_integers_stack implements the logic of maintaining a stack (list) seen for positive integers in reverse order and a counter to track consecutive -1 occurrences. When a -1 is read, based on the historical positive numbers and the count of consecutive -1, it appends the correct element to the result list or -1 when not enough past positives exist.
Complexity
Time Complexity: O(n), where n is the length of the input list nums, as we traverse the list once.
Space Complexity: O(n), as we maintain potential elements for the seen stack and answer list.
Approach 2: Approach 2: Using a Deque for Seen
This approach optimizes the storage and retrieval of last visited elements using a double-ended queue (deque). This structure allows appending to the front and accessing elements by index efficiently. While iterating through the array, prepend new positive integers, and resolve -1 elements by determining their position against the sequence recorded in the deque.
The function lastVisitedIntegersDeque leverages an array seen that acts like a deque by frequently adjusting with unshift to manage positive integers, akin to prepending to a list. It counts consecutive -1s and efficiently accesses the required past seen integers, yielding results in the array ans based on consecutive -1 conditions.
Code
JavaScript
Java
Complexity
Time Complexity: O(n) as we iterate through each element of nums once.
Space Complexity: O(n) for storing the seen deque structure.
Approach 3: Simulation
We directly simulate according to the problem description.
Define an array seen to store the positive integers we have encountered, and an array ans to store the answer. We also need a variable k to record the number of consecutive -1s.
We traverse the array nums:
- If the current element
x = -1, we incrementkby 1. Ifkis greater than the length ofseen, we append-1toans; otherwise, we append thek-th element from the end ofseentoans. - If the current element
xis a positive integer, we resetkto 0 and appendxto the end ofseen.
The time complexity is O(n) and the space complexity is O(n), where n is the length of the array nums.
Complexity Comparison
| Approach | Complexity |
|---|---|
| Approach 1: Using Two Stacks | Time Complexity: Space Complexity: |
| Approach 2: Using a Deque for Seen | Time Complexity: Space Complexity: |
| Simulation | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Two Stacks | O(n) | O(n) | When you want an explicit representation of history traversal and consecutive prev queries. |
| Deque/List Simulation | O(n) | O(n) | Best general solution. Minimal logic with constant-time lookup for the k-th last visited value. |
Video Solution
Leetcode BiWeekly contest 115 - Easy - Last Visited Integers • Prakhar Agrawal • 1,022 views views
Watch 7 more video solutions →Frequently Asked Questions
Is Last Visited Integers easy or hard?
Last Visited Integers Python/Java solution
How to solve Last Visited Integers in O(n)?
What is the best approach for Last Visited Integers?
Is Last Visited Integers asked at Google/Amazon/Meta?
What data structure is used in Last Visited Integers?
What is the time complexity of Last Visited Integers?
Ready to solve this problem?
Practice Last Visited Integers with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor