Check whether one string can be 1-to-1 mapped into another string

By | September 27, 2023

Given two lowercase alphabet strings s and t return whether you can create a 1-to-1 mapping for each letter in s to another letter (could be the same letter) such that s could be mapped to t, with the ordering of characters preserved.

Input:  s = "coco", t = "kaka"
Output: True
Explanation: We can create this mapping:
"c" -> "k"
"o" -> "a"

Input:  s = "cat", t = "foo"
Output: False
Explanation: 
We can't transform both "a" and "t" into "o"
Since it has to be a 1-to-1 mapping.

Approach:
This problem mentions a mapping so immediately we realize we need to use a “map” data structure to take one character and return another.
But, it is a 1 to 1 mapping, i.e. if a -> c then x -> c is not allowed ( no other char can map to c except a ).
So we need to use two maps to make sure that it is 1 to 1 mapping.

Follow the steps below to solve the problem:

  1. Initialize two Hashmaps st and ts, to make sure 1-to-1 mapping happens.
  2. If the length of s is not equal to the length of t, then s can not be transformed to t. Hence, return false.
  3. Iterate over characters of the string s and check the s -> t mapping,
  4. if it is already present or appear for the first time do st[s[i]] = t[i] else return false.
  5. Again check the t -> s mapping (same logic as above).

Below is the implementation of the above approach:

#include <bits/stdc++.h>
using namespace std;

bool solve(string s, string t)
{
    unordered_map<char, char> st, ts;
    // check whether length of s and t are equal or not
    // if not equal, its not possible to map return 0
    if (s.size() != t.size())
        return 0;

    for (int i = 0; i < s.size(); i++) {
        // check the s -> t mapping
        if (not st.count(s[i]) or st[s[i]] == t[i])
            // this is the first time I've seen this char in
            // s, or second time with the same mapped value
            // as last time
            st[s[i]] = t[i];
        else
            return false;

        // check the t -> s mapping (same logic as above)
        if (not ts.count(t[i]) or ts[t[i]] == s[i])
            ts[t[i]] = s[i];
        else
            return false;
    }

    return true;
}
// driver code
int main()
{

    string s = "coco";
    string t = "kaka";
    // function call
    bool result = solve(s, t);
    if (result)
        cout << "True";
    else
        cout << "False";
    return 0;
}

Output:

True

Time Complexity: O(n)
Auxiliary Space: O(n)

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.