Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two elements in the array.
DSA Go
func swap(arr []int, i, j int) {
temp := arr[[1]]
arr[i] = arr[j]
arr[j] = temp
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using arr[j] instead of arr[i] for temp causes incorrect swapping.
Forgetting to store the value before overwriting.
✗ Incorrect
We store the element at index i in temp to swap arr[i] and arr[j].
2fill in blank
mediumComplete the code to select the pivot as the last element in Lomuto partition.
DSA Go
func lomutoPartition(arr []int, low, high int) int {
pivot := arr[[1]]
i := low - 1
for j := low; j < high; j++ {
if arr[j] <= pivot {
i++
swap(arr, i, j)
}
}
swap(arr, i+1, high)
return i + 1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing pivot as low or 0 index causes incorrect partitioning.
Using len(arr)-1 instead of high when partitioning subarrays.
✗ Incorrect
In Lomuto partition, the pivot is the last element at index high.
3fill in blank
hardFix the error in the Hoare partition loop condition.
DSA Go
func hoarePartition(arr []int, low, high int) int {
pivot := arr[low]
i := low - 1
j := high + 1
for {
for {
i++
if arr[i] [1] pivot {
break
}
}
for {
j--
if arr[j] [1] pivot {
break
}
}
if i >= j {
return j
}
swap(arr, i, j)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= or >= causes infinite loops or wrong partition.
Mixing comparison directions for i and j.
✗ Incorrect
In Hoare partition, increment i while arr[i] < pivot and decrement j while arr[j] > pivot.
4fill in blank
hardFill both blanks to complete the Lomuto partition swap and return statement.
DSA Go
func lomutoPartition(arr []int, low, high int) int {
pivot := arr[high]
i := low - 1
for j := low; j < high; j++ {
if arr[j] <= pivot {
i++
swap(arr, [1], j)
}
}
swap(arr, [2], high)
return i + 1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping wrong indices causes incorrect partition.
Using j instead of i+1 in the final swap.
✗ Incorrect
Swap arr[i] and arr[j] inside the loop, then swap arr[i+1] and arr[high] after the loop.
5fill in blank
hardFill all three blanks to complete the Hoare partition loop increments and swap.
DSA Go
func hoarePartition(arr []int, low, high int) int {
pivot := arr[low]
i := low - 1
j := high + 1
for {
for {
i++
if arr[i] [1] pivot {
break
}
}
for {
j--
if arr[j] [2] pivot {
break
}
}
if i >= j {
return j
}
swap(arr, [3], j)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping arr[j] and arr[j] instead of arr[i] and arr[j].
Using wrong comparison operators causing infinite loops.
✗ Incorrect
i increments while arr[i] < pivot, j decrements while arr[j] > pivot, then swap arr[i] and arr[j].