Leetcode 2899: Last Visited Integers

grid47
grid47
Exploring patterns and algorithms
Jan 22, 2024 5 min read

Given an integer array nums, where each element is either a positive integer or -1. For each -1, find the respective last visited positive integer. The ’last visited integer’ refers to the most recent positive integer seen before each -1.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `nums` where each element is either a positive integer or -1.
Example: [7,-1,8,-1,-1]
Constraints:
• 1 <= nums.length <= 100
• nums[i] == -1 or 1 <= nums[i] <= 100
Output: Return an array `ans` where for each `-1` in the input, the corresponding element in `ans` is the last positive integer seen before it. If there aren't enough positive integers, append `-1`.
Example: [7,8,7]
Constraints:
• The length of the output array should be the same as the input array.
Goal: To keep track of the most recent positive integers and assign them to the respective `-1` based on the count of consecutive `-1` encountered.
Steps:
• Initialize an empty array `seen` and an empty array `ans`.
• Iterate through the array `nums`.
• For each positive integer, prepend it to `seen`.
• For each `-1`, find the `k`-th element in `seen` and append it to `ans`. If `k` exceeds the length of `seen`, append `-1`.
Goal: The problem constraints ensure that the input size is manageable and the values of `nums` are within a defined range.
Steps:
• 1 <= nums.length <= 100
• nums[i] == -1 or 1 <= nums[i] <= 100
Assumptions:
• The array `nums` is non-empty.
• Each `-1` in the array has a respective 'last visited integer' if enough positive integers precede it.
Input: [7,-1,8,-1,-1]
Explanation: For each `-1`, find the respective last positive integer based on the elements seen so far. If there aren't enough integers, append `-1`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus