Please read the new rule regarding the restriction on the use of AI tools. ×

SAHAL01's blog

By SAHAL01, history, 13 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

| Write comment?
»
13 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.

»
13 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