5
\$\begingroup\$

I had this question in an interview recently. Given a sorted array of integers, return a list of those integers squared, with the squares sorted. So given an array of these numbers:

-5, -3, 1, 2, 4 

the result should be this:

1 4 9 16 25 

I came up with this solution using Java 8 streams, but is there a way to do this without the call to Array.sort?

public static int[] sortedSquares(int[] arr) { arr = Arrays.stream(arr).map(i -> i * i).toArray(); Arrays.sort(arr); return arr; } 
\$\endgroup\$
4
  • 3
    \$\begingroup\$Yes, there is a linear solution. Find the minimal element. Its square is guaranteed to be minimal. Now think of two indices traversing the array to the left and to the right from the minimal element, producing squares in a desired order.\$\endgroup\$
    – vnp
    CommentedJun 4, 2020 at 1:20
  • \$\begingroup\$In the example, the minimal element of the original array is -5, but its square is +25, which is not the minimal square (which would be +1 squared = 1), so how would this work?. (The original array is guaranteed to be sorted, by the way. At least that's the way the problem was stated to me.)\$\endgroup\$
    – Frank
    CommentedJun 4, 2020 at 1:33
  • 2
    \$\begingroup\$Sorry, minimal abs.\$\endgroup\$
    – vnp
    CommentedJun 4, 2020 at 1:40
  • \$\begingroup\$@vnp no need for abs, just take the first nonnegative element and see how its sum with its previous element compares to zero.\$\endgroup\$
    – slepic
    CommentedJun 4, 2020 at 17:33

2 Answers 2

1
\$\begingroup\$

One way to be more concise is to use the Stream.sorted() method right in the stream:

public static int[] sortedSquares(int[] arr) { arr = Arrays.stream(arr).map(i -> i * i).sorted().toArray(); return arr; } 
\$\endgroup\$
0
    2
    \$\begingroup\$

    For an interview, this is bad code. It is \$O(n \log n)\$. But it can be done in \$O(n)\$ time. Your code does not show your skills in that direction. Also, many interviewers (justifiably) will be unhappy for using streams. Streams may look cute but at scale like Gmail, they cause performance problems.

    \$\endgroup\$
    1
    • 1
      \$\begingroup\$How would you code this so it's \$O(n)\$?\$\endgroup\$
      – Frank
      CommentedJul 9, 2020 at 4:44

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.