Non-bruteforce solution (initial ver)