0

New to coding, trying leetCode problems. This one is #14-longest common prefix. Don't want the solution to the problem just need help figuring out why my for loop repeats infinitely and resets my variable. I know it is repeating because the variable keeps getting reset, but I have no idea why the variable resets. Also, the debugger shows that it resets after the first if statement is passed in the for loop. Again, please don't provide a solution to the leetCode problem, and even if my solution won't work..don't tell me. Let me find that out on my own. Please help me stop the for loop from repeating.

I originally thought it was a variable name conflict, I originally used J, changed it to K. I'm not really sure what else to try. I've googled the issue and can't find anything that replicates my situation.

function commonPrefix() {
    let strs = ["flower", "flow", "flount", "flight"];
    let comPref = "";
    
    for (i = 0; i < strs.length; i++) {
        let curWord = strs[i];
        let nextWord = strs[i + 1];

The if loop below starts after the first two strings in the array are matched for a prefix in the else statement at the bottom

       if (i != 0) {
         for (let k = 0; k < comPref.length; k++) {
            if (comPref[k] != nextWord[k] && (k = 0)) {
               comPref = "";

Debugger shows that the var k resets to zero at this point after K reaches 3 and before it gets to the else if condition. This happens even if I change the initial value of K to any other number and no matter what I set the block execution limit to as well.

            } else if (comPref[k] != nextWord[k]) {
               comPref = comPref.slice(0, [k]);
            }
         }
      } else {
         let j = 0;
         while (curWord[j] == nextWord[j]) {
            comPref = comPref + curWord[j];
            j++;
         }
      }

    }
}

console.log(commonPrefix());

Barmar
  • 741,623
  • 53
  • 500
  • 612
TorenRob
  • 1
  • 1
  • 4
    `&& (k = 0)` what is happening to `k` at this point...? You're assigning zero to it rather than checking to see if it is zero which would probably be `k === 0`. – Andy Nov 23 '22 at 18:13
  • 1
    See [What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)](/q/11871616/4642212). – Sebastian Simon Nov 23 '22 at 18:20
  • Andy and Sebastian... thank you. Don't know how I missed that. – TorenRob Nov 24 '22 at 00:11

0 Answers0