Similar Problems

Similar Problems not available

Odd String Difference - Leetcode Solution

Companies:

LeetCode:  Odd String Difference Leetcode Solution

Difficulty: Easy

Topics: string hash-table array  

Problem Statement:

You are given two strings s and t of equal length consisting of letters "a" and "b". You want to find the maximum number of indices i (0 <= i < s.length) such that s[i] != t[i] (0-indexed).

For each index i, you can swap s[i] with t[i].

Return the maximum number of indices you can swap to make s and t equal.

Example:

Input: s = "aba", t = "aab"

Output: 1

Explanation:

Possible operations could be:

s = "aba" -> s[2] = 'b' -> "abb" s = "abb" -> s[1] = 'b' -> "aab"

Now, s = t = "aab", so it took 2 operations to make s and t equal.

We can swap the elements at index "1" to make both strings equal. Thus the output is 1.

Solution:

Let's start solving the problem. We need to find the maximum number of indices i (0 <= i < s.length) such that s[i] != t[i].

For each index i, we can have two scenarios:

  1. s[i] == t[i], in this case no swapping is required.

  2. s[i] != t[i], in this case swapping is required.

We can keep track of the number of indices where s[i] != t[i]. Let's call it "count".

Now, if count is odd, we can't make both strings equal as we can only swap two indices at a time. If count is even, we can always make both strings equal.

But the number of swaps we can make is limited to count / 2. Let's call it "ans".

Thus, the solution to the problem is ans if count is even, and ans - 1 if count is odd.

Here is the implementation of the above approach:

class Solution { public int countBinarySubstrings(String s) { int prev=0, curr=1, ans=0;

    for (int i=1; i<s.length(); i++) {
        if (s.charAt(i) == s.charAt(i-1)) {
            curr++;
        }
        else {
            ans += Math.min(prev, curr);
            prev = curr;
            curr = 1;
        }
    }
    ans += Math.min(prev, curr);
    
    return ans;
}

}

Time Complexity: O(n), where n is the length of the longer string.

Space Complexity: O(1), constant space is used.

Odd String Difference Solution Code

1