Integers arrive one by one in a stream. At any time, you may need to search for an element to check whether it has already arrived in the stream.
The same element can arrive more than once. Elements are never removed from the stream.
Solve this without using any built-in sets or maps, such as HashSet, TreeSet, HashMap or TreeMap in Java, or set or dict in Python. Build your own data structure to store the elements.
StreamSearch()
void add(int element)
element arrives in the stream.boolean search(int element)
true if element has arrived in the stream at least once, otherwise returns false.-1,000,000,000 ≤ element ≤ 1,000,000,000100,000 calls in total are made to add and search.StreamSearch stream = new StreamSearch()stream.add(element = 15)stream.add(element = -4)stream.search(element = 15) returns truestream.search(element = 7) returns falsestream.add(element = 7)stream.add(element = 15)stream.search(element = 7) returns truestream.search(element = -4) returns trueExplanation:
7 has not arrived yet when it is first searched, so the answer is false. Once it arrives, searching for it returns true.15 arrives twice. Adding an element that is already in the stream changes nothing.StreamSearch stream = new StreamSearch()stream.search(element = 0) returns falsestream.add(element = 1000000000)stream.add(element = -1000000000)stream.search(element = -1000000000) returns truestream.search(element = 999999999) returns falseExplanation:
0 is not found.1000000000 and -1000000000 have arrived, so 999999999 is not found.