Hone logo
Hone
Problems

Valid Anagram

Given two strings, determine if one is an anagram of the other. 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. This is a fundamental problem in string manipulation and has applications in areas like text processing, cryptography, and puzzle generation.

Problem Description

Your task is to write a function that takes two strings as input and returns true if the second string is an anagram of the first string, and false otherwise.

Key Requirements:

  • An anagram must use all the characters from the original string exactly once.
  • The comparison should be case-sensitive.
  • The function should handle strings of varying lengths and character sets.

Expected Behavior:

  • If string2 can be formed by rearranging the characters of string1, return true.
  • Otherwise, return false.

Edge Cases to Consider:

  • Empty strings.
  • Strings with different lengths.
  • Strings containing only whitespace characters.
  • Strings with duplicate characters.

Examples

Example 1:

Input: string1 = "anagram", string2 = "nagaram"
Output: true
Explanation: "nagaram" is an anagram of "anagram" because it contains the same characters with the same frequencies.

Example 2:

Input: string1 = "rat", string2 = "car"
Output: false
Explanation: "car" does not contain the same characters as "rat".

Example 3:

Input: string1 = "", string2 = ""
Output: true
Explanation: Two empty strings are considered anagrams of each other.

Example 4:

Input: string1 = "a", string2 = "ab"
Output: false
Explanation: The strings have different lengths.

Constraints

  • The length of both string1 and string2 will be between 0 and 5 * 10^4, inclusive.
  • string1 and string2 consist of lowercase English letters and potentially other ASCII characters.
  • The solution should aim for an efficient time complexity.

Notes

Consider how you can efficiently count or track the occurrences of each character in both strings. Think about data structures that can help you store and compare character frequencies. The order of characters within the strings does not matter, only their presence and count.

Loading editor...
plaintext