Initial solution.
added some comments to clarify and improved performance to 2N.