Data Structures & AlgorithmsModerateAmazon · Microsoft OA
For an array of n = 10⁶ integers, report the number of DISTINCT values in every window of k = 10⁵ consecutive elements. Which approach is efficient and correct?
- A. Slide one window with a hash map of counts and a distinct counter, O(n)
- B. Put each window into a set from scratch, O(n · k)
- C. Sort each window and count runs, O(n · k log k)
- D. Use prefix sums of the values, O(n)
Correct answer: A. Slide one window with a hash map of counts and a distinct counter, O(n)
Each step changes only two counts, so the distinct total updates in O(1) average time: about 10⁶ operations. Rebuilding a set per window is 10¹¹ steps. Prefix sums add values; they cannot count distinct ones.
More Coding Interview Problems questions
- n = 10⁵ points are given, followed by q = 10⁵ OFFLINE queries 'how many points lie in the axis-aligned rectangle [x1, x2] × [y1, y2]?'…
- Edge case: integer division and modulo with negative operands in Python. python print(-7 // 2, -7 % 2, int(-7 / 2)) What is printed?
- Problem: Replace at most k characters so that the longest possible substring consists of one repeated letter; return its length. python…
- Problem: Smallest length of a contiguous subarray of POSITIVE integers with sum ≥ target (0 if none). python def minlen(a, t): l, s, best…
- Problem: Return all start indices of anagrams of p inside s using a fixed-size window of letter counts. python from collections import…
- Problem: Intersect two lists of disjoint, sorted closed intervals. python def inter(A, B): i = j = 0; out = [] while i < len(A) and j <…