Repair a BST Index Where Exactly Two Nodes Were Swapped

Last updated: November 29, 2026

Quick Overview

Two nodes of a binary search tree had their values swapped by a bad migration. Restore the tree in place without changing its structure.

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

0

0

0 solved


Two nodes of a binary search tree had their values swapped by a bad migration. Restore the tree in place without changing its structure.

A Meta onsite hard question that builds on the inorder-is-sorted property. The interviewer wants you to find the swapped pair from the inversions in an inorder walk, handle the adjacent-swap case, and ideally discuss Morris traversal for O(1) space.

What the Interviewer Expects
  • Use inorder traversal to expose the sorted sequence
  • Find the first and last inversion
  • Handle adjacent swaps that produce only one inversion
  • Swap the two values back
  • Discuss Morris traversal for O(1) extra space
Key Topics to Cover
Binary search tree
Inorder traversal
Inversions
Morris traversal
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 does Morris traversal visit nodes in order without a stack?
  • What if more than two nodes might be misplaced?
  • 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 is the root of a BST where exactly two node values were exchanged. Fix it in place by swapping the values back; do not restructure nodes. Values are unique....

High-Level Design

In a valid BST, the inorder sequence increases. Swapping two values creates either two inversions (non-adjacent in inorder) or one inversion (adjacent). Walk inorder and track prev. On the first inv...


Submit Your Answer
Markdown supported