Generate a string which differs by only a single character from all given strings

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
#define ll long long
 
using namespace std;
 
// Function to check if a given string
// differs by a single character from
// all the strings in an array
bool check(string ans, vector<string>& s,
           int n, int m)
{
 
    // Traverse over the srings
    for (int i = 1; i < n; ++i) {
 
        // Stores the count of characters
        // differing from the strings
        int count = 0;
        for (int j = 0; j < m; ++j) {
            if (ans[j] != s[i][j])
                count++;
        }
 
        // If differs by more than one
        // character
        if (count > 1)
            return false;
    }
 
    return true;
}
 
// Function to find the string which only
// differ at one position from the all
// given strings of the array
string findString(vector<string>& s)
{
 
    // Size of the array
    int n = s.size();
 
    // Length of a string
    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;
 
            // Replace i-th character by all
            // possible characters
            x[i] = (j + 'a');
 
            // Check if it differs by a
            // single character from all
            // other strings
            if (check(x, s, n, m)) {
                ans = x;
                flag = 1;
                break;
            }
        }
 
        // If desired string is obtained
        if (flag == 1)
            break;
    }
 
    // Print the answer
    if (flag == 0)
        return "-1";
    else
        return ans;
}
 
// Driver code
int main()
{
 
    vector<string> s = { "geeks", "teeds" };
 
    // Function call
    cout << findString(s) << endl;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
// Function to check if a given string
// differs by a single character from
// all the strings in an array
static boolean check(String ans, String[] s,
                     int n, int m)
{
     
    // Traverse over the srings
    for(int i = 1; i < n; ++i)
    {
         
        // Stores the count of characters
        // differing from the strings
        int count = 0;
        for(int j = 0; j < m; ++j)
        {
            if (ans.charAt(j) != s[i].charAt(j))
                count++;
        }
 
        // If differs by more than one
        // character
        if (count > 1)
            return false;
    }
    return true;
}
 
// Function to find the string which only
// differ at one position from the all
// given strings of the array
static String findString(String[] s)
{
     
    // Size of the array
    int n = s.length;
    String ans = s[0];
     
    // Length of a string
    int m = ans.length();
 
    int flag = 0;
 
    for(int i = 0; i < m; ++i)
    {
        for(int j = 0; j < 26; ++j)
        {
            String x = ans;
 
            // Replace i-th character by all
            // possible characters
            x = x.replace(x.charAt(i), (char)(j + 'a'));
 
            // Check if it differs by a
            // single character from all
            // other strings
            if (check(x, s, n, m))
            {
                ans = x;
                flag = 1;
                break;
            }
        }
 
        // If desired string is obtained
        if (flag == 1)
            break;
    }
 
    // Print the answer
    if (flag == 0)
        return "-1";
    else
        return ans;
}
 
// Driver code
public static void main(String []args)
{
    String s[] = { "geeks", "teeds" };
 
    // Function call
    System.out.println(findString(s));
}
}
 
// This code is contributed by chitranayal

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to check if a given string
# differs by a single character from
# all the strings in an array
def check(ans, s, n, m):
 
    # Traverse over the srings
    for i in range(1, n):
 
        # Stores the count of characters
        # differing from the strings
        count = 0
        for j in range(m):
            if(ans[j] != s[i][j]):
                count += 1
 
        # If differs by more than one
        # character
        if(count > 1):
            return False
 
    return True
 
# Function to find the string which only
# differ at one position from the all
# given strings of the array
def findString(s):
 
    # Size of the array
    n = len(s)
 
    # Length of a string
    m = len(s[0])
 
    ans = s[0]
    flag = 0
 
    for i in range(m):
        for j in range(26):
            x = list(ans)
 
            # Replace i-th character by all
            # possible characters
            x[i] = chr(j + ord('a'))
 
            # Check if it differs by a
            # single character from all
            # other strings
            if(check(x, s, n, m)):
                ans = x
                flag = 1
                break
 
        # If desired string is obtained
        if(flag == 1):
            break
 
    # Print the answer
    if(flag == 0):
        return "-1"
    else:
        return ''.join(ans)
 
# Driver Code
 
# Given array of strings
s = [ "geeks", "teeds" ]
 
# Function call
print(findString(s))
 
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
class GFG{
     
// Function to check if a given string
// differs by a single character from
// all the strings in an array
static bool check(String ans, String[] s,
                  int n, int m)
{
     
    // Traverse over the srings
    for(int i = 1; i < n; ++i)
    {
         
        // Stores the count of characters
        // differing from the strings
        int count = 0;
        for(int j = 0; j < m; ++j)
        {
            if (ans[j] != s[i][j])
                count++;
        }
 
        // If differs by more than one
        // character
        if (count > 1)
            return false;
    }
    return true;
}
 
// Function to find the string which only
// differ at one position from the all
// given strings of the array
static String findString(String[] s)
{
     
    // Size of the array
    int n = s.Length;
    String ans = s[0];
     
    // Length of a string
    int m = ans.Length;
 
    int flag = 0;
 
    for(int i = 0; i < m; ++i)
    {
        for(int j = 0; j < 26; ++j)
        {
            String x = ans;
 
            // Replace i-th character by all
            // possible characters
            x = x.Replace(x[i], (char)(j + 'a'));
 
            // Check if it differs by a
            // single character from all
            // other strings
            if (check(x, s, n, m))
            {
                ans = x;
                flag = 1;
                break;
            }
        }
 
        // If desired string is obtained
        if (flag == 1)
            break;
    }
 
    // Print the answer
    if (flag == 0)
        return "-1";
    else
        return ans;
}
 
// Driver code
public static void Main(String []args)
{
    String []s = { "geeks", "teeds" };
 
    // Function call
    Console.WriteLine(findString(s));
}
}
 
// This code is contributed by Rajput-Ji

chevron_right


Output: 

teeks



 

Time Complexity: O(N * M2 * 26)
Auxiliary Space: O(M)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.