Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to select the pivot as the last element in Lomuto partition.
DSA Python
def lomuto_partition(arr, low, high): pivot = arr[[1]] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing the first element as pivot instead of the last.
Using an index outside the current sub-array.
✗ Incorrect
In Lomuto partition, the pivot is chosen as the last element, which is at index 'high'.
2fill in blank
mediumComplete the code to move the pointers correctly in Hoare partition.
DSA Python
def hoare_partition(arr, low, high): pivot = arr[low] i = low - 1 j = high + 1 while True: i += 1 while arr[i] < pivot: i += 1 j -= 1 while arr[j] > pivot: j -= 1 if i >= j: return [1] arr[i], arr[j] = arr[j], arr[i]
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 'i' instead of 'j'.
Returning the pivot index instead of the crossing point.
✗ Incorrect
In Hoare partition, the partition index returned is 'j', which is the crossing point of pointers.
3fill in blank
hardFix the error in the Lomuto partition loop condition to avoid index error.
DSA Python
def lomuto_partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, [1]): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'high + 1' causing index error.
Using 'high - 1' which misses the last element before pivot.
✗ Incorrect
The loop should run from low to high-1, so range(low, high) is correct because 'high' is excluded.
4fill in blank
hardFill both blanks to correctly implement the pointer movement in Hoare partition.
DSA Python
def hoare_partition(arr, low, high): pivot = arr[low] i = [1] j = [2] while True: i += 1 while arr[i] < pivot: i += 1 j -= 1 while arr[j] > pivot: j -= 1 if i >= j: return j arr[i], arr[j] = arr[j], arr[i]
Attempts:
3 left
💡 Hint
Common Mistakes
Starting pointers at low and high instead of outside the bounds.
Mixing up the start positions causing infinite loops.
✗ Incorrect
In Hoare partition, 'i' starts at low - 1 and 'j' starts at high + 1 to move inward correctly.
5fill in blank
hardFill all three blanks to complete the Lomuto partition swap and return statement.
DSA Python
def lomuto_partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i [1] 1], arr[[2]] = arr[[3]], arr[i + 1] return i + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' causing wrong index.
Swapping with low instead of high.
Returning wrong partition index.
✗ Incorrect
We swap arr[i + 1] with arr[high] (pivot) and then return i + 1 as the partition index.
