GeeksforGeeks » Interview Questions

Google Interview Question for Software Engineer/Developer about Strings

(4 posts)

Tags:

  1. ayush
    guest
    Posted 8 months ago #

    You are given two strings A and B, you have to find out whether all the characters of A are present in B or not?

  2. d1val
    Member
    Posted 8 months ago #

    #1 using bit vector approach space O(1) & time O(n)

    String input;
    String inputB;

    // assume all are lower case letters, i.e ASCII 65 - 90 [a - z].
    // charArray[3]==true indicates charcater 'd' is present.
    boolean[] charArray = new boolean[26];

    for (int i=0; i<inputA.length; i++) {
    char character = inputA.charAt(i);
    int position = int (character) - 65;
    charArray[position] = true;
    }

    for (int i=0; i<inputB.length; i++) {
    char character = inputB.charAt(i);
    int position = int (character) - 65;
    charArray[position] = false;
    }

    // print all the characters present in A but not in B

    for (int i=0; i<charArray.length; i++) {
    if (charArray[position]) System.out.print(charArray[position]);
    }

    /**

    // I have used boolean[] for simplicity but you can use an integer (8*4-1) > 26 bits.
    // initialize

    int bitHolder = 0;

    // setting nth bit to 1, where n < 32 - In first pass for inputA

    bitHolder += bitHolder + (1<<n)

    // flipping nth bit (i.e. 0 to 1 & 1 to 0) using xor, where n < 32 - In second pass for inputB

    bitHolder += bitHolder ^ (1<<n)

    // in third pass print all the corresponding bits whose value is 1

    **/

    #2 Using collections (Java) or data structure.

    1. Put all characters from input String A into a Set.
    2. Remove all characters from Set from input string B.
    3. Print all chracters in SET, remaining.

  3. sk
    guest
    Posted 7 months ago #

    better use hashing:-

    make hashtable for string A where each index of character represents number of occurrence of that character in string A .

    start read string B and decrease number of occurrence of character(reading in b) in hashtable.

    finally check ..if hash table contain 0 at all index ..it means string B has all characters of string A.

  4. anamika sharma
    Member
    Posted 4 months ago #

    If we assume that each character in string 1 has corresponding character in string 2, then following method can be used
    ie, it will work for aba and aab but not for ab, baa

    #include<iostream>
    int main()
    {
    char str1,str2;
    int x=0;
    for(int i=0;i<strlen(str1);i++)
    {
    x^=(str1[i]-'0');
    x^=(str2[i]-'0')
    }
    if(x==0)
    cout<<strings have same character;
    }

    or we can sort the strings (taking them as char arrays) and then compare, complexity o(nlogn)


Reply

You must log in to post.

RSS feed for this topic