Fenwick 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
- ✓Fenwick Tree runs in O(log n) time and O(n) space, in Swift as in every other language.
- ✓The standard library has no Fenwick; the storage is ContiguousArray<Int>, which guarantees a contiguous buffer and avoids the Objective-C bridging path a plain Array keeps on Apple platforms.
- ✓Reviewers want a struct with value semantics, a mutating func add(at:delta:) and a non-mutating prefix(upTo:), argument labels that make the index base obvious, and precondition rather than assert for range checks, because precondition survives -O and assert does not.
- ✓The Swift trap: Value semantics plus copy-on-write is the trap. var b = a shares the buffer until the first write, then clones all n + 1 elements, so passing the tree into a helper that mutates its own copy turns an O(log n) update into an O(n) copy on every call; take it inout.
- ✓ContiguousArray<Int> is one heap buffer of 8-byte payloads, and ARC never retains or releases an Int, so the hot loop performs zero reference counting.
What Fenwick Tree actually is
Fenwick Tree in Swift: what you actually reach for
Swift implementation
public struct FenwickTree {
private var tree: ContiguousArray<Int> // 1-based; slot 0 unused
public let count: Int
public init(_ values: [Int]) {
count = values.count
tree = ContiguousArray([0] + values)
for i in 1..<(count + 1) {
let j = i + (i & -i)
if j <= count { tree[j] += tree[i] }
}
}
public mutating func add(at index: Int, delta: Int) {
precondition(index >= 0 && index < count, "index out of range")
var i = index + 1
while i <= count {
tree[i] += delta
i += i & -i
}
}
public func prefix(upTo end: Int) -> Int {
var i = end
var sum = 0
while i > 0 {
sum += tree[i]
i -= i & -i
}
return sum
}
public func sum(from lo: Int, to hi: Int) -> Int {
prefix(upTo: hi) - prefix(upTo: lo)
}
}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 Fenwick Tree?
The standard library has no Fenwick; the storage is ContiguousArray<Int>, which guarantees a contiguous buffer and avoids the Objective-C bridging path a plain Array keeps on Apple platforms. FixedWidthInteger gives you both forms of the lowbit, i & -i and 1 << i.trailingZeroBitCount, plus addingReportingOverflow(_:) and the &+ operator when you want wrapping instead of trapping arithmetic. If tasks share the tree, wrap it in an actor; there is no lock-free integer array in the stdlib.
What is the most common Swift mistake when implementing Fenwick Tree?
Value semantics plus copy-on-write is the trap. var b = a shares the buffer until the first write, then clones all n + 1 elements, so passing the tree into a helper that mutates its own copy turns an O(log n) update into an O(n) copy on every call; take it inout. Second, Int arithmetic traps on overflow by default, so a sum that would wrap silently in C or Java instead terminates the process with a runtime error, and &+ is the deliberate opt-out. Third, an out-of-range subscript is a fatalError, not a Swift error you can catch.
How does Fenwick Tree actually perform in Swift?
ContiguousArray<Int> is one heap buffer of 8-byte payloads, and ARC never retains or releases an Int, so the hot loop performs zero reference counting. Bounds checks remain under -O and are removed only with -Ounchecked, which also removes the overflow traps. Generic code over AdditiveArithmetic dispatches through a witness table unless the compiler specialises it, so keep the type concrete, or mark it @inlinable when it crosses a module boundary and rely on whole-module optimisation. 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? Devin 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.