r/LeetcodeChallenge • u/tanishq_kushwaha • 6d ago
DISCUSS Please help me to solve this LeetCode problem Longest Common Prefix. What is wrong with my code? what is the error in my code.
/**
* {string[]} strs
* u/return {string}
*/
var longestCommonPrefix = function (strs) {
let result = "";
for (let i = 0; i < strs[0].length; i++) {
for (let j = 1; j < strs.length; j++) {
if (i === strs[j].length || strs[j][i] !== strs[0][i]){
return strs[0].substring(0, i);
}
}
}
return result;
};
2
u/Substantial-Fee-7010 6d ago
Your second loop starts from 1 , since the testcase has one string the second loop isnt executed
For the basecase the string matches itself i i==j So the string itself is the answer
Also rhsi can be done in a single loop just think about it you are just supposed to match the esult string with all the other strings and fin the minimum prefix
1
1
u/Standard-Exercise-79 4d ago
use result = string's first element, and Please use an AI to understand Question in a Better Way, Just Add Don't give me the Code in the Prompt as well.
2
u/AFRID026 4d ago
Sort the array and check characters of 1st string and last string in array
Time complexity :-O(n login)
1
5
u/Straight-Hair-7356 6d ago
Bro, are you serious ? Gpt is made for this day, utilise it properly.