Find the Longest Substring Conversion
Last Updated :
23 Jul, 2025
Given two strings source and target of equal length, and two positive integers, maxCost, and conversionCost, the task is to find the indices of the longest substring in source that can be converted into the same substring in target with a cost less than or equal to maxCost, where each character conversion having a cost of conversionCost units.
Note: If multiple valid substrings exist, return any one of them.
Examples:
Input: source = "abcd", target = "bcdf", conversionCost = 1, maxCost = 3
Output: 0 2
Explanation: The substring of source from index 0 to 2 is "abc" which can change to "bcd" in target. The cost of changing would be 3 <= maxCost. And the maximum length possible is 3.
Input: source = "adcf", target = "cdef", conversionCost = 3, maxCost = 5
Output: 1 3
Finding Longest Substring Conversion using Binary Search:
The idea is to use binary search on answer to find the maximum possible length, and for each length, check its possible to change within maxCost and based on that update the search space of answer and keep track of indices of start and end position of valid substring.
Step-by-step approach:
- Initialize low to 1 and high to the string's length.
- Initialize result to store the maximum length of a valid substring.
- While low is less than high, do the following:
- Calculate mid = (start + end) / 2
- Check if mid is a possible length for a valid substring.
- If valid, update result to mid and shift low to mid + 1.
- Otherwise, shift high to mid.
- If a valid substring is found, print its starting and ending indices.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
// Initilise source variable startPos
// and endPos for storing the starting
// and ending position of valid
// substring respectively.
int startPos = -1, endPos = -1;
// Function to check if a substring
// of a given length is a
// valid substring.
bool isValid(int len, string& s, string& t,
int conversionCost, int maxCost)
{
int start = 0, end = 0, n = s.size();
int currCost = 0;
while (end < n) {
// Increment the current
// cost if characters are
// different.
if (s[end] != t[end]) {
currCost += conversionCost;
}
// If the substring length matches
// the given length.
if (end - start + 1 == len) {
// Check if the cost is within
// the maximum cost.
if (currCost <= maxCost) {
// Update the starting position
// of the valid substring.
startPos = start;
// Update the ending position
// of the valid substring.
endPos = end;
// Return true as this is a
// valid substring.
return true;
}
// Subtract the cost
// if the first
// character of the
// previous substring
// was different.
if (s[start] != t[start]) {
currCost -= conversionCost;
}
// Move the start of the substring.
start++;
// Move the end of the substring.
end++;
}
// Increment the end position of the
// substring.
else {
end++;
}
}
// If no valid substring is found,
// return false.
return false;
}
void validSubstring(string source, string target,
int conversionCost, int maxCost)
{
// Initilise source variable low
// with minimum valid length
// substring possible.
int low = 1;
// Initilise source variable high
// with maximum valid length
// substring possible.
int high = source.size();
// Do while low is less
// than equal to high
while (low <= high) {
// Calculate the mid
int mid = (low + high) / 2;
// Check if mid is possible
// length for valid substring
if (isValid(mid, source, target, conversionCost,
maxCost)) {
// Shift low to mid + 1
low = mid + 1;
}
// Otherwise shift high
// to mid - 1
else {
high = mid - 1;
}
}
if (startPos == -1)
cout << "Not possible\n";
else
cout << startPos << " " << endPos << "\n";
}
// Driver code
int main()
{
// First test case
string source = "adcf", target = "cdef";
int conversionCost = 3, maxCost = 5;
// Function Call
validSubstring(source, target, conversionCost, maxCost);
return 0;
}
Java
// Java code for the above approach
class GFG {
// Initilise source variable startPos
// and endPos for storing the starting
// and ending position of valid
// substring respectively.
static int startPos = -1, endPos = -1;
// Function to check if a substring
// of a given length is a
// valid substring.
static boolean isValid(int len, String s, String t,
int conversionCost, int maxCost)
{
int start = 0, end = 0, n = s.length();
int currCost = 0;
while (end < n) {
// Increment the current
// cost if characters are
// different.
if (s.charAt(end) != t.charAt(end)) {
currCost += conversionCost;
}
// If the substring length matches
// the given length.
if (end - start + 1 == len) {
// Check if the cost is within
// the maximum cost.
if (currCost <= maxCost) {
// Update the starting position
// of the valid substring.
startPos = start;
// Update the ending position
// of the valid substring.
endPos = end;
// Return true as this is a
// valid substring.
return true;
}
// Subtract the cost
// if the first
// character of the
// previous substring
// was different.
if (s.charAt(start) != t.charAt(start)) {
currCost -= conversionCost;
}
// Move the start of the substring.
start++;
// Move the end of the substring.
end++;
}
// Increment the end position of the
// substring.
else {
end++;
}
}
// If no valid substring is found,
// return false.
return false;
}
static void validSubstring(String source, String target,
int conversionCost,
int maxCost)
{
// Initilise source variable low
// with minimum valid length
// substring possible.
int low = 1;
// Initilise source variable high
// with maximum valid length
// substring possible.
int high = source.length();
// Do while low is less
// than equal to high
while (low <= high) {
// Calculate the mid
int mid = (low + high) / 2;
// Check if mid is possible
// length for valid substring
if (isValid(mid, source, target, conversionCost,
maxCost)) {
// Shift low to mid + 1
low = mid + 1;
}
// Otherwise shift high
// to mid - 1
else {
high = mid - 1;
}
}
if (startPos == -1)
System.out.println("Not possible\n");
else
System.out.println(startPos + " " + endPos
+ "\n");
}
// Driver code
public static void main(String[] args)
{
// First test case
String source = "adcf", target = "cdef";
int conversionCost = 3, maxCost = 5;
// Function Call
validSubstring(source, target, conversionCost,
maxCost);
}
}
// This code is contributed by ragul21
Python3
def is_valid(length, s, t, conversion_cost, max_cost):
global start_pos, end_pos
start, end, n = 0, 0, len(s)
curr_cost = 0
while end < n:
# Increment the current cost if characters are different.
if s[end] != t[end]:
curr_cost += conversion_cost
if end - start + 1 == length:
# Check if the cost is within the maximum cost.
if curr_cost <= max_cost:
# Update the starting position of the valid substring.
start_pos = start
# Update the ending position of the valid substring.
end_pos = end
# Return true as this is a valid substring.
return True
# Subtract the cost if the first character
# of the previous substring was different.
if s[start] != t[start]:
curr_cost -= conversion_cost
# Move the start of the substring.
start += 1
# Move the end of the substring.
end += 1
else:
# Increment the end position of the substring.
end += 1
# If no valid substring is found, return false.
return False
def valid_substring(source, target, conversion_cost, max_cost):
global start_pos, end_pos
# Initialize source variable low with the
# minimum valid length substring possible.
low = 1
# Initialize source variable high with the
# maximum valid length substring possible.
high = len(source)
# Do while low is less than equal to high
while low <= high:
# Calculate the mid
mid = (low + high) // 2
# Check if mid is a possible length for a valid substring
if is_valid(mid, source, target, conversion_cost, max_cost):
# Shift low to mid + 1
low = mid + 1
else:
# Otherwise shift high to mid - 1
high = mid - 1
if start_pos == -1:
print("Not possible")
else:
print(f"{start_pos} {end_pos}")
# Driver code
source_str = "adcf"
target_str = "cdef"
# Function Call
conversion_cost_val = 3
max_cost_val = 5
start_pos, end_pos = -1, -1
valid_substring(source_str, target_str, conversion_cost_val, max_cost_val)
C#
// C# code for the above approach
using System;
class GFG
{
// Initialize source variable startPos
// and endPos for storing the starting
// and ending position of valid
// substring respectively.
static int startPos = -1, endPos = -1;
// Function to check if a substring
// of a given length is a
// valid substring.
static bool IsValid(int len, string s, string t,
int conversionCost, int maxCost)
{
int start = 0, end = 0, n = s.Length;
int currCost = 0;
while (end < n)
{
// Increment the current
// cost if characters are
// different.
if (s[end] != t[end])
{
currCost += conversionCost;
}
// If the substring length matches
// the given length.
if (end - start + 1 == len)
{
// Check if the cost is within
// the maximum cost.
if (currCost <= maxCost)
{
// Update the starting position
// of the valid substring.
startPos = start;
// Update the ending position
// of the valid substring.
endPos = end;
// Return true as this is a
// valid substring.
return true;
}
// Subtract the cost
// if the first
// character of the
// previous substring
// was different.
if (s[start] != t[start])
{
currCost -= conversionCost;
}
// Move the start of the substring.
start++;
// Move the end of the substring.
end++;
}
// Increment the end position of the
// substring.
else
{
end++;
}
}
// If no valid substring is found,
// return false.
return false;
}
static void ValidSubstring(string source, string target,
int conversionCost,
int maxCost)
{
// Initialize source variable low
// with minimum valid length
// substring possible.
int low = 1;
// Initialize source variable high
// with maximum valid length
// substring possible.
int high = source.Length;
// Do while low is less
// than equal to high
while (low <= high)
{
// Calculate the mid
int mid = (low + high) / 2;
// Check if mid is possible
// length for valid substring
if (IsValid(mid, source, target, conversionCost,
maxCost))
{
// Shift low to mid + 1
low = mid + 1;
}
// Otherwise shift high
// to mid - 1
else
{
high = mid - 1;
}
}
if (startPos == -1)
Console.WriteLine("Not possible\n");
else
Console.WriteLine(startPos + " " + endPos
+ "\n");
}
// Driver code
public static void Main(string[] args)
{
// First test case
string source = "adcf", target = "cdef";
int conversionCost = 3, maxCost = 5;
// Function Call
ValidSubstring(source, target, conversionCost,
maxCost);
}
}
// This code is contributed by uttamdp_10
JavaScript
//Javascript code for the above approach
// Initilise source variable startPos
// and endPos for storing the starting
// and ending position of valid
// substring respectively.
let startPos = -1, endPos = -1;
// Function to check if a substring
// of a given length is a
// valid substring.
function isValid(len, s, t, conversionCost, maxCost) {
let start = 0, end = 0, n = s.length;
let currCost = 0;
while (end < n) {
// Increment the current
// cost if characters are
// different.
if (s[end] !== t[end]) {
currCost += conversionCost;
}
// If the substring length matches
// the given length.
if (end - start + 1 === len) {
// Check if the cost is within
// the maximum cost.
if (currCost <= maxCost) {
// Update the starting position
// of the valid substring.
startPos = start;
// Update the ending position
// of the valid substring.
endPos = end;
// Return true as this is a
// valid substring.
return true;
}
// Subtract the cost
// if the first
// character of the
// previous substring
// was different.
if (s[start] !== t[start]) {
currCost -= conversionCost;
}
// Move the start of the substring.
start++;
// Move the end of the substring.
end++;
}
// Increment the end position of the
// substring.
else {
end++;
}
}
// If no valid substring is found,
// return false.
return false;
}
function validSubstring(source, target, conversionCost, maxCost) {
// Initilise source variable low
// with minimum valid length
// substring possible.
let low = 1;
// Initilise source variable high
// with maximum valid length
// substring possible.
let high = source.length;
// Do while low is less
// than equal to high
while (low <= high) {
// Calculate the mid
let mid = Math.floor((low + high) / 2);
// Check if mid is possible
// length for valid substring
if (isValid(mid, source, target, conversionCost, maxCost)) {
// Shift low to mid + 1
low = mid + 1;
} else {
// Otherwise shift high
// to mid - 1
high = mid - 1;
}
}
if (startPos === -1)
console.log("Not possible");
else
console.log(startPos + " " + endPos);
}
// Driver code
// First test case
let source = "adcf", target = "cdef";
// Function Call
let conversionCost = 3, maxCost = 5;
validSubstring(source, target, conversionCost, maxCost);
Time Complexity: O(N* log(N))
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem