Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Convert Sorted Array to Balanced BST in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Balanced BST Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Balanced BST Inorder Traversal
Given the following JavaScript code that converts a sorted array to a balanced BST and then prints its inorder traversal, what is the output?
DSA Javascript
class TreeNode {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

function sortedArrayToBST(nums) {
  if (!nums.length) return null;
  const mid = Math.floor(nums.length / 2);
  const root = new TreeNode(nums[mid]);
  root.left = sortedArrayToBST(nums.slice(0, mid));
  root.right = sortedArrayToBST(nums.slice(mid + 1));
  return root;
}

function inorderTraversal(root) {
  if (!root) return [];
  return [...inorderTraversal(root.left), root.val, ...inorderTraversal(root.right)];
}

const nums = [1, 2, 3, 4, 5, 6, 7];
const bstRoot = sortedArrayToBST(nums);
console.log(inorderTraversal(bstRoot).join(' -> ') + ' -> null');
A1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> null
B4 -> 2 -> 1 -> 3 -> 6 -> 5 -> 7 -> null
C7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> null
Dnull
Attempts:
2 left
💡 Hint
Inorder traversal of a BST returns the nodes in sorted order.
🧠 Conceptual
intermediate
1:30remaining
Height of Balanced BST from Sorted Array
If you convert a sorted array of length 15 into a balanced BST using the middle element as root recursively, what will be the height of the resulting BST?
A4
B3
C5
D15
Attempts:
2 left
💡 Hint
Height of balanced BST is about log2(n+1).
🔧 Debug
advanced
2:30remaining
Identify the Bug in BST Construction
What is the output of this code snippet? Identify if there is a bug and what it causes.
DSA Javascript
class TreeNode {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

function sortedArrayToBST(nums) {
  if (nums.length === 0) return null;
  const mid = Math.floor(nums.length / 2);
  const root = new TreeNode(nums[mid]);
  root.left = sortedArrayToBST(nums.slice(0, mid));
  root.right = sortedArrayToBST(nums.slice(mid + 1));
  return root;
}

function preorderTraversal(root) {
  if (!root) return [];
  return [root.val, ...preorderTraversal(root.left), ...preorderTraversal(root.right)];
}

const nums = [1, 2, 3, 4, 5];
const bstRoot = sortedArrayToBST(nums);
console.log(preorderTraversal(bstRoot).join(' -> ') + ' -> null');
A3 -> 1 -> 2 -> 5 -> 4 -> null
B4 -> 2 -> 1 -> 3 -> 5 -> null (with off-by-one bug)
C4 -> 2 -> 1 -> 3 -> 5 -> null
DTypeError due to invalid slice indices
Attempts:
2 left
💡 Hint
Check how mid index is calculated and how slice works.
🚀 Application
advanced
1:30remaining
Number of Nodes in Balanced BST
If you build a balanced BST from a sorted array of length 31, how many nodes will the left subtree of the root have?
A30
B16
C15
D31
Attempts:
2 left
💡 Hint
The root is the middle element, left subtree has elements before it.
❓ Predict Output
expert
2:30remaining
Output of Level Order Traversal of Balanced BST
What is the output of the level order traversal of the balanced BST created from the sorted array [10, 20, 30, 40, 50, 60, 70]?
DSA Javascript
class TreeNode {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

function sortedArrayToBST(nums) {
  if (!nums.length) return null;
  const mid = Math.floor(nums.length / 2);
  const root = new TreeNode(nums[mid]);
  root.left = sortedArrayToBST(nums.slice(0, mid));
  root.right = sortedArrayToBST(nums.slice(mid + 1));
  return root;
}

function levelOrderTraversal(root) {
  if (!root) return [];
  const queue = [root];
  const result = [];
  while (queue.length) {
    const node = queue.shift();
    result.push(node.val);
    if (node.left) queue.push(node.left);
    if (node.right) queue.push(node.right);
  }
  return result;
}

const nums = [10, 20, 30, 40, 50, 60, 70];
const bstRoot = sortedArrayToBST(nums);
console.log(levelOrderTraversal(bstRoot).join(' -> ') + ' -> null');
A10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> null
Bnull
C70 -> 60 -> 50 -> 40 -> 30 -> 20 -> 10 -> null
D40 -> 20 -> 60 -> 10 -> 30 -> 50 -> 70 -> null
Attempts:
2 left
💡 Hint
Level order visits nodes level by level from root.

Practice

(1/5)
1. What is the main goal when converting a sorted array to a balanced Binary Search Tree (BST)?
easy
A. To create a linked list from the array
B. To reverse the array elements
C. To create a BST with minimal height for efficient search
D. To sort the array again

Solution

  1. Step 1: Understand the problem goal

