solve problem3(this algorithm is not efficient)