Sort by

recency

|

3107 Discussions

|

  • + 0 comments
    def circularArrayRotation(a, k, queries):
        # Example: For array [1, 2, 3, 4, 5] (n=5):
        # k=0: [1, 2, 3, 4, 5] (no rotation)
        # k=1: [5, 1, 2, 3, 4] (rotated right once)
        # k=2: [4, 5, 1, 2, 3] (rotated right twice)
        # ...
        # k=5: [1, 2, 3, 4, 5] (full rotation, back to original)
        
        # To rotate efficiently without multiple single shifts:
        # 1. Calculate the effective rotation offset using modulo arithmetic
        #    (since rotating by n positions brings array back to original)
        # 2. Split the array at the offset and swap the two parts
        
        # Calculate the rotation point
        offset = len(a) - k % len(a)
        
        # Perform the rotation by concatenating the two slices
        rotated = a[offset:] + a[:offset]
        
        # Return the elements at the requested indices
        return [rotated[q] for q in queries]
    
  • + 0 comments

    My python solution:

    def swap(arr):
        el = arr.pop(-1)
        arr.insert(0, el)
        return arr
    
    def circularArrayRotation(a, k, queries):
        for i in range(k%len(a)):
            a = swap(a)
            
        return [a[x] for x in queries]
    
  • + 0 comments

    My C++ solution

    vector circularArrayRotation(vector & arr, int k, vector queries) { vector res; // k % arr.size() enusre that we are not unnecessarily rotating back to original std::rotate(arr.rbegin(), arr.rbegin() + (k % arr.size()), arr.rend());

    for (auto a : queries)
        res.push_back(arr[a]);
    
    return res;
    

    }

  • + 0 comments

    function circularArrayRotation(a, k, queries) {

        let x = k % a.length;
        let result = [];
        for(let i = 0; i < queries.length; i++) {
            // the formal is (queries[i] + a.length - x) % a.length to get the right index after rotation 
            result.push(a[(queries[i] + a.length - x) % a.length]);
        }
        return result;
    

    }

  • + 0 comments

    in scala without actually rotating

    def circularArrayRotation(a: Array[Int], k: Int, queries: Array[Int]): Array[Int] = {
      val kMod = k % a.length
      queries.map(x => a(if ((x - kMod + a.length) > 0) (x - kMod + a.length) % a.length else 0))
    }