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 INPUT nums array: 1 i=0 2 i=1 -1 i=2 -1 i=3 -1 i=4 Positive integer -1 (query) Initial State: seen = [] ans = [] k = 0 Approach: Deque/List ALGORITHM STEPS 1 Process nums[0]=1 Prepend to seen: [1] k resets to 0 2 Process nums[1]=2 Prepend to seen: [2,1] k resets to 0 3 Process -1s (i=2,3,4) idx k seen[k-1] ans 2 1 seen[0]=2 [2] 3 2 seen[1]=1 [2,1] 4 3 k>len! [2,1,-1] 4 Return Result ans = [2, 1, -1] Final seen: [2, 1] 2 1 FINAL RESULT Output array: 2 ans[0] 1 ans[1] -1 ans[2] Explanation: ans[0] = 2: 1st -1, k=1 seen[0] = 2 ans[1] = 1: 2nd -1, k=2 seen[1] = 1 ans[2] = -1: 3rd -1, k=3 k > len(seen)! OUTPUT: [2, 1, -1] OK - Verified Key Insight: Use a deque/list to prepend positive integers (most recent first). Track consecutive -1s with counter k. For each -1: if k <= len(seen), return seen[k-1]; else return -1. Reset k when encountering positive integer. Time: O(n) | Space: O(n) - optimal solution using deque for O(1) prepend operations TutorialsPoint - Last Visited Integers | Optimized with Deque/List
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