Array ( [0] => [1] => questions [2] => Basic [3] => Anagrams ) Strings | Anagrams | THE INQUISITIVE





Anagrams

LEVEL:Beginner

Description

Given two Strings. You have to find the given two strings are anagrams or not(Anagram means the characters which are present in 1st string also contains the same characters in 2nd string).

Input Format

First line contains a string. Next line also contains a string.

Output Format

Print Yes if the given strings are anagrams else No.


Example 1:

Input
abcde
edcba
Output
Yes
Example 2:

Input
abbcd
dbbca
Output
Yes
Example 3:

Input
asdfghjkl
lkjhggasd
Output
No

oops

Login to see Discussion




Approach

Approach 1: Using Sorting

Step-i) Calculate the length of both the strings
Step-ii) If string are of different length return "No" as anagrams are of same length
Step-iii) Convert String to Character Array
Step-iv) Sort both character arrays
Step-v) Check both arrays are equal or not
Step-vi) If equal return "Yes" else "No"

Time Complexity: O(nlogn)
Space Complexity: O(n) as we are creating a copy of string in array
In general it is O(1)

Approach 2: Using a single array

Step-i) compare length of two strings
Step-ii) if they are not equal return No
Step-iii) Create a array of size 256 ( as total no of characters are 256 )
Step-iv) Initialize them with zero
Step-v) Increment the value of array at index which is equal to ascii value of character of first string
Step-vi) Decrement the value of array at index which is equal to ascii value of character of second string
Step-vii) Continue step v and vi till you traverse both the strings
Step-viii) Check for any non zero numbers in the array
Step-ix) If there are any non zero numbers return "No" else return "Yes"

Time Complexity: O(n)
Space Complexity: O(1)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution