Okay, i am trying to understand OPT algorithm then it will make it easy for me to code it.
I cant follow along with the slide and its making no sense. Can someone walk me through it step by step on how to do it?
This looks identical to the LRU algorithm. Do we keep a second array with a counter?

You apparently must know in advance which pages are going to be used and in what order; this is the list
1, 2, 3, ..., 4, 5in your example. When you must replace a page, you choose the frame containing the page that will be used last amongst all of them.In this example, you access pages 1, 2, 3, 4, 1, and 2 without any page faults (since all pages are currently swapped in).
Your next page access, page 5, is not in any frame, so you must choose a frame to put it into. Based on upcoming page hits (1, 2, 3, 4), page 4 (in frame 4) will be last to be accessed, so you swap page 5 into frame 4 (as shown in your diagram).
The next pages, 1, 2, and 3 are accessed without any fault.
Now page 4 is accessed but it was previously swapped out so you have a page fault. Your list of upcoming accesses shows only page 5 will be needed, so any of 1, 2, and 3 may be swapped out. 1 was chosen, presumably because it is first.