4

I have a method similar to the following one:

public double[] foo(double[] doubleArray) { 
    DoubleStream stream = Arrays.stream(doubleArray);

    return stream.map(s -> s / stream.sum()).toArray();
}

What is the complexity of this method? How many times will DoubleStream's sum method be executed? Once or O(n) times, with n = doubleArray.length?

1
  • 3
    this will still fail... you need to create the stream again from the source Commented Aug 1, 2017 at 9:00

1 Answer 1

7

This code will throw an exception, since you can't consume the same Stream more than once. You can only execute one terminal operation on a Stream.

If you change the code to:

public double[] foo(double[] doubleArray) { 
    return Arrays.stream(doubleArray).map(s -> s / Arrays.stream(doubleArray).sum()).toArray();
}

it will work, but the running time will be quadratic (O(n^2)), since the sum will be computed n times.

A better approach would be to compute the sum just once:

public double[] foo(double[] doubleArray) { 
    double sum = Arrays.stream(doubleArray).sum();
    return Arrays.stream(doubleArray).map(s -> s / sum).toArray();
}

This will run in linear time.

Sign up to request clarification or add additional context in comments.

1 Comment

@Eugene You can mention it, or you can just write linear time as I did. It doesn't matter if it's n or 2n or cn. All are linear time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.