0

Consider this:

var longestCommonPrefix = function(strs) {
    strs.forEach((item, index) => {
      let splitArr = item.split('');
      console.log('split array item is: ' + splitArr)
    });
};

longestCommonPrefix(["flower","flow","flight"])

https://leetcode.com/problems/longest-common-prefix/

I need to compare these arrays to find the common prefix in them. So the output of this code at the ends needs to be:

common prefix is: "fl"

As of right now the output of the above code block is this

split array item is: f,l,o,w,e,r 
split array item is: f,l,o,w 
split array item is: f,l,i,g,h,t

I need to either

  1. Loop by each character and array so the output is something like:

f,f,f,l,l,l,o,o,i,w,w,g,e,,h,r,,t

I tried to do this like this:

Looping Through an Array of Characters

You might want to take a look at the String's split method.

So I am already doing that, and my thought process is now this:

lets get our arrays, iterate over each character, and then make a new master array where we can count each instance of a letter appearing 3 times and print out that character, in order to get our common prefix.

So now that approach is this:

var longestCommonPrefix = function(strs) {
    // establish the new array
    
    // we need this for later, outside our loop so we can have a giant array to sort/look at/count
     
    let charArray = [];
      
      
    // loop through each array
    strs.forEach((item, index) => {
    
      // split the array by character
      let splitArr = item.split('');
      
      // test console log
      console.log('split array item is: ' + splitArr)
      
      // iterate over each character, and push it into a new array
      splitArr.forEach((letter, index) => {
        charArray.push(letter)
      });
      
    });
    
    // log final array
    console.log('FINAL ARRAY IS...: ' + charArray)
};

longestCommonPrefix(["flower","flow","flight"])

So we're getting closer because we're now here:

FINAL ARRAY IS...: f,l,o,w,e,r,f,l,o,w,f,l,i,g,h,t

But we're not quite there with what we want, f,f,f,l,l,l,o,o,i,w,w,g,e,,h,r,,t

We need to somehow sort the array by matching character, I think...?

When we do charArray.sort() we get this:

"FINAL ARRAY IS...: e,f,f,f,g,h,i,l,l,l,o,o,r,t,w,w"

Not quite...

Here are some SO answers based on my google search keyword "sort array by matching characters" that kind of talk about it but aren't quite relevant to my question

Javascript sort an array by matching to string

Sort an array of strings based on a character in the string

What keyword/search should I have used to find the results?

How can I sort this array from e,f,f,f,g,h,i,l,l,l,o,o,r,t,w,w to f,f,f,l,l,l,o,o,i,w,w,g,e,,h,r,,t ... ?

Balastrong
  • 4,336
  • 2
  • 12
  • 31
kawnah
  • 3,204
  • 8
  • 53
  • 103
  • 1
    It sounds like you may not be aware that `array.sort()` already sorts alphabetically, and works just fine for nested arrays of primitives (with the caverat that it sorts alphabetically, even if the primitives are numbers or booleans). `[['c','d'], ['a','z']].sort()` will reorder as `[['a','z'], ['c','d']]` already. – Mike 'Pomax' Kamermans Oct 13 '21 at 17:17
  • So that I don't think is aligned with what I'm looking for, going `str.sort()` in my context just throws back at me `flight,flow,flower` , I need to find the common prefix in each word with the approach outlined (so making it go `f,f,f,l,l,l,o,o,i,w,w,g,e,,h,r,,t` and like, count each letter thats 3 in at order) granted i dont even know if thats the right way or if its something else. – kawnah Oct 13 '21 at 17:22
  • Then you _absolutely_ want to [change that title](/help/how-to-ask) =) As for the longest common prefix, or LCP, that's quite a well known (and _solved_) problem in computer science already, with Wikipedia articles and loads of "how to implement this in X" articles on the web, for almost every programming language under the sun, so you definitely want to read some of those (even if they're not specific to JS, because they'll show you how to implement it, which you should be able to quite easily port to JS) – Mike 'Pomax' Kamermans Oct 13 '21 at 17:58
  • thanks for the response I feel like if the title was just longest common prefix I woulda gotten downvoted, no? You have to be very specific it seems here with questions with lots of evidence and attempts - I've asked a lot of qwuestions on here for 6 years lol. – kawnah Oct 13 '21 at 20:52
  • @Mike'Pomax'Kamermans also I'm not a computer scientist by any means, just a Graphic Designer that taught himself some HTML and somehow became a dev.... – kawnah Oct 13 '21 at 20:58
  • Your title has to summarize the problem, and if that problem already has answers, there's no need to post the question. But the current title is just blatantly not what you need help with, making it a terrible title. No one's holding your qualifications against you, and now you know what it's called, and what to search for some more: the process doesn't not stop once you post. If someone gives you new terms for your problem that you can google for, you're expected to start a new journey of [searching and researching](/help/how-to-ask) =) – Mike 'Pomax' Kamermans Oct 13 '21 at 23:09

1 Answers1

1

Here's a possible solution, needs to cover cases with an empty array but you get an idea.

While all letters at index c are the same I keep looping, otherwise I exit. At the end I take c characters from the first word as it's the length of the common prefix.

function longestCommonPrefix(strs) {
  var splits = strs.map((item) => item.split(''));
  var c = 0;
  var matches = true;
  while (matches) {
    var letter = splits[0][c];
    if (letter != null) {
      matches = splits.every(s => s[c] == letter);
      if (matches)
        c++;
    } else matches = false;
  }

  var prefix = strs[0].slice(0, c);
  console.log("The prefix is: " + prefix);
};

longestCommonPrefix(["flower", "flow", "flight"])
Balastrong
  • 4,336
  • 2
  • 12
  • 31
  • This looks good! I have a few questions and am hoping you can give a more in depth line by line explanation of this code: 1. what was the intention of using `.map()` ? I thought that was only used to modify arrays? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map 2. why are there two indexes(?) on `splits`? – kawnah Oct 13 '21 at 17:56
  • `strs` is an array, so I can use `.map()` to modify its elements (each string). What I do inside the mapping function is convert each string into an array of strings with `split()`. As a result, I have an array of arrays of strings (each letter). This answers the second question on the two indexes. The first is for the array of each word, the second is for the array of each letter :) – Balastrong Oct 14 '21 at 06:29