Pattern After Double, Reverse, and Swap in Python

The Pattern After Double, Reverse, and Swap problem generates a sequence by applying three operations cyclically: double, reverse, and swap characters. Starting with "xxy", we apply these operations to find the nth pattern in the sequence.

Understanding the Pattern

The sequence follows this pattern:

  • xxy
  • xxyxxy (doubled)
  • yxxyxx (reversed)
  • xyyxyy (swapped x?y)
  • xyyxyyxyyxyy (doubled)
  • ...

Algorithm Steps

To generate the nth pattern, we follow these rules cyclically:

  • Step 0 (mod 3): Double the string (concatenate with itself)
  • Step 1 (mod 3): Reverse the string
  • Step 2 (mod 3): Swap all 'x' with 'y' and vice versa

Implementation

class Solution:
    def solve(self, n):
        i = 0
        pattern = "xxy"
        
        while i < n:
            if i % 3 == 0:
                # Double the pattern
                pattern += pattern
            elif i % 3 == 1:
                # Reverse the pattern
                pattern = pattern[::-1]
            else:
                # Swap x and y
                swapped = ""
                for char in pattern:
                    if char == "x":
                        swapped += "y"
                    else:
                        swapped += "x"
                pattern = swapped
            i += 1
        
        return pattern

# Test the solution
solution = Solution()
print(f"Pattern at n=5: {solution.solve(5)}")
print(f"Pattern at n=3: {solution.solve(3)}")
Pattern at n=5: yyxyyxyyxyyx
Pattern at n=3: xyyxyy

Step-by-Step Execution

Let's trace through the first few iterations:

  • Start: "xxy"
  • i=0 (double): "xxy" + "xxy" = "xxyxxy"
  • i=1 (reverse): "yxxyxx"
  • i=2 (swap): "xyyxyy"
  • i=3 (double): "xyyxyyxyyxyy"
  • i=4 (reverse): "yyxyyxyyxyyx"

Alternative Implementation Using String Translation

def generate_pattern(n):
    pattern = "xxy"
    
    for i in range(n):
        if i % 3 == 0:
            pattern = pattern * 2
        elif i % 3 == 1:
            pattern = pattern[::-1]
        else:
            # Use string translation for swapping
            pattern = pattern.translate(str.maketrans('xy', 'yx'))
    
    return pattern

# Test the alternative implementation
print(f"Pattern at n=5: {generate_pattern(5)}")
print(f"Pattern at n=2: {generate_pattern(2)}")
Pattern at n=5: yyxyyxyyxyyx
Pattern at n=2: yxxyxx

Conclusion

This pattern generation follows a simple three-step cycle: double, reverse, and swap. The algorithm efficiently builds each pattern by applying operations in sequence, making it useful for understanding string manipulation and cyclic operations in Python.

Updated on: 2026-03-25T10:20:51+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements