Unique String

Check if string made of unique ASCII characters

public class Solution {
  // private final static int NUM_DISTINCT_CHARS = 256; // change as appropriate for unicode

  public boolean allUnique(String word) {
    // int numBoxes = Math.ceil(NUM_DISTINCT_CHARS / 32);
    int[] vec = new int[8]; // UNICODE_CHAR_AMOUNT / 32
    char[] array = word.toCharArray();
    for (char c : array){
      if ((vec[c / 32] >> (c % 32) & 1) != 0)return false; 
      vec[c / 32] |= 1 << (c % 32); //at c / 32 index, set bit to c % 32 with OR EQUAL
    }
    return true;
  }
}

TC: O(N)

SC: O(N)

Last updated

Was this helpful?