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]))- A. [0, 1, 9, 16, 100] [4, 9, 9, 121, 49]
- B. [0, 1, 4, 9, 16] [4, 9, 9, 49, 121]
- C. [0, 1, 9, 16, 100] [4, 9, 9, 49, 121]
- 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
- What is printed? python def minpath(g): dp = [0] len(g[0]) for i, row in enumerate(g): for j, v in enumerate(row): if i == 0 and j == 0…
- What is printed? python from functools import lrucache def wb(s, words): @lrucache(maxsize=None) def go(i): if i == len(s): return 1…
- What is printed? python from functools import cache @cache def ways(s, i=0): if i == len(s): return 1 if s[i] == '0': return 0 total =…
- What is printed? python import heapq words = ['bb', 'a', 'cc', 'dd', 'e'] print(heapq.nlargest(2, words, key=len), heapq.nsmallest(2…
- What is printed? python data = [3, 8, 15, 4, 22] res = [y for x in data if (y := x 2) > 20] print(res, y)
- A sorted array holds 10^6 integers and receives 10^5 queries asking how many values are at most x. Which approach is fastest in CPython?