Arrays: Left Rotation

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