Categories
Uncategorized

Longest Common Prefix using Binary Search (ES6)

const arr = ["hello", "helloworld", "helloworld1"];

const allContains = (inp, start, end) => {
for(let i=0; i<inp.length; i++) {
	for(let j=start; j<=end; j++) {
		if(inp[0].charAt(j)!==inp[i].charAt(j)) {
			return false;
    	}
	}
}
return true;
};

const findSubstring = (inp) => {
let min = Number.MAX_VALUE;
  for(let i=0; i<inp.length; i++) {
  	 min = Math.min(inp[i].length, min);
  }
let low = 0, high = min-1;
let prefix = '';
 while(low<=high) {
 	let mid = low + Math.round((high-low)/2);
  	if(allContains(inp, low, mid)) {
   		prefix += inp[0].substring(low, mid+1);
  		low = mid+1;
  	} else
  	high = mid-1;
		}
return prefix;
};

console.log(findSubstring(arr));

// Output: hello
// Runtime complexity: O(m*log(n)) 
// m- length of input array or list and n is length of 
// smallest string.

Demo