Data Structures & AlgorithmsVery hardProduct Company SDE · prefix-sum OA
Problem: How many subarrays of [3, 4, 7, 2, -3, 1, 4, 2] have sum exactly 7? Run the prefix-sum hash code.
Problem: How many subarrays of [3, 4, 7, 2, -3, 1, 4, 2] have sum exactly 7? Run the prefix-sum hash code.
from collections import Counter
a = [3, 4, 7, 2, -3, 1, 4, 2]
c = Counter({0: 1})
s = ans = 0
for x in a:
s += x
ans += c[s - 7]
c[s] += 1
print(ans)What is printed?- A. 3
- B. 5
- C. 6
- D. 4
Correct answer: D. 4
Prefix sums stored in a hash map count every earlier prefix equal to s - 7, so each subarray with sum 7 is counted once; the total is 4.
More Coding Interview Problems questions
- Problem: What is the length of the shortest substring of 'aabcbcdbca' that contains all distinct characters of the string? Run the…
- Problem: What is the Levenshtein distance between 'horse' and 'ros'? Run the DP. python a, b = 'horse', 'ros' dp = [[0] (len(b) + 1) for…
- Problem: What is the sum of |ai - aj| over all pairs i < j of the sorted array [1, 4, 6]? Run the code. python a = sorted([1, 4, 6])…
- 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…