Determine if given strings are anagram.

Input : Two strings // 'dog', 'god' ; 'foo','bar'
Output : Boolean // True ; False

Clarifications :
  • Is the comparison of our string permutation case sensitive? Yes
  • Is whitespace significant? Yes

Approach 1 :

Logic :

  • If both the strings are of different lengths then they can not be permutations of each other. Hence, return false.
  • Sort both the strings.
  • Compare both the sorted strings.

Time Complexity :

  • O(N log N); where N is the length of the string

Solution :


Approach 2 :

If you have to provide solution in linear time O(N); where N is the length of the string or
If you are not allowed to use inbuilt methods of JavaScript then you can use this approach.

Logic :

  • If both the strings are of different lengths then they can not be permutations of each other. Hence, return false.
  • Create character count for string 1.
  • Compare the character count for string 1 with string 2.

Time Complexity :

  • O(N); where N is the length of the string

Solution :

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *