faster solution for Q5