Sort by

recency

|

3509 Discussions

|

  • + 0 comments

    O(1) time vector rotateLeft(int d, vector arr) { vector result; int step = d % arr.size();

    vector<int> left(arr.begin() + step, arr.end());
    vector<int> right(arr.begin(), arr.begin() + step);
    result.insert(result.end(), left.begin(), left.end());
    result.insert(result.end(), right.begin(), right.end());
    
    return result;
    

    }

  • + 0 comments
    public static List<Integer> rotateLeft(int d, List<Integer> arr) {
                //maybe it might be an unnecessarily long solution
        Queue<Integer> q = new LinkedList<>();
        List<Integer> list = new ArrayList<>();
        for(int arrItem : arr){
            q.add(arrItem);
        }
        for(int i = 0; i < d; i++){
            int temp = q.remove();
            q.add(temp);
    
        }
        for(int i = 0; i < arr.size(); i++ ){
            list.add(q.element());
            q.remove();
        }
    
        return list;
    }
    
  • + 0 comments

    Time Complexity: O(n) <\br>

    Space Complexity: O(n)

    int* rotateLeft(int d, int arr_count, int* arr, int* result_count) {
        int* res_arr = (int* )malloc(arr_count*sizeof(int));
        *result_count = 0;
        for (int i = 0; i<arr_count; i++){
            res_arr[i] = arr[(i+d)%arr_count];
            (*result_count) ++;
        }
        return res_arr;
    }
    
  • + 0 comments

    Here is my one line Python solution!

    def rotateLeft(d, arr):
        return arr[d % len(arr):] + arr[:d % len(arr)]
    
  • + 0 comments

    Here is my c++ solution, you can have the video explanation here : https://youtu.be/lyUDSB4Sg7Y

    vector<int> rotateLeft(int d, vector<int> arr) {
        int n = arr.size();
        vector<int> result(n);
        for(int i = 0; i < n; i++){
            int newIndex = (i - d + n) % n;
            result[newIndex] = arr[i];
        }
        return result;
    }