00:00

Problem Statement

Input/Output Examples

Visual Explanation

Recording each pair in both directions catches both failure types: a character of s that tries to change its partner, and a character of t that is already taken by someone else.

Approaches

Both approaches enforce the mapping in both directions. The first uses two arrays; the second uses a map and a set.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the strings and k the number of distinct characters. Each position is checked once with constant-time lookups.

Interview Tips and Recommended Approach

  • Check both directions. A one-way map accepts "ab" and "aa", which is wrong.
  • Avoid map.containsValue(). It scans all values, which makes the method O(n × k); use a set instead.
  • Compare boxed characters carefully. mapped != b works here because b is a primitive char, which unboxes mapped.
  • Know the related problem: word pattern matching applies the same idea to words instead of characters.

Recommended Approach: Two Lookup Arrays

Why: it runs in linear time with two small arrays and checks both directions of the mapping in a single pass.