Open In App

Print all Unique Strings present in a given Array

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
3 Likes
Like
Report

Given an array of strings arr[], the task is to print all unique strings that are present in the given array.

Examples:

Input: arr[] = { "geeks", "geek", "ab", "geek" "code", "karega" } 
Output: geeks ab code karega 
Explanation: 
The frequency of the string "geeks" is 1. 
The frequency of the string "geek" is 2. 
The frequency of the string "ab" is 1. 
The frequency of the string "code" is 1. 
The frequency of the string "karega" is 1. 
Therefore, the required output is "geeks ab code karega"

Input: arr[] = { "abcde", "abcd", "abcd", "co" "", "code" } 
Output: abcde co code

Naive Approach: The simplest approach to solve this problem is to traverse the array for every string encountered, check if that string occurs in the remaining array or not. Print those strings which are occurring only once in the array. 
Time Complexity: O(N2 * M), where M is the maximum length of the string 
Auxiliary Space: O(1)

Efficient Approach using STL:

Another approach to print all the unique elements in array is by using unordered_map

Steps involved in this approach are as follows:

  • In first step an unordered_map(freqMap) is declared, which will be used to store the frequency of each string in the array.
  • Then we run a for loop for all the elements of the array. In each iteration, the frequency of the i-th string in the array is incremented in the map.
  • Then we iterate through this unordered_map and print all the strings which is present only one time in the array.

Below is the code for the above approach.

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to Print all Unique Strings 
// present in a given Array
void printUniqueStrings(vector<string> arr) {
    unordered_map<string, int> freqMap;

    // Count the frequency of each string in arr
    for (auto str : arr) {
        ++freqMap[str];
    }

    // Print unique strings in arr
    for (auto p : freqMap) {
        if (p.second == 1) {
            std::cout << p.first << " ";
        }
    }
}

int main() {
    vector<string> arr = {"geeks", "for",
                           "geek", "ab", "geek",
                           "for", "code", "karega"};
    printUniqueStrings(arr);
    return 0;
}

// This code is contributed by Vaibhav
Java Python3 C# JavaScript

Output
karega code ab geeks 

Time Complexity: O(N*M) where N is the number of strings in the array and M is the maximum length of the strings.
Space Complexity: O(N*M)

Efficient Approach: The above approach can be optimized using Trie. The idea is to traverse the array and for every ith string in the array, check if arr[i] is present in the Trie or not. If found to be true, then mark arr[i] as duplicate array element. Otherwise, mark arr[i] as unique array element and insert arr[i] into the trie. Follow the steps below to solve the problem:

  • Initialize an array, say isUniq[], to check if an array element is unique or not.
  • Create a Trie having a root node, say root, to store the characters of each string present in the given array.
  • Traverse the array using variable i and for every ith element, check if arr[i] is present in the Trie or not. IF found to be true, then update isUniq[i] to false.
  • Otherwise, update isUniq[i] to true and insert arr[i] into the Trie.
  • Finally, traverse the isUniq[] array using variable i and for every ith element, check if isUniq[i] is true or not. If found to be true, then print arr[i].

Below is the implementation of the above approach:

C++
// C++ program to implement
// the above approach

#include <bits/stdc++.h>
using namespace std;

// Structure of
// a Trie node
struct TrieNode {

    // Stores index
    // of string
    int idx;

    // Check if a character is
    // present in the string or not
    TrieNode* child[26];

    // Initialize a TrieNode
    TrieNode()
    {
        // Idx = -1: String is not
        // present in TrieNode
        idx = -1;

        // Initialize all child nodes
        // of a TrieNode to NULL
        for (int i = 0; i < 26; i++) {

            // Update child[i]
            child[i] = NULL;
        }
    }
};

// Function to insert a string into Trie
void Insert(TrieNode* root,
            string str, int i)
{
    // Stores length of the string
    int N = str.length();

    // Traverse the string str
    for (int i = 0; i < N; i++) {

        // If str[i] not present in
        // a Trie at current index
        if (!root->child[str[i] - 'a']) {

            // Create a new node of Trie.
            root->child[str[i] - 'a']
                = new TrieNode();
        }

        // Update root
        root = root->child[str[i] - 'a'];
    }

    // Store index of str
    // in the TrieNode
    root->idx = i;
}

// Function to check if string str present
// in the Trie or not
int SearchString(TrieNode* root, string str)
{
    // Stores length of
    // the string
    int N = str.length();

    // Traverse the string
    for (int i = 0; i < N; i++) {

        // If a character not present
        // in Trie at current index
        if (!root->child[str[i] - 'a']) {

            // Return str as
            // unique string
            return -1;
        }

        // Update root
        root
            = root->child[str[i] - 'a'];
    }

    // Return index of str
    return root->idx;
}

// Utility function to find the unique
// string in array of strings
void UtilUniqStr(vector<string>& arr, int N)
{
    // Stores root node of the Trie
    TrieNode* root = new TrieNode();

    // isUniq[i]: Check if i-th string
    // is unique or not
    bool isUniq[N];

    // Initialize isUniq[] to false
    memset(isUniq, false, sizeof(isUniq));

    // Insert arr[0] into the Trie
    Insert(root, arr[0], 0);

    // Mark arr[0] as unique string
    isUniq[0] = true;

    // Traverse the given array
    for (int i = 1; i < N; i++) {

        // Stores previous 1st index
        // of arr[i] in the array
        int idx = SearchString(root,
                               arr[i]);

        // If arr[i] not present
        // in the Trie
        if (idx == -1) {

            // Mark i-th string
            // as unique string
            isUniq[i] = true;

            // Insert arr[i] into Trie
            Insert(root, arr[i], i);
        }

        // If arr[i] already present
        // in the Trie
        else {

            // Mark i-th string as
            // duplicate string in Trie
            isUniq[idx] = false;
        }
    }

    // Traverse the array
    for (int i = 0; i < N; i++) {

        // If i-th string is unique,
        // then print the string
        if (isUniq[i]) {

            cout << arr[i] << " ";
        }
    }
}

// Driver Code
int main()
{

    vector<string> arr = { "geeks", "for",
                           "geek", "ab", "geek",
                           "for", "code", "karega" };

    int N = arr.size();

    UtilUniqStr(arr, N);
    return 0;
}
Java Python3 C# JavaScript

Output
geeks ab code karega 

Time Complexity: O(N * M), where M is the maximum length of the string 
Auxiliary Space: O(N * 26)


Explore