TheAlgorithms/Go · error
right boundary cannot be greater than the length of the link
Error message
right boundary cannot be greater than the length of the linked list
What it means
Singly.CheckRangeFromIndex ensures the right bound does not exceed the list's current length, since ReversePartition walks exactly right-left+1 nodes; overshooting would dereference a nil Next pointer and panic.
Source
Thrown at structure/linkedlist/singlylinkedlist.go:169
pre = pre.Next
}
cur := pre.Next
for i := 0; i < right-left; i++ {
next := cur.Next
cur.Next = next.Next
next.Next = pre.Next
pre.Next = next
}
ll.Head = tmpNode.Next
return nil
}
func (ll *Singly[T]) CheckRangeFromIndex(left, right int) error {
if left > right {
return errors.New("left boundary must smaller than right")
} else if left < 1 {
return errors.New("left boundary starts from the first node")
} else if right > ll.length {
return errors.New("right boundary cannot be greater than the length of the linked list")
}
return nil
}
// Display prints out the elements of the list.
func (ll *Singly[T]) Display() {
for cur := ll.Head; cur != nil; cur = cur.Next {
fmt.Print(cur.Val, " ")
}
fmt.Print("\n")
}
View on GitHub (pinned to 5ba447ec5f)
Solutions
- Clamp right to ll.Length() before calling
- Re-read the current length after any mutations instead of using a cached value
- Validate user-provided positions against the live list length
Example fix
// before
ll.ReversePartition(left, cachedLen) // list has shrunk
// after
right := ll.Length()
if right > ll.Length() { right = ll.Length() }
ll.ReversePartition(left, right) Defensive patterns
Strategy: validation
Validate before calling
if right > ll.Length() {
return fmt.Errorf("right %d exceeds list length %d", right, ll.Length())
}
ll.ReversePartition(left, right) Try / catch
if err := ll.CheckRangeFromIndex(left, right); err != nil {
return fmt.Errorf("invalid range: %w", err)
} Prevention
- Clamp right to the live ll.Length() right before the call
- Avoid caching list lengths across mutations
- Validate any user-supplied position against the current length
When it happens
Trigger: Calling ReversePartition(left, right) with right > ll.length — e.g. using a stale length saved before removals, an index from another collection, or user input beyond the list size.
Common situations: Caching the list length across mutations; passing slice/array lengths from different data; hard-coded positions that exceed a shorter runtime list.
Related errors
- index out of range
- left boundary must smaller than right
- left boundary starts from the first node
- index out of range
- index out of bounds
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/1686a0cb3ba29bcc.
Report an issue: GitHub.