Arrays: Left Rotation

Sort by

recency

|

4968 Discussions

|

  • + 0 comments

    C#

                var newlist = new List<int>(a);
    
        for(int i = 0; i< a.Count; i++){
            var index = i - d%a.Count;
    
    
            if(index >=0){
                newlist[index] = a[i];
                continue;
            }
    
            index += a.Count;
            newlist[index] = a[i];
    
    
        return newlist;
    }
    
  • + 0 comments

    this is my python code

    return a[d:] + a [:d]

  • + 0 comments

    JAVA

    ** List s= new ArrayList<>();

        for (int i = d ;  ;  ) {
            s.add(a.get(i));
            i++;
            if (i==d) {break;}
            else if (i==a.size()) {i=0;}
    
    
    
        }
    return s;**
    
  • + 0 comments
    function getPositionAfterRotation(length: number, index: number, rotation: number) {
        if(index - rotation >= 0) {
            return index - rotation;
        }
        return length + index - rotation;
    }
    
    function rotLeft(a: number[], d: number): number[] {
        const positionMap:Record<number, number> = {};
    
        a.forEach((i, idx)=>{
            const newIndex = getPositionAfterRotation(a.length, idx, d);
            positionMap[newIndex] = a[idx];
        });
        return Object.values(positionMap);
    }
    
  • + 0 comments
    int n = a.size();
    std::vector<int> rotated_array(n);
    for (int i = 0; i < n; ++i) {
        rotated_array[i] = a[(i + d) % n];
    }
    return rotated_array;
    
        C++20