0
0
JavaProgramBeginner · 2 min read

Java Program to Check if String Has All Unique Characters

You can check if a string has all unique characters in Java by using a 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

Inputhello
Outputfalse
Inputworld
Outputtrue
Input
Outputtrue
🧠

How to Think About It

To check if all characters in a string are unique, think of going through each character one by one and remembering which ones you have seen. If you see a character again, it means the string does not have all unique characters. If you finish checking all characters without repeats, then all are unique.
📐

Algorithm

1
Get the input string.
2
Create an empty set to store characters.
3
For each character in the string:
4
Check if the character is already in the set.
5
If yes, return false because it's a duplicate.
6
If no, add the character to the set.
7
After checking all characters, return true.
💻

Code

java
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));
    }
}
Output
false
🔍

Dry Run

Let's trace the string "hello" through the code

1

Start with empty set

chars = {}

2

Check character 'h'

'h' not in chars, add 'h' -> chars = {'h'}

3

Check character 'e'

'e' not in chars, add 'e' -> chars = {'h', 'e'}

4

Check character 'l'

'l' not in chars, add 'l' -> chars = {'h', 'e', 'l'}

5

Check next character 'l'

'l' already in chars, return false

CharacterSet ContentsDuplicate 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

Using boolean array for ASCII characters
java
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;
}
Faster and uses fixed space for ASCII but only works for standard ASCII characters.
Sorting the string and checking neighbors
java
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;
}
No extra space needed but slower due to sorting (O(n log n)).

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.

ApproachTimeSpaceBest For
HashSetO(n)O(min(n,k))General strings with any characters
Boolean arrayO(n)O(1)ASCII strings only
SortingO(n log n)O(1)When no extra space allowed
💡
Use a HashSet to quickly detect duplicates when checking unique characters.
⚠️
Forgetting to check for duplicates before adding characters to the set causes incorrect results.