Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Return the squares of a sorted array (values may be negative) in non-decreasing order in O(n), filling the result from the back with two pointers.

Problem: Return the squares of a sorted array (values may be negative) in non-decreasing order in O(n), filling the result from the back with two pointers.
def sorted_squares(a):
    n = len(a); res = [0] * n
    l, r, k = 0, n - 1, n - 1
    while l <= r:
        if abs(a[l]) > abs(a[r]):
            res[k] = a[l] * a[l]; l += 1
        else:
            res[k] = a[r] * a[r]; r -= 1
        k -= 1
    return res
print(sorted_squares([-7, -3, 2, 3, 11]))
What is printed?
  1. A. [121, 49, 9, 9, 4]
  2. B. [4, 9, 9, 49, 121]
  3. C. [4, 9, 49, 121]
  4. D. [49, 9, 4, 9, 121]

Correct answer: B. [4, 9, 9, 49, 121]

The largest square is always at one of the two ends (most negative or most positive), so compare |a[l]| and |a[r]| and write the bigger square into the last free slot. Order of writes: 121, 49, 9 (from 3), 9 (from −3), 4. Squaring in place without re-sorting would leave [49, 9, 4, 9, 121]. O(n) time, O(n) output.

More Coding Interview Problems questions

Exams that ask this topic