Code Logo

String Rotation

Published at24 Jul 2026
PHP String Handling Medium 0 views
Like0

Write a PHP function that checks if string $b is a rotation of string $a. For example, 'waterbottle' is a rotation of 'erbottlewat' because you can rotate 'waterbottle' by moving the first 3 characters to the end.

A string rotation check can be done by concatenating $a with itself and checking if $b is a substring of the result. If $b is a rotation of $a, it will always appear within $a . $a.

Medium difficulty because it requires the insight that concatenation creates all possible rotations, and using strpos() for substring checking. Edge cases include empty strings and strings of different lengths.

The string concatenation approach for checking rotations is a classic algorithmic trick. If you concatenate a string with itself, all possible rotations appear as substrings of the result. This works because rotation preserves the cyclic order of characters.

PHP's strpos() function checks for substring existence efficiently. The strict comparison with !== false is necessary because strpos can return 0 (match at position 0) which is falsy in PHP.

The rotation check problem tests understanding of string manipulation and algorithmic problem-solving. The concatenation approach is O(n) time since strpos() uses efficient substring search algorithms. Edge cases include identical strings (rotation by full length) and single-character strings.

Example Input & Output

Example 1
Input
"abc","abcd"
Output
false
Example 2
Input
"abc","cab"
Output
true
Example 3
Input
"abc","acb"
Output
false
Example 4
Input
"waterbottle","erbottlewat"
Output
true
Example 5
Input
"",""
Output
true

Algorithm Flow

Recommendation Algorithm Flow for String Rotation
Recommendation Algorithm Flow for String Rotation

Solution Approach

First check if the strings have the same length. If not, return false. If they are the same length, concatenate $a with itself: $a . $a. Then use strpos() to check if $b is a substring of $a . $a. If strpos returns a non-false value, $b is a rotation.

The concatenation approach works because every rotation of $a is a substring of $a . $a. For example, all rotations of 'abc' (abc, bca, cab) appear in 'abcabc'.

Edge cases include empty strings (both empty is considered a rotation), strings of different lengths (cannot be rotations), and the rotation of a string by its full length (same string).

Best Answers

php - Approach 1
<?php
function isRotation($a, $b) {
    if (strlen($a) !== strlen($b)) return false;
    if ($a === '' && $b === '') return true;
    return strpos($a . $a, $b) !== false;
}