Google Interview Question for Senior Software Development Engineers


Team: TEZ
Country: India
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
1
of 1 vote

def sortCustomOrder(sortStr, sortOrder):

	placement = {item: index for index, item in enumerate(sortOrder)}

	return sorted(sortStr, key=lambda x: placement.get(x) or len(sortStr))

- Dan February 10, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

def sort_with_order(s1: str, s2: str) -> str:
    """Sort string 's1' using the order of the characters in string 's2'
    >>> sort_with_order('Google', 'dog')
    'oogGle'
    >>>
    >>> sort_with_order('god', 'dog')
    'dog'
    >>>
    >>> sort_with_order('acbdedadf', 'cae')
    'caaebdddf'
    >>>
    """
    order = {c: i + 1 for i, c in enumerate(s2)}
    return ''.join(sorted(s1, key=lambda c: order.get(c) or len(s1)))


if __name__ == '__main__':
    import doctest
    doctest.testmod()

- python April 10, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringManipulator 
{
	public String manipulate(String first, String second)
	{
		String result;
		
		if(first == null || first.length() == 0 || second == null || second.length() == 0)
		{
			result = first;
		}
		else
		{
			// convert both strings to lowercase
			String S1 = first.toLowerCase();
			String S2 = second.toLowerCase();
			
			int firstStringLength = S1.length();
			int secondStringLength = S2.length();
			
			int i, j, currentCount;
			char currentCharacter;
			
			// extract all unique characters from S2
			HashMap<Character, Integer> uniqueChars = new HashMap<Character, Integer>();
			for(i = 0; i < secondStringLength; i++)
			{
				// extract characters from S2 - ignoring duplicates
				// HashMap automatically ignores duplicates even if found
				uniqueChars.put(S2.charAt(i), 0);
			}
			
			// construct two strings - head and tail
			StringBuilder head = new StringBuilder();
			StringBuilder tail = new StringBuilder();
			
			for(i = 0; i < firstStringLength; i++)
			{
				// populate count of all valid characters and also construct the tail string simultaneously
				currentCharacter = S1.charAt(i);
				
				if(uniqueChars.containsKey(currentCharacter))
				{
					// increment count
					currentCount = uniqueChars.get(currentCharacter);
					++currentCount;
					uniqueChars.put(currentCharacter, currentCount);
				}
				else
				{
					tail.append(currentCharacter);
				}
			}
			
			// put the "known" characters according to the sequence of S2
			for(i = 0; i < secondStringLength; i++)
			{
				currentCharacter = S2.charAt(i);
				if(uniqueChars.containsKey(currentCharacter))
				{
					// append that many instances of currentCharacter to head
					// this retains the order as well
					currentCount = uniqueChars.get(currentCharacter);
					for(j = 0; j < currentCount; j++)
					{
						head.append(currentCharacter);
					}
					
					// remove this character from HashMap
					uniqueChars.remove(currentCharacter);
				}
			}
			
			result = head.toString() + tail.toString();
		}
		
		return result;
	}
}

- Interviewer February 07, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class compareWithOrderMap {
        const unordered_map<char, int> &map;
    public:
        compareWithOrderMap(const unordered_map<char, int> &m): map(m) {}
        int operator() (const char &lhs, const char &rhs) const {
            int a = map.find(lhs)->second;
            int b = map.find(rhs)->second;
            return a < b;
        }
    };

    string customSort(const string &a, const string &b) {
        string res = a;
        unordered_map<char, int> map;
        int order = 0;
        
        transform(res.begin(), res.end(), res.begin(), ::tolower);
        
        for(auto c: b) {
            map[c] = order++;
        }
        
        for(auto c: a) {
            if(!map.count(c)) {
                map[c] = order++;
            }
        }
        
        sort(res.begin(), res.end(), compareWithOrderMap(map));
        return res;
    }

- yasinh February 08, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String rearrange(String s1, String s2) {
    s1 = s1.toLowerCase();
    s2 = s2.toLowerCase();

    Map<Character, Integer> charCount = new LinkedHashMap<>();

    for (int i = 0; i < s1.length(); i++) {
        char c = s1.charAt(i);
        int count = charCount.getOrDefault(c, 0);
        charCount.put(c, count + 1);
    }

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < s2.length(); i++) {
        char c = s2.charAt(i);
        int count = charCount.getOrDefault(c, 0);

        while (count-- > 0) {
            sb.append(c);
        }

        charCount.remove(c);
    }

    for (char c : charCount.keySet()) {
        int count = charCount.get(c);

        while (count-- > 0) {
            sb.append(c);
        }
    }

    return sb.toString();
}

