another solution without sorting