0

Given a sequence S of n integer elements, I need a function min(i,j) that finds the minimum element of the sequence between index i and index j (both inclusive) such that:

  1. Initialization takes O(n);
  2. Memory space O(n);
  3. min(i,j) takes O(log(n)).

Please suggest an algorithm for this.

nevets
  • 4,631
  • 24
  • 40
Palak Jain
  • 143
  • 1
  • 3
  • 14

3 Answers3

0

This TopCoder tutorial: An < O(n), O(1) > approach discusses your problem in a more detail way. In the notation, means the approach takes f(n) complexity to setup, and g(n) complexity to query.

Also, this post chews the algorithm again: Range Minimum Query <O(n), O(1)> approach (from tree to restricted RMQ).

Hope them clarifies your question :)

Community
  • 1
  • 1
nevets
  • 4,631
  • 24
  • 40
0

Segment tree is just what you need(it can be build in O(n) time and one query takes O(log n) time). Here is an article about it: http://wcipeg.com/wiki/Segment_tree.
Even though there is an algorithm that uses O(n) time for initialization and O(1) time per query, segment tree can be a good choice because it is much simpler.

kraskevich
  • 18,368
  • 4
  • 33
  • 45
0

Segmenttree is that what you need because it fulfils all your requirements.

  1. Initialisation takes O(n) with Segment Tree
  2. Memory is also O(n)
  3. Queries can be done in O(log n)

Beside this, the tree is dynamic and can support updating in O(log n). This means one can modify the element of some element i in O(log n) and still retrieve the minimum.

Gary Ye
  • 847
  • 1
  • 7
  • 9