Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the map that stores nodes by their vertical column.
DSA Javascript
const columnTable = new Map();
function verticalOrder(root) {
if (!root) return [];
const queue = [[root, 0]];
while (queue.length > 0) {
const [node, column] = queue.shift();
if (!columnTable.has([1])) {
columnTable.set(column, []);
}
columnTable.get(column).push(node.val);
if (node.left) queue.push([node.left, column - 1]);
if (node.right) queue.push([node.right, column + 1]);
}
return Array.from(columnTable.keys()).sort((a, b) => a - b).map(key => columnTable.get(key));
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for the node object instead of the column number.
Using the root or queue variable incorrectly.
✗ Incorrect
We check if the map has the current column as a key before adding nodes to it.
2fill in blank
mediumComplete the code to add the left child node to the queue with the correct column index.
DSA Javascript
if (node.left) queue.push([node.left, [1]]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 1 instead of subtracting 1 for left child.
Using the same column index for left child.
✗ Incorrect
Left child nodes are in the column one less than the current node's column.
3fill in blank
hardFix the error in the sorting function to correctly sort the column keys numerically.
DSA Javascript
return Array.from(columnTable.keys()).sort((a, b) => [1]).map(key => columnTable.get(key));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or multiplication which does not sort correctly.
Reversing the order by subtracting a from b.
✗ Incorrect
Sorting numerically ascending requires subtracting b from a.
4fill in blank
hardFill both blanks to correctly add the right child node to the queue with the updated column index.
DSA Javascript
if (node.right) queue.push([[1], [2]]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using node.left instead of node.right.
Using column - 1 instead of column + 1 for right child.
✗ Incorrect
Right child node is node.right and its column is current column + 1.
5fill in blank
hardFill all three blanks to create a map of columns to sorted node values after traversal.
DSA Javascript
const sortedColumns = Array.from(columnTable.keys()).sort(([1], [2]) => [3]); const result = sortedColumns.map(key => columnTable.get(key).sort((a, b) => a - b));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using b - a which sorts descending.
Mixing parameter names or using incorrect subtraction.
✗ Incorrect
Sort keys by a and b, then subtract b from a for ascending order.