Last Visited Integers - Problem
π Track the Last Visited Integers
Imagine you're building a smart browsing history that tracks positive integers you've seen. When you encounter a special -1 token, you need to look back at your history to find specific previously visited integers.
Here's how it works:
- π’ When you see a positive integer, add it to the front of your history (most recent first)
- β When you see a
-1, count how many consecutive-1s you've seen (including this one) - call thisk - π If
k β€ history_length, return thek-th element from your history - π« If
k > history_length, return-1(not enough history)
Goal: Return an array containing the results for each -1 encountered.
Example: [1, 2, -1, -1, 3, -1, -1, -1]
History builds: [1] β [2, 1] β first -1 (k=1) returns 2 β second -1 (k=2) returns 1 β add 3: [3, 2, 1] β continue...
Input & Output
example_1.py β Basic Case
$
Input:
[1, 2, -1, -1, 3, -1, -1, -1]
βΊ
Output:
[2, 1, 3, 3, -1]
π‘ Note:
Process: 1βseen=[1], 2βseen=[2,1], -1(k=1)βresult=[2], -1(k=2)βresult=[2,1], 3βseen=[3,2,1],count=0, -1(k=1)βresult=[2,1,3], -1(k=2)βresult=[2,1,3,3], -1(k=3)βseen only has 3 elements, so result=[2,1,3,3,-1]
example_2.py β Only Positive
$
Input:
[1, 2, 3, 4]
βΊ
Output:
[]
π‘ Note:
No -1 encountered, so result array remains empty. The seen array builds up as [4,3,2,1] but no queries are made.
example_3.py β Edge Case
$
Input:
[-1, -1, -1]
βΊ
Output:
[-1, -1, -1]
π‘ Note:
No positive integers seen, so seen array is empty. All three -1s result in -1 since k > len(seen) for each query.
Constraints
- 1 β€ nums.length β€ 100
- nums[i] == -1 or 1 β€ nums[i] β€ 100
- All positive integers are distinct
- The array will contain at least one -1 or one positive integer
Visualization
Tap to expand
Understanding the Visualization
1
Book Return
When a book is returned (positive integer), place it on top of the stack
2
Query Request
When someone asks for a book (-1), increment the request counter
3
Stack Lookup
Look k positions down from the top of the stack
4
Reset on Return
Counter resets to 0 when a new book is returned
Key Takeaway
π― Key Insight: Track consecutive -1s with a simple counter that resets when positive integers appear. This eliminates the need to scan backwards through the array each time!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code