Check if a string can be obtained by rotating another string 2 places in Python

String rotation is a common programming problem where we check if one string can be obtained by rotating another string by a specific number of positions. In this case, we need to check if we can rotate a string exactly 2 places in either direction (left or right).

Problem Understanding

Given two strings s and t, we need to determine if string s can be obtained by rotating string t exactly 2 positions left or right.

For example, if t = "takolka":

  • Left rotation by 2: "takolka" ? "kolkata"
  • Right rotation by 2: "takolka" ? "katakolka"

Algorithm

To solve this problem, we follow these steps ?

  • Check if both strings have the same length (different lengths cannot be rotations)
  • Create left rotation by 2: take last 2 characters + remaining characters
  • Create right rotation by 2: take characters from index 2 + first 2 characters
  • Check if the target string matches either rotation

Implementation

def solve(s, t):
    if len(s) != len(t):
        return False
    
    l = len(t)
    # Left rotation by 2: last 2 chars + remaining chars
    left_rot = t[l - 2:] + t[0: l - 2]
    
    # Right rotation by 2: chars from index 2 + first 2 chars  
    right_rot = t[2:] + t[0:2]
    
    return s == right_rot or s == left_rot

# Test the function
s = "kolkata"
t = "takolka"
print(f"Can '{s}' be obtained by rotating '{t}' 2 places? {solve(s, t)}")
Can 'kolkata' be obtained by rotating 'takolka' 2 places? True

How It Works

Let's trace through the example step by step:

def demonstrate_rotation():
    t = "takolka"
    print(f"Original string: {t}")
    
    # Left rotation by 2
    left_rot = t[-2:] + t[:-2]  # Last 2 + rest
    print(f"Left rotation by 2: {left_rot}")
    
    # Right rotation by 2  
    right_rot = t[2:] + t[:2]   # From index 2 + first 2
    print(f"Right rotation by 2: {right_rot}")

demonstrate_rotation()
Original string: takolka
Left rotation by 2: kolkata
Right rotation by 2: kolkata

Additional Examples

# Test with different cases
test_cases = [
    ("kolkata", "takolka"),  # True - left rotation
    ("abcdef", "efabcd"),    # True - left rotation  
    ("hello", "llohe"),      # True - right rotation
    ("python", "thonpy"),    # True - left rotation
    ("test", "testing"),     # False - different lengths
    ("abc", "bca")           # False - rotation by 1, not 2
]

for s, t in test_cases:
    result = solve(s, t)
    print(f"'{s}' from '{t}': {result}")
'kolkata' from 'takolka': True
'abcdef' from 'efabcd': True
'hello' from 'llohe': True
'python' from 'thonpy': True
'test' from 'testing': False
'abc' from 'bca': False

Time and Space Complexity

  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(n) for storing the rotated strings

Conclusion

This solution efficiently checks if one string can be obtained by rotating another string exactly 2 places. The key insight is to generate both possible rotations (left and right by 2 positions) and compare them with the target string.

Updated on: 2026-03-25T14:08:47+05:30

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements