DEV Community

King coder
King coder

Posted on • Edited on

🧠 Day 27 of Learning DSA: Solved One LeetCode Problems (Valid Anagram - Easy for Beginners)

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.

Screenshot at 2025-08-07 17-02-33.png

🧩 Approach

To implement this idea:

  1. Check if the lengths of both strings are equal.

    If not, return false right away β€” because anagrams must have the same number of characters.

  2. Convert both strings into arrays of characters, so we can easily remove elements using splice().

  3. 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.
  4. After all loops:

    • If the second string is empty, return true (it's a valid anagram).
    • If not, return false.

⏱ Complexity

Time Complexity: O(nΒ²)

We are using a nested loop:

  • The outer loop runs n times (for each character in string s).
  • The inner loop may also run up to n times (to find the matching character in t).

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;

};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)