Skip to main content

Command Palette

Search for a command to run...

Strings - Isomorphic Strings

Published
1 min read
Strings - Isomorphic Strings
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

Isomorphic Strings

https://leetcode.com/problems/isomorphic-strings/description/

My approach:

We have to do bi-directional mapping so I used two hashmaps.

Code:

// TIME COMPLEXITY : O(N)
// SPACE COMPLEXITY : O(1) , Hashmaps will never exceed the size of 26
//                           no matter the size of 's' and 't'.

class Solution {
public:
    bool isIsomorphic(string s, string t) {

        if(s.size()!=t.size()){
            return false;
        }

        int n = s.size();
        unordered_map<char,char> map;
        unordered_map<char,char> map1;

        for(int i=0;i<n;i++){

// to avoid collision from s to t
            if(map.count(t[i])>0 && map[t[i]]!=s[i]){
                return false;
            }
            else{
                map[t[i]] = s[i];
            }
// to avoid collison from t to s
            if(map1.count(s[i])>0 && map1[s[i]]!=t[i]){
                return false;
            }
            else{
                map1[s[i]] = t[i];
            }
        }

        return true;
    }
};

DSA prep

Part 18 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Strings - Longest Common Prefix

Longest Common Prefix Problem Link: https://leetcode.com/problems/longest-common-prefix/description/ My approach: I sorted the array in the ascending order of the string sizes. Then I checked every character of the arr[0] with others strings. If t...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.