THWINKSUN's blog

By THWINKSUN, history, 8 months ago, In English

While solving another string problem (about rotations), I mistakenly interpreted the question in a different way — and ended up formulating a new problem of my own. I’m sharing it here to see if it can be solved more efficiently.

Problem Statement:

Given two strings s1 and s2 of equal length, the task is to check whether s2 can be obtained from s1 by performing the following operation exactly twice:

Choose any index in the string.

Rotate the string anticlockwise from that index (i.e., take the left part of the string up to that index and append it to the right).

If after two such operations, s1 can be transformed into s2, print Yes, otherwise print No.

Input:
s1 = "leetcode" s2 = "teelcoed"

Output:
Yes

Naive Approach (my solution):

Try all possible pairs of indices (i, j) and apply two rotations.

Compare the resulting string with s2.

This approach runs in O(n³) time because for each pair we perform string slicing and comparison.

Question

I have solved this using the naive approach above, but the time complexity is too high. Can anyone suggest a better solution than O(n³)?

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it