Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft
Longest run of consecutive integers (in any order) using a hash set and starting only from numbers whose predecessor is absent. What is printed?
Longest run of consecutive integers (in any order) using a hash set and starting only from numbers whose predecessor is absent. What is printed?
a = [7, 1, 14, 11, 3, 20, 15, 22, 10, 2, 16]
s, best, starts = set(a), 0, 0
for x in s:
if x - 1 not in s:
starts += 1; y = x
while y + 1 in s: y += 1
best = max(best, y - x + 1)
print(best, starts)- A. 3 6
- B. 5 6
- C. 3 11
- D. 3 7
Correct answer: A. 3 6
Only sequence starts (x with x − 1 absent) launch a scan, which keeps the whole pass O(n). Output (longest, number of runs): 3 6.
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
- Quickselect returns the k-th smallest element of an unsorted array in expected O(n) time. For [29, 18, 10, 32, 39, 19, 36, 13] and k = 4…
- A peak is an element larger than its neighbours (array ends count as −∞). Binary search runs on [43, 46, 49, 14, 48, 18, 24, 47, 28]…
- A fixed window of length 3 slides over s = "bcaacbccbbbbac" with a character-count array. At how many starting positions is the window an…
- For each element of [16, 4, 2, 19, 10, 6, 29, 9], find the next greater element to its RIGHT (−1 if none), using a monotonic stack. What…
- How many distinct non-empty substrings does the string "aaaaa" have, and how many substrings counted by position?
- Find the index of the first non-repeating character using a frequency table (−1 if none). What is printed? python from collections import…