Generate a string which differs by only a single character from all given strings | C ++ 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 ; Traverse over the strings ; Stores the count of characters differing from the strings ; If differs by more than one character ; Function to find the string which only differ at one position from the all given strings of the array ; Size of the array ; Length of a string ; Replace i - th character by all possible characters ; Check if it differs by a single character from all other strings ; If desired string is obtained ; Print the answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE #define ll  long long NEW_LINE 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 ; }