| 49 | // 2. Sorting approach |
| 50 | // Time Complexity: O(nlogn) | Space Complexity: O(n) |
| 51 | public boolean isAnagramUsingSorting(String s, String t) { |
| 52 | |
| 53 | // length check |
| 54 | if (s.length() != t.length()){ |
| 55 | return false; |
| 56 | } |
| 57 | else if(s.isEmpty()){ // empty string check |
| 58 | return true; |
| 59 | } |
| 60 | |
| 61 | char [] ch1 = s.toCharArray(); |
| 62 | char [] ch2 = t.toCharArray(); |
| 63 | |
| 64 | // sort both arrays |
| 65 | Arrays.sort(ch1); |
| 66 | Arrays.sort(ch2); |
| 67 | |
| 68 | return Arrays.equals(ch1, ch2); // compare each character at same position or index |
| 69 | } |
| 70 | |
| 71 | // 3. Efficient approach using hashing |
| 72 | // Time: O(n) | Space: O(1) [because the table's size stays constant no matter how large n is] |