Saturday, October 3, 2015

[1.1] A strign has all unique characters

1.Example

s= "abcd"
s= "aaaa"
s= ""
s= null
s= "aaabbb"

NOTE: you cannot use additional data structures

2. Implementation
For simplicity, assume char set is ASCII (if not, we need to increase the storage size. the rest of logic would be the same).
NOTE: This is a great thing to point out to your interviewer!


//1. Time :O(n), n is the length of the string, Space:O(n), [256]
// NOTE:  assume char set is ASCII 
public static boolean isUniqueChars(String str)
{



      //validate the input
      if (str == null)
          return true;



      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;


}



//2. Time:O(n) , Space:O(1), int checker 32 bit

// reduce our space usage by using bit vector
// NOTE:   int 32 bit but assume only 'a'-'z', we only need 26 bit
// 'a'-> bit 0
// 'z'-> bit 25
public static boolean isUniqueChars(String str){


      int checker = 0;
      for (int i = 0; i < str.length(); i++)
      {
          int val = str.charAt(i) - 'a';
          // NOTE : Test bit
          if ( ( checker & (1<0 ) 
          {  
            return false;
          }
          // NOTE : Set bit
          checker |=  (1<



//3. Time :O(n^2), Space:O(1)

// Two nested for loop
// check every char of the string with every other char of the string  
// for duplicate occurRences



//4. Time :O(n log n) time, Space:O(n), sorting algorithm 

// mergeO(n),heapO(1),quickO(n)
// linearly check the string for neighboring characters that are 
// identical. 
// Careful, though - many sorting algorithms take up extra space

3. Similar Ones

No comments:

Post a Comment