Determine if all characters are unique in string: Without using Bitwise operator

I am implementing the said question on "Cracking the Coding interview" using HashSet. Please have a look and suggest how I can improve the efficiency of the following code considering that I am only taking either all lower case or upper case characters.

static void detrUniqChar(String str)
{
int flag = 0; //Flag declared here
Set<Character> hashSet = new HashSet<Character>();

for(char c : str.toCharArray())
{
if(c != ' ')
{
{
System.out.println("Not unique " + c  );
flag = 0;
break;
}
else {
flag = 1;
}
}
}
if(flag ==1 )System.out.println("Unique characters");
}


Does the space and time efficiency of this code equal to bitwise operation as per the solution provided by the book. As in solution worse case will be when the common elements are at first and last position of the string.

The code given in "Cracking the coding interview" is as follows:

public static boolean isUniqueChars(String str) {
if (str.length() > 256) {
return false;
}
int checker = 0;
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i) - 'a';
if ((checker & (1 << val)) > 0) return false;
checker |= (1 << val);
}
return true;
}


The time complexity of both solutions is linear, proportional to the length of the input.

The space complexity of the solution in the book is constant, it uses a single integer regardless of the length of the input.

The space complexity of your solution is linear, it uses extra storage proportional to the size of the input. This is largely due to the str.toCharArray() call, which will result in an array the same size as the length of the input.

You could remedy that, by changing to a counting loop and using .charAt to access the characters. With that simple change, your space complexity becomes constant too, due to the finite size of the alphabet. However, you will still use more space than the book's solution, due to the set.

Your solution has several pretty grave mistakes:

• printing instead of functions returning values
• using an int with values 0 and 1 instead of a proper boolean
• using a flag variable, when it's not necessary at all
• strange, non-standard formatting
• Thank you for the advice. Yes it's just a first iteration of my solution so I just wrote whatever came to my mind. – Himanshu Verma Dec 12 '15 at 22:48
• You will get more out of this site by writing the very best code you can do. – Stop ongoing harm to Monica Dec 12 '15 at 22:50
• Ok. I will try to implement it from next time. – Himanshu Verma Dec 12 '15 at 22:51