ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita
What is printed?
What is printed?
def three_sum(a):
a = sorted(a)
out = []
for i in range(len(a) - 2):
if i and a[i] == a[i - 1]:
continue
l, r = i + 1, len(a) - 1
while l < r:
s = a[i] + a[l] + a[r]
if s < 0:
l += 1
elif s > 0:
r -= 1
else:
out.append([a[i], a[l], a[r]])
l += 1
while l < r and a[l] == a[l - 1]:
l += 1
return out
print(three_sum([-1, 0, 1, 2, -1, -4]))- A. [[-1, -1, 2], [-1, 0, 1]]
- B. [[-1, -1, 2], [-1, 0, 1], [-1, 0, 1]]
- C. [[-4, 0, 1]]
- D. [[-1, 0, 1], [-1, -1, 2]]
Correct answer: A. [[-1, -1, 2], [-1, 0, 1]]
Sorting lets the code fix one value and move two pointers, skipping repeated values so each triplet appears once. Only -1, -1, 2 and -1, 0, 1 sum to zero.
More Python Programming questions
- What is printed? python def distinct(s, t): dp = [1] + [0] len(t) for ch in s: for j in range(len(t), 0, -1): if t[j - 1] == ch: dp[j] +=…
- What is printed? python import bisect def pairsle(a, d): a = sorted(a) c = 0 for i, x in enumerate(a): j = bisect.bisectright(a, x + d, i…
- What is printed? python import bisect def closest(a, x): i = bisect.bisectleft(a, x) cands = a[max(i - 1, 0):i + 1] return min(cands…
- What is printed? python def content(g, s): g.sort(); s.sort() i = j = 0 while i < len(g) and j < len(s): if s[j] >= g[i]: i += 1 j += 1…
- What is printed? python from collections import Counter def least(tasks, n): c = Counter(tasks) m = max(c.values()) k = sum(1 for v in…
- What is printed? python s = 'abcdefg' print(s[::-2], s[5:1:-2], s[-3::-3])