HomeInterview QuestionsWrite a function that reads two input strings and …

Write a function that reads two input strings and returns true if they match exactly or if they can be made equal by swapping exactly one pair of characters in one of the strings; otherwise return false.

🟡 Medium Coding Junior level
1Times asked
Jun 2026Last seen
Jun 2026First seen

💡 Model Answer

The solution is identical to the one described for question 1. First verify that the strings have the same length. Then scan both strings simultaneously, collecting the indices where the characters differ. If there are no differences, the strings are already equal, so return true. If there are exactly two differences, check that swapping the two mismatched characters in one string would align the strings: the character at the first mismatch in the first string must equal the character at the second mismatch in the second string, and vice versa. If this holds, return true; otherwise return false. Any other number of mismatches (one or more than two) means a single swap cannot reconcile the strings, so return false. The algorithm runs in linear time O(n) and uses constant extra space.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.

Get Assisting AI — Starts at ₹500