Repair a Routing Table BST Where Two Entries Were Swapped

Last updated: November 29, 2026

Quick Overview

A bug swapped the values of exactly two nodes in a binary search tree used for an Azure routing table. Restore the tree without changing its structure.

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

0

0

0 solved


A bug swapped the values of exactly two nodes in a binary search tree used for an Azure routing table. Restore the tree without changing its structure.

This checks whether a candidate understands that an in-order walk of a BST is sorted and can spot the swapped pair from its inversions. Microsoft interviewers often push for O(h) or O(1) extra space.

What the Interviewer Expects
  • Recall that in-order traversal of a valid BST is strictly increasing
  • Find the first and last inversion in that sequence
  • Handle the case where the swapped nodes are adjacent (one inversion)
  • Swap values, not nodes
  • Mention Morris traversal for O(1) space
Key Topics to Cover
BST
in-order 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
  • Implement it with Morris traversal for O(1) extra space.
  • What if more than two nodes are misplaced? What is the minimum number of swaps?
  • How would you detect the corruption online before it causes misrouting?
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 with exactly two values swapped; values are distinct.
  • Fix it in place and return the root....
High-Level Design

In a sorted list with two values swapped, there are one or two places where a value is greater than its successor. If the swapped values are not neighbors in order, as in [1, 4, 3, 2, 5], there are tw...


Submit Your Answer
Markdown supported