Skip to content

2899. Last Visited Integers 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  vector<int> lastVisitedIntegers(vector<string>& words) {
    vector<int> ans;
    vector<int> nums;
    int k = 0;

    for (const string& word : words)
      if (word == "prev") {
        ++k;
        ans.push_back(k > nums.size() ? -1 : nums[nums.size() - k]);
      } else {
        k = 0;
        nums.push_back(stoi(word));
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public List<Integer> lastVisitedIntegers(List<String> words) {
    List<Integer> ans = new ArrayList<>();
    List<Integer> nums = new ArrayList<>();
    int k = 0;

    for (final String word : words)
      if (word.equals("prev")) {
        ++k;
        ans.add(k > nums.size() ? -1 : nums.get(nums.size() - k));
      } else {
        k = 0;
        nums.add(Integer.valueOf(word));
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def lastVisitedIntegers(self, words: list[str]) -> list[int]:
    ans = []
    nums = []
    k = 0

    for word in words:
      if word == 'prev':
        k += 1
        ans.append(-1 if k > len(nums) else nums[-k])
      else:
        k = 0
        nums.append(int(word))

    return ans