Data Structures & AlgorithmsModerateTCS NQT · counting
Problem: How many distinct products a[i] a[j] (i < j) does [1, 2, 3, 4] produce? Run the code.
Problem: How many distinct products a[i] * a[j] (i < j) does [1, 2, 3, 4] produce? Run the code.
from itertools import combinations
print(len({x * y for x, y in combinations([1, 2, 3, 4], 2)}))What is printed?- A. 5
- B. 6
- C. 4
- D. 3
Correct answer: B. 6
combinations gives the 6 pairs (i < j) and their products 2, 3, 4, 6, 8, 12 are all different, so the set keeps 6. A collision such as 1 × 4 = 2 × 2 would need an element paired with itself, which combinations never produces.
More Coding Interview Problems questions
- Problem: What is the smallest positive integer missing from [3, 4, -1, 1]? Run the code. python a = [3, 4, -1, 1] m = 1 while m in a: m +=…
- Problem: What is the sum of the lengths of all contiguous subarrays of [1, 2, 3]? Run the code. python a = [1, 2, 3] print(sum(len(a[i:j])…
- Problem: What is 6! mod 7, the value predicted by Wilson's theorem for a prime p = 7 (where (p-1)! ≡ -1 mod p, i.e. 6 mod 7)? Run the…
- Problem: How many integers in [1, 50] are divisible by both 2 and 3? Run the code. python print(sum(1 for x in range(1, 51) if x % 2 == 0…
- Problem: What is the sum of the first 10 odd positive integers? Run the code. python print(sum(2 i + 1 for i in range(10))) What is printed?
- Problem: How many 2-digit numbers have both digits odd? Run the code. python print(sum(1 for x in range(10, 100) if int(str(x)[0]) % 2 ==…