Find one extra character in a string - GeeksforGeeks

21 Jul, 2021
Given two strings which are of lengths n and n+1. The second string contains all the character of the first string, but there is one extra character. Your task to find the extra character in the second string.Examples :  
Input : string strA = "abcd";
        string strB = "cbdae";
Output : e
string B contain all the element 
there is a one extra character which is e

Input : string strA = "kxml";
        string strB = "klxml";
Output : l
string B contain all the element 
there is a one extra character which is l
 
Method 1(Brute Force):- Check with two for loop. Time Complexity:- O(n^2) Space Complexity:- O(1). Method 2(Hash Map):- Create an empty hash table and insert all character of second string. Now remove all characters of first string. Remaining character is the extra character.Time Complexity:- O(n) Auxiliary Space:- O(n).  
C++
Java
Python3
C#
Javascript
// CPP program to find extra character in one// string#include <bits/stdc++.h>using namespace std; char findExtraCharcter(string strA, string strB){    // store string values in map    unordered_map<char, int> m1;     // store second string in map with frequency    for (int i = 0; i < strB.length(); i++)        m1[strB[i]]++;     // store first string in map with frequency    for (int i = 0; i < strA.length(); i++)        m1[strA[i]]--;     for (auto h1 = m1.begin(); h1 != m1.end(); h1++) {         // if the frequency is 1 then this        // character is which is added extra        if (h1->second == 1)            return h1->first;    }} int main(){    // given string    string strA = "abcd";    string strB = "cbdad";     // find Extra Character    cout << findExtraCharcter(strA, strB);}
// Java program to find extra character in one// stringclass GFG{ static char findExtraCharcter(char []strA, char[] strB){    // store string values in map    int[] m1 = new int[256];     // store second string in map with frequency    for (int i = 0; i < strB.length; i++)        m1[strB[i]]++;     // store first string in map with frequency    for (int i = 0; i < strA.length; i++)        m1[strA[i]]--;     for (int i=0;i<m1.length;i++)    {         // if the frequency is 1 then this        // character is which is added extra        if (m1[i]== 1)            return (char) i;    }    return Character.MIN_VALUE;} // Driver codepublic static void main(String[] args){    // given string    String strA = "abcd";    String strB = "cbdad";     // find Extra Character    System.out.println(findExtraCharcter(strA.toCharArray(), strB.toCharArray()));    }} // This code is contributed by 29AjayKumar
# Python3 program to find extra character# in one stringdef findExtraCharacter(strA, strB):     # store string values in map    m1 = {}     # store second string in map    # with frequency    for i in strB:        if i in m1:            m1[i] += 1        else:            m1[i] = 1     # store first string in map    # with frequency    for i in strA:        m1[i] -= 1     for h1 in m1:         # if the frequency is 1 then this        # character is which is added extra        if m1[h1] == 1:            return h1 # Driver Codeif __name__ == "__main__":     # given string    strA = 'abcd'    strB = 'cbdad'     # find Extra Character    print(findExtraCharacter(strA, strB)) # This code is contributed by# sanjeev2552
// C# program to find extra character in one// stringusing System;     class GFG{ static char findExtraCharcter(char []strA, char[] strB){    // store string values in map    int[] m1 = new int[256];     // store second string in map with frequency    for (int i = 0; i < strB.Length; i++)        m1[strB[i]]++;     // store first string in map with frequency    for (int i = 0; i < strA.Length; i++)        m1[strA[i]]--;     for (int i = 0; i < m1.Length; i++)    {         // if the frequency is 1 then this        // character is which is added extra        if (m1[i]== 1)            return (char) i;    }    return char.MinValue;} // Driver codepublic static void Main(String[] args){    // given string    String strA = "abcd";    String strB = "cbdad";     // find Extra Character    Console.WriteLine(findExtraCharcter(strA.ToCharArray(),                                        strB.ToCharArray()));    }} // This code is contributed by Rajput-Ji
<script>// JavaScript program to find extra character in one// stringfunction findExtraCharcter(strA,strB){     // store string values in map    let m1 = new Array(256);     for(let i = 0; i < 256; i++)        m1[i] = 0;         // store second string in map with frequency    for (let i = 0; i < strB.length; i++)        m1[strB[i].charCodeAt(0)]++;      // store first string in map with frequency    for (let i = 0; i < strA.length; i++)        m1[strA[i].charCodeAt(0)]--;      for (let i = 0; i < m1.length; i++)    {          // if the frequency is 1 then this        // character is which is added extra        if (m1[i] == 1)            return String.fromCharCode(i);    }    return Number.MIN_VALUE;} // given stringlet strA = "abcd";let strB = "cbdad"; // find Extra Characterdocument.write(findExtraCharcter(strA.split(""), strB.split(""))); // This code is contributed by rag2127</script>
d
 
