added time efficient solution