Data Structures & AlgorithmsModerateTCS NQT · hashing warm-up
Problem: How many unordered pairs of distinct elements of [1, 5, 3, 9, 7, 2] have absolute difference exactly 2? Run the code.
Problem: How many unordered pairs of distinct elements of [1, 5, 3, 9, 7, 2] have absolute difference exactly 2? Run the code.
a = [1, 5, 3, 9, 7, 2] print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if abs(a[i] - a[j]) == 2))What is printed?
- A. 3
- B. 2
- C. 4
- D. 5
Correct answer: C. 4
The pairs (1,3), (3,5), (5,7) and (7,9) have difference 2, giving 4. A hash-set lookup of x + 2 counts the same pairs in O(n).
More Coding Interview Problems questions
- Problem: Minimum cost to climb stairs where cost[i] is paid when standing on step i and you may take one or two steps. Starting positions…
- Problem: Houses in a circle hold the amounts [2, 3, 2]. You may not rob two adjacent houses, and the first and last are adjacent. Run the…
- Problem: What is the length of the longest common subsequence of 'ABCBDAB' and 'BDCABA'? python a, b = 'ABCBDAB', 'BDCABA' dp = [[0]…
- Problem: The number of structurally distinct binary search trees on 5 keys is the Catalan number. What does this code print? python dp =…
- Problem: What is the sum over all pairs (i < j) of the Hamming distances (number of differing bits) between the values in [1, 3, 5]? Run…
- Problem: People with weights [3, 2, 2, 1] must cross a river. A boat carries at most 2 people with total weight at most limit = 3, and…