added another solution that used a smarter approach
added some short circuiting to speed it up