Smart back button, PLEASE HELP ME!

say I have 5 buttons that go to their corresponding frames (1 to 5):

1 2 3 4 5

I also have a back button. What I am trying to achieve is this:

I click on 5, then on 1, then on 3. the sequence was 5, 1, 3, the last
button pressed was 3, which is where I am currently. The second last
button pressed was 1. Now I click the back button. I want the back
button to recognize that frame 1 is actually the previous frame and not
frame 2.

I was thinking about global variables, but I have yet to get this concept
to work for me. If anyone is willing to help I’d appreciate it.

Thanks