Data Structures & AlgorithmsModerateTCS NQT · sorting
Problem: What is the sum of |ai - aj| over all pairs i < j of the sorted array [1, 4, 6]? Run the code.
Problem: What is the sum of |a_i - a_j| over all pairs i < j of the sorted array [1, 4, 6]? Run the code.
a = sorted([1, 4, 6]) print(sum(abs(a[i] - a[j]) for i in range(len(a)) for j in range(i + 1, len(a))))What is printed?
- A. 8
- B. 12
- C. 10
- D. 6
Correct answer: C. 10
On the sorted array each a[i] is added i times and subtracted (n − 1 − i) times: 1·(−2) + 4·0 + 6·2 = 10, matching the differences 3 + 5 + 2. Summing only adjacent gaps gives 5, and counting ordered pairs would double it.
More Coding Interview Problems questions
- Problem: Which complexity does the sieve of Eratosthenes have for finding all primes up to n?
- Problem: How many 3-digit numbers are palindromes? python print(sum(1 for x in range(100, 1000) if str(x) == str(x)[::-1])) What is printed?
- Problem: How many integers in [1, 200] are divisible by 2, 3 or 5? python print(sum(1 for x in range(1, 201) if x % 2 == 0 or x % 3 == 0…
- Problem: How many subsets of {1, 2, 3, 4, 5, 6} have sum exactly 10? python print(sum(1 for m in range(1 << 6) if sum(i + 1 for i in…
- Problem: What is the sum of the decimal digits of 9^9? python print(sum(int(c) for c in str(9 9))) What is printed?
- Problem: What is the length of the longest increasing subsequence of [3, 10, 2, 1, 20]? python import bisect a = [3, 10, 2, 1, 20] tails =…