Web Projects Consulting

EquiLeader Demo Task at Codility.com

codility netbeansLesson 6 – Leader – EquiLeader demo task solution code written in php. Gives 100/100 score at the time of publishing.

The description of the problem is copyrighted, so please see the following link for it: //codility.com/demo/take-sample-test/equi_leader

Solution in php:

function solution($A) {
    $cnt          = count($A);
    $equi_leaders = 0;
    if(!$cnt){
        return $equi_leaders;
    }

    $leader = $A[0];
    $ctr    = 1;
    for($i = 1; $i < $cnt; $i++){
        if($A[$i] == $leader){
            $ctr++;
        }
        else{
            $ctr--;
        }
        if($ctr == 0){
            $ctr    = 1;
            $leader = $A[$i];
        }
    }

    $total = 0;
    foreach($A as $i){
        if($i == $leader){
            $total++;
        }
    }

    if($total <= ($cnt / 2)){
        return 0;
    }

    $ldr_count = 0;
    for($i = 0; $i < $cnt; $i++){
        if($A[$i] == $leader){
            $ldr_count++;
        }
        $leaders_in_right_part = ($total - $ldr_count);
        if($ldr_count > ($i + 1) / 2 && $leaders_in_right_part > ($cnt - $i - 1) / 2){
            $equi_leaders++;
        }
    }

    return $equi_leaders;
}

Given “AS IS”, can be ported from other languages from solutions found on the internet, please use with care.

Please note: we think that codility.com does not give a correct assessment of your real-world programming skills. For instance, reading the below would bring more understanding why: //codility-test-questions.blogspot.com/2013/01/my-experience-with-codility-test.html

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.