solved using segment tree