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
Last Visited Integers Problem OverviewTrack positive numbers, answer -1 queries with k-th recent number12-1-1-1Input Array: [1, 2, -1, -1, -1]Seen Array Evolution:After 1: seen = [1]After 2: seen = [2, 1] (prepend)Query Processing:1st -1: k=1 → seen[0] = 22nd -1: k=2 → seen[1] = 13rd -1: k=3 > len(seen) → -1Output: [2, 1, -1]
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
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~15 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen