The short way to write a segment tree is a flat list tree of length 2n: leaves tree[n .. 2n-1] copy nums; each internal node i (from n - 1 down to 1) holds tree[2i] + tree[2i + 1]; tree[0] stays 0, and tree[1] is the total.
Write the two operations everything else builds on:
build(nums) -> list[int]: that list of length2 * len(nums).update(tree, i, value) -> None: set original positioni(0-based) tovaluein place and fix every ancestor.
tree = build([5, 3, 2, 7])
# [0, 17, 8, 9, 5, 3, 2, 7]
# ^root ^ ^ leaves...
update(tree, 1, 10)
# tree == [0, 24, 15, 9, 5, 10, 2, 7]
Up to 10**5 values, possibly negative; n needn't be a power of two.
⭐ Bonus: rebuilding the whole tree on each update still passes; a speed test with 50,000 updates earns a star if update only touches the O(log n) nodes on the way up.
Show hint
node i's parent is i // 2: after writing leaf n + i, walk i //= 2 to the root, recomputing each node from its children.