0

Given a list of keys, says [2, 6, 4, 9, 3], how can I find the predecessor of an element, with index left to the element only? For example

  1. The predecessor of 6 should be 2, not 4, because 4 is on the right of 6.
  2. The predecessor of 4 should be 2, not 3.

We know that in a balanced binary search tree, we can find predecessor and successor for given key in O(log n) time complexity, but that is not exactly what I wanted.

I seems like I wanted a data structure with functions from both BST and Interval Tree. But I don't know how to combine them.

Bi Ao
  • 704
  • 5
  • 11
  • Is this set static? What is predecessor for 9 - 6 or 4? – MBo May 18 '22 at 10:13
  • Why is 2 the predecessor of 4? I would say that 6 is the predecessor of 4 in that list. – Stef May 18 '22 at 10:17
  • @MBo Yes, the set will not change. The predecessor for 9 should be 6, it finds an maximum element from [2, 6, 4] that is smaller than 9. – Bi Ao May 18 '22 at 10:33
  • @Stef The predecessor of X I defined here is the the biggest element with smaller value than X, but required to be on the left of X. – Bi Ao May 18 '22 at 10:37
  • 1
    `the set will not change` - so you can just find predecessors once and store them in separate list? – MBo May 18 '22 at 10:42
  • @MBo I used the wrong word, it should be a list of numbers, not a set, because they are ordered. – Bi Ao May 18 '22 at 10:42
  • @MBo This is a way, but this cannot lower their time complexity. The initialization takes O(n^2) if I'm right – Bi Ao May 18 '22 at 10:45
  • 1
    OK, what's wrong with balanced BST being built "on the fly?" You insert elements one-by-one walking the list left-to right, and before inserting new element you look for predecessor in existing tree. – MBo May 18 '22 at 13:11
  • @MBo I just didn't though of that before, thanks! – Bi Ao May 18 '22 at 13:16

0 Answers0