Check if a String Has All Unique Characters in Java
A string is said to have all unique characters if no character appears more than once in the string.
This problem is very common in Java interviews and helps test understanding of string traversal, comparison, and logical thinking.
Understanding the Problem
Given a string, we need to:
- Check each character against every other character.
- If any character repeats, the string is NOT unique.
- If no duplicates are found, all characters are unique.
Example 1
Input: abcde
Output: All characters are unique
Example 2
Input: programming
Output: Characters are NOT unique
Logic Explanation
- Use two nested loops to compare characters.
- Fix one character and compare it with remaining characters.
- If a match is found, stop immediately.
- If the loop completes, all characters are unique.
Java Program to Check Unique Characters
import java.util.Scanner;
public class UniqueCharacters {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
boolean isUnique = true;
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
isUnique = false;
break;
}
}
if (!isUnique) {
break;
}
}
if (isUnique) {
System.out.println("All characters are unique");
} else {
System.out.println("Characters are NOT unique");
}
}
}
Sample Output
Enter a string: abcde
All characters are unique
Enter a string: programming
Characters are NOT unique
Important Notes
- Comparison is case-sensitive.
- Time complexity is O(n²).
- No extra data structures are used.
Practice Challenges
- Check unique characters ignoring case sensitivity.
- Use a frequency array to optimize the program.
- Check unique characters using HashSet.
This problem strengthens nested loop logic and builds a strong foundation for more advanced string manipulation techniques.