Leetcode Problem 2899. Last Visited Integers

2899. Last Visited Integers

Leetcode Solutions

Tracking Last Visited Integers with Stack

  1. Initialize an empty stack visitedIntegers to keep track of the integers seen so far.
  2. Initialize an empty list result to store the last visited integers for each 'prev'.
  3. Initialize a variable prevCount to 0 to count consecutive 'prev' strings.
  4. Iterate through each string in the words array. a. If the current string is an integer, reset prevCount to 0 and push the integer onto the visitedIntegers stack. b. If the current string is 'prev', increment prevCount. i. If prevCount is greater than the size of visitedIntegers, append -1 to result. ii. Otherwise, append the integer at index size - prevCount from the visitedIntegers stack to result.
  5. Return the result list.
UML Thumbnail

Iterative Approach with Consecutive 'prev' Counter

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...