How do the molecules know the future? How do they proceed to form "Most Stable" compound?
Chemical reactions occur because the thermal energy in a substance makes molecules bump into each other, and each time they bump into each other there is some chance for a reaction to take place.  This is an oversimplified model, but it suffices to get some intuition for what's going on.

The molecules of course do not "know" that some configuration is more stable than others.  What happens is that the molecules react randomly, again and again; they take a sort of random walk through the available configurations.  Every now and then, a molecule will purely randomly find its way into the stable state.  Once it's there, it's "stuck" - it has a much smaller chance of getting out of the stable state.  That's more or less what it means for a state to be stable.

Over time, more and more molecules will find their way into the stable state and get stuck, so the result looks as if the molecules "knew" which state to go to and just went straight there.  But actually they only got there through the process of randomly bouncing around the configuration space, plus the stable state acting as a trap that molecules can enter but not (as easily) leave.