Untitled

mail@pastecode.io avatar
unknown
plain_text
8 days ago
979 B
1
Indexable
Never
// @leet start
/**
 * @param {string[]} words
 * @return {string[]}
 */
function commonChars(words) {
  if (words.length === 0) return [];

  let res = words[0].split("").sort();

  for (let i = 1; i < words.length; i++) {
    //console.log({ res, word: words[i] });

    let cur = 0;
    let idx = 0;
    if (res.length === 0 || cur >= res.length) return [];

    const w = words[i].split("").sort();
    // const w = words[i]
    //console.log({ res, w, cr: w[idx] });

    while (cur < res.length) {
      const char = res[cur];
      if (!w[idx]) res.splice(cur);
      //console.log({ res, char, currentWord: words[i], widx: w[idx] });

      if (char === w[idx]) {
        cur++;
        idx++;
      } else if (char > w[idx]) {
        idx++;
      } else if (char < w[idx]) {
        //console.log("AX", { res, cur, c: res[cur] });
        res.splice(cur, 1);
        //console.log("AFTER cut", { res });

        // cur++
      }
    }
  }

  return res;
}
// @leet end
Leave a Comment