Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (sliding window: count subarrays with product less than k, positive values)
What is printed? (sliding window: count subarrays with product less than k, positive values)
def count_prod(a, k):
if k <= 1: return 0
prod = 1; l = res = 0
for r, x in enumerate(a):
prod *= x
while prod >= k:
prod //= a[l]; l += 1
res += r - l + 1
return res
print(count_prod([10, 5, 2, 6], 100), count_prod([1, 2, 3], 0))- A. 8 0
- B. 7 0
- C. 8 6
- D. 6 0
Correct answer: A. 8 0
For each right end, every window [l..r] whose product is below k counts: 1 + 2 + 2 + 3 = 8 ([10], [10,5], [5], [5,2], [2], [5,2,6], [2,6], [6]). k ≤ 1 can never be beaten by positive integers, and the early return avoids an empty-window infinite loop. O(n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (Java: == vs equals on Strings) java String a = "hello"; String b = "hel" + "lo"; String c = new String("hello"); String…
- What is printed? (expected probes in a hash table) python alpha = 0.75 chaining = 1 + alpha / 2 linearhit = 0.5 (1 + 1 / (1 - alpha))…
- What is printed? (reverse a sublist of a linked list between positions m and n, 1-based) python def revbetween(a, m, n): a = a[:] a[m…
- What is printed? (min-heap array after inserts) python import heapq h = [] for x in [9, 4, 7, 1, 8, 2]: heapq.heappush(h, x) print(h…
- What is printed? (queue using a fixed array without wrap-around) python N = 4; q = [None] N; front = rear = 0; log = [] def enq(x): global…
- A warehouse scores a shelf by adding, over every contiguous run of boxes, the weight of the lightest box in the run. Two monotonic-stack…