Interview Question

    Unique Character Mapping

Given two inputted strings, determine if there is a one-to-one mapping of characters between them.  For example:

Input: 'abc', 'xyz'
Output: 1 # a maps uniquely to x, b to y, c to z

Provide an answer to fit into the following pseudocode:

def has_unique_character_map(string1, string2) {
    # YOUR ANSWER HERE
}

print(has_unique_character_map('abc', 'xyz')
# Returns 1
print(has_unique_character_map('aac', 'xyz')
# Returns 0




Answers


  • 1024
    @yashshah.shah

    if len(string1) == len(string2):
       a = string1.split()
       b = string2.split()
       for i in a:
           if i ==


  • 512
    @paul.n.xavier

    if(string1 == string 2)
        return 0
    duplicates = {}
    //check for duplicates in string 1
    for c in string 1:
        if c in duplicates:
            return 0
        else
            duplicates[c] = 1
    //check for duplicates in string 2 along with string 1 chars
    for c in string 2:
        if c in duplicates:
            return 0
        else
            duplicates[c] = 1
    // if all are unique return 1
    return 1


  • 256
    @firas

    def has_unique_character_map(string1, string2) {
       var i = 0;
       var result = 1;
       var dict = { }
       while ( i < string1.length && result) {
         if (!dict[string1[i]]) {
    }
       i ++;
       } 
    }


  • 256

  • 192
    @shruti.kshirsagar912

    def has_unique_character_map(string1, string2) {
      char [] s1= string1. toCharArray();
      char [] s2= string2. toCharArray();
    Set ss1<char>=new HasSet()<>;
    Set ss2<char>=new HasSet()<>;
    Set ss3<char>=new HasSet()<>;
    for(int i=0;i<string1.length;i++)
    {
    ss1.add(s1(i));
    ss2.add(s2(i));
    ss3.add(s1(i));
    ss3.add(s2(i));
    }
    if(ss1.size()==string1.length&&ss2.size()==string2.length&&ss3.size()==string1.length+string2.length)
    {
    if(string1.length==string2.length)
    
         return 1;
    
    else
          return 0; 
    }
    else return 0;
    }

Interview Questions

This question was recently asked at a major tech company (ie Google, Apple, Facebook, Amazon)
We're compiling a definitive list of interview questions.

Take a practice interview and score yourself.

<< Return to Index