KatInterview

Rearrangement Check Using Letter Tallies, No Sorting

StringsAuto-graded · 22 test cases
EasyAuto-gradedStringsstringshash-tablefrequency-count

Last updated

Decide whether two lowercase strings are rearrangements of each other using letter frequency counting in linear time, without sorting.

You are given two strings, first and second, made up only of lowercase English letters (a to z).

Return True if second can be formed by rearranging the letters of first, using every letter of first exactly once. Otherwise return False.

In other words, the two strings must contain exactly the same letters, each appearing the same number of times, though the order may differ. A string is always a rearrangement of itself, and two empty strings count as rearrangements of each other.

Do not sort either string. Aim for a solution that runs in linear time in the length of the strings.

Constraints

  • Both strings contain only lowercase English letters a-z.
  • Either string may be empty.
  • The strings may have different lengths; in that case the answer is False.
  • Sorting either string is not allowed.
  • Target time complexity: O(n), where n is the string length.

Examples

Example 1

Input: is_rearrangement('listen', 'silent')

Output: True

Example 2

Input: is_rearrangement('rat', 'car')

Output: False

Hints

Hint 1

If the two strings have different lengths, can they possibly be rearrangements of each other? Check this first.

Hint 2

Only 26 distinct letters are possible, so a fixed-size array of counters indexed by letter position can replace a hash map.

Hint 3

Add one to a counter for each letter of the first string, then subtract one for each letter of the second. If a counter ever goes below zero, the second string has too many of that letter.