Explain Codes LogoExplain Codes Logo

Interview question: Check if one string is a rotation of other string

java
algorithm-implementation
performance-optimization
best-practices
Alex KataevbyAlex Kataev·Nov 1, 2024
TLDR
public static boolean isRotation(String str1, String str2) { // Hope you're not "rotate" phobic, because we're gonna spin some strings! return str1.length() == str2.length() && (str1 + str1).contains(str2); }

This sleek one-liner checks if string rotation is a thing between str1 and str2. Checking if their lengths are equal is essential before our substring search party gets into action. Concatenate str1 to itself, forming a superstring, and see if str2 hides inside this superstring.

The efficiency game

The method above uses the indexOf() method under the hood for substring search, providing an efficient algorithm baked right into Java's String class. However, for the algorithm enthusiasts among us, it might be interesting to recognize this as a sort of Knuth-Morris-Pratt (KMP) approach.

For those fluent in Pythonese 👨‍💻, the s1 in s2+s2 line of Python indeed takes the 🍰 for conciseness.

But beware, the quadratic time complexity monster lurks in dark corners. It's better to stick with solutions that are both efficient and elegant.

Pitfall protection and consideration corner

Like a silent guardian, a watchful protector for your code - Let's discuss some potential pitfalls and considerations:

  • Null strings: An alien invasion scenario for the NullPointerException, so strap-in and get those null checks ready.
  • Repeating string patterns: Testing with a variety of inputs is paramount to avoid false positives when dealing with repeating patterns.
  • I pity the 'FU' moment when large inputs creep up on you. Memory management is crucial — defer to algorithms like KMP for such scenarios.

Edge cases and coding best practices

Playing on the edge

The edge - where heroes are born. Consider these edgy scenarios:

  • Empty strings: Might seem insignificant, but two empty strings are indeed rotations of each other. Yes, they're introverted like that.
  • One character gang: Different characters? No rotation. Same character? Eternally rotational.
  • Substrings: Looking alike doesn't make one a rotation of the other. Length matters, folks!

The 'Best Practice' Wall of Fame

  • Clean code revolution: Clarity and readability take precedence. Our single-line method leads this march.
  • Algorithm arsenal: Suit up according to your battleground. Concatenation works well for smaller strings, but when grappling with larger strings — KMP, roll out!
  • Testing tavern: Write assertive unit tests, considering edge cases, for that verifyRotations() method to emerge victorious from your CI/CD pipeline.

Visualizing the solution

Consider the 'Rotation Rules' governing our string universe —

Before Rotation: 🚗🚕🚙 After Rotation: 🚙🚗🚕

Each emoji — a loyal representation of our string characters.

Original String: "cars" Rotated String: "scra"

Is it a rotation?

if original_string.length() == rotated_string.length() && (original_string + original_string).contains(rotated_string) { // 🔄✅ Rotation confirmed! }

A doubled-up string forms a circular track for our characters, exposing every possible shift.

Embrace feedback and cross-bridge consolidation

Power of open-source

Open-source communities give us the round-table platform to discuss, learn and improve. Review alternative approaches, seek performance opinions, consider real-world applications, and embrace the art of collective wisdom.

Be a solution blend master

Have alternatives in your quiver. A simple rotation check is a great start, but strive to understand the underlying principles of the problem. Explore learned algorithms and make the solution writing a fun exercise. But those wise words from the YAGNI manual – "The simplest solution often proves useful."