Longest Common Prefix in TypeScript

function longestCommonPrefix(strs: string[]): string {
    if (strs.length === 0) return "";

    // Initialize the prefix to the first string in the array
    let prefix = strs[0];

    for (let i = 1; i < strs.length; i++) {
        while (strs[i].indexOf(prefix) !== 0) {
            // Reduce the prefix by one character at a time
            prefix = prefix.substring(0, prefix.length - 1);

            // If the prefix becomes empty, there's no common prefix
            if (prefix === "") return "";
        }
    }

    return prefix;
}

PrevNext