Check if left and right shift of any string results into given string


A collection of characters is represented by a string data type. It is arranged logically using letters, numbers, symbols, and empty spaces. The majority of computer languages enclose strings in single or double quotation marks to distinguish them from other data types.

Programmers frequently employ strings to carry out some input and output operations, the storing, and the manipulation of textual data, and more. Concatenation (combining two or more strings), substring extraction (obtaining a segment of a string) and searching for certain characters or patterns inside a string are some frequent operations that can be carried out on strings.

Methods

We can use following methods to determine whether string's left and right shift results in each string −

Method 1. Brute Force Approach −

Method 2. Check for Substring −

Method 1: Brute Force Approach

Using the brute force method, all left and right shifts of input string are generated, and each one is then compared to target string. This method's temporal complexity, where n is length of the string, is O(n2).

Syntax

Iterating through all potential left and right shifts of original string and comparing them with the given string is the brute force method for determining whether a left and right shift of any string results in given string. The general syntax for this strategy is as follows −

string_shift_check (original_string, given_string):
   n = length of original string
   for int i from 0 to n-1:
      left shift = original string[i:n] + original string[0:i]
      right shift = original string[n-i:n] + original string[0:n-i]
      if left shift == given string or right shift == given string:
         return True
   return False

Algorithm

The brute force method of determining whether a string's left and right shifts result in the provided string involves testing out every conceivable shift for the string and determining whether any of them fits the given string. The algorithm is as follows −

Step 1 − Begin by initialising a variable to 0 to represent the current shift count.

Step 2 − When the number of shifts is less than the length of the string−

  • Left shift the string by moving the first character to the end of the string.

  • Verify that the shifted string matches the supplied string. Give a true answer if it does.

  • Apply a right shift to the string by shifting the final character to the beginning.

  • Verify that the shifted string matches the supplied string. Give a true answer if it does.

  • Increase the shift count by 1.

Step 3 − Return false if no match is discovered after trying every possible shift.

Example 1

This implementation states that the function is Shifted String receives two string parameters, s and target, and returns a Boolean result indicating whether target is a left or right shift of s.

Function initially confirms that the lengths of two strings are equal before determining whether target is a shifted version of s. After that, it builds new strings by combining the substrings before and after each possible shift position. The method gives true if the left-shifted or right-shifted string in the required string resembles. If that is the case, it returns the false.

In the main function, we define two sample strings, s and target, and utilise these strings to invoke the Shifted String method. The programme then indicates whether target is the shifted form of s.

#include <iostream>
#include <string>

using namespace std;

bool isShiftedString(string s, string target) {
   if(s.length() != target.length()) {
      return false;
   }
   int n = s.length();
   for(int i = 0; i < n; i++) {
      string leftShift = s.substr(i) + s.substr(0, i); // left shift the string
      string rightShift = s.substr(n-i) + s.substr(0, n-i); // right shift the string
      if(leftShift == target || rightShift == target) {
         return true;
      }
   }
   return false;
}

int main() {
   string s = "abcde";
   string target = "cdeab";
   if(isShiftedString(s, target)) {
      cout << "The string is shifted." << endl;
   } else {
      cout << "The string is not shifted." << endl;
   }
   return 0;
}

Output

The string is shifted.

Method 2: Check for Substring

To figure out if a smaller string is a part of a longer one, the "Check for Substring" approach can be employed. This process involves comparing individual substrings of the same length as the smaller string to the smaller string itself while walking through the greater string. If the two strings are a match, this confirms that the shorter string is indeed a subset of the larger text. To increase the level of complexity and varying sentence lengths in this article, the idea should be broken up into simple yet engaging sections.

Syntax

The following syntax can be used to determine whether left and right shift of any string results in provided string −

if (string_to_check_in.find(substring_to_check) != -1):
   //Substring found in string, so it is a left or right shift
else:
   //Substring not found, so it is not a left or right shift

Algorithm

The following algorithm is used to determine whether a string's left and right shifts produce the supplied string −

Step 1 − Start by entering the input and target strings.

Step 2 − Verify that the input string's length and the target string's length are equal. Return False if you don't.

Step 3 − To construct a novel sequence, the input string must be merged with the output string.

Step 4 − To confirm if the input string is included within the newly constructed sequence, a comparison between them ought to take place.

Step 5 − If the two strings coincide entirely, the answer would be Indubitable; conversely, the answer would be Negative.

Example 2

Here is a C++ code to see if left and right shifting any string will produce the provided string −

This example investigates the connection between two arrays, s1 and s2, to observe if they share any similar strings. By upholding the premise that the length of both s1 and s2 need to be the same, they are then joined as one array called "s1s1". This array is further scrutinized to determine if a piece of s2 can be found, where the outcome of the search will output either a "true" or "false". This technique, which gives a fundamental reaction to affiliation, is utilized to additionally assess the left and right fields of s1 and s2 to affirm the association between the two arrangements.

#include <iostream>
#include <string>

using namespace std;

bool checkForSubstring(string s1, string s2) {
   if (s1.length() != s2.length()) {
      return false;
   }
    
   string s1s1 = s1 + s1;
    
   if (s1s1.find(s2) != string::npos) {
      return true;
   }
    
   return false;
}
int main() {
   string s1 = "abcd";
   string s2 = "cdab";
    
   if (checkForSubstring(s1, s2)) {
      cout << "Yes, left or right shift of string " << s1 << " results in " << s2 << endl;
   } else {
      cout << "No, left or right shift of string " << s1 << " does not result in " << s2 << endl;
   }
   return 0;
}

Output

Yes, left or right shift of string abcd results in cdab

Conclusion

We were given a string for this topic, and we had to determine whether the string could be generated by repeatedly applying left and right shifts to itself.

Simply concatenating the provided string with itself and determining whether the new string retains the original string will solve this issue. If it does, then executing left and right shifts on the string itself will yield the original string.

As an alternative, we might go through every shift position and see whether any of the shifted strings match the input string.

The temporal complexity of the solution is O(n2) in both cases, where n is the length of the string. ft and right shift of any string results in given string −

Updated on: 31-Jul-2023

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements