Frequency-Matched Strings - Problem

Given two strings, determine if they have identical character frequency distributions. This means both strings must have the same pattern of character occurrences, but not necessarily the same characters.

For example, "abc" and "def" both have frequency pattern [1,1,1] (each character appears once), so they match. Similarly, "aab" and "xxy" both have pattern [2,1] (one character appears twice, one appears once).

The strings are considered frequency-matched if their character frequency histograms have the same shape when sorted.

Input & Output

Example 1 — Same Pattern Different Characters
$ Input: str1 = "aab", str2 = "xxy"
Output: true
💡 Note: Both strings have frequency pattern [1,2] when sorted: str1 has 'a' appearing 2 times and 'b' appearing 1 time, str2 has 'x' appearing 2 times and 'y' appearing 1 time.
Example 2 — Different Patterns
$ Input: str1 = "abc", str2 = "def"
Output: true
💡 Note: Both strings have frequency pattern [1,1,1]: each character appears exactly once in both strings, so they have identical frequency distributions.
Example 3 — Unmatched Patterns
$ Input: str1 = "aab", str2 = "abc"
Output: false
💡 Note: str1 has pattern [1,2] (one char appears 2 times, one appears 1 time) while str2 has pattern [1,1,1] (all chars appear 1 time each). Different patterns.

Constraints

  • 1 ≤ str1.length, str2.length ≤ 1000
  • str1 and str2 consist of lowercase English letters only

Visualization

Tap to expand
INPUT STRINGSFREQUENCY ANALYSISPATTERN MATCHstr1 = "aab"aabstr2 = "xxy"xxyDifferent charactersSame length (3)1Count frequenciesstr1: {a:2, b:1}str2: {x:2, y:1}2Extract patternsstr1: [2,1]str2: [2,1]3Sort patternsstr1: [1,2]str2: [1,2]FREQUENCY MATCHPattern 1: [1,2]Pattern 2: [1,2]✓ IDENTICALResult: trueSame distribution!Key Insight:Two strings have identical frequency distributions when their sortedcharacter frequency patterns match, regardless of actual characters used.TutorialsPoint - Frequency-Matched Strings | Optimized Frequency Counting
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
73.9K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen