501. Search for an Element in a Stream Without Built-In Sets
Search for an Element in a Stream Without Built-In Sets

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.

Methods

StreamSearch()
  • Creates an empty stream.
void add(int element)
  • element arrives in the stream.
boolean search(int element)
  • Returns true if element has arrived in the stream at least once, otherwise returns false.

Constraints

  • -1,000,000,000 ≤ element ≤ 1,000,000,000
  • At most 100,000 calls in total are made to add and search.

Examples

Example 1

  • StreamSearch stream = new StreamSearch()
  • stream.add(element = 15)
  • stream.add(element = -4)
  • stream.search(element = 15) returns true
  • stream.search(element = 7) returns false
  • stream.add(element = 7)
  • stream.add(element = 15)
  • stream.search(element = 7) returns true
  • stream.search(element = -4) returns true

Explanation:

  • 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.

Example 2

  • StreamSearch stream = new StreamSearch()
  • stream.search(element = 0) returns false
  • stream.add(element = 1000000000)
  • stream.add(element = -1000000000)
  • stream.search(element = -1000000000) returns true
  • stream.search(element = 999999999) returns false

Explanation:

  • The stream is empty at the first search, so 0 is not found.
  • Only 1000000000 and -1000000000 have arrived, so 999999999 is not found.


Please use Laptop/Desktop or any other large screen to add/edit code.