Javascript, functional solution


  • 0
    B

    Pretty easy to read and understand from the code.
    The candidates to be celebs are everyone 0 knows (because a celeb is known by everyone. Also - in case zero is the celeb - he knows himself)

    First leave only those who are known by all
    Second leave only those who know no one.
    (Order doesn't matter)

    Return remaining value or -1 if empty.

    function(n) {
        let all = Array(n)
          .fill(null)
          .map((_, i) => i);
    
        let calcKnownByAll = people => people.filter(cand => all.every(one => one === cand || knows(one, cand)));
        let calcKnowsNoOne = people =>
          people.filter(person => !all.some(one => person !== one && knows(person, one)));
    
        let candidates = all.filter(p => knows(0, p));
        let knowsNoOne = calcKnowsNoOne(candidates);
        let knownByAll = calcKnownByAll(knowsNoOne);
        let celeb = knownByAll[0] !== undefined ? knownByAll[0] : -1;
        return celeb;
      };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.