Last Visited Integers - 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.
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 -1 is encountered, let k be the number of consecutive -1s seen so far (including the current -1). If k is less than or equal to the length of seen, append the k-th element of seen to ans. If k is strictly greater than the length of seen, append -1 to ans.
Return the array ans.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,-1,-1,-1]
›
Output:
[2,1,-1]
💡 Note:
After seeing 1,2: seen=[2,1]. First -1 (k=1): seen[0]=2. Second -1 (k=2): seen[1]=1. Third -1 (k=3): k > len(seen), so -1.
Example 2 — Reset Counter
$
Input:
nums = [1,-1,2,-1,-1]
›
Output:
[1,2,1]
💡 Note:
After 1: seen=[1]. First -1: seen[0]=1. After 2: seen=[2,1], counter resets. Next -1 (k=1): seen[0]=2. Last -1 (k=2): seen[1]=1.
Example 3 — No Positives
$
Input:
nums = [-1,-1,-1]
›
Output:
[-1,-1,-1]
💡 Note:
No positive numbers seen, so seen=[] is always empty. Every -1 results in -1 since k > len(seen).
Constraints
- 1 ≤ nums.length ≤ 1000
- nums[i] == -1 or 1 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Processing
Array with positive numbers and -1s
2
Track Seen
Maintain list of recent positive numbers
3
Handle Queries
For each -1, find k-th most recent number
Key Takeaway
🎯 Key Insight: Use consecutive -1 count as index into most recently seen positive numbers
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code