🤖
Data Structures and Algorithms
  • CS Theory And Problems
  • Big O
    • Big O Notation
  • Algorithms
    • Binary Search
    • Breadth First Search (BFS)
    • Depth First Search (DFS)
    • Dynamic Programming
    • Kadane's Algorithm
    • Kahn's Algorithm
    • Quickselect
    • Recursion
    • Sorting Algorithms
    • Sliding Window
  • Data Structures
    • Binary Heap
    • Graph
    • Linked List
    • Trees
  • Problems
    • LeetCode
      • 1. Two Sum
      • 3. Longest Substring Without Repeating Characters
      • 5. Longest Palindromic Substring
      • 11. Container With Most Water
      • 15. 3 Sum
      • 19. Remove Nth Node From End of List
      • 20. Valid Parentheses
      • 33. Search in Rotated Sorted Array
      • 49. Group Anagrams
      • 53. Maximum Subarray
      • 55. Jump Game
      • 56. Merge Intervals
      • 76. Minimum Window Substring
      • 98. Validate Binary Search Tree
      • 105. Construct Binary Tree from Preorder and Inorder Traversal
      • 121. Best Time to Buy and Sell Stock
      • 133. Clone Graph
      • 141. Linked List Cycle
      • 152. Maximum Product Subarray
      • 153. Find Minimum in Rotated Sorted Array
      • 200. Number of Islands
      • 206. Reverse Linked List
      • 207. Course Schedule
      • 217. Contains Duplicate
      • 226. Invert Binary Tree
      • 238. Product of Array Except Self
      • 242. Valid Anagram
      • 297. Serialize and Deserialize Binary Tree
      • 347. Top K Frequent Elements
      • 417. Pacific Atlantic Water Flow
      • 424. Longest Repeating Character Replacement
      • 435. Non-overlapping Intervals
      • 647. Palindromic Substrings
Powered by GitBook
On this page
  • Description
  • Solutions
  • Solution 1
  • Solution 2
  • Solution 3
  1. Problems
  2. LeetCode

242. Valid Anagram

Description

See https://leetcode.com/problems/valid-anagram/

Solutions

There are several solutions to this problem. Here are a few of them. I like solution 3 the best as it is the simplest. However, if space is important than solution 2 is the way to go.

Solution 1

Sort the two strings and compare them.

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        return sorted(s) == sorted(t)

Space O(N). The sorted function creates new strings. Time is O(N log N) as both strings are sorted.

Solution 2

Since the strings are constrained to lower case English letters an array can be used to store whether or not a letter has been seen. If the strings did not have this constraint (i.e. unicode allowed), then a dict would be used instead.

In this solution the character is turned into its numerical representation. (ASCII uses the first 127 numbers). So we can map the character to an array index (with some math). "a" will be at index 0 and "z" at index 25.

The numerical count of each letter is kept in the array. The count is used rather than a True/False flag because we need to account for duplicate letters.

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        chars = [0] * 26
        offset = ord("a")
        for l in s:
            chars[ord(l) - offset] += 1
        for l in t:
            num = ord(l) - offset
            chars[num] -= 1
            if chars[num] < 0:
                return False
        return True

Time is O(N). Space is O(1) (the array is a constant size of 26).

Solution 3

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        return Counter(s) == Counter(t)

Space O(N). This is because two Counter objects are created. Time is O(n) for the equality check (assumption on my part of what equality is doing under the hood).

Previous238. Product of Array Except SelfNext297. Serialize and Deserialize Binary Tree

Last updated 3 years ago