使用Go实现Hackerrank Circular Array Rotation提交遇Runtime Error求助
Hey there! Let's figure out why your code works locally but throws a runtime error on one Hackerrank test case. I’ve run into this exact gotcha with rotation problems before, so let’s break it down.
The Root Cause
Your current logic calculates j = (i - k) and adds n if j is negative—but this fails when k is much larger than n.
Hackerrank likely has a test case where k is way bigger than the array length n (like k = 1000 and n = 5). For example, if i = 0, k = 1000, n =5:
i -k = -1000- Adding
nonce gives-995, which is still negative - Accessing
a[-995]causes an array index out of bounds panic (the runtime error you’re seeing)
Since rotating an array n times brings it back to the original state, we only need to care about k % n—the effective number of rotations.
The Fix
Make two key adjustments to your code:
- Modulo
kwithnto get the effective rotation count - Calculate
jsafely using(i - k + n) % nto ensure it’s always a non-negative index (no need for anifcheck!)
Here’s the revised code:
package main import "fmt" func CircularArrayRotation() { var n, k, q int fmt.Scanf("%d%d%d", &n, &k, &q) // Reduce k to its effective value (rotating n times does nothing) k = k % n a := make([]int, n) for i := range a { fmt.Scanf("%d", &a[i]) } var i int for t:=0; t<q; t++ { fmt.Scanf("%d", &i) // Safely compute the original index without negative values j := (i - k + n) % n fmt.Println(a[j]) } } func main() { CircularArrayRotation() }
Why This Works
k % nensures we only rotate by a value between 0 andn-1, eliminating the problem of hugekvalues(i - k + n) % nguaranteesjis always a valid index (addingnfirst ensures the numerator is positive before taking modulo, so we never get a negative result)
Why It Worked Locally
Your local test cases probably used small k values where i -k only needed one addition of n to become positive. Hackerrank’s edge case with a massive k exposed the flaw in that logic.
内容的提问来源于stack exchange,提问作者targat