- jgriesser February 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ArrangeSequenceOfChar {

private static String arrangeSeqOfChar(String s1, String s2) {
// TODO Auto-generated method stub
String result="";
String temp="";
for(int i=0;i<s2.length();i++) {
for(int j=0;j<s1.length();j++) {
if(s2.charAt(i)==s1.charAt(j)) {
result=result+s1.charAt(j);
}
}
}
for(int i=0;i<s1.length();i++) {
boolean flag=false;
for(int j=0;j<s2.length();j++) {
if(s1.charAt(i)==s2.charAt(j)) {
flag=true;
}
}if(flag==false) {
temp=temp+s1.charAt(i);
}
}
return result+temp;
}


public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="abcdedadf";
String s2="cae";
String seq=arrangeSeqOfChar(s1,s2);
System.out.println(seq);
}

}

- Anonymous February 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String arrangeSeqOfChar(String s1, String s2) {
// TODO Auto-generated method stub
String result="";
String temp="";
for(int i=0;i<s2.length();i++) {
for(int j=0;j<s1.length();j++) {
if(s2.charAt(i)==s1.charAt(j)) {
result=result+s1.charAt(j);
}
}
}
for(int i=0;i<s1.length();i++) {
boolean flag=false;
for(int j=0;j<s2.length();j++) {
if(s1.charAt(i)==s2.charAt(j)) {
flag=true;
}
}if(flag==false) {
temp=temp+s1.charAt(i);
}
}
return result+temp;
}

- shubham dwivedi February 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String arrangeSeqOfChar(String s1, String s2) {
String result="";
String temp="";
for(int i=0;i<s2.length();i++) {
for(int j=0;j<s1.length();j++) {
if(s2.charAt(i)==s1.charAt(j)) {
result=result+s1.charAt(j);
}
}
}
for(int i=0;i<s1.length();i++) {
boolean flag=false;
for(int j=0;j<s2.length();j++) {
if(s1.charAt(i)==s2.charAt(j)) {
flag=true;
}
}if(flag==false) {
temp=temp+s1.charAt(i);
}
}
return result+temp;
}

- shubham dwivedi February 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String arrangeSeqOfChar(String s1, String s2) {
		String result="";
		String temp="";
		for(int i=0;i<s2.length();i++) {
			for(int j=0;j<s1.length();j++) {
				if(s2.charAt(i)==s1.charAt(j)) {
				  result=result+s1.charAt(j);
				}
			}
		}
		for(int i=0;i<s1.length();i++) {
			boolean flag=false;
			for(int j=0;j<s2.length();j++) {
				if(s1.charAt(i)==s2.charAt(j)) {
					flag=true;
				}
			}if(flag==false) {
				temp=temp+s1.charAt(i);
			}
		}
		return result+temp;
	}

- Anonymous February 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String arrangeSeqOfChar(String s1, String s2) {
String result="";
String temp="";
for(int i=0;i<s2.length();i++) {
for(int j=0;j<s1.length();j++) {
if(s2.charAt(i)==s1.charAt(j)) {
result=result+s1.charAt(j);
}
}
}
for(int i=0;i<s1.length();i++) {
boolean flag=false;
for(int j=0;j<s2.length();j++) {
if(s1.charAt(i)==s2.charAt(j)) {
flag=true;
}
}if(flag==false) {
temp=temp+s1.charAt(i);
}
}
return result+temp;
}

- shubham dwivedi February 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def sort(s1, s2):
    index = {c: i + len(s2) for i, c in enumerate(s1)}
    index.update({c: i for i, c in enumerate(s2)})
    return ''.join(sorted(s1, key=index.get))

- nav February 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def sort(s1, s2):
    index = {c: i + len(s2) for i, c in enumerate(s1)}
    index.update({c: i for i, c in enumerate(s2)})
    return ''.join(sorted(s1, key=index.get))

- Anonymous February 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class RearrangeCharactersOrder {

	public static String rearrange(String s1, String s2) {
		String output = "";
		Character[] s1Array = new Character[s1.length()];
		HashMap<Character, Integer> positions = new HashMap<Character, Integer>();

		for (int i = 0; i < s2.length(); i++) {
			char ch = Character.toLowerCase(s2.charAt(i));
			if (!positions.containsKey(ch)) {
				positions.put(ch, i);
			}
		}

		for (int i = 0; i < s1.length(); i++) {
			char ch = Character.toLowerCase(s1.charAt(i));
			s1Array[i] = ch;
			if (!positions.containsKey(ch)) {
				positions.put(ch, s2.length() + i);
			}
		}

		Comparator<Character> s1Comparator = new Comparator<Character>() {
			@Override
			public int compare(Character o1, Character o2) {
				return positions.get(o1) - positions.get(o2);
			}
		};

		Arrays.sort(s1Array, s1Comparator);
		output = Arrays.stream(s1Array).map(Object::toString)
				.collect(Collectors.joining());

		return output;
	}

	public static void main(String args[]) {
		System.out.println(rearrange("google", "dog"));
		System.out.println(rearrange("Google", "Dog"));
		System.out.println(rearrange("abcdedadf", "cae"));
	}

}

