KatInterview

Check Character Mapping Consistency

StringsAuto-graded · 24 test cases
MediumAuto-gradedStringshash-maptwo-pointersbijection

Last updated

Tests whether two strings establish a valid one-to-one character correspondence at each position.

You are given two strings text1 and text2 containing printable ASCII characters. Your task is to determine whether these strings define a valid character-to-character mapping where:

  1. Each character in text1 consistently maps to exactly one character in text2 throughout the entire string
  2. No two different characters in text1 map to the same character in text2
  3. The mapping is only valid if both strings have identical length

Write a function that returns True if such a valid mapping exists, and False otherwise.

Important: The mapping is position-based. If text1[i] == text1[j], then text2[i] must equal text2[j]. Conversely, if text1[i] != text1[j], then text2[i] must not equal text2[j].

Constraints

  • 0 <= len(text1), len(text2) <= 10^5
  • Both strings contain only printable ASCII characters (ASCII values 32-126)
  • Character comparisons are case-sensitive ('A' and 'a' are treated as different characters)

Examples

Example 1

Input: has_valid_mapping('paper', 'title')

Output: True

Example 2

Input: has_valid_mapping('foo', 'bar')

Output: False

Example 3

Input: has_valid_mapping('ab', 'aa')

Output: False

Example 4

Input: has_valid_mapping('Send $100!', 'Wfoe %211?')

Output: True

Hints

Hint 1

If the strings have different lengths, can any position-based mapping be valid?

Hint 2

Track what each character in text1 should map to. If you see the same character again, does it map to the same target?

Hint 3

A single mapping dictionary isn't enough—you also need to prevent two different source characters from mapping to the same destination character.