Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: Count contiguous subarrays of positive integers whose product is strictly less than k, using a shrinking window.
Problem: Count contiguous subarrays of positive integers whose product is strictly less than k, using a shrinking window.
def prod_less(a, k):
if k <= 1: return 0
p, l, res = 1, 0, 0
for r, x in enumerate(a):
p *= x
while p >= k:
p //= a[l]; l += 1
res += r - l + 1
return res
print(prod_less([4, 3, 5, 2], 30), prod_less([2, 9, 1], 1), prod_less([1, 1, 1], 2))What is printed?- A. 7 3 6
- B. 8 0 6
- C. 7 0 6
- D. 7 0 3
Correct answer: C. 7 0 6
Because all values are positive, the window product only grows as r moves right, so shrink from the left until it is < k; every subarray ending at r and starting in [l, r] then qualifies (r − l + 1 of them). [4, 3, 5, 2] with k = 30: 4, 3, 5, 2, 12, 15, 10 → 7 (3·5·2 = 30 is not < 30). k ≤ 1 → 0. [1, 1, 1] with k = 2: all 6 subarrays. O(n).
More Coding Interview Problems questions
- Problem: An array is a permutation of 0..n−1. Split it into the maximum number of chunks so that sorting each chunk separately and…
- Problem: Seat numbers must become pairwise distinct; one move increments a seat number by 1. Find the minimum moves (sort, then push each…
- Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval. python…
- Problem: A sensor array is 'steady' between positions i < j if a[j] − a[i] = j − i. Count steady pairs in O(n) by grouping a[i] − i…
- Problem: Four price lists A, B, C, D (each of length n ≤ 500). Count index tuples (i, j, k, l) with A[i] + B[j] + C[k] + D[l] = 0 by…
- Problem: A hiking trail is a list of heights. Find the length of the longest 'ridge' – a contiguous stretch that strictly rises and then…