Finding Strings with Unique Characters in an Array

Checking if a string contains only unique characters is a common problem in Java programming and frequently appears in coding interviews. This article explains how to find strings in an array where all characters are unique.

Problem statement:

Write a Java program to find strings where all characters are unique (i.e., no character repeats) in an array. For example:

Explanation:

  • "hello"Not unique (letter l repeats).
  • "world"Unique (all characters are distinct).
  • "abc"Unique (all characters are distinct).
  • "unique"Not unique (letter u and i repeat).
  • "java"Not unique (letter a repeats).
  • "coder"Unique (all characters are distinct).

Approach to Solve the Problem

  1. Iterate through each string in the array.
  2. Check if the string has unique characters:
    • Use a HashSet to track seen characters.
    • If a character appears twice, mark the string as not unique.
  3. Store and return the valid strings.

Java program to find strings with unique characters in an Array

The Java program finds strings in an array that contain only unique characters (no repetitions). This approach efficiently finds unique-character strings using O(N) time per word and O(M * N) for the array, making it a practical solution for moderate input sizes.

package com.javacodepoint.stringarray;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UniqueCharacterStrings {

	// Method to check if a string has all unique characters
	public static boolean hasUniqueCharacters(String str) {
		Set<Character> seenChars = new HashSet<>();
		for (char ch : str.toCharArray()) {
			if (!seenChars.add(ch)) { // If add() returns false, character is duplicate
				return false;
			}
		}
		return true;
	}

	// Method to find all strings with unique characters in an array
	public static List<String> findUniqueCharacterStrings(String[] words) {
		List<String> uniqueStrings = new ArrayList<>();

		for (String word : words) {
			if (hasUniqueCharacters(word)) {
				uniqueStrings.add(word);
			}
		}
		return uniqueStrings;
	}

	public static void main(String[] args) {
		// Example array of strings
		String[] words = { "hello", "world", "abc", "unique", "java", "coder" };

		// Find and print unique character strings
		List<String> uniqueStrings = findUniqueCharacterStrings(words);
		System.out.println("Strings with unique characters: " + uniqueStrings);
	}
}

OUTPUT:

Strings with unique characters: [world, abc, coder]

Alternative Approach: Using a Bit Manipulation (for lowercase letters only)

We can use a bitmask (int flag) to track character occurrences efficiently.

public static boolean hasUniqueCharactersBitwise(String str) {
    int checker = 0;
    for (char ch : str.toCharArray()) {
        int bit = 1 << (ch - 'a'); // Shift bit for character position
        if ((checker & bit) > 0) { // If bit is already set, return false
            return false;
        }
        checker |= bit;
    }
    return true;
}

Conclusion

This article covered a HashSet-based approach to finding strings with all unique characters. We also explored an optimized bitwise solution. Understanding these techniques improves problem-solving skills for Java interviews.

You can learn the Top 20 string array programs for interview preparation (Click here).

Java logical programs list


Java Basic Programs

Java String Programs

Java String Array Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *