Treap (Tree + Heap) - Problem

A Treap (Tree + Heap) is a randomized binary search tree that maintains both BST property on keys and max-heap property on priorities. Each node has a key and a random priority.

Properties:

  • BST property: For any node, all keys in left subtree < node.key < all keys in right subtree
  • Heap property: For any node, node.priority >= children priorities

Implement a treap with the following operations:

  • insert(key, priority) - Insert a key with given priority
  • search(key) - Search for a key, return true if found
  • delete(key) - Delete a key from the treap
  • inorder() - Return inorder traversal of keys

Given a list of operations, execute them and return the final inorder traversal.

Input & Output

Example 1 — Basic Operations
$ Input: operations = [["insert",5,10],["insert",3,15],["insert",7,12]]
Output: [3,5,7]
💡 Note: Insert (5,10), (3,15), (7,12). Node 3 has highest priority 15, becomes root. BST property gives inorder: 3,5,7
Example 2 — With Delete
$ Input: operations = [["insert",10,5],["insert",5,10],["delete",10]]
Output: [5]
💡 Note: Insert (10,5), then (5,10). Since 5 has higher priority, it becomes root. Delete 10, only 5 remains
Example 3 — Complex Tree
$ Input: operations = [["insert",4,8],["insert",2,12],["insert",6,15],["insert",1,3],["insert",3,7]]
Output: [1,2,3,4,6]
💡 Note: Multiple inserts create treap. Node 6 has highest priority 15. Final inorder traversal: 1,2,3,4,6

Constraints

  • 1 ≤ operations.length ≤ 1000
  • 1 ≤ key ≤ 105
  • 1 ≤ priority ≤ 105
  • All priorities are unique

Visualization

Tap to expand
INPUTALGORITHMRESULTOperations Listinsert(5,10), insert(3,15)insert(7,12)Key,Priority pairs for treap nodes1. BST Insert by Key2. Check Heap Property3. Rotate if Violated4. Inorder Traversal315510712Final Tree StructureRoot: 3 (highest priority 15)Left: 5, Right: 7Inorder Traversal:[3, 5, 7]Key Insight:Tree rotations maintain both BST ordering by keys AND heap ordering by priorities simultaneouslyTutorialsPoint - Treap Implementation | Tree Rotations Approach
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
8.5K Views
Medium Frequency
~45 min Avg. Time
285 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