Open In App

Print all distinct strings from a given array

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

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++
Java Python3 C# JavaScript

Output: 
Coder Code Geeks For

 

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


Practice Tags :

Explore