Exercise 17: Find Longest Common Prefix
Problem Statement
Function `longestCommonPrefix(strs)` banao jo array of strings me longest common prefix find kare.
Example: longestCommonPrefix(["flower", "flow", "flight"]) => "fl"
Sample Output:
longestCommonPrefix(["flower", "flow", "flight"]) => "fl" longestCommonPrefix(["dog", "cat"]) => ""
Solution
const longestCommonPrefix = (strs) => {
if (strs.length === 0) return "";
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (!strs[i].startsWith(prefix)) prefix = prefix.slice(0, -1);
}
return prefix;
};Explanation
Overall Goal:
- Multiple strings me common prefix find karna.
Real world:
- String algorithms: prefix matching.
- Data analysis: common patterns.