• + 3 comments

    my answer in Typescript

    const NO = 'NO', YES = 'YES';
    function larrysArray(A: number[]): string {
        /**
         * idea: create a [num] increament from 1, find index that contains [num] index and 
         *      always larger than 2 be cause i will rotate [index,index-2,index-1] to move
         *      [num] toward start of array. once [num] is at start of array, [num] increate
         *      and shift array. re do this till array have 2 element, if 2 element is not
         *      incrementing by 1, return NO else YES.
         */
    
        const rotate = (A: number[], index: number): number[] => {
            const a = [...A]
            return [...a.slice(0, index - 2), ...[a[index], a[index - 2], a[index - 1]], ...A.slice(index + 1)]
        }
    
        let is_larry_array = NO
        let num = 1
    
        while (true) {
            if (A.length < 3) {
                if (A[0] == A[1] - 1) is_larry_array = YES
                break
            }
    
            if (A[0] == num) { A.shift(); num++; continue }
    
            let index = A.indexOf(num); while (index < 2) index++
    
            A = rotate(A, index)
        }
    
        return is_larry_array
    }