Skip to content

Commit

Permalink
Fix: segmenttree algorithm bug (TheAlgorithms#497)
Browse files Browse the repository at this point in the history
  • Loading branch information
hugokung authored Apr 20, 2022
1 parent 30c24e8 commit 8befb60
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
12 changes: 7 additions & 5 deletions structure/segmenttree/segmenttree.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/TheAlgorithms/Go/math/min"
)

const emptyLazyNode = -1
const emptyLazyNode = 0

//SegmentTree with original Array and the Segment Tree Array
type SegmentTree struct {
Expand All @@ -29,11 +29,12 @@ func (s *SegmentTree) Propagate(node int, leftNode int, rightNode int) {

if leftNode == rightNode {
//leaf node
s.Array[leftNode] = s.LazyTree[node]
s.Array[leftNode] += s.LazyTree[node]
} else {
//propagate lazy node value for children nodes
s.LazyTree[2*node] = s.LazyTree[node]
s.LazyTree[2*node+1] = s.LazyTree[node]
//may propagate multiple times, children nodes should accumulate lazy node value
s.LazyTree[2*node] += s.LazyTree[node]
s.LazyTree[2*node+1] += s.LazyTree[node]
}

//clear lazy node
Expand Down Expand Up @@ -81,7 +82,8 @@ func (s *SegmentTree) Update(node int, leftNode int, rightNode int, firstIndex i

if (leftNode >= firstIndex) && (rightNode <= lastIndex) {
//inside the interval
s.LazyTree[node] = value
//accumulate the lazy node value
s.LazyTree[node] += value
s.Propagate(node, leftNode, rightNode)
} else {
//update left and right nodes
Expand Down
8 changes: 8 additions & 0 deletions structure/segmenttree/segmenttree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ func TestSegmentTree(t *testing.T) {
queries: []query{{0, 5}, {0, 2}, {2, 4}},
expected: []int{31, 14, 24},
},
{
description: "test array with size 11 and range updates",
array: []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
updates: []update{{firstIndex: 2, lastIndex: 8, value: 2},
{firstIndex: 2, lastIndex: 8, value: 2}},
queries: []query{{3, 5}, {7, 8}, {4, 5}, {8, 8}},
expected: []int{15, 10, 10, 5},
},
}
for _, test := range segmentTreeTestData {
t.Run(test.description, func(t *testing.T) {
Expand Down

0 comments on commit 8befb60

Please sign in to comment.