Saturday, May 14, 2022

[Solved] How to Check If a Given String has No Duplicate Characters in Java? Unique Example

Hello guys, if you are looking to solve the classic problem "checking if a String has all Unique characters" or not then you have come to the right place. Earlier, I have shown you how to reverse String in place, and in this article, I will show you how to check for unique and duplicate characters in String.  You need to write a program to determine if a given string has all unique characters or not. For example input= "Java" then your function should return false because all characters are not unique, and if the input is "Python" then your program should return true because all characters in Python are unique.

This is also one of the popular string-based coding problems from programming job interviews. For the purpose of this problem, you can assume the given String only contains ASCII printable characters, though you should always verify that with the interviewer.

You can also assume that your solution needs to case-sensitive, I mean, "P" and "p" will be considered two different characters and a string containing a letter in both capital and the small case will be considered unique. You are also free to solve the problem in place of using any additional data structure.

The first solution which comes to mind to solve this problem is by using a Set data structure. A Set is an unordered collection that doesn't allow duplicates. The JDK provides several Set implementations like HashSet, TreeSet, or LinkedHashSet but to solve this problem we can use general-purpose HashSet.

The add() method is used to insert an element into Set and this method returns true if an element is successfully inserted otherwise it returns false i.e. when an element is already present in the Set.

If we go through each character of String and insert them into Set using the add() method then we can find if all characters of String are unique or not. If there are any duplicate characters then add() will return false and we can stop our program from returning that all characters of String are not unique.

Here is the exact algorithm and steps to solve this problem:

1. Create a Set like HashSet
2. Get all characters of String using the chars() method.
3. loop over all characters and insert into Set one at a time
4. If add() method returns false then terminate the program because not all characters are unique.
5. If all characters are successfully inserted then return true because all characters of String is unique

Btw, if you are preparing for coding interviews then I also suggest you refresh your data structure and algorithmic skills as it plays an important role in coding interviews. If you need a resource, I recommend Data Structures and Algorithms: Deep Dive Using Java by Tim Buchalaka and Team on Udemy. In this course, you will find examples in Java that make it easy for Java programmers to understand concepts. 





Java Program to determine if a string has all unique characters 

Here is a Java program to convert the above algorithm into code. You can copy-paste this code and run it in your IDE like Eclipse or NetBeans, or IntelliJ IDEA. 
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/*
 * Java Program to check if all characters of String are unique. 
 */
public class Demo {

  public static void main(String[] args) throws Exception {

    // create Scanner to read user input
    Scanner sc = new Scanner(System.in);

    System.out.println("Please enter a String");
    String input = sc.nextLine();

    if (isUnique(input)) {
      System.out.println("All characters of String are unique");
    } else {
      System.out.println("All characters of String are not unique");
    }

    sc.close();
  }

  /**
   * Returns true if all characters of given String are unique
   * 
   * @param input
   * @return true if no duplicate characters
   */
  public static boolean isUnique(String input) {
    // Create a Set to insert characters
    Set<Character> set = new HashSet<>();

    // get all characters form String
    char[] characters = input.toCharArray();

    for (Character c : characters) {
      if (!set.add(c)) {
        return false;
      }
    }
    return true;
  }
}
Output
Please enter a String
Java
All characters of String are not unique
Please enter a String
Python
All characters of String are unique

From the output, it's clear that our program is working fine. When the user enters "Java" it returns that all characters are not unique because "a" is repeated in "Java", but when the user enters "Python" it prints "all characters are unique" because there is no duplicate character in "Python".

And, if you are serious about improving your coding skill then Grokking the Coding Interview: Patterns for Coding Questions is another resource, which I highly recommend you to checkout. This is an interactive course to learn essential coding patterns which can be used to solve 100+ Leetcode problems like Sliding Window, Merge Interval, Fast and Slow pointers, etc. 

How to Check If Given String has Only Unique Characters in Java? [Solution]


It's of its kind resource and I believe every programmer should join this course. Particularly if you are preparing for a coding interview with tech giants like Amazon, Google, Apple, NetFlix, Flipkart, Uber, and other Unicorn startups. 


That's all about how to check if a given string has all unique characters. As I said, there are multiple ways to do it like you can do it in place, or you can use an additional data structure like a set or hash table to determine if a string has all unique characters. This problem is also asked as to how to check if String contains duplicates or finding the repeated characters from the string. You can use the same technique to solve those problems as well.

Other String based Coding Problem You may like
  • How to print the first non-repeated character from String? (solution)
  • How to check if a string contains only digits?  (solution)
  • How to check if String is Palindrome? (solution)
  • How to Print duplicate characters from String? (solution)
  • How to count the number of vowels and consonants in a String? (solution)
  • How to check if two Strings are anagrams of each other? (solution)
  • How to find duplicate characters in a String? (solution)
  • How to reverse String in Java using Iteration and Recursion? (solution)
  • How to count the occurrence of a given character in String? (solution)
  • How to find all permutations of String? (solution)
  • 10 Algorithms Courses to Crack Programming Job Interviews (courses)
  • How to reverse words in a sentence without using a library method? (solution)
  • How to reverse a String in place in Java? (solution)
  • How to convert a numeric string to an int? (solution)
  • How to return the highest occurred character in a String? (solution)
  • 21 String coding problems for Java developers (questions)

Thanks for reading this article so far. If you like this interview question and my explanation then please share it with your friends and colleagues. If you have any doubt then please drop a comment.

6 comments:

  1. one liner in java 8
    s.chars().distinct().count() == (int)s.length();

    ReplyDelete
  2. Using a HashSet to solve this problem is very poor approach. It works, but the comment posted above provides a far better solution in one line!

    In general, Java streams frequently offer a much more concise and readable solution than Collections for solving many data processing problems.

    ReplyDelete
  3. What does s.chars() means? I've not seen any method like "chars()" in String class?
    And to which class "distinct()" method belong?

    ReplyDelete
    Replies
    1. I think those are new methods added on String class on JDK 8. which gives you a stream of characters. The distinct() and count() method are from java.util.stream.Stream class.

      Delete
  4. what about space and time complexity between using hashset vs stream api

    ReplyDelete
    Replies
    1. Using HashSet given O(1) for access but Stream API is sequential so will give you O(n)

      Delete

Feel free to comment, ask questions if you have any doubt.