Merkle Tree Builder - Problem

A Merkle tree is a cryptographic data structure where each leaf node represents a data block, and each internal node represents the hash of its children. The root hash represents the integrity of all data blocks.

Build a Merkle tree from an array of data blocks and implement a function to verify if a given data block exists in the tree (proof-of-inclusion).

Requirements:

  • Use SHA-256 hashing (simulate with simple hash function for this problem)
  • For odd number of nodes at any level, duplicate the last node
  • Return the root hash and implement verification

Input & Output

Example 1 — Four Data Blocks
$ Input: data_blocks = ["block1", "block2", "block3", "block4"]
Output: {"root_hash": "7890", "tree": [["1234", "5678", "9012", "3456"], ["1357", "2468"], ["7890"]], "verify": true}
💡 Note: Build Merkle tree: hash each block to get leaf level, then pair and hash adjacent nodes level by level until reaching single root hash
Example 2 — Odd Number of Blocks
$ Input: data_blocks = ["A", "B", "C"]
Output: {"root_hash": "4567", "tree": [["1111", "2222", "3333"], ["4444", "3333"], ["4567"]], "verify": true}
💡 Note: With odd number, duplicate last node C at each level: pair A+B, then duplicate C, continue until root
Example 3 — Single Block
$ Input: data_blocks = ["single"]
Output: {"root_hash": "9999", "tree": [["9999"]], "verify": true}
💡 Note: Single block case: hash the block once, it becomes both leaf and root of the tree

Constraints

  • 1 ≤ data_blocks.length ≤ 1000
  • 1 ≤ data_blocks[i].length ≤ 100
  • data_blocks[i] contains only alphanumeric characters

Visualization

Tap to expand
INPUT DATAALGORITHMRESULTblock1block2block3block4Data blocks to organizein cryptographic tree1Hash all leaf blocks2Pair adjacent hashes3Combine into parents4Repeat until rootRoot Hash: ABC123H(1+2)H(3+4)Tree Structure BuiltVerification: O(log n)💡Key Insight:Building a tree of combined fingerprints enables verifying any single itemwith just a few intermediate proofs instead of checking everything.TutorialsPoint - Merkle Tree Builder | Binary Tree Construction
Asked in
Coinbase 25 Blockchain.com 20 Ripple 15 Microsoft 12
12.0K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen