Check whether String is Unique or not in Java (Optimized)

In this tutorial, we will learn how to check whether the string is Unique or not in Java.

Problem Statement: Check whether the given string is unique or not i.e the alphabets in the string should not be repeated or all the alphabets present in the string must be repeated only once in O(N) time complexity.

Input format: 
The first line contains a string s without spaces.

Output format:
print “unique”(without double quotes) if the string is unique otherwise print “not unique”(without double quotes).
Constraints:
<< 10000

Sample Input:
background

Sample Output:
unique

Explanation: In the word “background” all the alphabets are present only once. Hence it is a unique string.

To solve this problem we will maintain a count array of size 26 which stores the count of each alphabet such as,    c[0] contains count of ‘a’, c[1] contains count of ‘b’, c[2] contains count of ‘c’ so on upto c[25] stores count of ‘z’. Firstly we initialize count of all alphabets to zero. If there exists an alphabet we increment respective alphabets count. If the count of each alphabet is 1 then it is a unique string otherwise it is not a unique string.

Source Code:

import java.util.*;
class codespeedy
{
     public static void main(String args[])
     {
         Scanner sc=new Scanner(System.in);
         String str="codespeedy";
         //Convert the given string into character array
         char s[]=str.toCharArray();
         int c[]=new int[26];
         //initialize count of all alphabets to zero;
         Arrays.fill(c,0);
         for(int i=0;i<s.length;i++){
             /*if s[i] is 'a'. Asii of a=65 
               then s[i]-'a' becomes 65-65=0
               therefore c[0] stores count of 'a'*/
              c[s[i]-'a']++;
         }
         int flag=0;
         for(int i=0;i<26;i++)
         {
             if(c[i]>1)
             {
                flag=1;
             }
          }
          if(flag==1)
             System.out.println("Not Unique");
          else
             System.out.println("Unique");
     }
}

 

Not unique

Time Complexity: O(N)

That is how we can check whether the string is unique or not in Java programming language.

Also, read:

 

Leave a Reply