Generate a string which differs by only a single character from all given strings
Last Updated :
09 Nov, 2023
Given an array of strings str[] of length N, consisting of strings of the same length, the task is to find the string which only differs by a single character from all the given strings. If no such string can be generated, print -1. In case of multiple possible answers, print any of them.
Example:
Input: str[] = { “abac”, “zdac”, “bdac”}
Output: adac
Explanation:
The string “adac” differs from all the given strings by a single character.
Input: str[] = { “geeks”, “teeds”}
Output: teeks
Approach: Follow the steps below to solve the problem:
- Set the first string as the answer.
- Now, replace the first character of the string to all possible characters and check if it differs by a single character from the other strings or not.
- Repeat this process for all the characters in the first string.
- If any such string of the required type is found from the above step, print the string.
- If no such situation arises where replacing a single character of the first string generates a string of the required type, print -1.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
bool check(string ans, vector<string>& s,
int n, int m)
{
for ( int i = 1; i < n; ++i) {
int count = 0;
for ( int j = 0; j < m; ++j) {
if (ans[j] != s[i][j])
count++;
}
if (count > 1)
return false ;
}
return true ;
}
string findString(vector<string>& s)
{
int n = s.size();
int m = s[0].size();
string ans = s[0];
int flag = 0;
for ( int i = 0; i < m; ++i) {
for ( int j = 0; j < 26; ++j) {
string x = ans;
x[i] = (j + 'a' );
if (check(x, s, n, m)) {
ans = x;
flag = 1;
break ;
}
}
if (flag == 1)
break ;
}
if (flag == 0)
return "-1" ;
else
return ans;
}
int main()
{
vector<string> s = { "geeks" , "teeds" };
cout << findString(s) << endl;
}
|
Java
import java.util.*;
class GFG{
static boolean check(String ans, String[] s,
int n, int m)
{
for ( int i = 1 ; i < n; ++i)
{
int count = 0 ;
for ( int j = 0 ; j < m; ++j)
{
if (ans.charAt(j) != s[i].charAt(j))
count++;
}
if (count > 1 )
return false ;
}
return true ;
}
static String findString(String[] s)
{
int n = s.length;
String ans = s[ 0 ];
int m = ans.length();
int flag = 0 ;
for ( int i = 0 ; i < m; ++i)
{
for ( int j = 0 ; j < 26 ; ++j)
{
String x = ans;
x = x.replace(x.charAt(i), ( char )(j + 'a' ));
if (check(x, s, n, m))
{
ans = x;
flag = 1 ;
break ;
}
}
if (flag == 1 )
break ;
}
if (flag == 0 )
return "-1" ;
else
return ans;
}
public static void main(String []args)
{
String s[] = { "geeks" , "teeds" };
System.out.println(findString(s));
}
}
|
Python3
def check(ans, s, n, m):
for i in range ( 1 , n):
count = 0
for j in range (m):
if (ans[j] ! = s[i][j]):
count + = 1
if (count > 1 ):
return False
return True
def findString(s):
n = len (s)
m = len (s[ 0 ])
ans = s[ 0 ]
flag = 0
for i in range (m):
for j in range ( 26 ):
x = list (ans)
x[i] = chr (j + ord ( 'a' ))
if (check(x, s, n, m)):
ans = x
flag = 1
break
if (flag = = 1 ):
break
if (flag = = 0 ):
return "-1"
else :
return ''.join(ans)
s = [ "geeks" , "teeds" ]
print (findString(s))
|
C#
using System;
class GFG{
static bool check(String ans, String[] s,
int n, int m)
{
for ( int i = 1; i < n; ++i)
{
int count = 0;
for ( int j = 0; j < m; ++j)
{
if (ans[j] != s[i][j])
count++;
}
if (count > 1)
return false ;
}
return true ;
}
static String findString(String[] s)
{
int n = s.Length;
String ans = s[0];
int m = ans.Length;
int flag = 0;
for ( int i = 0; i < m; ++i)
{
for ( int j = 0; j < 26; ++j)
{
String x = ans;
x = x.Replace(x[i], ( char )(j + 'a' ));
if (check(x, s, n, m))
{
ans = x;
flag = 1;
break ;
}
}
if (flag == 1)
break ;
}
if (flag == 0)
return "-1" ;
else
return ans;
}
public static void Main(String []args)
{
String []s = { "geeks" , "teeds" };
Console.WriteLine(findString(s));
}
}
|
Javascript
<script>
function check(ans, s, n, m)
{
for ( var i = 1; i < n; ++i)
{
var count = 0;
for ( var j = 0; j < m; ++j) {
if (ans[j] !== s[i][j]) count++;
}
if (count > 1) return false ;
}
return true ;
}
function findString(s)
{
var n = s.length;
var ans = s[0];
var m = ans.length;
var flag = 0;
for ( var i = 0; i < m; ++i) {
for ( var j = 0; j < 26; ++j) {
var x = ans;
x = x.replace(x[i], String.fromCharCode(j + "a" .charCodeAt(0)));
if (check(x, s, n, m)) {
ans = x;
flag = 1;
break ;
}
}
if (flag === 1) break ;
}
if (flag === 0) return "-1" ;
else return ans;
}
var s = [ "geeks" , "teeds" ];
document.write(findString(s));
</script>
|
Time Complexity: O(N * M2 * 26)
Auxiliary Space: O(M)
Another approach: using a hash table
We can iterate over each string in the given array and for each character in the string, we can replace it with all the possible characters and store the resulting strings in the hash table along with their frequency. If a string occurs n-1 times in the hash table, where n is the number of strings in the array, then it is the required string. If no such string is found, then we can return -1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
string findString(vector<string>& s)
{
int n = s.size();
int m = s[0].size();
unordered_map<string, int > mp;
for ( int i = 0; i < n; ++i) {
for ( int j = 0; j < m; ++j) {
string temp = s[i];
for ( char ch = 'a' ; ch <= 'z' ; ++ch) {
temp[j] = ch;
mp[temp]++;
}
}
}
for ( auto it : mp) {
if (it.second == n && s[0] != it.first) {
int count = 0;
for ( int i = 0; i < m; ++i) {
if (s[0][i] != it.first[i])
count++;
}
if (count == 1)
return it.first;
}
}
return "-1" ;
}
int main()
{
vector<string> s = { "abac" , "zdac" , "bdac" };
cout << findString(s) << endl;
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static String findString(List<String> s) {
int n = s.size();
int m = s.get( 0 ).length();
Map<String, Integer> mp = new HashMap<>();
for ( int i = 0 ; i < n; ++i) {
for ( int j = 0 ; j < m; ++j) {
String temp = s.get(i);
for ( char ch = 'a' ; ch <= 'z' ; ++ch) {
char [] tempArray = temp.toCharArray();
tempArray[j] = ch;
temp = new String(tempArray);
mp.put(temp, mp.getOrDefault(temp, 0 ) + 1 );
}
}
}
for (Map.Entry<String, Integer> entry : mp.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
if (value == n && !s.get( 0 ).equals(key)) {
int count = 0 ;
for ( int i = 0 ; i < m; ++i) {
if (s.get( 0 ).charAt(i) != key.charAt(i))
count++;
}
if (count == 1 )
return key;
}
}
return "-1" ;
}
public static void main(String[] args) {
List<String> s = new ArrayList<>();
s.add( "abac" );
s.add( "zdac" );
s.add( "bdac" );
System.out.println(findString(s));
}
}
|
Python3
def find_string(strings):
n = len (strings)
m = len (strings[ 0 ])
mp = {}
for i in range (n):
for j in range (m):
temp = list (strings[i])
for ch in range ( ord ( 'a' ), ord ( 'z' ) + 1 ):
temp[j] = chr (ch)
modified_string = ''.join(temp)
if modified_string in mp:
mp[modified_string] + = 1
else :
mp[modified_string] = 1
for key, value in mp.items():
if value = = n and strings[ 0 ] ! = key:
count = 0
for i in range (m):
if strings[ 0 ][i] ! = key[i]:
count + = 1
if count = = 1 :
return key
return "-1"
if __name__ = = "__main__" :
strings = [ "abac" , "zdac" , "bdac" ]
result = find_string(strings)
print (result)
|
C#
using System;
using System.Collections.Generic;
class Program {
static string FindString(List< string > s)
{
int n = s.Count;
int m = s[0].Length;
Dictionary< string , int > frequencyMap
= new Dictionary< string , int >();
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
char [] temp = s[i].ToCharArray();
for ( char ch = 'a' ; ch <= 'z' ; ch++) {
temp[j] = ch;
string modifiedString
= new string (temp);
if (frequencyMap.ContainsKey(
modifiedString)) {
frequencyMap[modifiedString]++;
}
else {
frequencyMap[modifiedString] = 1;
}
}
}
}
foreach ( var kvp in frequencyMap)
{
if (kvp.Value == n && !s[0].Equals(kvp.Key)) {
int count = 0;
for ( int i = 0; i < m; i++) {
if (s[0][i] != kvp.Key[i]) {
count++;
}
}
if (count == 1) {
return kvp.Key;
}
}
}
return "-1" ;
}
static void Main()
{
List< string > s
= new List< string >{ "abac" , "zdac" , "bdac" };
Console.WriteLine(FindString(s));
}
}
|
Javascript
function findString(strings) {
const n = strings.length;
const m = strings[0].length;
const freqMap = {};
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
const temp = strings[i].split( '' );
for (let ch = 'a' .charCodeAt(0); ch <= 'z' .charCodeAt(0); ch++) {
temp[j] = String.fromCharCode(ch);
const generatedString = temp.join( '' );
freqMap[generatedString] = (freqMap[generatedString] || 0) + 1;
}
}
}
for (const generatedString in freqMap) {
if (freqMap[generatedString] === n && strings[0] !== generatedString) {
let count = 0;
for (let i = 0; i < m; i++) {
if (strings[0][i] !== generatedString[i]) {
count++;
}
}
if (count === 1) {
return generatedString;
}
}
}
return "-1" ;
}
const inputStrings = [ "abac" , "zdac" , "bdac" ];
console.log(findString(inputStrings));
|
Time Complexity: O(N * M * 26)
Auxiliary Space: O(N * M * 26)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...