Is there any efficient solution for this problem?