Segment Trees Flashcards

1
Q

Segment Tree

A
  • Binary tree
  • Each element in original array is leaf of binary tree
  • Allows you to ask questions about a range of indices in an array
  • static data strcture – cannot be modified once built
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Segment Tee

Construction

A
  • Elements of array should become leaves of tree
  • Root is minimum of entire range
  • Represented implicity with array (like binary heap)

Steps

  1. Split array into halves recursively into array is size 2 and 1
  2. Bubble up, recording minimums of elements in pairs
  3. Create segment tree array using formula:
  4. If array size is power of 2

size*2 - 1

If not

Find next power of 2

num*2 - 1

  1. Initialize segment tree array to inf

Time: O(n)

Space: O(n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Segment Tree

Searching

A
  • Describes the overlap of the query interval to the node itnervals

3 conditions

  1. Total overlap
    • Node interval fits completely inside query interval
    • Stop, return value at node
  2. No overlap/disjoint
    • Node interval and query interval are disjoint
    • Return max (really big number)
  3. Partial overlap
    • Node interval not completely inside query interval
    • Basically not 1 or 2
    • Must check both sides

OlogN

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Segment Tree

Size

A
  • If array size is power of 2
    • size*2 - 1
  • If not
    • Find next power of 2
    • num*2 - 1
      *
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Segment Tree

range query

A

*

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Segment Tree

Lazy Propagation

A
  • Increase the size of a range by increasing nodes
  • Propogation only happens when nodes are visited

Steps

  1. Find range nodes like normal
  2. Increase val at node
  3. Increase val during recursive return
How well did you know this?
1
Not at all
2
3
4
5
Perfectly