logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

796. Rotate String

1 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

To check if one string is a rotation of another, we can double the original string. If the rotated version exists, it must appear as a substring within this doubled string.

# Complexity

Space ComplexityTime Complexity
O(N)\text{O}(N)O(N)O(N2)\text{O}(N^2)O(N2)

# Code

public boolean rotateString(String original, String target) {
    // Edge case: if lengths differ, rotation is not possible
    if (original.length() != target.length()) return false;
 
    // Create a doubled version of the original string
    String doubledOriginal = original + original;
    int originalLength = original.length();
 
    // Check all substrings of length originalLength in doubledOriginal
    for (int i = 0; i < originalLength; ++i) {
        // Extract substring and compare it with target
        if (doubledOriginal.substring(i, i + originalLength).equals(target)) {
            return true; // Found a match; it's a valid rotation
        }
    }
 
    return false; // No valid rotation found
}
 
←Previous704. Binary SearchNext→1071. Greatest Common Divisor of Strings

On this page

IntuitionComplexityCode