Sort by

recency

|

3067 Discussions

|

  • + 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;
    }
    
  • + 0 comments

    JAVASCRIPT BIG O(N) SOLUTION:

    for(let i=0;i<k;i++) {
    			// Remove the last elment and add into the first position and moves remaining element to the right
            a.unshift(a.pop());
        }
        let finalArr = queries.map((query) => a[query]);
        return finalArr;
    
  • + 0 comments

    Simple Java solution without additional list

       int size = a.size();
        k=k%size;
        List<Integer> res = new ArrayList<>();
        for(int i:queries){
            int idx = i-k;
            if(idx<0) idx+=size;
            res.add(a.get(idx));
        }
        return res;
    
  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/MaT-4dnozJI

    Solution 1 O(n + m) :

    vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
        vector<int> newArray(a.size()), result;
        for(int i = 0; i < a.size(); i++){
            newArray[(i + k) % a.size()] = a[i];
        }
        for(int i = 0; i < queries.size(); i++) result.push_back(newArray[queries[i]]);
        return result;
    }
    

    Solution 2 O(m) :

    vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
        vector<int> result;
        for(int i = 0; i < queries.size(); i++) {
            int previousIndex = (queries[i] - k + a.size() * 100000 ) % a.size();
            result.push_back(a[previousIndex]);
        }
        return result;
    }
    
  • + 0 comments

    Java Streams with better efficiency:

      
    Deque<Integer> deque = new ArrayDeque<>(a);
    
    IntStream.rangeClosed(1, k).forEach(value -> {
        Integer last = deque.pollLast();
        deque.addFirst(last);
    });
    
    List<Integer> dequeList = new ArrayList<>(deque);
    
    return queries.stream()
            .map(dequeList::get)
            .collect(Collectors.toList());