LeetCode 2899: Last Visited Integers

ArraySimulation

Problem Description

Explanation

The problem requires finding the last visited positive integer for each occurrence of -1 in the given array. We can achieve this by maintaining two arrays, seen and ans. We iterate through the nums array, updating seen with positive integers and handling -1 occurrences to calculate the last visited integer. The algorithm involves keeping track of consecutive -1 occurrences and accessing the appropriate element from the seen array.

  • Time complexity: O(n) where n is the length of the input array nums.
  • Space complexity: O(n) for the seen and ans arrays.

Solutions

class Solution {
    public int[] findLastVisited(int[] nums) {
        int n = nums.length;
        int[] seen = new int[n];
        int[] ans = new int[n];
        int idx = 0;
        
        for (int num : nums) {
            if (num != -1) {
                seen[idx++] = num;
            } else {
                int k = 1;
                while (k <= idx && seen[idx - k] == -1) {
                    k++;
                }
                ans[idx] = k <= idx ? seen[idx - k] : -1;
                idx++;
            }
        }
        
        return Arrays.copyOf(ans, idx);
    }
}

Loading editor...