Hi everyone!
Today I solved a string problem where we need to check whether two strings are anagrams of each other.
Problem
Given two strings s and t, return True if t is an anagram of s, else return False.
An anagram means both strings have the same characters with same frequency, just arranged differently.
Example:
Input: s = "anagram", t = "nagaram"
Output: True
My Approach
At first, I thought of sorting both strings and comparing them.
But that would take O(n log n) time.
Then I used a better approach:
Count character frequencies using an array
Logic
- If lengths are different β return False
- Create a count array of size 26 (for lowercase letters)
- Traverse both strings together:
- Increase count for
s - Decrease count for
t
- Increase count for
- At the end, if all values are 0 β anagram
Code (Python)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26
for a, b in zip(s, t):
count[ord(a) - ord('a')] += 1
count[ord(b) - ord('a')] -= 1
return all(c == 0 for c in count)
Time & Space Complexity
- Time: O(n)
- Space: O(1) (fixed size array)
Key Insight
Instead of sorting, we can use frequency counting, which is faster and more efficient.
What I Learned
- Frequency arrays are useful for string problems
- Avoid sorting when linear solutions exist
-
ord()helps map characters to indices
Thanks for reading!
Feel free to share other approaches like hashmap or sorting.
United States
NORTH AMERICA
Related News

Open Harness: The Multi-Panel AI Powerhouse Revolutionizing Developer Workflows
10h ago
Firefox Announces Built-In VPN and Other New Features - and Introduces Its New Mascot
9h ago
50% of Consumers Prefer Brands That Avoid GenAI Content
9h ago
Officer Leaks Location of French Aircraft Carrier With Strava Run
9h ago
CBS News Shutters Radio Service After Nearly a Century
9h ago