Google | Phone | Merge Files with Key Val | Reject
Anonymous User
2051

This was my first time interviewing for google. Working in non-FAANG 5 yoe.

Given 2 files which hold key-value pairs. Create a result file with common keys and concatenated values.

File1
k1, abc
k2, pqr
k3, lml

File2
k2, zzz
k3, uuu
k5, ttt

Expected Output
Result File
k2, pqrzzz
k3, lmluuu

Follow Up: what if both files are sorted?

I first gave a solution including hashmap - O(n+m)
Then after interviewer gave hint what if files are sorted I simply iterated both files - O (min(n,m))
n- len of file 1
m- len of file 2

You are allowed to assume APIs to read files and any data structure to hold file data.

Edit 1: Here is what I did:

while(file1 has more data && file2 has more data){
		key1 = file1.currKey
		key2 = file2.currKey
		if(key1 == key2) {
			write to dest
			move file1 pointer
			move file2 pointer
		}
		else if(key1 < key2) { move file1 pointer }
		else if(key1 > key2) { move file2 pointer }
}

In this case we only go to the end of the shorter file. O(min(n,m))
One way to think about this is as if you were manually checking 2 english dictionaries by placing finger on first word of each and looking for common words.
PS: I know I am not taking care of values in the above code. It doesnt matter, you pick the values at the same time that you pick keys.

Comments (9)