Java String Program · S27
Check If Two Strings Are Isomorphic in Java
Two strings are isomorphic when you can rename the characters of one to get the other, using each new name only once. The mapping must work in both directions.
Problem Statement
Write a method that returns true if two strings are isomorphic: every character of s can be replaced by a character of t so that s becomes t.
The same character must always map to the same character, and no two different characters may map to the same one. Strings of different lengths are never isomorphic.
Input/Output Examples
"abca", "zbxz"OutputtrueExplanation: a→z, b→b and c→x are used consistently."ab", "aa"OutputfalseExplanation: a and b would both have to become a."aa", "ab"OutputfalseExplanation: a would have to become both a and b.Visual Explanation
"abca" against "zbxz": the first three positions create new pairs; the last a must map to z again, and it does (purple).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.
Approach 1: Two Lookup Arrays (Recommended)
Idea: store the partner of each character of s and of t in two char[128] arrays.
- Return
falseif the lengths differ. - For each position, read
a = s[i]andb = t[i]. - If neither has a partner yet, record
a→bandb→a. - Otherwise, both recorded partners must match the current pair.
Time: O(n) · Space: O(1). Two fixed arrays of 128 entries.
Approach 2: HashMap and HashSet
Idea: a map holds s→t, and a set holds the characters of t that are already taken.
- Look up the partner of
ain the map. - If there is none,
bmust not be in the set; add it and recorda→b. - If there is one, it must equal
b.
Time: O(n) · Space: O(k).
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.
Approach 1: Two Lookup Arrays (Recommended)
Array lookups are fast and allocation-free; the value 0 means "no partner yet" (ASCII input).
public class IsomorphicArrays {
// Two lookup tables enforce the mapping in both directions (ASCII input)
static boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char[] sToT = new char[128];
char[] tToS = new char[128];
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i);
char b = t.charAt(i);
if (sToT[a] == 0 && tToS[b] == 0) {
sToT[a] = b; // new pair: record it both ways
tToS[b] = a;
} else if (sToT[a] != b || tToS[b] != a) {
return false; // conflicts with an earlier pair
}
}
return true;
}
public static void main(String[] args) {
String[][] pairs = {{"abca", "zbxz"}, {"ab", "aa"}, {"aa", "ab"}, {"noon", "deed"}};
for (String[] p : pairs) {
System.out.println("\"" + p[0] + "\", \"" + p[1] + "\" -> " + isIsomorphic(p[0], p[1]));
}
}
}
"abca", "zbxz" -> true "ab", "aa" -> false "aa", "ab" -> false "noon", "deed" -> true
Time complexity: O(n) · Space complexity: O(1).
Approach 2: HashMap and HashSet
Works for any character set. used.add(b) returns false when b was already taken.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class IsomorphicMap {
// The map gives s -> t; the set makes sure no t character is used by two s characters
static boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Character> mapping = new HashMap<>();
Set<Character> used = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i);
char b = t.charAt(i);
Character mapped = mapping.get(a);
if (mapped == null) {
if (!used.add(b)) {
return false; // b already belongs to another character
}
mapping.put(a, b);
} else if (mapped != b) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[][] pairs = {{"abca", "zbxz"}, {"ab", "aa"}, {"aa", "ab"}, {"noon", "deed"}};
for (String[] p : pairs) {
System.out.println("\"" + p[0] + "\", \"" + p[1] + "\" -> " + isIsomorphic(p[0], p[1]));
}
}
}
"abca", "zbxz" -> true "ab", "aa" -> false "aa", "ab" -> false "noon", "deed" -> true
Time complexity: O(n) · Space complexity: O(k).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Two Lookup Arrays | O(n) | O(1) |
| HashMap and HashSet | O(n) | O(k) |
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 methodO(n × k); use a set instead. - Compare boxed characters carefully.
mapped != bworks here becausebis a primitivechar, which unboxesmapped. - 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.