appro's blog

By appro, history, 8 years ago, In English

What is the time complexity for building a segment tree for an array of size n?

  • Vote: I like it
  • +10
  • Vote: I do not like it

»
8 years ago, # |
  Vote: I like it 0 Vote: I do not like it

O(n). Because in each recursuion call you recurse twice for subtasks of size n / 2 and do O(1) operations (that's if you're building segment tree for simple operation like sum or max).

T(n) = 2T(n / 2) + O(1) = O(n) (by Master-theorem)

Another way to see this — segment tree has n nodes on lowest level, n / 2 nodes on second level, n / 4 on third, ..., 1 on top level = 2 * n nodes = O(n) nodes, and in all of them you do O(1) operations.

»
8 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Also, you can appreciate segtree visualization here. :D

»
8 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

2N memory and operations required. [N; N + N — 1] leaves + [1; N — 1] internal nodes and root.