Method 3(Bits):- traverse first and second string from starting with xor operation at the end you get the character which is extra. Time Complexity:- O(n+n+1) Space Complexity:- O(1). 
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find extra character in one// string#include <iostream>using namespace std; char findExtraCharcter(string strA, string strB){    // result store the result    int res = 0, i;     // traverse string A till end and    // xor with res    for (i = 0; i < strA.length(); i++) {         // xor with res        res ^= strA[i];    }     // traverse string B till end and    // xor with res    for (i = 0; i < strB.length(); i++) {         // xor with res        res ^= strB[i];    }     // print result at the end    return ((char)(res));} int main(){    // given string    string strA = "abcd";    string strB = "cbdad";    cout << findExtraCharcter(strA, strB);    return 0;}
// Java program to find extra// character in one stringimport java.io.*; class GFG {         static char findExtraCharcter(String strA,                                  String strB)    {        // result store the result        int res = 0, i;             // traverse string A till        // end and xor with res        for (i = 0; i < strA.length(); i++)        {            // xor with res            res ^= strA.charAt(i);        }             // traverse string B till end and        // xor with res        for (i = 0; i < strB.length(); i++)        {            // xor with res            res ^= strB.charAt(i);        }             // print result at the end        return ((char)(res));    }         // Driver code    public static void main(String args[])    {        // given string        String strA = "abcd";        String strB = "cbdad";        System.out.println(findExtraCharcter(strA, strB));    }} /*This code is contributed by Nikita Tiwari.*/
# Python 3 program to find# extra character in one string def findExtraCharcter(strA, strB) :         # result store the result    res = 0     # traverse string A till    # end and xor with res    for i in range(0,len(strA)) :                 # xor with res        res =res ^ (ord)(strA[i])             # traverse string B till    # end and xor with res    for i in range(0,len(strB)) :                 # xor with res        res = res ^ (ord)(strB[i])             # print result at the end    return ((chr)(res)); # given stringstrA = "abcd"strB = "cbdad"print(findExtraCharcter(strA, strB)) # This code is contributed by Nikita Tiwari.
// C# program to find extra character// in one stringusing System; class GFG {     static char findExtraCharcter(string strA,                                  string strB)    {        // result store the result        int res = 0, i;             // traverse string A till end and        // xor with res        for (i = 0; i < strA.Length; i++) {                 // xor with res            res ^= strA[i];        }             // traverse string B till end and        // xor with res        for (i = 0; i < strB.Length; i++) {                 // xor with res            res ^= strB[i];        }             // print result at the end        return ((char)(res));    }         // Driver Code    public static void Main()    {        // given string        string strA = "abcd";        string strB = "cbdad";        Console.WriteLine(            findExtraCharcter(strA, strB));    }} // This code is contributed by Manish Shaw// (manishshaw1)
<?php// PHP program to find extra character in// one string function findExtraCharcter($strA, $strB){    // result store the result    $res = 0;     // traverse string A till end and    // xor with res    for ($i = 0; $i < strlen($strA); $i++)    {         // xor with res        $res ^= ord($strA[$i]);    }     // traverse string B till end and    // xor with res    for ($i = 0; $i < strlen($strB); $i++)    {         // xor with res        $res ^= ord($strB[$i]);    }     // print result at the end    return $res;} // Driver code$strA = "abcd";$strB = "cbdad";echo chr(findExtraCharcter($strA, $strB)); // This code is contributed by Manish Shaw// (manishshaw1)?>
<script>// Javascript program to find extra character in// one string function findExtraCharcter(strA, strB){    // result store the result    let res = 0;     // traverse string A till end and    // xor with res    for (let i = 0; i < strA.length; i++)    {         // xor with res        res ^= strA.charCodeAt(i);    }     // traverse string B till end and    // xor with res    for (let i = 0; i < strB.length; i++)    {         // xor with res        res ^= strB.charCodeAt(i);    }     // print result at the end    return res;} // Driver codelet strA = "abcd";let strB = "cbdad";document.write(String.fromCharCode(findExtraCharcter(strA, strB)));   // This code is contributed by gfgking</script>
d
 
Method 4(Character Code):- Add the character codes of both the strings. Minus character codes of smaller string from larger string and convert the result integer into character.Time Complexity:- O(n) Auxiliary Space:- O(1).  
C++
Java
Python3
C#
Javascript
    // C++ program to find extra// character in one string#include<bits/stdc++.h>using namespace std; char findExtraCharacter(string s1, string s2){        string smallStr;    string largeStr;     // Determine string with extra character.    if(s1.size() > s2.size())    {        smallStr = s2;        largeStr = s1;    }    else    {        smallStr = s1;        largeStr = s2;    }     int smallStrCodeTotal = 0;    int largeStrCodeTotal = 0;    int i = 0;     // Add character codes of both the strings    for(; i < smallStr.size(); i++)    {        smallStrCodeTotal += smallStr[i];        largeStrCodeTotal += largeStr[i];    }     // Add last character code of large string.    largeStrCodeTotal += largeStr[i];     // Minus the character code of smaller string from    // the character code of large string.    // The result will be the extra character code.    int intChar = largeStrCodeTotal - smallStrCodeTotal;        return (char)intChar;} // Driver codeint main(){    string s1 = "abcd";    string s2 = "cbdae";         char extraChar = findExtraCharacter(s1, s2);    cout<<"Extra character: " <<(extraChar)<<endl;    return 0;} // This code is contributed by Princi Singh
