JSFiddle - React, Tailwind, and code Playground

by Tim Ko

JavaScript

// Simple Words
/*
Dr Albert Bertastein is a mathematician who is also interested in linguistics. When he learns a new language, he lieks to start with "simple" words before he moves on to "compound" ones. A "compound" word is defined as a word that can be expressed as a concatenation of two or more other words, while ther est is considered a "simple" word. For example, given the following vocabulary:

sales
person
salesperson
whatsoever
what
so
ever
per
son

"person" (= "per" + "son"), "salesperson", and "whatsoever" are compound words: while the rest are siple ones.

Your task is to write a method that picks out all the simple words out of a vocabulary.


Input

The first line is a positive number N (1 <= N <= 1,000,000), followed by N lines, each line is a word. The words are not sorted, but there will be no duplicate words in the input. Each word has length between 1 and 1000 characters, consisting of "a" to "z", all small capital.


Output: Simple words in the input, each taking one line. The order of the words must be the same as input (i.e. for simple words, A and B, if word A precedes word B in the input, it should also be the case in the output.


Sample Input:

12
chat
ever
snapchat
snap
salesperson
per
person
sales
son
whatsoever
what
so


Sample Output:

chat
ever
snap
per
sales
son
what
so
*/


function simpleWords(inputArray) {
	var simpleWords = {};
  var simpleWordsArr = [];
  
  // Sort words from smallest to biggest
  var sortedInput = inputArray.slice().sort((a, b) => {
  	return a.length - b.length;
  });
  
  // Find the simple words by checking that every word before is not a substring
  sortedInput.forEach((word, index, arr) => {
    var isSimple = checkIsSimple(word, simpleWords, simpleWordsArr);
  	
    if (isSimple) {
    	simpleWords[word] = true;
      simpleWordsArr.push(word);
    }
  });
  
  // Make a new array that's in the same order of only the simple words
  var result = [];
  inputArray.forEach(word => {
  	if (word in...