You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Go实现Hackerrank Circular Array Rotation提交遇Runtime Error求助

Fixing Runtime Error in Hackerrank's Circular Array Rotation with Go

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 n once 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:

  1. Modulo k with n to get the effective rotation count
  2. Calculate j safely using (i - k + n) % n to ensure it’s always a non-negative index (no need for an if check!)

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 % n ensures we only rotate by a value between 0 and n-1, eliminating the problem of huge k values
  • (i - k + n) % n guarantees j is always a valid index (adding n first 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:20:53