Find one extra character in a string
Last Updated :
11 Jul, 2025
Given two strings which are of lengths n and n+1. The second string contains all the characters of the first string, but there is one extra character. Your task is 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 a loop.
- Take two input strings s1 and s2 as inputs.
- Find the length of both strings using the length() function.
- For each character c in s1, iterate over all characters d in s2 until you find a mismatch. If a mismatch is found, break out of the inner loop and continue with the next character in s1. If all characters in s2 match the character c, then c is the extra character and we can return it.
- If we reach the end of s1 and have not found an extra character, then the extra character must be the last character in s2.
- Return the extra character.
C++
#include <iostream>
#include <string>
using namespace std;
char findExtraChar(string s1, string s2)
{
// input length of strings
int n1 = s1.length();
int n2 = s2.length();
int i, j;
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
if (s1[i] == s2[j]) {
break;
}
}
if (j == n2) {
return s1[i];
}
}
return s2[n2 - 1];
}
int main()
{
string s1 = "abcd";
string s2 = "cbdad";
cout << findExtraChar(s1, s2) << endl;
return 0;
}
C#
using System;
class Program {
static char FindExtraChar(string s1, string s2)
{
// get length of strings
int n1 = s1.Length;
int n2 = s2.Length;
int i, j;
// iterate through the first string
for (i = 0; i < n1; i++) {
// iterate through the second string
for (j = 0; j < n2; j++) {
// if the current character of the first
// string matches the current character of
// the second string, break out of the loop
// and move on to the next character in the
// first string
if (s1[i] == s2[j]) {
break;
}
}
// if the loop finished without finding a match,
// return the current character of the first
// string
if (j == n2) {
return s1[i];
}
}
// if we get to this point, it means that the extra
// character is at the end of the second string, so
// return it
return s2[n2 - 1];
}
static void Main(string[] args)
{
string s1 = "abcd";
string s2 = "cbdad";
Console.WriteLine(FindExtraChar(s1, s2));
}
}
// This code is contributed by sarojmcy2e
Java
import java.util.*;
public class Main {
static char findExtraChar(String s1, String s2)
{
// input length of strings
int n1 = s1.length();
int n2 = s2.length();
int i, j;
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
if (s1.charAt(i) == s2.charAt(j)) {
break;
}
}
if (j == n2) {
return s1.charAt(i);
}
}
return s2.charAt(n2 - 1);
}
public static void main(String[] args)
{
String s1 = "abcd";
String s2 = "cbdad";
System.out.println(findExtraChar(s1, s2));
}
}
// This code is contributed by sarojmcy2e
Python3
def FindExtraChar(s1, s2):
# get length of strings
n1 = len(s1)
n2 = len(s2)
# iterate through the first string
for i in range(n1):
# iterate through the second string
for j in range(n2):
# if the current character of the first
# string matches the current character of
# the second string, break out of the loop
# and move on to the next character in the
# first string
if s1[i] == s2[j]:
break
# if the loop finished without finding a match,
# return the current character of the first
# string
if j == n2 - 1:
return s1[i]
# if we get to this point, it means that the extra
# character is at the end of the second string, so
# return it
return s2[n2 - 1]
s1 = "abcd"
s2 = "cbdad"
print(FindExtraChar(s1, s2))
JavaScript
function FindExtraChar(s1, s2) {
// get length of strings
let n1 = s1.length;
let n2 = s2.length;
let i, j;
// iterate through the first string
for (i = 0; i < n1; i++) {
// iterate through the second string
for (j = 0; j < n2; j++) {
// if the current character of the first
// string matches the current character of
// the second string, break out of the loop
// and move on to the next character in the
// first string
if (s1[i] == s2[j]) {
break;
}
}
// if the loop finished without finding a match,
// return the current character of the first
// string
if (j == n2) {
return s1[i];
}
}
// if we get to this point, it means that the extra
// character is at the end of the second string, so
// return it
return s2[n2 - 1];
}
let s1 = "abcd";
let s2 = "cbdad";
console.log(FindExtraChar(s1, s2));
- Time Complexity:- O(n^2)
- Space Complexity:- O(1)
Method 2: Using Hash Map
Create an empty hash table and insert all character of the second string. Now remove all characters of the first string. The remaining character is the extra character.
Implementation:
C++
// 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
// Java program to find extra character in one
// string
import java.io.*;
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 Character.MIN_VALUE;
}
// Driver code
public 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
# Python3 program to find extra character
# in one string
def 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 Code
if __name__ == "__main__":
# given string
strA = 'abcd'
strB = 'cbdad'
# find Extra Character
print(findExtraCharacter(strA, strB))
# This code is contributed by
# sanjeev2552
C#
// C# program to find extra character in one
// string
using 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 code
public 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
JavaScript
<script>
// JavaScript program to find extra character in one
// string
function 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 string
let strA = "abcd";
let strB = "cbdad";
// find Extra Character
document.write(findExtraCharcter(strA.split(""), strB.split("")));
// This code is contributed by rag2127
</script>
- Time Complexity:- O(n)
- Auxiliary Space:- O(n).
Method 3(Bits):- traverse first and second string from starting with the xor operation at the end you get the character which is extra.
C++
// 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
// Java program to find extra
// character in one string
import 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
# 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 string
strA = "abcd"
strB = "cbdad"
print(findExtraCharcter(strA, strB))
# This code is contributed by Nikita Tiwari.
C#
// C# program to find extra character
// in one string
using 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
// 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)
?>
JavaScript
<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 code
let strA = "abcd";
let strB = "cbdad";
document.write(String.fromCharCode(findExtraCharcter(strA, strB)));
// This code is contributed by gfgking
</script>
- Time Complexity:- O(n+n+1)
- Space Complexity:- O(1).
Method 4(Character Code):
Add the character codes of both strings. Minus character codes of smaller strings from larger string and convert the resulting integer into a character.
Implementation:
C++
// 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 code
int 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
// Java program to find extra
// character in one string
import java.io.*;
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.*/
Python3
# Python Program to find extra character in one string
def 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 code
s1 = "abcd"
s2 = "cbdae"
extraChar = findExtraCharacter(s1, s2)
print("Extra Character:", extraChar)
# This code is contributed by simranjenny84
C#
// C# program to find extra
// character in one string
using 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
JavaScript
<script>
// Javascript program to find extra
// character in one string
function 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>
Output: Extra character: e
- Time Complexity:- O(n)
- Auxiliary Space:- O(1)
Find one extra character in a string | Data Structures and Algorithms
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