Description:
Given two strings check if those two are permutation of each other. Its expected that input string can contain ASCII characters.
Code:
class Main {
public static boolean isPermutation(String s1, String s2) {
if (s1 == null || s2 == null) {
throw new IllegalArgumentException("Input string cannot be null");
}
if (s1.length() != s2.length()) {
return false;
}
int[] count = new int[256];
for (int i = 0; i < s1.length(); i++) {
int index = s1.charAt(i) - '0';
count[index] += 1;
}
for (int i = 0; i < s2.length(); i++) {
int index = s2.charAt(i) - '0';
count[index] -= 1;
}
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) return false;
}
return true;
}
public static void main(String[] args) {
//System.out.println(isPermutation(null, null) == true);
System.out.println(isPermutation("", "") == true);
System.out.println(isPermutation("a", "") == false);
System.out.println(isPermutation("", "b") == false);
System.out.println(isPermutation("a", "a") == true);
System.out.println(isPermutation("a", "b") == false);
System.out.println(isPermutation("foo", "bar") == false);
System.out.println(isPermutation("eat", "ate") == true);
System.out.println(isPermutation("1010", "1100") == true);
}
}
Questions:
From interview point of view are the test cases sufficient?
am I using Java features correctly?
I think I can merge the two for loops but I did above coding in time bounded fashion, can it raise red flag from interviewer perspective?
PS: According to me I can use map if the input string can contain unicode characters.