Recent FANG interview
Anonymous User
936

I had a recent interview where I was asked to see if a target string can be made from a pharse. I dont remember the exact question but it was something as follows. your given a tartget string and a pharse. see if you can build the string from the pharse. you can only use one letter from each word and the target string must be built vertically/in order. Can some share a better approach or technique. Thank you!

example 1 -
Target word = 'hello'
Phrase - 'Sam went to the shop and the bakery and left with yellow cookies'

expectd output - true
explantion -
t[h]e
bak[e]ry
[l]eft
ye[l]low
c[o]okies

example 2 -
target word - 'nice'
phrase - 'today was a another day in the cold'
expecte ouput - false

my approach below -

function findTarget(target, pharse){
	if(pharse.length <= target.length || !phrase.length || !target.length) return false;
	const newTarget = target.toLowerCase();
	const newPhrase = phrase.toLowerCase();
	const arr = newPharse.split(' '); 
	let p1 = 0; 
	let p2 = 0; 
	
	while (p1 < newTarget.length && p2 < arr.length){
		let word = arr[p2]; 
		let letter = newTarget[p1]; 
		
		if(word.indexOf(letter) === -1){
			p2++;
		}else{
			p1++
			p2++
		}
	}
	
	return p1 === newTarget.length;
}
Comments (3)