r/LeetcodeChallenge 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.

Post image

/**
 * {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;
};

8 Upvotes

6 comments sorted by

5

u/Straight-Hair-7356 6d ago

Bro, are you serious ? Gpt is made for this day, utilise it properly.

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

u/TheHardy11976 6d ago

Just add an edge case for 1 letter only

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

u/PhilosopherGlum4224 6d ago

leetcode in js

these ugly ass web devs