Segment Tree Implementation in Swift
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 Swift as in every other language.
- ✓An Array or ContiguousArray for storage; no tree type ships with Swift. The decisive standard-library behaviour is that Swift's integer operators TRAP on overflow, the program halts rather than producing a wrong number, and the &+ family gives you wrapping arithmetic explicitly when you want it.
- ✓Store the tree in a ContiguousArray and make the element Numeric with the merge supplied as a closure, or specialise on Int for speed.
- ✓The Swift trap: This is the mirror image of the Java and Go problem, and it catches people from the other direction: a sum that overflows does not wrap, it CRASHES the process with "Swift runtime failure: arithmetic overflow".
- ✓ContiguousArray avoids the Objective-C bridging check that Array performs for element types that could be class-bound, which matters in a loop this tight.
What Segment Tree actually is
Segment Tree in Swift: what you actually reach for
Swift implementation
struct SegmentTree {
private let n: Int
private var tree: ContiguousArray<Int>
init(_ data: [Int]) {
n = data.count
tree = ContiguousArray(repeating: 0, count: 2 * n)
tree.replaceSubrange(n..<(2 * n), with: data)
guard n > 1 else { return }
for i in stride(from: n - 1, through: 1, by: -1) {
// Plain +: overflow TRAPS (crashes) rather than wrapping.
tree[i] = tree[2 * i] + tree[2 * i + 1]
}
}
mutating func update(_ index: Int, to value: Int) {
var i = index + n
tree[i] = value
while i > 1 {
i /= 2
tree[i] = tree[2 * i] + tree[2 * i + 1]
}
}
/// Sum of [left, right).
func query(_ left: Int, _ right: Int) -> Int {
var acc = 0
var lo = left + n
var hi = right + n
while lo < hi {
if lo % 2 == 1 { acc += tree[lo]; lo += 1 }
if hi % 2 == 1 { hi -= 1; acc += tree[hi] }
lo /= 2
hi /= 2
}
return acc
}
}
// To handle overflow deliberately instead of trapping:
// let (sum, didOverflow) = a.addingReportingOverflow(b)
// &+ wraps on purpose, correct for hashes, wrong for a sum tree.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 Swift-specific trap
Performance in Swift, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Segment Tree?
An Array or ContiguousArray for storage; no tree type ships with Swift. The decisive standard-library behaviour is that Swift's integer operators TRAP on overflow, the program halts rather than producing a wrong number, and the &+ family gives you wrapping arithmetic explicitly when you want it.
What is the most common Swift mistake when implementing Segment Tree?
This is the mirror image of the Java and Go problem, and it catches people from the other direction: a sum that overflows does not wrap, it CRASHES the process with "Swift runtime failure: arithmetic overflow". That is the safer default and it is still a production outage if the input grows past what you tested. Use Int64 headroom, or addingReportingOverflow to handle it deliberately; reach for &+ only when wrapping is genuinely what the algorithm wants, such as in a hash.
How does Segment Tree actually perform in Swift?
ContiguousArray avoids the Objective-C bridging check that Array performs for element types that could be class-bound, which matters in a loop this tight. Overflow checking costs a branch per operation that the optimiser usually predicts perfectly, so the safety is close to free. Passing the merge as a non-inlinable closure is the real cost, mark the generic method @inlinable, or specialise on Int, if the tree is hot. 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 trialStudying for this? Replit free tiers and academic plans are laid out 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.