- Viv February 18, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String function(String s1, String s2) {
        if (s1 == null || s2 == null)
            return ''
        if (s1.isEmpty() || s2.isEmpty() || s1.length() == 1)
            return s1.toLowerCase()

        LinkedList<String> listOfStrings = Arrays.asList(s1.split(''))
        ArrayList<String> templateString = s2.split('')
        int outsideIterator = 0

        for (String ts in templateString) {
            int i = outsideIterator

            for (i; i < listOfStrings.size(); i++) {
                if (listOfStrings[i].equalsIgnoreCase(ts)) {
                    if (i != outsideIterator) {
                        listOfStrings.add(outsideIterator, listOfStrings.remove(i))
                    }
                    outsideIterator++
                }
            }
        }
        listOfStrings.join().toLowerCase()
    }

- Natalia March 08, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def findCorrectOrder(S1, S2):
	char_dict = dict()
	for char in S1:
		char_dict[char] = char_dict.get(char, 0) + 1
	res = ''
	for char in S2:
		if char in char_dict:
			res += char_dict[char]*char
		else:
			res += char
	return res

- Nitish March 12, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I used a custom comparator with static hashmap.
It depends on, however I can use Arrays.sort with char[] and custom comparator.

static final HashMap<Character, Integer> orderMap = new HashMap<>();

static {
orderMap.put('c', 1);
orderMap.put('a', 2);
orderMap.put('e', 3);
}


public static Comparator<Character> customComp = new Comparator<Character>() {

@Override
public int compare(Character e1, Character e2) {
if (orderMap.containsKey(e1) && orderMap.containsKey(e2)) {
return orderMap.get(e1) - orderMap.get(e2);
} else if (orderMap.containsKey(e1) && !orderMap.containsKey(e2)) {
return -1;
} else if (!orderMap.containsKey(e1) && orderMap.containsKey(e2)) {
return 1;
} else {
return e1.charValue() - e2.charValue();
}
}
};

- Han Lee March 21, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String sortString(String str1, String str2) {
        if (str2 == null || str2.length() == 0) return str1;
        str1 = str1.toLowerCase();
        str2 = str2.toLowerCase();
        int len1 = str1.length(), len2 = str2.length();

        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < len2; i++) {
            char ch = str2.charAt(i);
            map.put(ch, i+1);
        }
        Character[] charArray = new Character[len1];
        for (int i = 0; i < len1; i++) charArray[i] = str1.charAt(i);
        Arrays.sort(charArray, new Comparator<Character>() {
            public int compare(Character a, Character b) {
                int v1 = Integer.MAX_VALUE, v2 = Integer.MAX_VALUE;
                if (map.containsKey(a)) v1 = map.get(a);
                if (map.containsKey(b)) v2 = map.get(b);
                return v1-v2;
            }
        });
        StringBuilder retString = new StringBuilder();
        for (int i = 0; i < len1; i++) {
            retString.append(charArray[i]);
        }
        return retString.toString();

        // HashMap<Character, Integer> mapString1 = new HashMap<>();
        // HashSet<Character> setString2 = new HashSet<>();
        // StringBuilder retString = new StringBuilder();
        // for (int i = 0; i < len1; i++) {
        //     char ch = str1.charAt(i);
        //     if (mapString1.containsKey(ch)) {
        //         mapString1.put(ch, mapString1.get(ch)+1);
        //     } else {
        //         mapString1.put(ch, 1);
        //     }
        // }
        // for (int i = 0; i < len2; i++) {
        //     char ch = str2.charAt(i);
        //     setString2.add(ch);
        //     if (mapString1.containsKey(ch)) {
        //         int freq = mapString1.get(ch);
        //         for (int j = 0; j < freq; j++) retString.append(ch);
        //     }
        // }
        // for (int i = 0; i < len1; i++) {
        //     char ch = str1.charAt(i);
        //     if (setString2.contains(ch) == false) {
        //         retString.append(ch);
        //     }
        // }
        // return retString.toString();
}

