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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code