In this article, we are going to find one extra character in given two strings.
Problem:-
we have two strings s1 and s2 of length n and n+1. we need to find that one extra character in string s2 that is not present in string s1.
Java code to find one extra character in given strings:-
package gangforcode;
import java.util.Arrays;
public class FindExtraChar {
static char search1Extra(String s1, String s2) {
char[]a1=s1.toCharArray();
Arrays.sort(a1);
char[]a2=s2.toCharArray();
Arrays.sort(a2);
int n=s1.length();
for(int i=0;i<n;i++) {
if(a1[i]!=a2[i]) {
return a2[i];
}
}
return a2[n];
}
public static void main(String[] args) {
String s1="abcd";
String s2="abcde";
System.out.println("Extra Character is "+search1Extra(s1,s2));
}
}
Output:-
same logic can be used to find one extra character in given string by using other programing languages like C, C++, Python, etc.