For fun: Java 8 unreadable 5-liner :)

  • 0

    Playing with Java 8 features again :) This code is super slow on LeetCode. In practice it should be as fast as loops and maybe even faster if streams are manipulated in parallel using the parallel() modifier.

    public int numSquares(int n) {
        List<Integer> mem = IntStream.range(0,n+1).boxed().collect(Collectors.toList()); 
        IntStream.range(0,n+1).forEach(i -> { 
                IntStream.range(0,(int)Math.sqrt(i)+1).forEach(j -> mem.set(i,Math.min(mem.get(i-j*j)+1, mem.get(i))));
        return mem.get(n);

  • 0

    Aaaah, sideffects! Streams are not magic bullet... kudos for sharing though. I think some of the bad performance comes from class-loading on first execution.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.