0
0
DSA Javascriptprogramming~10 mins

Heap Concept Structure and Properties in DSA Javascript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to get the index of the left child in a heap array.

DSA Javascript
function leftChildIndex(parentIndex) {
  return 2 * parentIndex [1] 1;
}
Drag options to blanks, or click blank then click option'
A+
B/
C*
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition.
Using multiplication instead of addition.
Using division which is incorrect here.
2fill in blank
medium

Complete the code to get the index of the parent node in a heap array.

DSA Javascript
function parentIndex(childIndex) {
  return Math.floor((childIndex [1] 1) / 2);
}
Drag options to blanks, or click blank then click option'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 1 instead of subtracting 1.
Not using floor which causes wrong index.
Using multiplication or division incorrectly.
3fill in blank
hard

Fix the error in the code to check if a node has a right child in the heap array.

DSA Javascript
function hasRightChild(index, heapSize) {
  return (2 * index + [1]) < heapSize;
}
Drag options to blanks, or click blank then click option'
A-1
B0
C1
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 instead of 2 for right child index.
Using 0 or negative numbers which are invalid here.
4fill in blank
hard

Fill both blanks to create a function that swaps two elements in a heap array.

DSA Javascript
function swap(heap, i, j) {
  const temp = heap[1];
  heap[2] = heap[j];
  heap[j] = temp;
}
Drag options to blanks, or click blank then click option'
A[i]
B[j]
C.i
D.j
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation instead of bracket notation.
Mixing indices between temp and heap assignments.
5fill in blank
hard

Fill all three blanks to complete the siftDown function that maintains the heap property.

DSA Javascript
function siftDown(heap, index, heapSize) {
  let largest = index;
  const left = 2 * index + [1];
  const right = 2 * index + [2];

  if (left < heapSize && heap[left] > heap[[3]]) {
    largest = left;
  }

  if (right < heapSize && heap[right] > heap[largest]) {
    largest = right;
  }

  if (largest !== index) {
    swap(heap, index, largest);
    siftDown(heap, largest, heapSize);
  }
}
Drag options to blanks, or click blank then click option'
A1
B2
Cindex
Dlargest
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up left and right child offsets.
Comparing with largest instead of index in first if condition.