Longest equal substring with cost less than K
Last Updated :
11 Oct, 2023
Given two strings X and Y of the same length, which consist of lowercase letters and also an integer K. The task is to find the maximum length up to which X can be changed to Y within the given cost K.
The cost of changing a character is given by the absolute difference between the ASCII value of the characters. That is, to change a character at index i, cost = |x[i] - Y[i]|
Examples:
Input: X = abcd, Y = bcde, K = 3
Output: 3
Explanation: A maximum of 3 characters can be changed because the cost to change each article is 1.
Approach: The idea is to maintain a prefix array of length N to store the absolute sum of the strings. That is, the cost of changing the string X to Y. The following steps can be followed to compute the result:
- Maintain two pointers, say i and j.
- In a while loop, check if the difference between ith index and jth index of prefix array is greater than given cost or not.
- If the difference is greater than the given cost, then increase the j pointer to compensate for the cost, else increase the i pointer.
Below is the implementation of the above approach:
C++
// C++ program to find the
// maximum length of equal substring
// within a given cost
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum length
int solve(string X, string Y, int N, int K)
{
int count[N + 1] = { 0 };
int sol = 0;
count[0] = 0;
// Fill the prefix array with
// the difference of letters
for (int i = 1; i <= N; i++) {
count[i] = count[i - 1] + abs(X[i - 1] - Y[i - 1]);
}
int j = 0;
for (int i = 1; i <= N; i++) {
while ((count[i] - count[j]) > K) {
j++;
}
// Update the maximum length
sol = max(sol, i - j);
}
return sol;
}
// Driver code
int main()
{
int N = 4;
string X = "abcd", Y = "bcde";
int K = 3;
cout << solve(X, Y, N, K) << "\n";
return 0;
}
Java
// Java program to find the
// maximum length of equal subString
// within a given cost
class GFG
{
// Function to find the maximum length
static int solve(String X, String Y,
int N, int K)
{
int []count = new int[N + 1];
int sol = 0;
count[0] = 0;
// Fill the prefix array with
// the difference of letters
for (int i = 1; i <= N; i++)
{
count[i] = count[i - 1] +
Math.abs(X.charAt(i - 1) -
Y.charAt(i - 1));
}
int j = 0;
for (int i = 1; i <= N; i++)
{
while ((count[i] - count[j]) > K)
{
j++;
}
// Update the maximum length
sol = Math.max(sol, i - j);
}
return sol;
}
// Driver code
public static void main(String[] args)
{
int N = 4;
String X = "abcd", Y = "bcde";
int K = 3;
System.out.print(solve(X, Y, N, K) + "\n");
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to find the
# maximum length of equal subString
# within a given cost
# Function to find the maximum length
def solve(X, Y, N, K):
count = [0] * (N + 1);
sol = 0;
count[0] = 0;
# Fill the prefix array with
# the difference of letters
for i in range(1, N + 1):
count[i] = (count[i - 1] +
abs(ord(X[i - 1]) -
ord(Y[i - 1])));
j = 0;
for i in range(1, N + 1):
while ((count[i] - count[j]) > K):
j += 1;
# Update the maximum length
sol = max(sol, i - j);
return sol;
# Driver code
if __name__ == '__main__':
N = 4;
X = "abcd";
Y = "bcde";
K = 3;
print(solve(X, Y, N, K));
# This code is contributed by PrinciRaj1992
C#
// C# program to find the
// maximum length of equal subString
// within a given cost
using System;
class GFG
{
// Function to find the maximum length
static int solve(string X, string Y,
int N, int K)
{
int []count = new int[N + 1];
int sol = 0;
count[0] = 0;
// Fill the prefix array with
// the difference of letters
for (int i = 1; i <= N; i++)
{
count[i] = count[i - 1] +
Math.Abs(X[i - 1] -
Y[i - 1]);
}
int j = 0;
for (int i = 1; i <= N; i++)
{
while ((count[i] - count[j]) > K)
{
j++;
}
// Update the maximum length
sol = Math.Max(sol, i - j);
}
return sol;
}
// Driver code
public static void Main()
{
int N = 4;
string X = "abcd", Y = "bcde";
int K = 3;
Console.WriteLine(solve(X, Y, N, K) + "\n");
}
}
// This code is contributed by AnkitRai01
JavaScript
<script>
// Javascript program to find the
// maximum length of equal subString
// within a given cost
// Function to find the maximum length
function solve(X, Y, N, K)
{
let count = new Array(N + 1);
count.fill(0);
let sol = 0;
count[0] = 0;
// Fill the prefix array with
// the difference of letters
for (let i = 1; i <= N; i++)
{
count[i] = count[i - 1] +
Math.abs(X[i - 1].charCodeAt() -
Y[i - 1].charCodeAt());
}
let j = 0;
for (let i = 1; i <= N; i++)
{
while ((count[i] - count[j]) > K)
{
j++;
}
// Update the maximum length
sol = Math.max(sol, i - j);
}
return sol;
}
let N = 4;
let X = "abcd", Y = "bcde";
let K = 3;
document.write(solve(X, Y, N, K));
</script>
Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the given string.
Efficient Approach:
Our Approach is simple and we can reduce the space complexity from O(n) to O(1) that is constant space .
Approach:
- We maintain a sliding window of length len that starts at index 0 and ends at index i.
- We calculate the total cost of changing the characters within this window and compare it with the given cost K.
- If the total cost is less than or equal to K, we update the maximum length seen so far. If the total cost is greater than K, we shrink the window from the left to decrease the cost until it becomes less than or equal to K.
- To calculate the cost of changing the characters at each index i, we use the absolute difference between the ASCII value of the characters.
- Hence we return the maxlen as our Output.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum length up to which X can be changed to Y within the given cost K.
int max_Length(string X, string Y, int K) {
int n = X.size();
int cost = 0, len = 0, maxlen = 0;
for (int i = 0; i < n; i++) {
cost += abs(X[i] - Y[i]); // calculate the cost of changing the characters at each index i within the window.
len++;
while (cost > K) { // if the total cost of changing the characters within the window is more than K, shrink the window from the left to decrease the cost.
cost -= abs(X[i - len + 1] - Y[i - len + 1]);
len--;
}
maxlen = max(maxlen, len); // update the maximum length seen so far.
}
return maxlen;
}
int main() {
string X="abcd", Y="bcde";
int K=3;
// call the maxLength function and print the result
int result = max_Length(X, Y, K);
cout << result << "\n";
return 0;
}
Java
import java.util.*;
public class GFG {
// Function to find the maximum length up to which X can be changed to Y within the given cost K.
public static int maxLength(String X, String Y, int K) {
int n = X.length();
int cost = 0, len = 0, maxlen = 0;
for (int i = 0; i < n; i++) {
cost += Math.abs(X.charAt(i) - Y.charAt(i)); // calculate the cost of changing the characters at each index i within the window.
len++;
while (cost > K) { // if the total cost of changing the characters within the window is more than K, shrink the window from the left to decrease the cost.
cost -= Math.abs(X.charAt(i - len + 1) - Y.charAt(i - len + 1));
len--;
}
maxlen = Math.max(maxlen, len); // update the maximum length seen so far.
}
return maxlen;
}
public static void main(String[] args) {
String X = "abcd";
String Y = "bcde";
int K = 3;
// Call the maxLength function and print the result
int result = maxLength(X, Y, K);
System.out.println(result);
}
}
Python3
# Function to find the maximum length up to which
# X can be changed to Y within the given cost K.
def max_length(X, Y, K):
n = len(X)
cost = 0
length = 0
max_length = 0
for i in range(n):
# calculate the cost of changing the characters at
# each index i within the window.
cost += abs(ord(X[i]) - ord(Y[i]))
length += 1
# if the total cost of changing the characters within
# the window is more than K, shrink the window from the left
# to decrease the cost.
while cost > K:
cost -= abs(ord(X[i - length + 1]) - ord(Y[i - length + 1]))
length -= 1
max_length = max(max_length, length) # update the maximum length seen so far.
return max_length
def main():
X = "abcd"
Y = "bcde"
K = 3
# call the max_length function and print the result
result = max_length(X, Y, K)
print(result)
if __name__ == "__main__":
main()
C#
using System;
class Program {
// Function to find the maximum length up to which X can
// be changed to Y within the given cost K.
static int MaxLength(string X, string Y, int K)
{
int n = X.Length;
int cost = 0, len = 0, maxlen = 0;
for (int i = 0; i < n; i++) {
cost += Math.Abs(
X[i]
- Y[i]); // calculate the cost of changing
// the characters at each index i
// within the window.
len++;
while (cost > K) {
// if the total cost of changing the
// characters within the window is more than
// K, shrink the window from the left to
// decrease the cost.
cost -= Math.Abs(X[i - len + 1]
- Y[i - len + 1]);
len--;
}
maxlen = Math.Max(maxlen,
len); // update the maximum
// length seen so far.
}
return maxlen;
}
static void Main(string[] args)
{
string X = "abcd", Y = "bcde";
int K = 3;
// call the MaxLength function and print the result
int result = MaxLength(X, Y, K);
Console.WriteLine(result);
// Keep the console window open until a key is
// pressed
Console.ReadKey();
}
}
JavaScript
// Function to find the maximum length up to which X can be changed to
// Y within the given cost K.
function max_Length(X, Y, K) {
// Calculate the length of the string.
const n = X.length;
// Initialize the cost, length, and maximum length variables.
let cost = 0;
let len = 0;
let maxlen = 0;
// Iterate over the string.
for (let i = 0; i < n; i++) {
// Calculate the cost of changing the characters at each index i within the window.
cost += Math.abs(X.charCodeAt(i) - Y.charCodeAt(i));
// Increase the length of the window.
len++;
// While the total cost of changing the characters within the window is more than K, shrink the window from the left to decrease the cost.
while (cost > K) {
// Decrease the cost by subtracting the cost of changing the character at the leftmost index of the window.
cost -= Math.abs(X.charCodeAt(i - len + 1) - Y.charCodeAt(i - len + 1));
// Decrease the length of the window.
len--;
}
// Update the maximum length seen so far.
maxlen = Math.max(maxlen, len);
}
// Return the maximum length up to which X can be changed to Y within the given cost K.
return maxlen;
}
// Example usage:
const X = "abcd";
const Y = "bcde";
const K = 3;
// Call the max_Length function to find the maximum length up to which X can be changed to Y within the given cost K.
const result = max_Length(X, Y, K);
// Print the result.
console.log(result);
Time Complexity: O(N), where N is the length of the input strings X and Y.
Auxiliary Space: O(1), No extra space is being used.
Similar Reads
Longest substring that starts with X and ends with Y Given a string str, two characters X and Y. The task is to find the length of the longest substring that starts with X and ends with Y. It is given that there always exists a substring that starts with X and ends with Y. Examples: Input: str = "QWERTYASDFZXCV", X = 'A', Y = 'Z' Output: 5 Explanation
10 min read
C++ Program To Find Length Of The Longest Substring Without Repeating Characters Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
6 min read
Largest substring where all characters appear at least K times | Set 2 Given a string str and an integer K, the task is to find the length of the longest sub-string S such that every character in S appears at least K times.Examples:Input: str = "aabbba", K = 3Output: 6 Explanation: In substring aabbba, each character repeats at least k times and its length is 6.Input:
7 min read
Minimum length of Run Length Encoding possible by removing at most K characters from a given string Given a string S of length N, consisting of lowercase English alphabets only, the task is to find the minimum possible length of run-length-encoding that can be generated by removing at most K characters from the string S. Examples: Input: S = "abbbcdcdd", N = 9, K = 2 Output: 5 Explanation: One pos
10 min read
Length of the longest substring with equal 1s and 0s Given a binary string. We need to find the length of the longest balanced substring. A substring is balanced if it contains an equal number of 0 and 1. Examples: Input : input = 110101010Output : Length of longest balanced sub string = 8 Input : input = 0000Output : Length of longest balanced sub st
10 min read
Longest substring with k unique characters Given a string you need to print longest possible substring that has exactly k unique characters. If there is more than one substring of longest possible length, then print any one of them.Note:- Source(Google Interview Question).Examples: Input: Str = "aabbcc", k = 1Output: 2Explanation: Max substr
12 min read
Length of the longest substring with no consecutive same letters Given a string str, the task is to find the length of the longest sub-string which does not have any pair of consecutive same characters. Examples: Input: str = "abcdde" Output: 4 "abcd" is the longestInput: str = "ccccdeededff" Output: 5 "ededf" is the longest Approach: The following steps can be f
7 min read
Longest substring containing exactly K vowels Given string str containing both uppercase and lowercase letters, and an integer K. The task is to find the longest substring containing exactly K vowels (maybe repetitive). Examples: Input: GeeksForGeeks, K = 2Output: 7, eksForGExplanation: The longest substring having exactly two vowels is "eksFor
13 min read
Longest sub-string having frequency of each character less than equal to k Given a string str of length n. The problem is to find the length of the longest sub-string in str having frequency of each character less than equal to the given value k. Examples : Input : str = "babcaag", k = 1 Output : 3 abc and bca are the two longest sub-strings having frequency of each charac
10 min read