Rearrangement Equivalence Checker — Problem Statement & Solution Guide
Problem Description
Given two strings s and t, determine if one can be rearranged to form the other by comparing the frequency of each character.
Examples
Input
s = 'listen', t = 'silent'
Output
false
Explanation: Step-by-step: 1. Count the frequency of each character in both strings. 2. Compare the frequency of each character. If any character has a different frequency, return false. 3. If all characters have the same frequency, return true.
Input
s = 'abcde', t = 'edcba'
Output
true
Explanation: Step-by-step: 1. Count the frequency of each character in both strings. 2. Compare the frequency of each character. If all characters have the same frequency, return true.
Constraints
- 1 <= s.length, t.length <= 5 * 10^4
- s and t consist of lowercase English letters.
Optimal Approach & Strategy
Use a hash table to count character frequencies in both codes with a time complexity of O(n)
Brute Force Approach
Generate all permutations of the first code and check if the second code matches any permutation
Verified Code Solutions
function areAnagrams(str1, str2) { if (!str1 || !str2) return str1 === str2; if (str1.length !== str2.length) return false; const charCount = {}; for (let char of str1) { if (!charCount[char]) charCount[char] = 0; charCount[char]++; } for (let char of str2) { if (!charCount[char] || charCount[char] === 0) return false; charCount[char]--; } return Object.keys(charCount).every(key => charCount[key] === 0); }class Solution {
public boolean rearrangementEquivalenceChecker(String s, String t) {
if (s.length() != t.length())
return false;
char[] sArray = s.toCharArray();
char[] tArray = t.toCharArray();
Arrays.sort(sArray);
Arrays.sort(tArray);
return Arrays.equals(sArray, tArray);
}
}def rearrangement_equivalence_checker(s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)function areAnagrams(str1, str2) { if (!str1 || !str2) return str1 === str2; if (str1.length !== str2.length) return false; const charCount = {}; for (let char of str1) { if (!charCount[char]) charCount[char] = 0; charCount[char]++; } for (let char of str2) { if (!charCount[char] || charCount[char] === 0) return false; charCount[char]--; } return Object.keys(charCount).every(key => charCount[key] === 0); }Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.