Bird
Raised Fist0
Interview Prephash-maps-setseasyAmazonFacebookMicrosoft

Valid Anagram

Choose your preparation mode4 modes available
📋
Problem

Imagine you want to quickly check if two words are just jumbled versions of each other, like 'listen' and 'silent'. This problem helps you verify that efficiently.

Given two strings s and t, write a function to determine if t is an anagram of s. 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, using all the original letters exactly once.

1 ≤ length of s, t ≤ 10^5s and t consist of lowercase English letters only
Edge cases: Empty strings s = '', t = '' → trueStrings of different lengths s = 'a', t = 'aa' → falseStrings with same letters but different counts s = 'aabb', t = 'abab' → true
</>
IDE
def isAnagram(s: str, t: str) -> bool:public boolean isAnagram(String s, String t)bool isAnagram(string s, string t)function isAnagram(s, t)
def isAnagram(s: str, t: str) -> bool:
    # Write your solution here
    pass
class Solution {
    public boolean isAnagram(String s, String t) {
        // Write your solution here
        return false;
    }
}
#include <string>
using namespace std;

bool isAnagram(string s, string t) {
    // Write your solution here
    return false;
}
function isAnagram(s, t) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: trueNot checking length equality before frequency counting, causing false positives.✅ Add a length check: if len(s) != len(t): return False
Wrong: falseComparing strings directly or sorting incorrectly, failing to recognize anagrams with same counts.✅ Use frequency counting or correct sorting comparison: return sorted(s) == sorted(t)
Wrong: falseOrder sensitivity bug: comparing strings directly without sorting or counting.✅ Use frequency counts or sort both strings before comparing.
Wrong: truePartial frequency counting or ignoring extra characters in one string.✅ Count all characters and verify counts match exactly; check length equality.
Wrong: timeoutUsing sorting or nested loops on large inputs causing TLE.✅ Implement O(n) frequency counting using fixed-size array for lowercase letters.
✓
Test Cases
t1_01basic
Input{"s":"anagram","t":"nagaram"}
Expectedtrue

Both strings have the same characters with the same frequency.

t1_02basic
Input{"s":"rat","t":"car"}
Expectedfalse

Strings have different characters; 'rat' and 'car' are not anagrams.

t2_01edge
Input{"s":"","t":""}
Expectedtrue

Empty strings are trivially anagrams of each other.

t2_02edge
Input{"s":"a","t":"aa"}
Expectedfalse

Strings have different lengths; cannot be anagrams.

t2_03edge
Input{"s":"aabb","t":"abab"}
Expectedtrue

Both strings have the same characters with the same frequency, just different order.

t3_01corner
Input{"s":"aabbcc","t":"abcabc"}
Expectedtrue

Strings have same character counts but different grouping; tests order independence.

t3_02corner
Input{"s":"aabbcc","t":"aabbc"}
Expectedfalse

Strings differ in length by one; tests length check and frequency mismatch.

t3_03corner
Input{"s":"abc","t":"abcc"}
Expectedfalse

Tests handling of extra characters in one string; not anagrams.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

Input size n=100000 requires O(n) solution to complete within 2 seconds.

Practice

(1/5)
1. You need to design a data structure that supports inserting elements, deleting elements, and retrieving a random element, all in average constant time. Which approach best guarantees this performance?
easy
A. Using a balanced binary search tree to maintain elements and their indices
B. Combining a hash map for element indices with an array to store elements, using a swap-delete trick on removal
C. Using a linked list for elements and a hash set for membership checks
D. Maintaining a sorted array and performing binary search for insertions and deletions

Solution

  1. Step 1: Understand operation requirements

    Insert, delete, and getRandom must all be O(1) average time.
  2. Step 2: Evaluate data structures

    Balanced BST or sorted array have O(log n) or worse for insert/delete. Linked list lacks O(1) random access. Hash map + array with swap-delete achieves O(1) for all operations.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Hash map + array with swap-delete is the classic O(1) solution [OK]
Hint: Hash map + array with swap-delete enables O(1) ops [OK]
Common Mistakes:
  • Thinking balanced BST gives O(1) insert/delete
  • Using linked list for O(1) random access
  • Assuming sorted array can do O(1) insert/delete
2. Consider the following Python code implementing the optimal approach for finding the intersection of two arrays. What is the final returned list when calling intersect([4,9,5], [9,4,9,8,4])?
def intersect(nums1, nums2):
    nums1.sort()
    nums2.sort()
    i, j = 0, 0
    intersection = []
    while i < len(nums1) and j < len(nums2):
        if nums1[i] == nums2[j]:
            intersection.append(nums1[i])
            i += 1
            j += 1
        elif nums1[i] < nums2[j]:
            i += 1
        else:
            j += 1
    return intersection
easy
A. [4, 4, 9]
B. [9, 9]
C. [4, 9]
D. [4, 9, 5]

Solution

  1. Step 1: Sort both arrays

    nums1 sorted: [4,5,9], nums2 sorted: [4,4,8,9,9]
  2. Step 2: Traverse with two pointers

    Compare 4 and 4 -> equal, add 4; i=1, j=1 Compare 5 and 4 -> 5>4, increment j=2 Compare 5 and 8 -> 5<8, increment i=2 Compare 9 and 8 -> 9>8, increment j=3 Compare 9 and 9 -> equal, add 9; i=3, j=4 (end)
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Intersection is [4,9] matching common elements with duplicates counted correctly [OK]
Hint: Sort arrays and advance pointers carefully [OK]
Common Mistakes:
  • Off-by-one errors in pointer increments
  • Including extra duplicates
  • Returning unsorted results
3. What is the average time complexity of the remove operation in the optimal Insert Delete GetRandom data structure that uses a hash map and an array with the swap-delete trick?
medium
A. O(n), because removing an element requires shifting elements in the array
B. O(log n), because hash map operations take logarithmic time on average
C. O(1), because swapping with the last element and updating the hash map takes constant time
D. O(1) amortized, but worst-case O(n) due to occasional resizing of the array

Solution

  1. Step 1: Identify operations in remove

    Remove finds index in O(1) via hash map, swaps with last element, updates hash map, and pops last element.
  2. Step 2: Analyze time per step

    All steps are O(1) average time; no shifting of elements occurs.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Swap-delete avoids O(n) shifting, ensuring O(1) remove [OK]
Hint: Swap-delete avoids shifting, so remove is O(1) [OK]
Common Mistakes:
  • Assuming array remove requires shifting O(n)
  • Confusing hash map average O(1) with O(log n)
  • Ignoring that resizing is amortized and rare
4. What is the time complexity of the optimal sorting + two pointers approach for finding the intersection of two arrays of sizes m and n, respectively?
medium
A. O(m * n)
B. O(m log m + n log n)
C. O(m + n)
D. O(min(m, n) * log(max(m, n)))

Solution

  1. Step 1: Identify sorting cost

    Sorting nums1 costs O(m log m), sorting nums2 costs O(n log n).
  2. Step 2: Identify two-pointer traversal cost

    Two-pointer traversal is O(m + n) which is dominated by sorting.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Sorting dominates, so total is O(m log m + n log n) [OK]
Hint: Sorting dominates time complexity [OK]
Common Mistakes:
  • Confusing traversal cost as total
  • Assuming nested loops complexity
  • Misreading min/max in complexity
5. What is the time and space complexity of the optimal solution using prefix sums and a hash map (or array) for the longest subarray with sum divisible by k problem, given an input array of length n and integer k?
medium
A. Time: O(n log n), Space: O(n)
B. Time: O(n), Space: O(k)
C. Time: O(n * k), Space: O(n)
D. Time: O(n^2), Space: O(1)

Solution

  1. Step 1: Analyze time complexity

    The algorithm iterates once over the array (length n), performing O(1) operations per element, so time is O(n).
  2. Step 2: Analyze space complexity

    We store earliest indices for each remainder modulo k, so space is O(k), independent of n.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Linear time and space proportional to k [OK]
Hint: Prefix sums + hash map -> O(n) time, O(k) space [OK]
Common Mistakes:
  • Confusing nested loops complexity with prefix sum approach
  • Assuming space is O(n) due to prefix sums stored
  • Thinking time is O(n*k) due to modulo operations
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard