DEV Community

Edrick Ee
Edrick Ee

Posted on

Learning Map & Set (in JS) while doing leetcode

I was going through a leetcode question yesterday with my pair
This was my pair's problem.

question was:

You are given an array of words where each word consists of lowercase English letters.

wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.

For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".
A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.

Return the length of the longest possible word chain with words chosen from the given list of words.
Enter fullscreen mode Exit fullscreen mode
const longestStringChain = (wordsArray) => {
  let result = [];
  let index = 0;
  wordsArray = wordsArray.sort((a,b) => {return a.length - b.length});
  const innerHelper = (start) => {
  if (start > wordsArray.length -1) {
    return;
  }
  let currentChain = [];
  currentChain.push(wordsArray[start]);
  for (let i = start + 1; i < wordsArray.length; i++) {
    let currentComparison = wordsArray[i];
    if (currentComparison.length - currentChain[currentChain.length - 1].length === 1) {
      let chainWord = currentChain[currentChain.length - 1];
      for (var j = 0; j < currentComparison.length; j++) {
        if (currentComparison[j] !== chainWord[j]) {
          chainWord.slice(0, j) + currentComparison[j] + chainWord.slice(j + 1);
          if (chainWord === currentComparison) {
            currentChain.push(currentComparison);
          }
        }
      }
      }
    }
    result.push(currentChain);
    currentChain = [];
    index++;
    innerHelper(index);
  };
  innerHelper(index);
  let longest = 1;
  for (var k = 0; k < result.length; k++) {
    if (result[k].length > longest) {
      longest = result[k].lenght;
    }
  }
  return longest;
  };
Enter fullscreen mode Exit fullscreen mode
var longestStrChain = function(words) {
  words.sort((a, b) => a.length > b.length ? 1 : -1)
  const memo = new Map()
  for (let j = 0; j < words.length; j++) {
      memo.set(words[j], 1)
      for (let i = 0; i < words[j].length; i++) {
          const x = words[j].slice(0, i) + words[j].slice(i+1)
          if (memo.has(x)) {
              memo.set(words[j], Math.max(memo.get(words[j]), memo.get(x) + 1))
          }
      }
  }
  return Math.max(...memo.values());
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)