- Aim_Google April 02, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public String arrange(final String s1, final String s2) {
		if (s1 == null || s2 == null) return null;
		
		Map<Character, Integer> counts = new HashMap<>();
		for (char c : s1.toLowerCase()) {
			final int count = counts.getOrDefault(c, 0) + 1;
			counts.put(c, count);
		}
		
		final String existingChars = arrange(s2, counts);
		final String remainingChars = arrange(s1, counts);
		
		return existingChars + remainingChars;
	}
	
	private String arrange(final String s, Map<Character, Integer> counts) {
		final StringBuilder sb = new StringBuilder();
		for (char c : s.toLowerCase()) {
			if (counts.contains(c)) {
				final int count = count.get(c);
				final str = repeatChar(c, count);
				sb.append(str);
				counts.remove(c);
			}
		}
		return sb.toString();
	}
	
	private String repeatChar(final char c, final int count) {
		final char[] array = new char[count];
		Arrays.fill(array, c);
		return array;
	}

- jtcgen April 03, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
* Note:
* 1. Assume both string have only a-z characters.
* 2. Assume String S2 have distinct char, no repeated char allowed.
*/

public static String arrange1stStringBasedOn2ndString(String s1, String s2) {
		if(s1==null || s2 == null ) return null;
		StringBuilder resStr = new StringBuilder();
		
		int s1Len = s1.length(), s2Len = s2.length();
		
		//Create array of 26 chars to store repeated char count in S1.
		byte s1alpha[] = new byte[26];		
		for(int i=0; i<s1Len; i++)
			s1alpha[s1.charAt(i) - 'a']++;
		
		//Arrange the characters of S1 in same alphabetical order as the characters of S2. 
		for(int i=0; i<s2Len; i++){
			if(s1alpha[s2.charAt(i) - 'a'] != 0) {
				for(int j=0; j<s1alpha[s2.charAt(i) - 'a']; j++)
					resStr.append(s2.charAt(i));
				// Init with -1 as No need to consider this char in next loop
				s1alpha[s2.charAt(i) - 'a'] = -1; 
			}
		}
		
		//Loop to add character of S1 is not present in S2.
		for(int i=0; i<s1Len; i++)
			if(s1alpha[s1.charAt(i) - 'a'] != -1)
				resStr.append(s1.charAt(i));
		
		return resStr.toString();
	}

- jhunter April 07, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String compareTwoStr(String data, String pattern) {
		// edge cases strings with length 0 and 1
		if(pattern == null | data == null) return "";
		if(data.length() == 1) return data; 	
		StringBuilder ans = new StringBuilder();
		data = data.toLowerCase();
				Queue<Character> dataQ = new LinkedList<>();
				for(int i = 0;i<data.length();i++) {
					dataQ.add(data.charAt(i));
				}
				for (int j=0;j<pattern.length();j++) {
					while (!dataQ.isEmpty() && dataQ.contains(pattern.charAt(j))) {
						Character atTop = dataQ.peek();
						dataQ.remove();
						if(atTop == pattern.charAt(j)) {
							ans.append(atTop);
						} else {
							dataQ.add(atTop);
						}
					}
				}
				while(!dataQ.isEmpty()){
					ans.append(dataQ.peek());
					dataQ.remove();
				}
				
		return ans.toString();
	}

- Anonymous April 12, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String compareTwoStr(String data, String pattern) {
		// edge cases strings with length 0 and 1
		if(pattern == null | data == null) return "";
		if(data.length() == 1) return data; 	
		StringBuilder ans = new StringBuilder();
		data = data.toLowerCase();
				Queue<Character> dataQ = new LinkedList<>();
				for(int i = 0;i<data.length();i++) {
					dataQ.add(data.charAt(i));
				}
				for (int j=0;j<pattern.length();j++) {
					while (!dataQ.isEmpty() && dataQ.contains(pattern.charAt(j))) {
						Character atTop = dataQ.peek();
						dataQ.remove();
						if(atTop == pattern.charAt(j)) {
							ans.append(atTop);
						} else {
							dataQ.add(atTop);
						}
					}
				}
				while(!dataQ.isEmpty()){
					ans.append(dataQ.peek());
					dataQ.remove();
				}
				
		return ans.toString();

}

- HelloWorld April 12, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

nlogn algorithm with constant space

#include <iostream>
#include <algorithm>
using namespace std;
struct myClass
{
int order[26];
int count = 0;
myClass()
{
for(int i=0; i<26; i++)
{
order[i] = 26;
}
}
void setNext(char c)
{
int x;
x = c < 'a' ? c - 'A' : c - 'a';
if(order[x] == 26)
{
order[x] = count++;
}
}
bool operator() (char i, char j)
{
int x, y;
x = i < 'a' ? i - 'A' : i - 'a';
y = j < 'a' ? j - 'A' : j - 'a';
return order[x] < order[y];
}
};

int main() {
string s1;
string s2;
cin>>s1;
cin>>s2;
myClass myObject;
for(int i=0; i <s2.length(); i++)
{
myObject.setNext(s2[i]);
}
sort(s1.begin(), s1.end(), myObject);
cout<<s1;
}

- Nishagrawa March 14, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More