C++ Program to check if a string has been seen before

C++Server Side ProgrammingProgramming

Suppose, we have n number of strings given to us in an array 'stringArr'. We iterate through the string elements one by one and find out if a string has appeared before in the array. If such occurs, we print 'Seen Before!' or otherwise, we print 'Didn't see before!'

Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the data type for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.



So, if the input of our problem is like n = 6, s = {"apple", "dog", "cat", "mouse", "apple", "cat"}, then the output will be

Didn't see before!
Didn't see before!
Didn't see before!
Didn't see before!
Seen Before.
Seen Before.


To solve this, we will follow these steps −

Define one set s
for initialize i := 0, when i < n, update (increase i by 1), do:
   if stringArr[i] is present in s, then:
      print("Seen Before.")
      print("Didn't see before!")
      insert stringArr[i] into s


Let us see the following implementation to get better understanding −

using namespace std;
void solve(int n, string stringArr[]) {
   set<string> s;
   for(int i = 0; i < n; i++) {
         cout << "Seen Before." << endl;
         cout<< "Didn't see before!" <<endl;
int main() {
   int n = 6;
   string s[] = {"apple", "dog", "cat", "mouse", "apple", "cat"};
   solve(n, s);
   return 0;


6, {"apple", "dog", "cat", "mouse", "apple", "cat"}


Didn't see before!
Didn't see before!
Didn't see before!
Didn't see before!
Seen Before.
Seen Before.
Updated on 07-Apr-2022 08:50:15