• + 0 comments

    PHP

    function circularArrayRotation($a, $k, $queries) {
        $result = [];
        
        foreach ($queries as $queryIndex) {
            $lastIterationOffset = $k % count($a); // eliminate iterations over whole array
            $index = $queryIndex - $lastIterationOffset; // calculate initial index before shifting
            if ($index < 0) { // initial index exceeded beggining of array limit
                $index = count($a) + $index; // counting index from the end of array
            }
            $result[] = $a[$index];
        }
        
        return $result;
    }