harttle / contest.js

Ready for contest use! Data structures and algorithms in pure JavaScript with zero dependency.
http://harttle.land/contest.js/
MIT License
41 stars 9 forks source link

treeset should support lower_bound and upper_bould as ES6 iterator #22

Open upupming opened 2 years ago

upupming commented 2 years ago

Would you consider supporting lower_bound and upper_bound iterator, proposed usage maybe:

const s = new TreeSet([1, 2, 3, 4, 5])
const a = [...s.lower_bound(2)]
console.log(a) // [2, 3, 4 5]

Related problem: https://leetcode.cn/problems/range-module/

harttle commented 2 years ago

Do we have an example for this API in other languages/libraries? I guess it's similiar to TreeSet.floor() but returns an iterator, from which we can iterate through.

Since JavaScript iterator is single-directioned, maybe we need a set of methods like .floorIter(), .floorIterReverse(), etc. As for the naming, again, do you know there's other lib we can refer to?

upupming commented 2 years ago

@harttle Glad to receive your reply!

An example

See this C++ solution page of LeetCode range-module, it is just like what you said:

TreeSet.floor() but returns an iterator

set<pair<int, int>> st;  // 存储区间 {R, L}

auto it = st.lower_bound({left, 0});  // 找第一个可以合并的区间

while(it != st.end()) { 
  // ...
}

The lower_bound is needed in this kind of problem because it can let us find the demanded data in O(log n) time and then only iterate the target data needed, without lower_bound, we cannot avoid redundant time-complexity used on iterating unneeded data.

I think floorIter() can do more things than floor(), our new floor() may depend on the floorIter() method!