The idea is to use a linkedList to represents the body of snake, and use a hashset to represents the position of snake's body. So we can get constant time to check whether the next position is valid.

Also note that the snake can move to it's own tail. So it means that we have to delete the tail position from the hashset before we check the valid.public class SnakeGame { Map<String, int[]> map; int idx = 0; int[][] food; LinkedList<int[]> snake; int width; int height; Set<String> posi = new HashSet<>();