ProgrammingHardInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
def sq_sorted(a):
    l, r = 0, len(a) - 1
    out = [0] * len(a)
    k = len(a) - 1
    while l <= r:
        if abs(a[l]) > abs(a[r]):
            out[k] = a[l] * a[l]
            l += 1
        else:
            out[k] = a[r] * a[r]
            r -= 1
        k -= 1
    return out
print(sq_sorted([-4, -1, 0, 3, 10]), sq_sorted([-7, -3, 2, 3, 11]))
  1. A. [0, 1, 9, 16, 100] [4, 9, 9, 121, 49]
  2. B. [0, 1, 4, 9, 16] [4, 9, 9, 49, 121]
  3. C. [0, 1, 9, 16, 100] [4, 9, 9, 49, 121]
  4. D. [0, 1, 9, 16, 100] [2, 9, 9, 49, 121]

Correct answer: C. [0, 1, 9, 16, 100] [4, 9, 9, 49, 121]

Filling from the back with the larger absolute value gives sorted squares in O(n) without a sort. The first array squares to 0, 1, 9, 16, 100 and the second to 4, 9, 9, 49, 121.

More Python Programming questions

Exams that ask this topic