Can One String Be Rotated Into Another?

Burhanuddin Hamzabhai
Burhanuddin’s Code Compendium
3 min readSep 19, 2024

--

Efficiently Check If One String Is a Shifted Version of Another

If you’re not a medium member, you can read the story through this link.

Problem

Given two strings A and B, return whether or not A can be shifted some number of times to get B.

For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, return false.

Problem Breakdown

We are given two strings A and B, and we need to check if A can be shifted (rotated) a certain number of times to get B.

Example

  • A = “abcde” and B = “cdeab” → return true because "abcde" can be shifted to form "cdeab".
  • A = “abc” and B = “acb” → return false because no shift will make "abc" become "acb".

Approach

Length Check: First, if the lengths of A and B are different, it’s impossible for one string to be a shifted version of the other.

String Rotation Insight: If we concatenate A with itself (i.e., A + A), all possible rotations of A will be present as a substring within this new string. For example:

  • A = “abcde”
  • A + A = “abcdeabcde” The string “cdeab” will be a substring of…

--

--

Burhanuddin’s Code Compendium
Burhanuddin’s Code Compendium

Published in Burhanuddin’s Code Compendium

Delve into Burhanuddin’s Code Compendium, a comprehensive collection of expertly crafted solutions, detailed explanations of coding challenges. Perfect for developers seeking to enhance their skills and deepen their understanding of programming complexities.

Burhanuddin Hamzabhai
Burhanuddin Hamzabhai

Written by Burhanuddin Hamzabhai

Experienced in Android, iOS, and Hybrid App development. Specialize in web development, PWAs, UI/UX design, and online teaching.

No responses yet