LeetCode 2899: Last Visited Integers Solution

Master LeetCode problem 2899 (Last Visited Integers), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2899. Last Visited Integers

Problem Explanation

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.

Solution Code

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);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2899 (Last Visited Integers)?

This page provides optimized solutions for LeetCode problem 2899 (Last Visited Integers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2899 (Last Visited Integers)?

The time complexity for LeetCode 2899 (Last Visited Integers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2899 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2899 in Java, C++, or Python.

Back to LeetCode Solutions