Home > front end >  Find the longest common prefix from an array of strings
Find the longest common prefix from an array of strings

Time:10-15

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 ... ?

CodePudding user response:

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"])

  • Related