Check whether one string can be shifted into another by moving its first character to the end

Quick Overview

Decide whether a string can be turned into a target string by repeatedly moving its first character to the end. The problem tests reasoning about string rotations, the length edge case, and the time cost of substring search.

Check whether one string can be shifted into another by moving its first character to the end

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given two strings `s` and `goal`, return `True` if and only if `s` can become `goal` after some number of shifts on `s`. A shift on `s` moves the leftmost character of `s` to the rightmost position. For example, if `s = "abcde"`, it becomes `"bcdea"` after one shift. ### Function Signature ```python def rotate_string(s: str, goal: str) -> bool: ``` ### Rules - Zero shifts are allowed, so `True` is the answer whenever `s == goal`. - Return `False` when the two strings have different lengths, since a shift never changes the length. ### Constraints - `1 <= len(s), len(goal) <= 100` - `s` and `goal` consist of lowercase English letters. ### Examples ```text Input: s = "abcde", goal = "cdeab" Output: True ``` Two shifts do it: `"abcde"` becomes `"bcdea"`, then `"cdeab"`. ```text Input: s = "abcde", goal = "abced" Output: False ``` The five rotations of `"abcde"` are `"abcde"`, `"bcdea"`, `"cdeab"`, `"deabc"` and `"eabcd"`, and none of them is `"abced"`. ```text Input: s = "aa", goal = "a" Output: False ``` Every shift of `"aa"` still has two characters, so it can never equal the one-character `"a"`.

Overview: Decide whether a string can be turned into a target string by repeatedly moving its first character to the end. The problem tests reasoning about string rotations, the length edge case, and the time cost of substring search.

General logo
General
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given two strings s and goal, return True if and only if s can become goal after some number of shifts on s.

A shift on s moves the leftmost character of s to the rightmost position. For example, if s = "abcde", it becomes "bcdea" after one shift.

Function Signature

def rotate_string(s: str, goal: str) -> bool:

Rules

  • Zero shifts are allowed, so True is the answer whenever s == goal .
  • Return False when the two strings have different lengths, since a shift never changes the length.

Constraints

  • 1 <= len(s), len(goal) <= 100
  • s and goal consist of lowercase English letters.

Examples

Input: s = "abcde", goal = "cdeab"
Output: True

Two shifts do it: "abcde" becomes "bcdea", then "cdeab".

Input: s = "abcde", goal = "abced"
Output: False

The five rotations of "abcde" are "abcde", "bcdea", "cdeab", "deabc" and "eabcd", and none of them is "abced".

Input: s = "aa", goal = "a"
Output: False

Every shift of "aa" still has two characters, so it can never equal the one-character "a".