Java Program to Check if String Has All Unique Characters
HashSet to track seen characters and returning false if a duplicate is found; for example, iterate each character and add it to the set, returning true if no duplicates appear.Examples
How to Think About It
Algorithm
Code
import java.util.HashSet; public class UniqueCharacters { public static boolean hasAllUniqueChars(String str) { HashSet<Character> chars = new HashSet<>(); for (char c : str.toCharArray()) { if (chars.contains(c)) { return false; } chars.add(c); } return true; } public static void main(String[] args) { String input = "hello"; System.out.println(hasAllUniqueChars(input)); } }
Dry Run
Let's trace the string "hello" through the code
Start with empty set
chars = {}
Check character 'h'
'h' not in chars, add 'h' -> chars = {'h'}
Check character 'e'
'e' not in chars, add 'e' -> chars = {'h', 'e'}
Check character 'l'
'l' not in chars, add 'l' -> chars = {'h', 'e', 'l'}
Check next character 'l'
'l' already in chars, return false
| Character | Set Contents | Duplicate Found |
|---|---|---|
| h | {h} | No |
| e | {h, e} | No |
| l | {h, e, l} | No |
| l | {h, e, l} | Yes |
Why This Works
Step 1: Use a set to track characters
A HashSet stores characters seen so far and allows quick checks if a character appeared before.
Step 2: Check each character once
Looping through the string lets us examine every character to find duplicates.
Step 3: Return false on duplicate
If a character is already in the set, it means the string is not unique, so return false immediately.
Step 4: Return true if no duplicates
If the loop finishes without finding duplicates, return true because all characters are unique.
Alternative Approaches
public static boolean hasAllUniqueChars(String str) { if (str.length() > 128) return false; // ASCII limit boolean[] charSet = new boolean[128]; for (int i = 0; i < str.length(); i++) { int val = str.charAt(i); if (charSet[val]) return false; charSet[val] = true; } return true; }
import java.util.Arrays; public static boolean hasAllUniqueChars(String str) { char[] chars = str.toCharArray(); Arrays.sort(chars); for (int i = 0; i < chars.length - 1; i++) { if (chars[i] == chars[i + 1]) return false; } return true; }
Complexity: O(n) time, O(min(n, k)) space
Time Complexity
The program loops through each character once, so time is O(n), where n is string length.
Space Complexity
The set stores up to n characters, so space is O(min(n, k)) where k is character set size.
Which Approach is Fastest?
Using a boolean array is fastest for ASCII strings due to fixed space and O(n) time; HashSet is flexible but slightly slower; sorting is slower due to O(n log n) time.
| Approach | Time | Space | Best For |
|---|---|---|---|
| HashSet | O(n) | O(min(n,k)) | General strings with any characters |
| Boolean array | O(n) | O(1) | ASCII strings only |
| Sorting | O(n log n) | O(1) | When no extra space allowed |
HashSet to quickly detect duplicates when checking unique characters.