Determine if a string has all Unique Characters

Given a string, Determine if the string has all unique characters.

Examples :

Input : abcd10jk
Output : true

Input : hutg9mnd!nk9
Output : false

Approach 1 – Brute Force technique: Run 2 loops with variable i and j. Compare str[i] and str[j]. If they become equal at any point, return false.
Time Complexity: O(n2)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate string
// with unique characters using
// brute force technique
#include <bits/stdc++.h>
using namespace std;
  
bool uniqueCharacters(string str)
{
  
    // If at any time we encounter 2
    // same characters, return false
    for (int i = 0; i < str.length() - 1; i++) {
        for (int j = i + 1; j < str.length(); j++) {
            if (str[i] == str[j]) {
                return false;
            }
        }
    }
  
    // If no duplicate characters encountered,
    // return true
    return true;
}
  
// driver code
int main()
{
    string str = "GeeksforGeeks";
  
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate string with
// unique characters using brute force technique
import java.util.*;
  
class GfG {
    boolean uniqueCharacters(String str)
    {
        // If at any time we encounter 2 same
        // characters, return false
        for (int i = 0; i < str.length(); i++)
            for (int j = i + 1; j < str.length(); j++)
                if (str.charAt(i) == str.charAt(j))
                    return false;
  
        // If no duplicate characters encountered,
        // return true
        return true;
    }
  
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
  
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input + " has all unique characters");
        else
            System.out.println("The String " + input + " has duplicate characters");
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to illustrate string
# with unique characters using 
# brute force technique
  
def uniqueCharacters(str):
      
    # If at any time we encounter 2 
    # same characters, return false
    for i in range(len(str)):
        for j in range(i + 1,len(str)): 
            if(str[i] == str[j]):
                return False;
  
    # If no duplicate characters 
    # encountered, return true
    return True;
  
  
# Driver Code
str = "GeeksforGeeks";
  
if(uniqueCharacters(str)):
    print("The String ", str," has all unique characters");
else:
    print("The String ", str, " has duplicate characters");
  
# This code contributed by PrinciRaj1992

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate string with
// unique characters using brute force
// technique
using System;
  
public class GFG {
  
    static bool uniqueCharacters(String str)
    {
  
        // If at any time we encounter 2
        // same characters, return false
        for (int i = 0; i < str.Length; i++)
            for (int j = i + 1; j < str.Length; j++)
                if (str[i] == str[j])
                    return false;
  
        // If no duplicate characters
        // encountered, return true
        return true;
    }
  
    public static void Main()
    {
        string input = "GeeksforGeeks";
  
        if (uniqueCharacters(input) == true)
            Console.WriteLine("The String " + input
                              + " has all unique characters");
        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");
    }
}
  
// This code is contributed by shiv_bhakt.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to illustrate string
// with unique characters using 
// brute force technique
  
function uniqueCharacters($str
{
      
    // If at any time we encounter 2 
    // same characters, return false
    for($i = 0; $i < strlen($str); $i++)
    {
        for($j = $i + 1; $j < strlen($str); $j++) 
        {
            if($str[$i] == $str[$j])
            {
                return false;
            }
        }
    }
      
    // If no duplicate characters 
    // encountered, return true
    return true;
}
  
// Driver Code
$str = "GeeksforGeeks";
  
if(uniqueCharacters($str)) 
{
    echo "The String ", $str,
          " has all unique characters\n";
}
else
{
    echo "The String ", $str
         " has duplicate characters\n";
}
  
// This code is contributed by ajit
?>

chevron_right



Output :

The String GeeksforGeeks has duplicate characters

Note: Please note that the program is case sensitive.

 

Approach 2 – Sorting: Using sorting based on ASCII values of characters
Time Complexity: O(n log n)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate string
// with unique characters using
// brute force technique
#include <bits/stdc++.h>
using namespace std;
  
bool uniqueCharacters(string str)
{
  
    // Using sorting
    sort(str.begin(), str.end());
  
    for (int i = 0; i < str.length(); i++) {
  
        // if at any time, 2 adjacent
        // elements become equal,
        // return false
        if (str[i] == str[i + 1]) {
            return false;
        }
    }
    return true;
}
  
// driver code
int main()
{
  
    string str = "GeeksforGeeks";
  
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
  
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check string with unique
// characters using sorting technique
import java.util.*;
  
class GfG {
    /* Convert the string to character array
       for sorting */
    boolean uniqueCharacters(String str)
    {
        char[] chArray = str.toCharArray();
  
        // Using sorting
        // Arrays.sort() uses binarySort in the background
        // for non-primitives which is of O(nlogn) time complexity
        Arrays.sort(chArray);
  
        for (int i = 0; i < chArray.length - 1; i++) {
            // if the adjacent elements are not
            // equal, move to next element
            if (chArray[i] != chArray[i + 1])
                continue;
  
            // if at any time, 2 adjacent elements
            // become equal, return false
            else
                return false;
        }
        return true;
    }
  
    // Driver code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
  
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to check string with unique
// characters using sorting technique
using System;
  
public class GFG {
  
    /* Convert the string to character array
    for sorting */
    static bool uniqueCharacters(String str)
    {
        char[] chArray = str.ToCharArray();
  
        // Using sorting
        Array.Sort(chArray);
  
        for (int i = 0; i < chArray.Length - 1; i++) {
  
            // if the adjacent elements are not
            // equal, move to next element
            if (chArray[i] != chArray[i + 1])
                continue;
  
            // if at any time, 2 adjacent elements
            // become equal, return false
            else
                return false;
        }
  
        return true;
    }
  
    // Driver code
    public static void Main()
    {
        string input = "GeeksforGeeks";
  
        if (uniqueCharacters(input) == true)
            Console.WriteLine("The String " + input
                              + " has all unique characters");
        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");
    }
}
  
// This code is contributed by shiv_bhakt.

chevron_right



Output:

The String GeeksforGeeks has duplicate characters

 

Approach 3 – Use of Extra Data Structure: This approach assumes ASCII char set(8 bits). The idea is to maintain a boolean array for the characters. The 256 indices represent 256 characters. All the array elements are initially set to false. As we iterate over the string, set true at the index equal to the int value of the character. If at any time, we encounter that the array value is already true, it means the character with that int value is repeated.

Time Complexity: O(n)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <cstring>
#include <iostream>
using namespace std;
  
const int MAX_CHAR = 256;
  
bool uniqueCharacters(string str)
{
  
    // If length is greater than 265,
    // some characters must have been repeated
    if (str.length() > MAX_CHAR)
        return false;
  
    bool chars[MAX_CHAR] = { 0 };
    for (int i = 0; i < str.length(); i++) {
        if (chars[int(str[i])] == true)
            return false;
  
        chars[int(str[i])] = true;
    }
    return true;
}
  
// driver code
int main()
{
    string str = "GeeksforGeeks";
  
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
  
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate String With
// Unique Characters using data structure
import java.util.*;
  
class GfG {
    final static MAX_CHAR = 256;
  
    boolean uniqueCharacters(String str)
    {
        // If length is greater than 256,
        // some characters must have been repeated
        if (str.length() > MAX_CHAR)
            return false;
  
        boolean[] chars = new boolean[MAX_CHAR];
        Arrays.fill(chars, false);
  
        for (int i = 0; i < str.length(); i++) {
            int index = (int)str.charAt(i);
  
            /* If the value is already true, string
               has duplicate characters, return false */
            if (chars[index] == true)
                return false;
  
            chars[index] = true;
        }
  
        /* No duplicates encountered, return true */
        return true;
    }
  
    // Driver code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
  
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate String With
// Unique Characters using data structure
using System;
  
class GfG {
    static int MAX_CHAR = 256;
  
    bool uniqueCharacters(String str)
    {
        // If length is greater than 256,
        // some characters must have been repeated
        if (str.Length > MAX_CHAR)
            return false;
  
        bool[] chars = new bool[MAX_CHAR];
        for (int i = 0; i < MAX_CHAR; i++) {
            chars[i] = false;
        }
        for (int i = 0; i < str.Length; i++) {
            int index = (int)str[i];
  
            /* If the value is already true, string
            has duplicate characters, return false */
            if (chars[index] == true)
                return false;
  
            chars[index] = true;
        }
  
        /* No duplicates encountered, return true */
        return true;
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
  
        if (obj.uniqueCharacters(input))
            Console.WriteLine("The String " + input
                              + " has all unique characters");
        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");
    }
}
  
// This code has been contributed by 29AjayKumar

chevron_right



Output:

The String GeeksforGeeks has duplicate characters

Approach 4 – Without Extra Data Structure: The approach is valid for strings having alphabet as a-z. This approach is little tricky. Instead of maintaining a boolean array, we maintain an integer value called checker(32 bits). As we iterate over the string, we find the int value of the character with respect to ‘a’ with the statement int bitAtIndex = str.charAt(i)-‘a’;
Then the bit at that int value is set to 1 with the statement 1 << bitAtIndex .
Now, if this bit is already set in the checker, the bit AND operation would make checker > 0. Return false in this case.
Else Update checker to make the bit 1 at that index with the statement checker = checker | (1 <<bitAtIndex);

Time Complexity: O(n)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate string
// with unique characters using
// brute force technique
#include <bits/stdc++.h>
using namespace std;
  
bool uniqueCharacters(string str)
{
  
    // Assuming string can have characters
    // a-z, this has 32 bits set to 0
    int checker = 0;
  
    for (int i = 0; i < str.length(); i++) {
  
        int bitAtIndex = str[i] - 'a';
  
        // if that bit is already set in
        // checker, return false
        if ((checker & (1 << bitAtIndex)) > 0) {
            return false;
        }
  
        // otherwise update and continue by
        // setting that bit in the checker
        checker = checker | (1 << bitAtIndex);
    }
  
    // no duplicates encountered, return true
    return true;
}
  
// driver code
int main()
{
  
    string str = "GeeksforGeeks";
  
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate String with unique
// characters without using any data structure
import java.util.*;
  
class GfG {
    boolean uniqueCharacters(String str)
    {
        // Assuming string can have characters a-z
        // this has 32 bits set to 0
        int checker = 0;
  
        for (int i = 0; i < str.length(); i++) {
            int bitAtIndex = str.charAt(i) - 'a';
  
            // if that bit is already set in checker,
            // return false
            if ((checker & (1 << bitAtIndex)) > 0)
                return false;
  
            // otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
  
        // no duplicates encountered, return true
        return true;
    }
  
    // Driver Code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeekforGeeks";
  
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate String
// with unique characters without
// using any data structure
using System;
  
class GFG {
    public virtual bool uniqueCharacters(string str)
    {
        // Assuming string can have
        // characters a-z this has
        // 32 bits set to 0
        int checker = 0;
  
        for (int i = 0; i < str.Length; i++) {
            int bitAtIndex = str[i] - 'a';
  
            // if that bit is already set
            // in checker, return false
            if ((checker & (1 << bitAtIndex)) > 0) {
                return false;
            }
  
            // otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
  
        // no duplicates encountered,
        // return true
        return true;
    }
  
    // Driver Code
    public static void Main(string[] args)
    {
        GFG obj = new GFG();
        string input = "GeekforGeeks";
  
        if (obj.uniqueCharacters(input)) {
            Console.WriteLine("The String " + input + " has all unique characters");
        }
        else {
            Console.WriteLine("The String " + input + " has duplicate characters");
        }
    }
}
  
// This code is contributed by Shrikant13

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to illustrate 
// string with unique characters 
// using brute force technique
function uniqueCharacters($str
{
      
    // Assuming string can have 
    // characters a-z, this has 
    // 32 bits set to 0
    $checker = 0;
      
    for ($i = 0; $i < strlen($str); $i++) 
    {
        $bitAtIndex = $str[$i] - 'a';
          
        // if that bit is already set 
        // in checker, return false
        if (($checker
            (1 << $bitAtIndex)) > 0) 
        {
            return false;
        }
          
    // otherwise update and continue by
    // setting that bit in the checker
    $checker = $checker
               (1 << $bitAtIndex);
    }
      
    // no duplicates encountered,
    // return true
    return true;
}
  
// Driver Code
$str = "GeeksforGeeks";
  
if(uniqueCharacters($str)) 
{
    echo "The String ", $str,
         " has all unique characters\n";
}
else 
{
    echo "The String ", $str
         " has duplicate characters\n";
}
  
// This code is contributed by ajit
?>

chevron_right



Output :

The String GeekforGeeks has duplicate characters

Exercise : Above program is case sensitive, you can try making same program which is case insensitive i.e Geeks and GEeks both give similar output.

Reference:
Cracking the Coding Interview by Gayle

This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


6


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.