Repair a BST in Which Exactly Two Keys Were Swapped

Last updated: November 29, 2026

Quick Overview

A bug swapped the keys of exactly two nodes in a binary search tree. Restore the tree without changing its structure, ideally in O(1) extra space.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


A bug swapped the keys of exactly two nodes in a binary search tree. Restore the tree without changing its structure, ideally in O(1) extra space.

A Google onsite hard problem about detecting and fixing corrupted order. The first answer collects the in-order sequence; the interviewer then asks for O(1) space using Morris traversal, which is the real bar.

What the Interviewer Expects
  • Observe that in-order of a valid BST is sorted
  • Find the one or two inversion points in the in-order sequence
  • Handle adjacent swaps (one inversion) and distant swaps (two inversions)
  • Implement Morris in-order traversal for O(1) space
  • Restore Morris threads so the tree structure is intact
Key Topics to Cover
binary search tree
in-order traversal
Morris traversal
inversions
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
  • Why does Morris traversal leave the tree unchanged after it finishes?
  • What if k pairs were swapped?
  • Detect whether a tree differs from a valid BST by exactly one swap.
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 nodes' keys were swapped. Mutate in place so it is valid again. Structure must not change. Target O(n) time and O(1) extra space....

High-Level Design

In-order traversal of a valid BST is increasing. Swapping two keys creates inversions where prev.val > cur.val. If the swapped nodes were adjacent in in-order, there is one inversion and the culprit...


Submit Your Answer
Markdown supported