Repair a Price Search Tree After Two Values Were Swapped

Last updated: November 29, 2026

Quick Overview

A bad migration swapped the values of exactly two nodes in a pricing binary search tree. Restore the tree in place without changing its shape.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


A bad migration swapped the values of exactly two nodes in a pricing binary search tree. Restore the tree in place without changing its shape.

Amazon onsite interviewers like this because it rewards reasoning about where sortedness breaks. It connects to data repair jobs where a corrupted index must be fixed without a full rebuild.

What the Interviewer Expects
  • Observe that inorder of a BST is sorted, so a swap creates one or two inversions
  • Identify the first node as the larger element of the first inversion and the second as the smaller element of the last inversion
  • Handle adjacent swaps that produce only one inversion
  • Fix by swapping values only
  • Mention Morris traversal for O(1) space
Key Topics to Cover
BST
inorder traversal
inversions
in-place repair
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you do this in O(1) extra space?
  • What if more than two values could be out of place?
  • How would you detect whether the tree needs repair at all?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: root of a BST where exactly two node values were swapped. Output: none; mutate the tree so it is a valid BST again. Shape must be preserved, so swap values rather than relinking nodes....

High-Level Design

Walk inorder and compare each node with the previous one. Each place where prev.val > cur.val is an inversion. On the first inversion, set first = prev and second = cur. On a later inversion, upda...


Submit Your Answer
Markdown supported