Determine if a string has all Unique Characters

Question :

Determine giving string has all Unique Characters. Without Using additional data structures.

Solution :

  1. Convert String to Char Array 
  2. Sort Char Array
  3. Compare char[i ] == char[i+1] if true then String not has all uniques characters.
import java.util.Arrays;
public class Hello {
    public static void main(String ar[]) {
        // given String
        String str = "Rohit";
        // char array
        char[] charsArray = str.toCharArray();
        //sorting array
        Arrays.sort(charsArray);
        for (int i = 0; i < charsArray.length - 1; i++) {
            if (charsArray[i] == charsArray[i + 1]) {
                System.out.println("Unique character String  : false");
                break;
            } else System.out.println("Unique character String  : false");
            break;
        }
    }
}

Output :

Unique character String : false


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.