DEV Community

Discussion on: The Scrabbling String Problem

Collapse
 
gkucmierz profile image
Grzegorz Kućmierz • Edited

What do you think about this solution?

const canScrabbleString = (word, letters) => {
  const map = new Map();

  [...letters].map(char => {
    const count = map.get(char) ?? 0;
    map.set(char, count + 1);
  });

  for (let i = 0; i < word.length; ++i) {
    const char = word[i];
    const count = map.get(char) ?? 0
    if (count <= 0) return false;
    map.set(char, count - 1);
  };

  return true;
};

const lettersInHand = "heulselo";
const wordToBeFound = "hello";

console.log(
  canScrabbleString(wordToBeFound, lettersInHand)
);
Enter fullscreen mode Exit fullscreen mode

I hope it is clear and it's time complexity is O(w + l) where w = word length and l = letters length

You can play with this code here:

instacode.app