Segment Tree Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Segment Tree runs in O(log n) time and O(n) space, in C# as in every other language.
- ✓A long[] or Span<long> for storage; the BCL has no segment tree. The relevant language facts are that integer arithmetic is UNCHECKED by default, that the checked keyword turns overflow into an OverflowException, and that the whole assembly can be switched with the CheckForOverflowUnderflow compiler option.
- ✓Use long[] for sum trees and wrap the merge in a checked block so overflow throws instead of wrapping, the cost is negligible and it converts a silent wrong answer into a stack trace.
- ✓The C# trap: C# sits exactly between Java and Swift and inherits the worst default of the three: overflow wraps silently, but unlike Go there IS a checked mechanism and most code simply never uses it.
- ✓A long[] is contiguous and the RyuJIT compiles this loop tightly. checked arithmetic adds a jump-on-overflow instruction that costs essentially nothing on modern hardware given branch prediction.
What Segment Tree actually is
Segment Tree in C#: what you actually reach for
C# implementation
using System;
using System.Runtime.CompilerServices;
public sealed class SegmentTree
{
private readonly int _n;
private readonly long[] _tree; // long, not int
public SegmentTree(ReadOnlySpan<long> data)
{
_n = data.Length;
_tree = new long[2 * _n];
data.CopyTo(_tree.AsSpan(_n));
for (int i = _n - 1; i > 0; i--)
_tree[i] = Merge(_tree[2 * i], _tree[2 * i + 1]);
}
// checked: overflow THROWS instead of wrapping silently. C# is
// unchecked by default, so this must be explicit.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static long Merge(long a, long b) => checked(a + b);
public void Update(int index, long value)
{
int i = index + _n;
_tree[i] = value;
while (i > 1)
{
i >>= 1;
_tree[i] = Merge(_tree[2 * i], _tree[2 * i + 1]);
}
}
/// <summary>Merge of [left, right).</summary>
public long Query(int left, int right)
{
long acc = 0;
int lo = left + _n, hi = right + _n;
while (lo < hi)
{
if ((lo & 1) == 1) acc = Merge(acc, _tree[lo++]);
if ((hi & 1) == 1) acc = Merge(acc, _tree[--hi]);
lo >>= 1;
hi >>= 1;
}
return acc;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Segment Tree?
A long[] or Span<long> for storage; the BCL has no segment tree. The relevant language facts are that integer arithmetic is UNCHECKED by default, that the checked keyword turns overflow into an OverflowException, and that the whole assembly can be switched with the CheckForOverflowUnderflow compiler option.
What is the most common C# mistake when implementing Segment Tree?
C# sits exactly between Java and Swift and inherits the worst default of the three: overflow wraps silently, but unlike Go there IS a checked mechanism and most code simply never uses it. So the failure mode is a negative total from a sum tree, identical to Java, with the added twist that whether it throws depends on a project-level compiler flag somebody may flip. Never rely on the ambient setting, write checked explicitly where it matters.
How does Segment Tree actually perform in C#?
A long[] is contiguous and the RyuJIT compiles this loop tightly. checked arithmetic adds a jump-on-overflow instruction that costs essentially nothing on modern hardware given branch prediction. Passing the merge as a Func<long, long, long> prevents inlining and roughly halves throughput; a struct implementing an interface with a generic constraint is the standard trick to keep the call devirtualised. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.