DEV Community

Lokeshwaran S
Lokeshwaran S

Posted on

Valid Anagram - CA14

My Thinking and Approach


Introduction

In this problem, I was given two strings and asked to check whether one string is an anagram of the other.

An anagram means both strings contain the same characters with the same frequency but possibly in a different order.


Problem Statement

  • Given two strings s and t

  • Return true if t is an anagram of s

  • Otherwise return false

  • Conditions:

    • Strings contain only lowercase English letters

My Initial Thought

At first, I considered:

  • Sorting both strings
  • Comparing them

If both sorted strings are equal, then they are anagrams.


Key Observation

Instead of sorting:

  • I can count frequency of each character
  • Compare frequencies of both strings

Optimized Approach

I decided to:

  • Use a dictionary to count characters
  • Compare counts

Logic:

  • If lengths are not equal → return false
  • Count characters of first string
  • Decrease count using second string
  • If all counts become zero → valid anagram

My Approach (Step-by-Step)

  1. If length of s and t are not equal → return false
  2. Create a dictionary count
  3. Traverse string s:
  • Increase count of each character

    1. Traverse string t:
  • Decrease count of each character

  • If any count becomes negative → return false

    1. If all counts are zero → return true

Code (Python)

Below is the implementation clearly separated inside a code block:

```python id="t3q4xz"
class Solution:
def isAnagram(self, s, t):
if len(s) != len(t):
return False

    count = {}

    for ch in s:
        count[ch] = count.get(ch, 0) + 1

    for ch in t:
        if ch not in count or count[ch] == 0:
            return False
        count[ch] -= 1

    return True
Enter fullscreen mode Exit fullscreen mode



---

## Example Walkthrough

### Input:



```text id="h8u9dn"
s = "anagram", t = "nagaram"
Enter fullscreen mode Exit fullscreen mode

Steps:

  • Count characters in s
  • Reduce counts using t
  • All counts become zero

Output:

```text id="9pkz0y"
true




---

## Complexity Analysis

| Type             | Complexity |
| ---------------- | ---------- |
| Time Complexity  | O(n)       |
| Space Complexity | O(1)       |

---

## Key Takeaways

* Sorting is simple but not optimal
* Frequency counting is efficient
* Hashmap helps in tracking characters

---

## Conclusion

This problem helped me understand how to efficiently check anagrams using character frequency instead of sorting.

---
Enter fullscreen mode Exit fullscreen mode

Top comments (0)