본문 바로가기
IT/JavaScript & TypeScript

[JavaScript/알고리즘] PermCheck

by 저당단 2025. 1. 8.

Lesson 4 (Counting Elements) - PermCheck(Easy)

 

Test results - Codility

A non-empty array A consisting of N integers is given. A permutation is a sequence containing each element from 1 to N once, and only once. For example, array A such that: A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2 is a permutation, but array A such that: A[0] =

app.codility.com

배열의 값들이 연속적인 값이면 1을, 그렇지 않다면 0을 출력하는 문제입니다.

 

시도1 (실패)

function solution(A) {
    return A.every(num => num <= A.length) ? 1 : 0;
}

[2, 2, 2, 2] 면 통과하지 못하는 코드.

 

스트레스 테스트를 하지 않더라도 반복값 테스트 경계값 테스트는 꼭 하는 습관을 들입시다.

지금 새벽이라 컨디션이 좋지않군요.

 

 

시도2 (성공)

function solution(A) {
    const table = new Map();

    for (let i = 0; i < A.length; i++) {
        if (A[i] > A.length) {
            return 0;
        }
        
        if (!table.get(A[i])) {
            table.set(A[i], 1);
        } else {
            return 0;
        }
    }

    return 1;
}

 

첫번째 알고리즘에서 중복이 있는지 검사하는 로직도 추가했습니다.

Map 대신 List를 써서 contains로 검사를 해도 되긴한데 조금이라도 시간 복잡도를 줄이기 위해 선택한 방법입니다. 이건 코딜리티니까...