Transform the given String into two same Strings by removing at most one character
Last Updated :
22 Feb, 2023
Given a string S of length N where (N ? 1). The task is to check whether by removing at most one character from the given string it can be divided into two same sub-strings or not return YES or NO for possibilities.
Examples:
Input: N = 5, S = abzab
Output: YES
Explanation: Character 'z' at index 3 can be removed so that the remaining S will be "abab". Which consists of two same sub-strings "ab" and "ab". Therefore the output is YES.
Input: N = 4, S = abcd
Output: NO
Explanation: It can be verified that a given string can't be divided into two sub-strings by removing at most one character from it.
Approach: Follow the below observations to solve the problem:
Concept of approach:
The problem is observation based and can be divided into followings parts:
- If S has length equal to 1:
- In this case it is impossible to make two equal strings.
- If S has even length:
- It should be noted that removing one character from even length will make the S string's length equal to odd, Then we can't divide odd length string S into two strings having the same length. Formally, only even length S can be divided into two strings. Therefore, We can't remove any character from even length String.
- Just divide the string into two halves and compare them using in-built function String. equals(String a, String b) of String class.
- If S has odd length:
- It is possible to make two sub-strings of equal length from odd length. For example, S = "ababd", Then it can be divided into two strings of odd and even lengths as {"ab", "bd"}, {"aba", "abd"} respectively by removing one or zero character.
- Then just check for both parity sub-strings separately, If they differs by at most one character or not.
Follow the below steps to solve the above approach:
- If the input String has a length equal to 1.
- Then it is not possible to make two equal strings.
- If the input string has an even length
- Then divide the input string into two halves and check if they both are the same or not using the in-built String.equals(a, b) function.
- If the input string has an odd length
- Then divide the input string into two odd and two even parts and compare if there is at most one different character, Then it is possible else not possible.
Below is the Implementation of the above approach:
C++
#include <iostream>
#include <string>
using namespace std;
// Function to check if there is at most
// different character in strings given
// as two arguments
bool check(string a, string b)
{
int l = 0;
int k = 0;
int countdiff = 0;
while (l < a.length()) {
if (k < b.length() && a[l] == b[k]) {
l++;
k++;
}
else {
l++;
countdiff++;
}
}
return countdiff <= 1;
}
int main()
{
// Input N
int N = 5;
// Input String
string s = "ababz";
// If length of string is 1
if (s.length() == 1) {
cout << "NO" << endl;
}
// If length of string is even
else if (s.length() % 2 == 0) {
// First half sub-string
string fir = s.substr(0, (s.length() / 2));
// Second half sub-string
string sec = s.substr((s.length() / 2));
// If first and second are equals
// then printing YES
if (fir == sec) {
cout << "YES" << endl;
}
// Else printing NO
else {
cout << "NO" << endl;
}
}
// If length of string is odd
else {
// Four sub-strings as discussed
// in concept of approach section
string fir = s.substr(0, s.length() / 2 + 1);
string sec = s.substr(s.length() / 2 + 1);
string third = s.substr(s.length() / 2);
string fourth = s.substr(0, s.length() / 2);
// Checking using user-defined
// function that sub-strings differs
// by at most one characters or not.
if (check(fir, sec) || check(third, fourth)) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.math.*;
import java.util.*;
public class GFG {
// Function to check if there is at most
// different character in strings given
// as two arguments
public static boolean check(String a, String b)
{
int l = 0;
int k = 0;
int countdiff = 0;
while (l < a.length()) {
if (k < b.length()
&& a.charAt(l) == b.charAt(k)) {
l++;
k++;
}
else {
l++;
countdiff++;
}
}
return countdiff <= 1;
}
// Driver function
public static void main(String args[])
{
// Input N
int N = 5;
// Input String
String s = "ababz";
// If length of string is 1
if (s.length() == 1) {
System.out.println("NO");
}
// If length of string is even
else if (s.length() % 2 == 0) {
// First half sub-string
String fir = s.substring(0, (s.length() / 2));
// Seconf half sub-string
String sec = s.substring((s.length() / 2));
// If first and second are equals
// then printing YES
if (fir.equals(sec)) {
System.out.println("YES");
}
// Else printing NO
else {
System.out.println("NO");
}
}
// If length of string is odd
else {
// Four sub-strings as discussed
// in concept of approach section
String fir = s.substring(0, s.length() / 2 + 1);
String sec = s.substring(s.length() / 2 + 1);
String third = s.substring(s.length() / 2);
String fourth = s.substring(0, s.length() / 2);
// Checking using user-defined
// function that sub-strings differs
// by at most one characters or not.
if (check(fir, sec) || check(third, fourth)) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
}
Python3
def check(a: str, b: str) -> bool:
l = 0
k = 0
countdiff = 0
while l < len(a):
if k < len(b) and a[l] == b[k]:
l += 1
k += 1
else:
l += 1
countdiff += 1
return countdiff <= 1
def main():
# Input N
N = 5
# Input String
s = "ababz"
# If length of string is 1
if len(s) == 1:
print("NO")
# If length of string is even
elif len(s) % 2 == 0:
# First half sub-string
fir = s[0:len(s) // 2]
# Second half sub-string
sec = s[len(s) // 2:]
# If first and second are equals
# then printing YES
if fir == sec:
print("YES")
# Else printing NO
else:
print("NO")
# If length of string is odd
else:
# Four sub-strings as discussed
# in concept of approach section
fir = s[0:len(s) // 2 + 1]
sec = s[len(s) // 2 + 1:]
third = s[len(s) // 2:]
fourth = s[0:len(s) // 2]
# Checking using user-defined
# function that sub-strings differs
# by at most one characters or not.
if check(fir, sec) or check(third, fourth):
print("YES")
else:
print("NO")
if __name__ == "__main__":
main()
# This code is contributed by divya_p123.
C#
// C# code to implement the approach
using System;
using System.Linq;
public class GFG {
// Function to check if there is at most
// different character in strings given
// as two arguments
public static bool Check(string a, string b)
{
int l = 0;
int k = 0;
int countdiff = 0;
while (l < a.Length) {
if (k < b.Length && a[l] == b[k]) {
l++;
k++;
}
else {
l++;
countdiff++;
}
}
return countdiff <= 1;
}
static public void Main()
{
// Code
// Input N
int N = 5;
// Input String
string s = "ababz";
// If length of string is 1
if (s.Length == 1) {
Console.WriteLine("NO");
}
// If length of string is even
else if (s.Length % 2 == 0) {
// First half sub-string
string fir = s.Substring(0, s.Length / 2);
// Second half sub-string
string sec = s.Substring(s.Length / 2);
// If first and second are equals
// then printing YES
if (fir.Equals(sec)) {
Console.WriteLine("YES");
}
// Else printing NO
else {
Console.WriteLine("NO");
}
}
// If length of string is odd
else {
// Four sub-strings as discussed
// in concept of approach section
string fir = s.Substring(0, s.Length / 2 + 1);
string sec = s.Substring(s.Length / 2 + 1);
string third = s.Substring(s.Length / 2);
string fourth = s.Substring(0, s.Length / 2);
// Checking using user-defined
// function that sub-strings differs
// by at most one characters or not.
if (Check(fir, sec) || Check(third, fourth)) {
Console.WriteLine("YES");
}
else {
Console.WriteLine("NO");
}
}
}
}
// This code is contributed by lokesh.
JavaScript
// Javascript code to implement the approach
// Function to check if there is at most
// different character in lets given
// as two arguments
function Check(a, b)
{
let l = 0;
let k = 0;
let countdiff = 0;
while (l < a.length) {
if (k < b.length && a[l] == b[k]) {
l++;
k++;
}
else {
l++;
countdiff++;
}
}
return countdiff <= 1;
}
function Main()
{
// Code
// Input N
let N = 5;
// Input String
let s = "ababz";
// If length of let is 1
if (s.length == 1) {
console.log("NO");
}
// If length of let is even
else if (s.length % 2 == 0) {
// First half sub-let
let fir = s.substring(0, s.Length / 2);
// Second half sub-let
let sec = s.substring(s.Length / 2);
// If first and second are equals
// then printing YES
if (fir.localeCompare(sec)) {
console.log("YES");
}
// Else printing NO
else {
console.log("NO");
}
}
// If length of let is odd
else {
// Four sub-lets as discussed
// in concept of approach section
let fir = s.substring(0, s.Length / 2 + 1);
let sec = s.substring(s.Length / 2 + 1);
let third = s.substring(s.Length / 2);
let fourth = s.substring(0, s.Length / 2);
// Checking using user-defined
// function that sub-lets differs
// by at most one characters or not.
if (Check(fir, sec) || Check(third, fourth)) {
console.log("YES");
}
else {
console.log("NO");
}
}
}
Main()
// This code is contributed by Shubham Singh.
Time Complexity: O(N)
Auxiliary Space: O(1)
Related Articles:
Similar Reads
Transform string str1 into str2 by taking characters from string str3 Given three strings str1, str2 & str3. The task is to find whether string str1 can be transformed to string str2 by taking characters from str3. If yes then print âYESâ, Else print âNOâ.Examples: Input: str1 = "abyzf", str2 = "abgdeyzf", str3 = "poqgode". Output: YES Explanation: Remove 'g' from
9 min read
Transform string A into B by deleting characters from ends and reinserting at any position Given two strings A and B that are anagrams of each other, the task is to convert A to B if possible in minimum number of operations. An operation is defined as removing either the first or the last character in A and inserting it back anywhere in the string. Examples: Input: A = "edacb", B = "abcde
13 min read
Minimum characters to be replaced to remove the given substring Given two strings str1 and str2. The task is to find the minimum number of characters to be replaced by $ in string str1 such that str1 does not contain string str2 as any substring. Examples: Input: str1 = "intellect", str2 = "tell" Output: 1 4th character of string "str1" can be replaced by $ such
7 min read
Minimize the count of characters to be added or removed to make String repetition of same substring Given a string S consisting of N characters, the task is to modify the string S by performing the minimum number of following operations such that the modified string S is the concatenation of its half. Insert any new character at any index in the string.Remove any character from the string S.Replac
15+ min read
Convert given Strings into T by replacing characters in between strings any number of times Given an array, arr[] of N strings and a string T of size M, the task is to check if it is possible to make all the strings in the array arr[] same as the string T by removing any character from one string, say arr[i] and inserting it at any position to another string arr[j] any number of times. Exa
9 min read
Encode given string by replacing substrings with prefix same as itself with * Given string str of size N containing only lowercase English letters. The task is to encrypt the string such that the substrings having same prefix as itself are replaced by a *. Generate the encrypted string. Note: If the string can be encrypted in multiple ways, find the smallest encrypted string.
9 min read
Check if String T can be made Substring of S by replacing given characters Given two strings S and T and a 2D array replace[][], where replace[i] = {oldChar, newChar} represents that the character oldChar of T is replaced with newChar. The task is to find if it is possible to make string T a substring of S by replacing characters according to the replace array. Note: Each
9 min read
Count characters to be shifted from the start or end of a string to obtain another string Given two strings A and B where string A is an anagram of string B. In one operation, remove the first or the last character of the string A and insert at any position in A. The task is to find the minimum number of such operations required to be performed to convert string A into string B. Examples
6 min read
Minimize length of a string by removing suffixes and prefixes of same characters Given a string S of length N consisting only of characters 'a', 'b', and 'c', the task is to minimize the length of the given string by performing the following operations only once: Divide the string into two non-empty substrings and then, append the left substring to the end of the right substring
6 min read
Remove characters from the first string which are present in the second string Given two strings string1 and string2, remove those characters from the first string(string1) which are present in the second string(string2). Both strings are different and contain only lowercase characters.NOTE: The size of the first string is always greater than the size of the second string( |st
15+ min read