PracHub
QuestionsPremiumCoachesLearningGuidesInterview Prep
|Home/Coding & Algorithms/TikTok

Fix a BST with two misplaced keys

Last updated: Mar 29, 2026

Quick Overview

This question evaluates understanding of binary search trees, in-order traversal invariants, and in-place detection and correction of two swapped keys without altering tree structure.

  • Medium
  • TikTok
  • Coding & Algorithms
  • Machine Learning Engineer

Fix a BST with two misplaced keys

Company: TikTok

Role: Machine Learning Engineer

Category: Coding & Algorithms

Difficulty: Medium

Interview Round: Technical Screen

You are given the root of a binary search tree in which exactly two nodes’ keys were accidentally swapped. Restore the tree so that its in-order traversal is strictly non-decreasing, without changing the tree’s structure. Aim for O(n) time and O( 1) extra space; discuss an approach that does not use recursion or an explicit stack. Describe how you would detect the misplaced nodes, handle both adjacent and non-adjacent violations, and analyze time/space complexity.

Quick Answer: This question evaluates understanding of binary search trees, in-order traversal invariants, and in-place detection and correction of two swapped keys without altering tree structure.

Related Interview Questions

  • Parse a nested list from a string - TikTok (medium)
  • Implement stacks, streaming median, and upward path sum - TikTok (easy)
  • Solve common string/DP/stack problems - TikTok (medium)
  • Implement stack variants and path-sum check - TikTok (medium)
  • Maximize sum with no adjacent elements - TikTok (medium)
TikTok logo
TikTok
Aug 8, 2025, 12:00 AM
Machine Learning Engineer
Technical Screen
Coding & Algorithms
2
0

You are given the root of a binary search tree in which exactly two nodes’ keys were accidentally swapped. Restore the tree so that its in-order traversal is strictly non-decreasing, without changing the tree’s structure. Aim for O(n) time and O(

  1. extra space; discuss an approach that does not use recursion or an explicit stack. Describe how you would detect the misplaced nodes, handle both adjacent and non-adjacent violations, and analyze time/space complexity.

Submit Your Answer to Earn 20XP

Sign in to leave a comment

Loading comments...

Browse More Questions

More Coding & Algorithms•More TikTok•More Machine Learning Engineer•TikTok Machine Learning Engineer•TikTok Coding & Algorithms•Machine Learning Engineer Coding & Algorithms
PracHub

Master your tech interviews with 8,000+ real questions from top companies.

Product

  • Questions
  • Learning Tracks
  • Interview Guides
  • Resources
  • Premium
  • For Universities
  • Student Access

Browse

  • By Company
  • By Role
  • By Category
  • Topic Hubs
  • SQL Questions
  • Compare Platforms
  • Discord Community

Support

  • support@prachub.com
  • (916) 541-4762

Legal

  • Privacy Policy
  • Terms of Service
  • About Us

© 2026 PracHub. All rights reserved.