first solution to problem 2. Needs to be optimized as the current version is brute force