{"size": 841, "ext": "js", "max_stars_repo_path": "problems/720_longest-word-in-dictionary/index.js", "max_stars_repo_name": "sakuraiki/leetcode", "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:49:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T18:38:55.000Z", "max_issues_repo_path": "problems/720_longest-word-in-dictionary/index.js", "max_issues_repo_name": "sakuraiki/leetcode", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/720_longest-word-in-dictionary/index.js", "max_forks_repo_name": "sakuraiki/leetcode", "max_forks_repo_forks_event_min_datetime": "2016-04-17T05:55:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T07:48:56.000Z"}
{"max_stars_count": 158, "max_issues_count": null, "max_forks_count": 35, "avg_line_length": 23.3611111111, "max_line_length": 81, "alphanum_fraction": 0.5493460166}
/**
 * Problem: https://leetcode.com/problems/longest-word-in-dictionary/description/
 */
/**
 * @param {string[]} words
 * @return {string}
 */
var longestWord = function(words) {
  words.sort((w1, w2) => w1.length > w2.length ? 1 : -1);
  const existance = words.reduce((pre, word) => {
    pre[word] = { exist: true };
    return pre;
  }, {});

  let result = [];
  for (let word of words) {
    let pre = word.split('').slice(0, word.length - 1).join('');

    if ((existance[pre] && existance[pre].hasPre) || 1 === word.length ) {
      existance[word].hasPre = true;

      if (result.length) {
        if (word.length > result[0].length) {
          result = [word];
        } else {
          result.push(word);
        }
      } else result.push(word);
    }
  }

  return result.sort()[0] || '';
};

module.exports = longestWord;