    The goal is to build a BST that is balanced, meaning the tree height is minimized for faster search operations.
  2. Step 2: Recognize the importance of balance

    A balanced BST ensures operations like search, insert, and delete run efficiently, typically in O(log n) time.
  3. Final Answer:

    To create a BST with minimal height for efficient search -> Option C
  4. Quick Check:

    Balanced BST = minimal height = efficient search [OK]
Hint: Pick the option about balanced tree and efficient search [OK]
Common Mistakes:
  • Thinking the goal is to reverse or sort the array again
  • Confusing BST with linked list
  • Ignoring the balance aspect of the tree
2. Which of the following is the correct way to find the middle index of an array arr in JavaScript for building a balanced BST?
easy
A. const mid = Math.floor(arr.length / 2);
B. const mid = arr.length / 2;
C. const mid = Math.ceil(arr.length / 2);
D. const mid = arr.length - 1;

Solution

  1. Step 1: Understand array indexing

    Array indices start at 0, so to get the middle index, we divide length by 2 and take the floor to get an integer index.
  2. Step 2: Use Math.floor for integer index

    Using Math.floor(arr.length / 2) gives the correct middle index for both even and odd lengths.
  3. Final Answer:

    const mid = Math.floor(arr.length / 2); -> Option A
  4. Quick Check:

    Middle index = floor(length/2) [OK]
Hint: Use Math.floor to get integer middle index [OK]
Common Mistakes:
  • Using division without floor, resulting in float index
  • Using Math.ceil which may pick wrong middle
  • Using last index instead of middle
3. What will be the root node value of the balanced BST created from the sorted array [1, 3, 5, 7, 9]?
medium
A. 3
B. 5
C. 7
D. 9

Solution

  1. Step 1: Find the middle element of the array

    The array length is 5, middle index = floor(5/2) = 2, so middle element is arr[2] = 5.
  2. Step 2: Middle element becomes root

    In balanced BST from sorted array, the middle element is chosen as root to keep tree balanced.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Middle element = root = 5 [OK]
Hint: Root is middle element of sorted array [OK]
Common Mistakes:
  • Picking first or last element as root
  • Using ceil instead of floor for middle index
  • Confusing array index with value
4. Consider this code snippet to convert a sorted array to a balanced BST:
function sortedArrayToBST(arr) {
  if (!arr.length) return null;
  const mid = Math.floor(arr.length / 2);
  const root = { val: arr[mid], left: null, right: null };
  root.left = sortedArrayToBST(arr.slice(0, mid));
  root.right = sortedArrayToBST(arr.slice(mid));
  return root;
}
What is the bug in this code?
medium
A. The right subtree slice should start from mid + 1, not mid
B. The base case should check for arr === null instead of length
C. The mid index calculation is incorrect
D. The root node is not created properly

Solution

  1. Step 1: Analyze the slicing for right subtree

    The right subtree should exclude the middle element already used as root, so slice should start from mid + 1.
  2. Step 2: Identify the bug

    Using arr.slice(mid) includes the middle element again in the right subtree, causing duplicate nodes and incorrect tree.
  3. Final Answer:

    The right subtree slice should start from mid + 1, not mid -> Option A
  4. Quick Check:

    Right subtree slice = arr.slice(mid + 1) [OK]
Hint: Right subtree excludes middle element: slice from mid+1 [OK]
Common Mistakes:
  • Including middle element in both subtrees
  • Wrong base case condition
  • Incorrect mid calculation
5. Given the sorted array [-10, -3, 0, 5, 9], what is the preorder traversal (root-left-right) of the balanced BST created by the standard algorithm?
hard
A. [0, -10, -3, 5, 9]
B. [-3, -10, 0, 5, 9]
C. [5, 0, -10, -3, 9]
D. [0, -3, -10, 9, 5]

Solution

  1. Step 1: Build the balanced BST

    Middle index = Math.floor(5/2) = 2, root = 0. Left subarray [-10, -3], length=2, mid=Math.floor(2/2)=1, left child = -3 (left of -3: [-10] mid=0 value -10; right of -3: empty). Right subarray [5, 9], length=2, mid=1, right child = 9 (left of 9: [5]; right of 9: empty).
  2. Step 2: Perform preorder traversal (root-left-right)

    0, then left subtree: -3 then -10, then right subtree: 9 then 5. Result: [0, -3, -10, 9, 5].
  3. Final Answer:

    [0, -3, -10, 9, 5] -> Option D
  4. Quick Check:

    Preorder = root-left-right = [0, -3, -10, 9, 5] [OK]
Hint: Preorder = root, then left subtree, then right subtree [OK]
Common Mistakes:
  • Wrong middle element selection for subtrees
  • Confusing preorder with inorder or postorder
  • Incorrect subtree construction
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard