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++
// 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 strings
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;
}
Java
// 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 strings
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
Python3
# 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 strings
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
C#
// 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 strings
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
JavaScript
<script>
// JavaScript 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
function check(ans, s, n, m)
{
// Traverse over the strings
for (var i = 1; i < n; ++i)
{
// Stores the count of characters
// differing from the strings
var count = 0;
for (var 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
function findString(s)
{
// Size of the array
var n = s.length;
var ans = s[0];
// Length of a string
var m = ans.length;
var flag = 0;
for (var i = 0; i < m; ++i) {
for (var j = 0; j < 26; ++j) {
var x = ans;
// Replace i-th character by all
// possible characters
x = x.replace(x[i], String.fromCharCode(j + "a".charCodeAt(0)));
// 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
var s = ["geeks", "teeds"];
// Function call
document.write(findString(s));
// This code is contributed by rdtank.
</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;
// 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();
// Create an unordered map to store the frequency of each generated string
unordered_map<string, int> mp;
// Generate all possible strings that can be formed by changing exactly one character in each input string
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]++;
}
}
}
// Traverse over the map and find the string that differs from all input strings at exactly one position
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;
}
}
// If no such string is found, return "-1"
return "-1";
}
// Driver code
int main()
{
// Input vector of strings
vector<string> s = {"abac", "zdac", "bdac"};
// Function call
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 {
// Function to find the string which only differs at one position from all given strings in the array
public static String findString(List<String> s) {
// Size of the array
int n = s.size();
// Length of a string
int m = s.get(0).length();
// Create a HashMap to store the frequency of each generated string
Map<String, Integer> mp = new HashMap<>();
// Generate all possible strings that can be formed by changing exactly one character in each input string
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);
}
}
}
// Traverse the map and find the string that differs from all input strings at exactly one position
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;
}
}
// If no such string is found, return "-1"
return "-1";
}
// Driver code
public static void main(String[] args) {
// Input list of strings
List<String> s = new ArrayList<>();
s.add("abac");
s.add("zdac");
s.add("bdac");
// Function call
System.out.println(findString(s));
}
}
// This code is contributed by rambabuguphka
Python3
# Function to find the string which only differs at one position from all given strings in the array
def find_string(strings):
# Number of strings in the input array
n = len(strings)
# Length of a string (assuming all strings have the same length)
m = len(strings[0])
# Create a dictionary to store the frequency of each generated string
mp = {}
# Generate all possible strings that can be formed by changing exactly one character in each input string
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
# Traverse the dictionary and find the string that differs from all input strings at exactly one position
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
# If no such string is found, return "-1"
return "-1"
# Driver code
if __name__ == "__main__":
# Input list of strings
strings = ["abac", "zdac", "bdac"]
# Function call
result = find_string(strings)
print(result)
C#
using System;
using System.Collections.Generic;
class Program {
// Function to find the string which differs at one
// position from all given strings
static string FindString(List<string> s)
{
// Size of the array
int n = s.Count;
// Length of a string
int m = s[0].Length;
// Create a dictionary to store the frequency of
// each generated string
Dictionary<string, int> frequencyMap
= new Dictionary<string, int>();
// Generate all possible strings that can be formed
// by changing exactly one character in each input
// string
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;
}
}
}
}
// Traverse the dictionary and find the string that
// differs from all input strings at exactly one
// position
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;
}
}
}
// If no such string is found, return "-1"
return "-1";
}
// Driver code
static void Main()
{
// Input list of strings
List<string> s
= new List<string>{ "abac", "zdac", "bdac" };
// Function call
Console.WriteLine(FindString(s));
}
}
JavaScript
// Function to find the string which only differs at one position from all given strings in the array
function findString(strings) {
// Get the size of the array
const n = strings.length;
// Get the length of a string
const m = strings[0].length;
// Create an object to store the frequency of each generated string
const freqMap = {};
// Generate all possible strings that can be formed by changing exactly one character in each input string
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;
}
}
}
// Traverse over the object and find the string that differs from all input strings at exactly one position
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;
}
}
}
// If no such string is found, return "-1"
return "-1";
}
// Driver code
const inputStrings = ["abac", "zdac", "bdac"];
// Function call
console.log(findString(inputStrings));
Time Complexity: O(N * M * 26)
Auxiliary Space: O(N * M * 26)
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