Similar Problems

Similar Problems not available

Get Equal Substrings Within Budget - Leetcode Solution

Companies:

LeetCode:  Get Equal Substrings Within Budget Leetcode Solution

Difficulty: Medium

Topics: string sliding-window prefix-sum binary-search  

Problem Description: You are given two strings s and t of the same length, and a budget. You want to change the first string s into the second string t using the following operation:

  • Choose an index i in s (0 <= i < s.length).
  • Choose a character c_1 that is different from s[i], and c_2 which is different from t[i]. These can be the same character as long as they are different from both s[i] and t[i].
  • Replace s[i] with c_1 and t[i] with c_2. You can make at most budget operations. Return the maximum length of the resulting strings you can get to be equal to each other.

Solution Approach: This problem can be solved using binary search. First find the maximum length of the equal substrings, by traversing both the strings and counting the number of equal substrings. Now, we can perform binary search on the length of equal substrings to find the maximum length of equal substrings that can be achieved within the given budget. In each iteration of the binary search, we check if it is possible to reach that length of equal substrings. We can do this by keeping track of the number of operations required to modify s to t, for each substring of that length. If the total number of operations required is less than or equal to the budget, then we can get to that length, else we can't.

Algorithm:

  1. Compute the array of equal substring lengths between s and t.
  2. Perform binary search for the maximum length of the equal substring.
  3. For each possible length, compute the cost of modifying s to t.
  4. If the cost is less than or equal to the budget, update the maximum length of the equal substring and continue binary search in the upper half of the interval, otherwise continue binary search in the lower half of the interval.
  5. Return the maximum length found.

Time Complexity:

  • Computing the array of equal substring lengths takes O(n) time.
  • Binary search takes O(log n) iterations.
  • For each possible length, computing the cost takes O(n) time.
  • Thus the total time complexity is O(n log n).

Space Complexity:

  • We only need to store the array of equal substring lengths, which takes O(n) space.

Python Code:

class Solution: def getEqualSubstring(self, s: str, t: str, maxCost: int) -> int: n = len(s) costs = [abs(ord(s[i]) - ord(t[i])) for i in range(n)] l, r, ans = 0, n, 0 while l <= r: mid = (l + r) // 2 window_cost = sum(costs[:mid]) if window_cost <= maxCost: ans = mid l = mid + 1 else: r = mid - 1 for i in range(mid, n): window_cost -= costs[i - mid] window_cost += costs[i] if window_cost <= maxCost: ans = mid break return ans

Get Equal Substrings Within Budget Solution Code

1