BackeasyStringsTCS

Rearrangement Equivalence Checker Solution

Problem Statement

Given two strings s and t, determine if one can be rearranged to form the other by comparing the frequency of each character.

Example 1
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.

Example 2
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.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Rearrangement Equivalence Checker — Problem Statement & Solution Guide

StringsEasyFrequency Map
TimeO(n)
|
SpaceO(n)

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

Example 1

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.

Example 2

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

JavaScript Solution
Time: O(n)
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

TCS

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.