Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Segment & Fenwick trees

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Segment & Fenwick trees

Implement a Fenwick (Binary Indexed) Tree

advancedlayer A6 · Segment & Fenwick trees5 tests

Implement the data structure itself, from scratch. A FenwickTree holds size numbers, all 0 to begin with.

  • new FenwickTree(size) — size zeros
  • update(i, delta) — adds delta to the value at the 0-based index i (this one is a delta, not a replacement)
  • prefixSum(i) — the sum of indices 0 through i inclusive; prefixSum(-1) is 0
  • Both operations must be O(log size)
  • Deltas may be negative

The trick the structure is built on: index x of the internal array covers the x & -x values ending at x, where x & -x isolates the lowest set bit.

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen