Skip to content
Related Articles

Related Articles

Improve Article

Print all distinct strings from a given array

  • Last Updated : 18 Jun, 2021

Given an array of strings arr[] of size N, the task is to print all the distinct strings present in the given array.

 Examples:

Input: arr[] = { “Geeks”, “For”, “Geeks”, “Code”, “Coder” } 
Output: Coder Code Geeks For 
Explanation: Since all the strings in the array are distinct, the required output is Coder Code Geeks For.

Input: arr[] = { “Good”, “God”, “Good”, “God”, “god” } 
Output: god Good God

Naive Approach: The simplest approach to solve this problem is to sort the array based on the lexicographical order of the strings. Traverse the array and check if the current string of the array is equal to the previously traversed string or not. If found to be false, then print the current string. 



Time Complexity: O(N * M * log(N)), where M is the length of the longest string. 
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to use Hashing. Follow the steps below to solve the problem:

  • Initialize a Set, say DistString, to store the distinct strings from the given array.
  • Traverse the array and insert array elements into DistString.
  • Finally, print all strings from DistString.

Below is the implementation of the above approach.

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the distinct strings
// from the given array
void findDisStr(vector<string>& arr, int N)
{
    // Stores distinct strings
    // from the given array
    unordered_set<string> DistString;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If current string not
        // present into the set
        if (!DistString.count(arr[i])) {
 
            // Insert current string
            // into the set
            DistString.insert(arr[i]);
        }
    }
 
    // Traverse the set DistString
    for (auto String : DistString) {
 
        // Print distinct string
        cout << String << " ";
    }
}
 
// Driver Code
int main()
{
    vector<string> arr = { "Geeks", "For", "Geeks",
                           "Code", "Coder" };
 
    // Stores length of the array
    int N = arr.size();
 
    findDisStr(arr, N);
    return 0;
}

Java




// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to find the distinct strings
// from the given array
static void findDisStr(List<String> arr, int N)
{
     
    // Stores distinct strings
    // from the given array
    Set<String> DistString = new HashSet<String>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // If current string not
        // present into the set
        if (!DistString.contains(arr.get(i)))
        {
             
            // Insert current string
            // into the set
            DistString.add(arr.get(i));
        }
    }
 
    // Traverse the set DistString
    for(String string : DistString)
    {
         
        // Print distinct string
        System.out.print(string + " ");
    }
}
 
// Driver code
public static void main(String[] args)
{
    List<String> arr = Arrays.asList(new String[]{
        "Geeks", "For", "Geeks", "Code", "Coder" });
 
    // Stores length of the array
    int N = arr.size();
 
    findDisStr(arr, N);
}
}
 
// This code is contributed by jithin

Python3




# Python3 program to implement
# the above approach
 
# Function to find the distinct
# strings from the given array
def findDisStr(arr, N):
     
    # Stores distinct strings
    # from the given array
    DistString = set()
 
    # Traverse the array
    for i in range(N):
 
        # If current string not
        # present into the set
        if (arr[i] not in DistString):
 
            # Insert current string
            # into the set
            DistString.add(arr[i])
 
    # Traverse the set DistString
    for string in DistString:
         
        # Print distinct string
        print(string, end = " ")
    
# Driver Code
if __name__ == "__main__":
   
    arr = [ "Geeks", "For", "Geeks",
            "Code", "Coder" ]
 
    # Stores length of the array
    N = len(arr)
 
    findDisStr(arr, N)
     
# This code is contributed by chitranayal

C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the distinct strings
// from the given array
static void findDisStr(List<string> arr, int N)
{
     
    // Stores distinct strings
    // from the given array
    HashSet<string> DistString = new HashSet<string>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // If current string not
        // present into the set
        if (!DistString.Contains(arr[i]))
        {
             
            // Insert current string
            // into the set
            DistString.Add(arr[i]);
        }
    }
 
    // Traverse the set DistString
    foreach(string a in DistString)
    
      Console.Write(a +" "); 
    
}
 
// Driver code
public static void Main(String[] args)
{
    List<String> arr = new List<string>(new []{
        "Geeks", "For", "Geeks", "Code", "Coder" });
 
    // Stores length of the array
    int N = arr.Count;
 
    findDisStr(arr, N);
}
}
 
// This code is contributed by jana_sayantan

Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
 
// Function to find the distinct strings
// from the given array
function findDisStr(arr, N) {
    // Stores distinct strings
    // from the given array
    let DistString = new Set();
 
    // Traverse the array
    for (let i = N - 1; i >= 0; i--) {
        // If current string not
        // present into the set
        if (!DistString.has(arr[i])) {
 
            // Insert current string
            // into the set
            DistString.add(arr[i]);
        }
    }
     
 
    for (let String of DistString) {
 
        // Print distinct string
        document.write(String + " ");
    }
}
 
// Driver Code
 
let arr = ["Geeks", "For", "Geeks",
    "Code", "Coder"];
 
// Stores length of the array
let N = arr.length;
 
findDisStr(arr, N);
 
</script>
Output: 
Coder Code Geeks For

 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :