Sort by

recency

|

3096 Discussions

|

  • + 0 comments

    Java solution 100% time O(n):

    public static List<Integer> circularArrayRotation(List<Integer> a, int k, List<Integer> queries) {
        int n = a.size(), shift = k % n;
        return queries.stream()
                    .map(query -> a.get((query - shift + n) % n))
                    .collect(Collectors.toList());
    }
    
  • + 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
    function circularArrayRotation(a, k, queries) {
        // Normalize k to avoid unnecessary rotations if k is larger than the array length
        k = k % a.length;
    
        // Rotate the array
        let slicedElements = a.slice(a.length - k);  // Get the last k elements
        let remainingElements = a.slice(0, a.length - k);  // Get the first part of the array
        let rotatedArray = slicedElements.concat(remainingElements);  // Concatenate to get the rotated array
    
        // Initialize an array to store the results of the queries
        let results = [];
    
        // For each query, push the corresponding element from the rotated array
        for (let i = 0; i < queries.length; i++) {
            results.push(rotatedArray[queries[i]]);
        }
    
        return results;
    }
    
  • + 0 comments
    k=k%len(a)
    A=a[-k:]+a[:-k]
    ans=[A[i] for i in queries]
    return ans
    
  • + 0 comments
    def circularArrayRotation(a, r, q):
        x = r%len(a)
        z = a[-x:]+a[:-x]
        return [z[i] for i in q]