Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get the index of the left child in a heap array.
DSA Java
int leftChildIndex = 2 * parentIndex [1] 1;
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition.
Using multiplication or division instead of addition.
✗ Incorrect
In a heap stored as an array, the left child of a node at index i is at 2*i + 1.
2fill in blank
mediumComplete the code to swap two elements in the heap array.
DSA Java
int temp = heap[[1]]; heap[[1]] = heap[childIndex]; heap[childIndex] = temp;
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with the wrong index.
Using an undefined variable.
✗ Incorrect
To swap, we temporarily store the parent's value and then assign child's value to parent's position.
3fill in blank
hardFix the error in the condition to check if the child index is within heap size.
DSA Java
while (childIndex [1] heapSize) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' or '>' which causes out of bounds errors.
Using '<=' which allows invalid index.
✗ Incorrect
The child index must be less than heap size to be valid inside the array bounds.
4fill in blank
hardFill both blanks to correctly update the parent and child indices during bubble down.
DSA Java
parentIndex = [1]; childIndex = 2 * parentIndex [2] 1;
Attempts:
3 left
💡 Hint
Common Mistakes
Not updating indices correctly causing infinite loops.
Using wrong arithmetic operators.
✗ Incorrect
After swapping, the parent moves to child's position, and child index is recalculated as left child of new parent.
5fill in blank
hardFill all three blanks to complete the bubble down logic comparing parent and child values.
DSA Java
if (heap[childIndex + 1] [1] heap[childIndex]) { childIndex = childIndex [2] 1; } if (heap[parentIndex] [3] heap[childIndex]) { break; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators causing incorrect bubbling.
Not updating child index correctly.
✗ Incorrect
We check if right child is smaller or equal to left child to pick the smaller child, then if parent is smaller or equal to child, we stop bubbling down.
