Q.no:- Valid Anagram
π§ Intuition
At first, my idea was simple:
If two strings are anagrams, they must contain the same characters with the same frequency, just in a different order.
So the plan was:
- Take each character from the first string.
- Try to find and remove that character from the second string.
- If all characters from the first string are found and removed successfully from the second string, and nothing is left, then it is a valid anagram.
π§© Approach
To implement this idea:
Check if the lengths of both strings are equal.
If not, returnfalse
right away β because anagrams must have the same number of characters.Convert both strings into arrays of characters, so we can easily remove elements using
splice()
.-
Use a nested loop:
- The outer loop goes through each character in the first string.
- The inner loop tries to find that character in the second string.
- If the character is found, remove it from the second string and break the inner loop.
-
After all loops:
- If the second string is empty, return
true
(it's a valid anagram). - If not, return
false
.
- If the second string is empty, return
β± Complexity
Time Complexity: O(nΒ²)
We are using a nested loop:
- The outer loop runs
n
times (for each character in strings
). - The inner loop may also run up to
n
times (to find the matching character int
).
So in the worst case, itβs O(n * n)
= O(nΒ²).
β This is not the most efficient solution, but it works for small inputs and is easy to understand.
Space Complexity: O(1)
(Constant)
Weβre not using any additional data structures that grow with input size.
Only a few variables and the input arrays are used, so space complexity stays constant.
π Notes
- This approach is easy to understand but not optimal.
- For larger strings or performance-sensitive code, a better method would be to:
- Use hash maps to count character frequency, or
- Sort both strings and compare them directly.
Still, this method is a good starting point for beginners learning how to manipulate strings and arrays.
Code
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
s = s.split('')
t = t.split('')
if(s.length !== t.length) return false;
let char = null;
for(let j = 0 ; j < s.length ; j++){
char = s[j]
for(let x = 0 ; x < s.length ; x++ ){
if(char === t[x]){
t.splice(x, 1);
break;
}
}
}
if(t.length > 0){
return false
}
return true;
};
Top comments (0)