Toptal | OA | Phone Directory Search
871

Find name of person for whom query (partially) matches number.
Return alphabetically smallest person.

Test Cases

Input format: [arrayOfNames, arrayOfNumbers, searchString]

[
		{
			input: [['pim', 'pom'], ['999999999', '777888999'], '88999'],
			output: 'pom',
		},
		{
			input: [
				['sander', 'amy', 'ann', 'michael'],
				['123456789', '234567890', '789123456', '123123123'],
				'1',
			],
			output: 'ann',
		},
		{
			input: [
				['adam', 'eva', 'leo'],
				['121212121', '111111111', '444555666'],
				'112',
			],
			output: 'NO CONTACT',
		},
	]

Solution

/**
 * @param {string[]} A list of names
 * @param {string[]} B list of phone numbers
 * @param {string} P phone number to search
 */
function phoneDirectorySearch(A, B, P) {
	const N = B.length
	let result
	for (let i = 0; i < N; i++) {
		const phoneNumber = B[i]
		if (phoneNumber.includes(P)) {
			// first match
			if (!result) result = A[i]
			// alphabatically smallest
			if (result && A[i] < result) {
				result = A[i]
			}
		}
	}
	if (result) return result
	return 'NO CONTACT'
}
Comments (1)