coding-interview|October 01, 2020|3 min read

Determine if a string has all unique characters

Determine if a string has all unique characters

Problem

Implement an algorithm to determine if a string has all the characters as unique.

Lets try to understand the problem first. Always clear out the doubts. Clear about the character set, is it ASCII or what. Before moving on to the solution, declare your input points. Example: you are considering only lower case alphabets.

Solution using HashSet

A very simple solution can be to use a HashSet and just check if you found a character or not. If not, then save it. At any point, if you found a character exists in your HashSet, return false.

public boolean isUnique(String str) {
  Set<Character> set = new HashSet<>();
  for (int i=0; i<str.length(); i++) {
    if (set.contains(str.charAt(i))) {
      return false;
    }
    set.add(str.charAt(i));
  }
  return true;
}

Complexity

The complexity of this solution would be O(n)

Solution using Array

Clear out from your interviewer the size of your input set. It can be 256 cgaracters or 26 characters. For this solution, lets assume characters to be 256.

We can then take a boolean array of size 256, where each index represents a character position. On finding a character, set it to true.

public boolean isUnique2(String str) {
  if (str.length() > 256) {
    //means at least one character is coming more than once
    return false;
  }
  boolean chars[] = new boolean[256];
  
  for (int i=0; i<str.length(); i++) {
    if (chars[str.charAt(i)]) {
      return false;
    }
    chars[str.charAt(i)] = true;
  }
  //did not find any duplicate
  return true;
}

Complexity

The complexity is also O(n)

Solution using a Bit Vector

For this solution, lets assume we have all lower-case letters. Hence, we have 26 characters in total.

We can take an Integer variable which takes 4 bytes = 32 bits. Which can help us in representing 26 characters and will be out Bit Vector.

public boolean isUnique_BitVector(String str) {
  if (str.length() >= 26) {
    return false;
  }
  int bit_vector = 0;
  for (int i=0; i<str.length(); i++) {
    int charVal = str.charAt(i) - 'a';
    int shiftedVal = 1 << charVal;
    
    if ((bit_vector & shiftedVal) > 0) {
      return false;
    }
    bit_vector |= shiftedVal;
  }
  return true;
}

In above solution:

  • First we are finding the position of the character by doing val - 'a'. Example, for character: b we will get index=1.
  • Then, we will check if there is 1 bit set already or not.
  • If its not set, we will set the respective bit.

Example

achc

Assumming last 1 byte of bit vector (8 bits)
Initial bit vector: 0 0 0 0 0 0 0 0

For 'a': charVal=0, 1 << 0 = 1
0 0 0 0 0 0 0 0 & 1 = 0
0 0 0 0 0 0 0 0 | 1 = 0 0 0 0 0 0 0 1

For 'c': charVal=2, 1 << 2 = 1 0 0
(0 0 0 0 0 0 0 0) & (1 0 0) = 0
(0 0 0 0 0 0 0 0) | (1 0 0) = (0 0 0 0 0 1 0 0)

For 'h': charVal=7, 1 << 7 = (1 0 0 0 0 0 0)
(0 0 0 0 0 1 0 0) & (1 0 0 0 0 0 0) = 0
(0 0 0 0 0 1 0 0) | (1 0 0 0 0 0 0) = (0 1 0 0 0 1 0 0)

For 'c': charVal=2, 1 << 2 = (1 0 0)
(0 1 0 0 0 1 0 0) & (1 0 0) = 1
Found > 0, return false

Complexity

Its O(n)

Related Posts

Container with Most Water - Leet Code Solution

Container with Most Water - Leet Code Solution

Problem Statement Given n non-negative integers a1, a2, …, an , where each…

Find the maximum sum of any continuous subarray of size K

Find the maximum sum of any continuous subarray of size K

Introduction You are given an array of integers with size N, and a number K…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Crawler Log Folder - minimum number of operations needed to go back to the main folder after the change folder operations.

Crawler Log Folder - minimum number of operations needed to go back to the main folder after the change folder operations.

Problem The Leetcode file system keeps a log each time some user performs a…

Check whether number is palindrome or not - Leet Code Solution

Check whether number is palindrome or not - Leet Code Solution

Problem Statement Determine whether an integer is a palindrome. An integer is a…

Binary Tree Data Structure

Binary Tree Data Structure

A Binary tree is a data structure which has two children nodes attached to it…

Latest Posts

Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Introduction In this post we will see following: How to schedule a job on cron…

How to Git Clone Another Repository from Jenkin Pipeline in Jenkinsfile

How to Git Clone Another Repository from Jenkin Pipeline in Jenkinsfile

Introduction There are some cases, where I need another git repository while…

How to Fetch Multiple Credentials and Expose them in Environment using Jenkinsfile pipeline

How to Fetch Multiple Credentials and Expose them in Environment using Jenkinsfile pipeline

Introduction In this post, we will see how to fetch multiple credentials and…

Jenkins Pipeline - How to run Automation on Different Environment (Dev/Stage/Prod), with Credentials

Jenkins Pipeline - How to run Automation on Different Environment (Dev/Stage/Prod), with Credentials

Introduction I have an automation script, that I want to run on different…

Jenkinsfile - How to Create UI Form Text fields, Drop-down and Run for Different Conditions

Jenkinsfile - How to Create UI Form Text fields, Drop-down and Run for Different Conditions

Introduction I had to write a CICD system for one of our project. I had to…

Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Introduction Java log4j has many ways to initialize and append the desired…