Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Fenwick Tree Implementation in Swift

19 min readadvanced
Website QA and SEO audits

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

A Fenwick tree is not a tree of nodes and pointers at all. It is a flat array of n+1 accumulators in which the tree structure lives entirely in the index bits: position i holds the sum of the half-open range (i - (i & -i), i], where i & -i is the lowest set bit under two's complement negation. A point update walks upward by i += i & -i, a prefix query walks downward by i -= i & -i, and each touches one slot per set bit, so both are O(log n), about twenty steps at a million elements. Range sums are prefix(hi) - prefix(lo), which is exactly why the combining operation must be invertible. Index 0 is unusable because 0 & -0 is 0, so one-based indexing is effectively mandatory. Against a segment tree it is roughly half the memory, needs no recursion and has a far tighter constant, but it cannot answer min or arbitrary non-invertible merges. The eight languages diverge on how the index type behaves under unary minus, on whether overflow wraps, traps or is impossible, and on what an array of integers actually costs in memory.

Fenwick Tree in Swift: what you actually reach for

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.

Swift implementation

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. They reject a class unless the tree genuinely needs reference sharing, reject throwing functions here since nothing can fail recoverably, and reject exposing the storage array as a public property.
swift
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 Free

The Swift-specific 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. 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.

Performance in Swift, beyond the O(log n)

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. The asymptotic cost is the same in every language, O(log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Fenwick Tree between languages.

Real-World Applications

Fenwick Tree applies wherever its problem shape appears in your own code. In Swift, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Fenwick Tree helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Fenwick Tree appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Fenwick Tree over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Fenwick Tree to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Devin free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.