Optimized Approach to Retrieve Recent Positive Integers with Each Negative Input || JAVA
Intuition\nThe problem requires tracking the most recent positive integers and retrieving the k-th last positive integer whenever a negative integer is encounte
# Intuition\nThe problem requires tracking the most recent positive integers and retrieving the k-th last positive integer whenever a negative integer is encountered. The core idea is to maintain a list of seen positive integers and, upon encountering a negative integer, determine the appropriate positive integer from this list based on the count of negative integers seen so far.\n\n# Approach\nInitialization:\n\nUse a LinkedList named seen to store positive integers as they are encountered. This allows efficient addition of elements to the end of the list.\nUse an ArrayList named ans to collect the results for each negative integer encountered.\nProcessing the Array:\n\nTraverse through each element in the array nums.\nFor each positive integer, add it to the seen list.\nFor each negative integer, increment a counter that tracks how many negative integers have been processed. Use this counter to retrieve the appropriate positive integer from the end of the seen list. If there aren\'t enough positive integers, add -1 to ans.\nResult Compilation:\n\nReturn the ans list, which contains the results for each negative integer in the order they were encountered.\n\n# Complexity\n- Time complexity:\nO(n): Each element in the nums array is processed exactly once. Operations on LinkedList (like add) and ArrayList (like get) are constant time on average, making the overall time complexity linear with respect to the size of the array.\n\n- Space complexity:\nO(n): The space complexity is determined by the storage used for the seen and ans lists. In the worst case, where all elements are positive, seen can store up to n elements, and ans will have up to n entries. Thus, the space complexity is linear with respect to the size of the input array.\n\n# Code\n```\nclass Solution {\n    public List<Integer> lastVisitedIntegers(int[] nums) {\n        List<Integer> seen=new ArrayList<>();\n        List<Integer> ans=new ArrayList<>();\n\n        int counter=0;\n\n        for (int i = 0; i < nums.length; i++) {\n            if (nums[i]>0) {\n                counter=0;\n                seen.addFirst(nums[i]);\n            }\n            if (nums[i]<0) {\n                counter++;\n\n                if (counter<=seen.size()) {\n                    ans.add(seen.get(counter-1));\n                }else{\n                    ans.add(-1);\n                }\n            }\n        }\n\n        return ans;\n    }\n}\n```
['Java']