Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Given n ≤ 10⁵ integers (not sorted), find the length of the longest run of consecutive values, e.g. [100, 4, 200, 1, 3, 2] → 4 (1, 2, 3, 4). What is the time complexity of the optimal approach?
- A. O(n log n) – sorting is unavoidable
- B. O(n) – put all values in a hash set and start counting only from values x where x − 1 is absent
- C. O(n²) – each value must be extended in both directions
- D. O(n √n) – using square-root decomposition
Correct answer: B. O(n) – put all values in a hash set and start counting only from values x where x − 1 is absent
With a hash set, a run is extended only from its smallest element (x − 1 not present), so every value is visited a constant number of times overall: O(n) average. Sorting gives O(n log n), which passes but is not optimal; extending from every element without the start check is O(n²) in the worst case.
More Coding Interview Problems questions
- Problem: Group words that are anagrams of each other and report how many groups there are. python from collections import defaultdict def…
- Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative. python def countk(a, k): seen = {0: 1} p =…
- Problem: Count subarrays whose sum is divisible by k (values may be negative). python def divk(a, k): cnt = [0] k cnt[0] = 1 p = ans = 0…
- Problem: For n ≤ 2 × 10⁵ integers in the range −10⁴..10⁴, count subarrays with sum exactly k. Why does a two-pointer sliding window NOT…
- Problem: A game keeps scores in a non-decreasing array. Remove duplicates in place and return the number of unique scores. python def…
- Problem: Allow each value at most twice in a sorted array (in place) and return the new length. python def keep2(a): w = 0 for x in a: if…