This article will highlight two approaches to this problem
Question
Leetcode link -> https://leetcode.com/problems/valid-anagram/description/
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
typically using all the original letters exactly once.
Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Constraints: 1 <= s.length, t.length <= 5 * 104 s and t consist of lowercase English letters. Two approaches
- For both approaches if the length of both strings is not equal return
False
1. Using Counters
- Create two counters for each string
- loop through each string counting the number of occurrences for each character
- Compare the two counters and return the boolean output
Complexity
Time
π(π)
- loop the two string (s and t) = π(π) + π(π)
- insertion into dict counters = π(1) + π(1)
- compare dicts = π(1)
2π(π) + 3π(1) = π(π)
Space
π(1)
- 2 counters = π(1) + π(1)
2π(1)
Code
class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False s_counter = {} t_counter = {} for char in s: if char in s_counter: s_counter[char] += 1 else: s_counter[char] = 1 for char in t: if char in t_counter: t_counter[char] += 1 else: t_counter[char] = 1 return s_counter == t_counter 2. Using inbuilt sort method
- Use python's inbuilt
sorted()method for each string - Compare if the two sorted strings are equal
Complexity
Time
π(π log π )
- The python's
sorted()function uses aTimsort algorithm= π(π log π ) + π(π log π ) - compare the two strings = π(π)
2π(π log π ) + π(π) = π(π log π )
Space
π(π)
- Sort function will create a new sorted string from the input string = π(π) + π(π)
- compare the two strings = π(π)
3π(π) = π(π)
Code
class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False return sorted(s) == sorted(t)
Top comments (0)