What is the Big Oh of these two implementations of the same algorithm? -
i writing algorithm return true if string contains no duplicate characters, , false otherwise. have 2 different implementations:
the first uses hashmap:
public static boolean hasuniquecharsfast(string s) { char[] input = s.tochararray(); map<character, character> map = new hashmap<character, character>(); (char c: input) { if (map.get(c) != null) { return false; } else { map.put(c, c); } } return true; }
the second in-place , compares each character every other character:
public static boolean hasuniquechars(string s) { char[] input = s.tochararray(); //compare string (i.e. ignore chars @ same index) (int i=0;i<input.length;i++) { (int j=0;j<input.length;j++) { if (input[i] == input[j] && != j ) { return false; } } } return true; }
is correct big oh of first implementation o(n), , big oh of second implementation o(n^2)?
i guess trade-offs first 1 uses additional storage space, whereas second implementation doesn't use additional storage (i.e. in-place)?
is correct big oh of first implementation o(n), , big oh of second implementation o(n^2)?
yes. hash operations considered have constant cost.
i guess trade-offs first 1 uses additional storage space, whereas second implementation doesn't use additional storage (i.e. in-place)?
yes. should note constant value of first higher. large strings first algorithm crush second.
note code can optimized twice fast.
first algorithm (assuming put
returns previous value, in java):
public static boolean hasuniquecharsfast(string s) { char[] input = s.tochararray(); map<character, character> map = new hashmap<character, character>(); (char c: input) { if (map.put(c, c) != null) { return false; } } return true; }
second algorithm:
public static boolean hasuniquechars(string s) { char[] input = s.tochararray(); //compare string (i.e. ignore chars @ same index) (int i=0;i<input.length;i++) { (int j=i+1;j<input.length;j++) { // changed starting index if (input[i] == input[j]) { // removed == j check return false; } } } return true; }
Comments
Post a Comment