// Java program to find extra// character in one string public class Test {     private static char findExtraCharacter(String s1, String s2) {               String smallStr;        String largeStr;         // Determine String with extra character.        if(s1.length() > s2.length()) {            smallStr = s2;            largeStr = s1;        } else {            smallStr = s1;            largeStr = s2;        }         int smallStrCodeTotal = 0;        int largeStrCodeTotal = 0;        int i = 0;         // Add character codes of both the strings        for(; i < smallStr.length(); i++) {            smallStrCodeTotal += smallStr.charAt(i);            largeStrCodeTotal += largeStr.charAt(i);        }         // Add last character code of large String.        largeStrCodeTotal += largeStr.charAt(i);         // Minus the character code of smaller string from        // the character code of large string.        // The result will be the extra character code.        int intChar = largeStrCodeTotal - smallStrCodeTotal;               return (char)intChar;    }         public static void main(String[] args) {        String s1 = "abcd";        String s2 = "cbdae";                 char extraChar = findExtraCharacter(s1, s2);        System.out.println("Extra character: " + extraChar);             }}  /*This code is contributed by Amol Bhosale.*/
# Python Program to find extra character in one stringdef findExtraCharacter(s1,s2):    smallStr = ""    largeStr = ""         # Determine string with extra character    if(len(s1) > len(s2)):        smallStr = s2        largeStr = s1    else:        smallStr = s1        largeStr = s2    smallStrCodeTotal = 0    largeStrCodeTotal = 0    i = 0         # Add Character codes of both the strings    while(i < len(smallStr)):        smallStrCodeTotal += ord(smallStr[i])        largeStrCodeTotal += ord(largeStr[i])        i += 1         # Add last character code of large string    largeStrCodeTotal += ord(largeStr[i])         # Minus the character code of smaller string    # from the character code of large string    # The result will be the extra character code    intChar = largeStrCodeTotal - smallStrCodeTotal    return chr(intChar) # Driver codes1 = "abcd"s2 = "cbdae"extraChar = findExtraCharacter(s1, s2)print("Extra Character:", extraChar) # This code is contributed by simranjenny84
// C# program to find extra// character in one stringusing System; class GFG{    private static char findExtraCharacter(String s1,                                           String s2)    {            String smallStr;        String largeStr;         // Determine String with extra character.        if(s1.Length > s2.Length)        {            smallStr = s2;            largeStr = s1;        }        else        {            smallStr = s1;            largeStr = s2;        }         int smallStrCodeTotal = 0;        int largeStrCodeTotal = 0;        int i = 0;         // Add character codes of both the strings        for(; i < smallStr.Length; i++)        {            smallStrCodeTotal += smallStr[i];            largeStrCodeTotal += largeStr[i];        }         // Add last character code of large String.        largeStrCodeTotal += largeStr[i];         // Minus the character code of smaller string        // from the character code of large string.        // The result will be the extra character code.        int intChar = largeStrCodeTotal -                      smallStrCodeTotal;                return (char)intChar;    }         public static void Main(String[] args)    {        String s1 = "abcd";        String s2 = "cbdae";                 char extraChar = findExtraCharacter(s1, s2);        Console.WriteLine("Extra character: " +                                    extraChar);    }} // This code is contributed by PrinciRaj1992
<script>// Javascript program to find extra// character in one stringfunction findExtraCharacter(s1, s2){        let smallStr;        let largeStr;          // Determine String with extra character.        if(s1.length > s2.length)        {            smallStr = s2;            largeStr = s1;        }        else        {            smallStr = s1;            largeStr = s2;        }          let smallStrCodeTotal = 0;        let largeStrCodeTotal = 0;        let i = 0;          // Add character codes of both the strings        for(; i < smallStr.length; i++)        {            smallStrCodeTotal += smallStr[i].charCodeAt(0);            largeStrCodeTotal += largeStr[i].charCodeAt(0);        }          // Add last character code of large String.        largeStrCodeTotal += largeStr[i].charCodeAt(0);          // Minus the character code of smaller string from        // the character code of large string.        // The result will be the extra character code.        let intChar = largeStrCodeTotal - smallStrCodeTotal;                   return String.fromCharCode(intChar);} let s1 = "abcd";let s2 = "cbdae"; let extraChar = findExtraCharacter(s1, s2);document.write("Extra character: " + extraChar); // This code is contributed by avanitrachhadiya2155</script>
Extra character: e
 
YouTubeGeeksforGeeks507K subscribersFind one extra character in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=NrvoNxLThg0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Nikita tiwari
manishshaw1
ashuk1992
samyakjain677
AmolBhosale1
princi singh
29AjayKumar
Rajput-Ji
princiraj1992
nidhi_biet
sanjeev2552
simranjenny84
gfgking
rag2127
avanitrachhadiya2155
Bitwise-XOR
frequency-counting
Bit Magic
Strings
Strings
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
1's and 2's complement of a Binary Number
Divide two integers without using multiplication, division and mod operator
Check whether K-th bit is set or not
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4