Advertisement

Rotate String - LeetCode 796 Solution

Rotate String - Complete Solution Guide

Rotate String is LeetCode problem 796, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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 consists of moving the leftmost character of s to the rightmost position. For example, if s = "abcde" , then it will be "bcdea" after one shift. Example 1: Input: s = "abcde", goal = "cdeab" Output: true Example 2: Input: s = "abcde", goal = "abced" Output: false Constraints: 1 <= s.length, goal.length <= 100 s and goal consist of lowercase English letters.

Detailed Explanation

The problem asks us to determine if a string `goal` can be obtained by rotating another string `s` a certain number of times. A single rotation involves moving the leftmost character of `s` to the rightmost position. The input consists of two strings, `s` and `goal`, and the output should be `true` if `goal` can be obtained by rotating `s`, and `false` otherwise. The length of both strings is between 1 and 100 characters.

Solution Approach

The solution checks if the lengths of the strings `s` and `goal` are equal. If not, it returns `false`. Otherwise, it concatenates `s` with itself (i.e., creates `s + s`). It then checks if `goal` is a substring of the concatenated string. If it is, then `goal` is a rotation of `s`, and the function returns `true`. Otherwise, it returns `false`.

Step-by-Step Algorithm

  1. Step 1: Check if the lengths of `s` and `goal` are equal. If not, return `false`.
  2. Step 2: Concatenate `s` with itself to create a new string `ss = s + s`.
  3. Step 3: Check if `goal` is a substring of `ss` using the `contains` or `find` method. If it is, return `true`.
  4. Step 4: If `goal` is not a substring of `ss`, return `false`.

Key Insights

  • Insight 1: If the lengths of `s` and `goal` are different, `goal` cannot be a rotation of `s`. This is a necessary initial check.
  • Insight 2: If `goal` is a rotation of `s`, then `goal` must be a substring of `s + s`. For instance, if `s = 'abcde'` and `goal = 'cdeab'`, then `s + s = 'abcdeabcde'`, and `goal` is a substring of it.
  • Insight 3: Check for edge cases like empty strings or null strings.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: String, String Matching.

Companies

Asked at: Amdocs, Rivian, SAP, Visa, Wells Fargo, tcs.