✅Easy to Understand | Beginner Friendly | String | Hash Table | Counting | Detailed Video 🔥
IntuitionThe problem requires us to determine whether two strings can be made equal by swapping at most one pair of characters.
If two strings are already equal
# Intuition
The problem requires us to determine whether two strings can be made equal by swapping at most one pair of characters.  
If two strings are already equal, no swap is needed. Otherwise, we should check if exactly two characters differ and whether swapping them results in equality.

# Approach
1. Initialize variables to track the indices of differing characters and count the number of differences.
2. Traverse both strings simultaneously:
   - If a character differs, store its index.
   - If more than two differences are found, return `false` (as swapping one pair won't be enough).
3. After traversal:
   - If there are no differences, return `true` (strings are already equal).
   - If exactly two differences exist, check if swapping those characters makes the strings equal.
   - If only one character is different, return `false` (swapping won't help).
   
# Complexity
- **Time complexity:**  
  $$O(n)$$ – We traverse both strings once in a single pass.

- **Space complexity:**  
  $$O(1)$$ – We use only a few integer variables to track differences, requiring constant extra space.


# Code
```java []
class Solution {
    public boolean areAlmostEqual(String s1, String s2) {
        int n = s1.length();  // Get the length of the strings

        int firstIdxDiff = -1, secondIdxDiff = -1; // Variables to store the indices where characters differ
        int diffCount = 0;  // Counter to track the number of differing characters

        int i = 0, j = 0;
        while (i < n && j < n) {  // Loop through both strings
            if (s1.charAt(i) != s2.charAt(j)) {  // If characters at the current index are different
                if (diffCount > 0) {  
                    secondIdxDiff = i;  // Store the second mismatch index
                } else {
                    firstIdxDiff = i;  // Store the first mismatch index
                }

                diffCount++;  // Increment the difference counter

                if (diffCount > 2) return false;  // More than two mismatches mean swapping won't work
            }
            i++; j++;  // Move to the next character
        }

        if (diffCount == 2) {
            // Check if swapping the two differing characters makes the strings equal
            return s1.charAt(firstIdxDiff) == s2.charAt(secondIdxDiff) &&
                   s2.charAt(firstIdxDiff) == s1.charAt(secondIdxDiff);
        } else if (diffCount == 1) {
            return false;  // If only one mismatch exists, swapping isn't possible
        }

        return true;  // If no mismatches exist, the strings are already equal
    }
}

```

https://youtu.be/nynQBxWrB0U

['Hash Table', 'String', 'Counting', 'Java']