Determine if a string has all unique characters - Coding Problem

Write an algorithm to determine if a string has all unique characters.

A string may contain unique or duplicate characters. Return true if it has all unique characters otherwise return false.
For e.g.

  1. qwertyopl
    Output: Is unique present? - true

  2. aweeerty
    Output: Is unique present? - false

Solution

We can create here a boolean array to keep track of chars present in the string.
The boolean flag at index i indicates whether char i is contained in the string. When the first time a char is encountered, its flag is set to true. When next time same char is found, it means chars in the string are not unique and false is returned.

Implementation

Java
import java.util.*;
public class MyJavaClass {
    public static void main(String args[]) 
   {
        Scanner sc = new Scanner(System.in);
        String in_string = sc.nextLine();
        System.out.println("Is unique present? - "+Boolean.toString(isUniqueCharsPresent(in_string)));
    }

    static boolean isUniqueCharsPresent(String input)
    {
        // Considering character set is ASCII. If any char is repeated once, length of string will exceed 128.
        if(input.length() > 128) return false; 
        
        boolean[] chars=new boolean[128];
        for(int i=0; i< input.length(); i++)
        {
            int value= input.charAt(i);
            if(chars[value])
                return false;
            chars[value] = true;    
        }
        return true;
    }
}
//Input: qwertyopl
//Output: Is unique present? - true

// second
// third
fourth