ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
def pairs(a, t):
a = sorted(a)
i, j, c = 0, len(a) - 1, 0
while i < j:
s = a[i] + a[j]
if s == t:
c += 1
i += 1
j -= 1
elif s < t:
i += 1
else:
j -= 1
return c
print(pairs([1, 1, 1, 1], 2))- A. 6
- B. 2
- C. 4
- D. 3
Correct answer: B. 2
After a match the code moves both pointers, which skips the other copies of the same value. For [1,1,1,1] it finds only two matches, although the true number of index pairs with sum 2 is 6.
More Python Programming questions
- What is printed? python def countk(a, k): pre = {0: 1} s = 0 ans = 0 for x in a: s += x ans += pre.get(s - k, 0) pre[s] = pre.get(s, 0) +…
- What is printed? python from collections import deque g = ['..#', '.##', '...'] def bfs(g): R, C = len(g), len(g[0]) d = {(0, 0): 0} q =…
- What is printed? python from functools import lrucache calls = 0 @lrucache(maxsize=None) def f(n): global calls calls += 1 if n < 2…
- What is printed? python def greedy(coins, amt): cnt = 0 for c in sorted(coins, reverse=True): cnt += amt // c amt %= c return cnt if amt…
- What is printed? python import bisect def lis(a): t = [] for x in a: i = bisect.bisectleft(t, x) if i == len(t): t.append(x) else: t[i] =…
- A list a is sorted in ascending order and may contain duplicates. Using bisectleft and bisectright from the bisect module, which…