Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check whether the given strings are isomorphic using C#?
Two strings are called isomorphic if there exists a one-to-one character mapping between them. This means each character in the first string maps to exactly one character in the second string, and no two characters can map to the same character. The mapping must be consistent throughout both strings.
For example, "egg" and "add" are isomorphic because 'e' maps to 'a', and 'g' maps to 'd'. However, "foo" and "bar" are not isomorphic because 'o' would need to map to both 'a' and 'r'.
Algorithm Approach
The solution uses two arrays to track the last seen position of each character in both strings. If the characters at the same position have different last-seen values, the strings are not isomorphic.
Using Array-Based Mapping
This approach uses two integer arrays to store the last position where each character was encountered −
using System;
public class Solution {
public bool IsStringIsomorphic(string s, string t) {
if (s == null || t == null || s.Length != t.Length) {
return false;
}
int[] chars1 = new int[256];
int[] chars2 = new int[256];
for (int i = 0; i
The output of the above code is −
True
False
True
Using Dictionary for Character Mapping
An alternative approach uses dictionaries to explicitly track character mappings −
using System;
using System.Collections.Generic;
public class Solution {
public bool IsStringIsomorphic(string s, string t) {
if (s.Length != t.Length) return false;
Dictionary mapST = new Dictionary();
Dictionary mapTS = new Dictionary();
for (int i = 0; i
The output of the above code is −
Testing 'abab' and 'baba': True
Testing 'abc' and 'def': True
Testing 'abba' and 'abab': False
Complexity Analysis
Approach
Time Complexity
Space Complexity
Array-based mapping
O(n)
O(1) - fixed array size
Dictionary mapping
O(n)
O(k) - k unique characters
Conclusion
Isomorphic strings can be efficiently checked using character mapping techniques. The array-based approach offers constant space complexity, while the dictionary approach provides more intuitive character-to-character mapping. Both methods ensure that the one-to-one mapping constraint is maintained throughout the comparison.
