SAHAL01's blog

By SAHAL01, history, 9 months ago, In English

How to solve the problem below in O(log2n) C++: You have the i'th element of an unsorted array. you have to find the nearest(absolute difference of the values is as small as possible) element of the i'th element from the right side.

  • Vote: I like it
  • -1
  • Vote: I do not like it

»
9 months ago, # |
Rev. 3   Vote: I like it +1 Vote: I do not like it

Impossible. You will spend at least O(n) to read everything and while you're reading you can just calc the answer.

if j > i: res = ...

If you're trying to solve for O(logn) per query. You can do binary search on set/sorted array etc.

  • »
    »
    9 months ago, # ^ |
    Rev. 3   Vote: I like it 0 Vote: I do not like it

    I'm thinking about that too. but we can use set and lower_bound to complete the task.

»
9 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

if you mean right side of the sorted array then you can use a set and do lower_bound on that to give the element just greater than your current element.

if you mean right side of the unsorted array then you can iterate from right and find the nearest element in the set i guess something like that although i admit this approach seems like it might not be that simple.

P.S. do tell the approach when you find it, it seems interesting :)

»
9 months ago, # |
  Vote: I like it 0 Vote: I do not like it

maintain a set, iterate from n to 1. for each i, find the value closest to a[i] on set (can be done using lower_bound), then insert a[i] into set