This problem requires a new data structure --- Segment Tree. You may use this GeeksforGeeks article to get some ideas of it. However, the code in this article may be too verbose. To solve this problem using segment tree, 2guotou has posted a very nice Java code, which is rewritten below in C++. I try to conform to the LeetCode traditions of defining structures and classes.