Coding Interview Question – Determine if a string has all Unique Characters

Please follow & like us :)

Interview Preparation
Coding Interview

Interview Question: Given a string, determine if the string has all unique characters.

This is Easy Level coding question. We can solve this problem by comparing all the characters from the string and return true or false based on the repeated characters.

To improve performance, we can use map to have characters and we can check in Map if character from given string already exist, if yes we can return false at that point without executing whole for loop gaining performance.

So We need Map with characters and set with boolean false, for loop to scan string and verify character exist in Map or not.

So Here is the working code using Java with Time Complexity O(N).

public static boolean isUniqueChars(String str) {
  boolean[] char_set = new boolean[256];
  for (int i = 0; i < str.length(); i++) {
    int val = str.charAt(i);
    if (char_set[val]) return false;
      char_set[val] = true;
    }
    return true;
  }
	
public static void main(String[] args) {
  String[] words = {"abcde", "test", "code", "java", "testing"};
  for (String word : words) {
    System.out.println(word + ": " + isUniqueChars(word));
  }
}

Here is the solution in Javascript.

We are using Map with key/val pair, where we are adding character(key) from string into map and setting value “1”. We will check if there is already value in map for current character. If yes then we will return false as we found repeated character.

const allUnique = (str) => {
  let charMap = {};
  for (let i = 0; i < str.length; i++) {
    if (charMap[str[i]]) {
      return false;
    }
    else {
      charMap[str[i]] = 1;
    }
  }
  return true;
}
console.log(allUnique('abccsde'));

Be the first to comment

Leave a Reply