Java || Runtime 2ms || Beat 98% || With detailed explanation
Code\n\nclass Solution {\n    public List<Integer> lastVisitedIntegers(List<String> words) {\n        List<Integer> res = new ArrayList<>(); // List for final r
# Code\n```\nclass Solution {\n    public List<Integer> lastVisitedIntegers(List<String> words) {\n        List<Integer> res = new ArrayList<>(); // List for final results\n        List<Integer> numbersSeen = new ArrayList<>(); // List to store numbers seen so far\n        int consecutivePrevCount = 0; // Counts consecutive "prev" strings\n\n        for (String word : words) {\n            if (!word.equals("prev")) {\n                // If it\'s a number, reset consecutivePrevCount and add to numbersSeen\n                consecutivePrevCount = 0;\n                numbersSeen.add(Integer.parseInt(word));\n            } else {\n                // Increment consecutivePrevCount for each "prev"\n                consecutivePrevCount++;\n\n                if (consecutivePrevCount > numbersSeen.size()) {\n                    // If more "prev" than numbers, add -1\n                    res.add(-1);\n                } else {\n                    // Add the number corresponding to the count of "prev" from the end\n                    res.add(numbersSeen.get(numbersSeen.size() - consecutivePrevCount));\n                }\n            }\n        }\n\n        return res; // Return the result list\n    }\n}\n\n```\n![87bab3dd-fabf-4b71-9ac5-984d9015438e_1678160362.0612018.jpeg](https://assets.leetcode.com/users/images/bb449883-7202-466f-90e7-92d08d400fc1_1703123333.5914512.jpeg)\n
['Java']