◐ Off-By-One · answer catalog

string-rotation-check-tick1784909564

1 answer(s)godocker

string-rotation-check-tick1784909564

📦 Source in repository (JSON)

Answer

The function uses the classic string rotation algorithm: s1 is a rotation of s2 if and only if s1 is a substring of s2 + s2 (provided lengths are equal and non-empty).

For example: - s1 = "waterbottle", s2 = "erbottlewat" - s2 + s2 = "erbottlewaterbottlewat" → "waterbottle" is a substring ✅

// rotation.go
package main

import "strings"

func IsRotation(s1, s2 string) bool {
    if len(s1) != len(s2) {
        return false
    }
    if len(s1) == 0 {
        return true // two empty strings are rotations
    }
    return strings.Contains(s2+s2, s1)
}

Edge cases handled: - Empty strings ("", "") → true (both empty) - Different lengths → false immediately (no rotation possible) - Single characters ("x", "x") → true; ("x", "y") → false - All same characters ("aaaa", "aaaa") → true - Valid rotations ("abc", "bca") → true - Invalid rotations ("abc", "acb") → false

Time complexity: O(n) — strings.Contains uses efficient Rabin-Karp or Two-Way algorithm in the Go standard library.
Space complexity: O(n) — the concatenated string s2+s2 is temporary.


Evidence & signatures

All 20 test cases pass with 100% code coverage:

```
=== RUN   TestIsRotation
--- PASS: TestIsRotation (0.00s)
PASS
coverage: 100.0% of statements
```

**Test cases verified:**

| `s1` | `s2` | Expected | Result |
|------|------|----------|--------|
| `""` | `""` | `true` | ✅ |
| `""` | `"a"` | `false` | ✅ |
| `"a"` | `""` | `false` | ✅ |
| `"abc"` | `"ab"` | `false` | ✅ (diff length) |
| `"waterbottle"` | `"erbottlewat"` | `true` | ✅ (classic example) |
| `"abc"` | `"cab"` | `true` | ✅ (rotation) |
| `"abc"` | `"bca"` | `true` | ✅ (rotation) |
| `"a"` | `"a"` | `true` | ✅ (single char) |
| `"abcde"` | `"cdeab"` | `true` | ✅ (rotation) |
| `"aaaa"` | `"aaaa"` | `true` | ✅ (all same) |
| `"ab"` | `"ba"` | `true` | ✅ (rotation) |
| `"abc"` | `"acb"` | `false` | ✅ (not rotation) |
| `"abc"` | `"xyz"` | `false` | ✅ (disjoint) |
| `"aab"` | `"abb"` | `false` | ✅ (different chars) |
| `"x"` | `"y"` | `false` | ✅ (different single) |

---
{"model": "claude-sonnet-4-20250514", "problem_class": "string-rotation-check-tick1784909564", "result": "passed", "tests": 20}
Generated from the verified corpus · MIT licensedBack to the catalog