|
| 1 | +# Intuition |
| 2 | +<!-- Describe your first thoughts on how to solve this problem. --> |
| 3 | +To be anagram both strings should have same characters with same frequencies. |
| 4 | + |
| 5 | +# Approach |
| 6 | +<!-- Describe your approach to solving the problem. --> |
| 7 | + |
| 8 | +- Created a HashMap |
| 9 | +- - stored the characters of 's' along with its respective frequencies |
| 10 | +- Now checked every character of 't' |
| 11 | +- - if found in hashmap |
| 12 | +- - - decrease the frequency of that character by 1 |
| 13 | +- - else ( it means not in hashmap) |
| 14 | +- - - return false ( as different character present ) |
| 15 | +- If 't' is anagram then all frequencies of character should be zero |
| 16 | +- - to check this ran a 'for' loop |
| 17 | + |
| 18 | +--- |
| 19 | +Have a look at the code , still have any confusion then please let me know in the comments |
| 20 | +Keep Solving.:) |
| 21 | + |
| 22 | +# Complexity |
| 23 | +- Time complexity : $$O(n)$$ |
| 24 | +<!-- Add your time complexity here, e.g. $$O(n)$$ --> |
| 25 | + |
| 26 | +- Space complexity : $$O(n)$$ |
| 27 | +<!-- Add your space complexity here, e.g. $$O(n)$$ --> |
| 28 | + |
| 29 | +# Code |
| 30 | +``` |
| 31 | +class Solution { |
| 32 | + public boolean isAnagram(String s, String t) { |
| 33 | + if( s.length() != t.length()){ |
| 34 | + return false; |
| 35 | + } |
| 36 | + HashMap<Character, Integer> h = new HashMap<>(); |
| 37 | + // filling hashmap |
| 38 | + for( int i = 0; i < s.length(); i++){ |
| 39 | + if( h.containsKey(s.charAt(i))){ |
| 40 | + h.put(s.charAt(i) , h.get(s.charAt(i)) + 1); |
| 41 | + } |
| 42 | + else{ |
| 43 | + h.put(s.charAt(i) , 1); |
| 44 | + } |
| 45 | + } |
| 46 | + /*for ( char name: h.keySet()) { |
| 47 | + int value = h.get(name); |
| 48 | + System.out.println( name + " " + value); |
| 49 | + }*/ |
| 50 | + |
| 51 | + // checking 't' |
| 52 | + for( int i = 0; i < t.length(); i++){ |
| 53 | + if( h.containsKey(t.charAt(i))){ |
| 54 | + h.put(t.charAt(i) , h.get(t.charAt(i)) - 1); |
| 55 | + } |
| 56 | + else{ |
| 57 | + return false; |
| 58 | + } |
| 59 | + } |
| 60 | + /*for ( char name: h.keySet()) { |
| 61 | + int value = h.get(name); |
| 62 | + System.out.println( name + " " + value); |
| 63 | + }*/ |
| 64 | +
|
| 65 | + // ensuring all frequencies are zero |
| 66 | + for( char c : h.keySet()){ |
| 67 | + if( h.get(c) != 0){ |
| 68 | + return false; |
| 69 | + } |
| 70 | + } |
| 71 | + return true; |
| 72 | + } |
| 73 | +} |
| 74 | +``` |
0 commit comments