Last Visited Integers - O(n) Java | Beats 100%
Intuition\nThe code essentially maintains a list of integers encountered, and when the word "prev" is encountered, it looks back a certain number of positions i
# Intuition\nThe code essentially maintains a list of integers encountered, and when the word "prev" is encountered, it looks back a certain number of positions in the list to find the last visited integer(s) and adds them to the result list. If "prev" is not encountered, it adds the current integer to the list for future reference.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\n    public List<Integer> lastVisitedIntegers(List<String> words) {\n        final List<Integer> answers = new LinkedList<>();\n        final List<Integer> numbers = new ArrayList<>();\n        \n        int prevSeen = 0;\n        \n        for(String word: words){\n            if("prev".equals(word)){\n                prevSeen++;\n                \n                int i = numbers.size() - prevSeen;\n                \n                answers.add(0 <= i ? numbers.get(i) : -1);\n            } else {\n                prevSeen = 0;\n                numbers.add(Integer.valueOf(word));\n            }\n        }\n        \n        return answers;\n    }\n}\n```
['Array', 'String', 'Java']