~/coding-interview/algorithm-determine-string-has-unique-characters.md

Determine if a string has all unique characters

3 min readOctober 01, 2020by Gorav Singal#cracking-the-coding-interview#coding-problems#algorithm
// TL;DR

Use a boolean array of size 128 (ASCII) as a lookup — mark each character as seen. If you see one twice, return false. O(n) time, O(1) space since the array is fixed-size.

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)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

How to calculate First Common Ancestor of two Nodes in Binary Tree

How to calculate First Common Ancestor of two Nodes in Binary Tree

First try to understand question. Its a binary tree, not a binary search tree…

How to calculate angle between hour and minute hand, given a time

How to calculate angle between hour and minute hand, given a time

This problem is a simple mathematical calculation. Lets start deriving some…

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…