Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the middle node of the linked list.
DSA Go
func getMiddle(head *Node) *Node {
if head == nil {
return nil
}
slow := head
fast := head
for fast != nil && fast.Next != nil {
slow = slow.[1]
fast = fast.Next.Next
}
return slow
}Attempts:
3 left
💡 Hint
Common Mistakes
Using fast pointer instead of slow for moving one step.
Using Prev or Tail which do not exist or are incorrect here.
✗ Incorrect
The slow pointer moves one step at a time using slow.Next to find the middle node.
2fill in blank
mediumComplete the code to merge two sorted linked lists.
DSA Go
func sortedMerge(a, b *Node) *Node {
if a == nil {
return b
}
if b == nil {
return a
}
var result *Node
if a.Data <= b.Data {
result = a
result.Next = sortedMerge(a.Next, [1])
} else {
result = b
result.Next = sortedMerge([1], b.Next)
}
return result
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping a and b incorrectly in recursive calls.
Using nil instead of the other list.
✗ Incorrect
When a.Data <= b.Data, we merge the rest of a.Next with b, so the blank is 'b'.
3fill in blank
hardFix the error in the mergeSort function to split the list correctly.
DSA Go
func mergeSort(head *Node) *Node {
if head == nil || head.Next == nil {
return head
}
middle := getMiddle(head)
nextToMiddle := middle.[1]
middle.Next = nil
left := mergeSort(head)
right := mergeSort(nextToMiddle)
sortedList := sortedMerge(left, right)
return sortedList
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Prev or Head which are incorrect here.
Not splitting the list properly causing infinite recursion.
✗ Incorrect
To split the list, we get the node after middle using middle.Next.
4fill in blank
hardFill both blanks to complete the mergeSort function that sorts the linked list.
DSA Go
func mergeSort(head *Node) *Node {
if head == nil || head.Next == nil {
return head
}
middle := [1](head)
nextToMiddle := middle.[2]
middle.Next = nil
left := mergeSort(head)
right := mergeSort(nextToMiddle)
sortedList := sortedMerge(left, right)
return sortedList
}Attempts:
3 left
💡 Hint
Common Mistakes
Using sortedMerge instead of getMiddle.
Using mergeSort instead of Next for the pointer.
✗ Incorrect
We use getMiddle to find the middle and Next to get the node after middle.
5fill in blank
hardFill all three blanks to complete the sortedMerge function that merges two sorted linked lists.
DSA Go
func sortedMerge(a, b *Node) *Node {
if a == nil {
return [1]
}
if b == nil {
return [2]
}
var result *Node
if a.Data <= b.Data {
result = a
result.Next = sortedMerge(a.Next, [3])
} else {
result = b
result.Next = sortedMerge([3], b.Next)
}
return result
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning nil instead of the other list.
Using result instead of the other list in recursive calls.
✗ Incorrect
If a is nil, return b; if b is nil, return a; recursive calls use the other list accordingly.
