[LeetCode] Last Visited Integers

2899. Last Visited Integers

Given a 0-indexed array of strings words where words[i] is either a positive integer represented as a string or the string "prev".

Start iterating from the beginning of the array; for every "prev" string seen in words, find the last visited integer in words which is defined as follows:

  • Let k be the number of consecutive "prev" strings seen so far (containing the current string). Let nums be the 0-indexed array of integers seen so far and nums_reverse be the reverse of nums, then the integer at (k - 1)th index of nums_reverse will be the last visited integer for this "prev".
  • If k is greater than the total visited integers, then the last visited integer will be -1.

Return an integer array containing the last visited integers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
vector<int> lastVisitedIntegers(vector<string>& words) {
vector<int> res;
vector<int> st;
int cons = 0;
for(auto w : words) {
if(w == "prev") {
cons += 1;
if(st.size() < cons) {
res.push_back(-1);
} else res.push_back(st[st.size() - cons]);
} else {
cons = 0;
st.push_back(stoi(w));
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/15/PS/LeetCode/last-visited-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.