Repair a Trip-Time BST Where Two Entries Were Swapped

Last updated: November 29, 2026

Quick Overview

A binary search tree indexes trip start times, but a bad migration swapped the values of exactly two nodes. Restore the BST in place without changing its shape.

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

0

0

0 solved


A binary search tree indexes trip start times, but a bad migration swapped the values of exactly two nodes. Restore the BST in place without changing its shape.

Asked in Uber onsite rounds to see if you connect BST validity to sorted in-order traversal. Strong candidates find the two misplaced nodes in one pass and explain the adjacent-swap case.

What the Interviewer Expects
  • Uses the fact that in-order traversal of a valid BST is strictly increasing
  • Finds the first and second violation in a single in-order pass
  • Handles the case where the swapped nodes are adjacent in order
  • Swaps values, not nodes, to keep the shape
  • States O(n) time and O(h) space, and mentions Morris traversal for O(1)
Key Topics to Cover
binary search tree
in-order traversal
invariant repair
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 do you do this in O(1) extra space?
  • What if more than two nodes might be out of place?
  • How would you detect the corruption in a stream of inserts before it happens?
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 distinct values where exactly two values were swapped.
  • Output: none; fix the tree in place.
  • The tree's structure must stay the same....
High-Level Design

An in-order walk of a BST visits values in increasing order. Swapping two values creates either one or two places where prev.val > curr.val. On the first drop, the earlier node prev is the first c...


Submit Your Answer
Markdown supported