LeetCode Valid Sudoku (JavaScript), Set

2025. 11. 24. 20:48·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/valid-sudoku/

문제 설명

더보기

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.

Example 1:

Input: board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true

Example 2:

Input: board =
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Same as Example 1, except with the5 in the top left corner being modified to8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Constraints:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit 1-9 or '.'.

문제 풀이

일반 for문을 통해 row, col, box부분의 검사하는 로직을 작성 -> O(n^4)의 복잡도로 시간 초과 오류

  • 내부에 row, col, box를 검사하는 for문 로직이 O(n^2)을 띄워 최종적으로 O(n^4)라는 시간 복자도를 가짐

개선

row, col, box에 유효성을 검증하기 위해 O(1)로 검사할 수 있도록 Set 자료구조를 이용하여 값을 관리

ex) rows[0] -> 0번째 row에 해당 하는 값들을 모아 두는 배열 -> rows[0].has(target)형태로 O(1)로 유효성 검사

  • 없다면 새로 값 추가
  • 있다면 중복으로 false리턴

중요한 건 box의 index를 구하는 것 2차원 배열을 1차원 index로 관리를 해야 함

  • boxIndex 구하는 법 : `Math.floor(y / 3) * 3 + Math.floor(x / 3);`
boxIndex = 0 boxIndex = 1 boxIndex = 2
boxIndex = 3 boxIndex = 4 boxIndex = 5
boxIndex = 6 boxIndex = 7 boxIndex = 8
/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
    const rows = Array.from({length: 9}, () => new Set());
    const cols = Array.from({length: 9}, () => new Set());
    const boxs = Array.from({length: 9}, () => new Set());

    let boxIndex = 0;
    for (let y = 0; y < 9; y++) {
        for (let x = 0; x < 9; x++) {
            if (board[y][x] === '.') continue;

            boxIndex = Math.floor(y / 3) * 3 + Math.floor(x / 3);

            // row에 같은 값 체크
            if (rows[y].has(board[y][x])) {
                return false;
            } else {
                rows[y].add(board[y][x]);
            }

            // col에 같은 값 체크
            if (cols[x].has(board[y][x])) {
                return false;
            } else {
                cols[x].add(board[y][x]);
            }
            
            // 3x3 박스에 같은 값 체크
            if (boxs[boxIndex].has(board[y][x])) {
                return false;
            } else {
                boxs[boxIndex].add(board[y][x]);
            }
        }
    }

    return true;
};

결론

유효성 검증을 위해 판단하는 부분을 Set을 이용해 O(1)로 줄여 최종적으로 O(n^2)의 시간 복잡도로 문제를 해결해야 함.

boxs 배열을 1차원으로 관리하기 때문에 2차원 배열의 x, y값에 다른 적절한 위치를 계산하는 로직을 구해야 함.

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Combination Sum (JavaScript), BackTracking  (0) 2025.11.25
LeetCode Count and Say (JavaScript)  (0) 2025.11.25
LeetCode Find First and Last Position of Element in Sorted Array (JavaScript), 이분 탐색  (1) 2025.11.24
LeetCode Next Permutaion (JavaScript), 순열  (0) 2025.11.22
LeetCode Divide Two Integers (JavaScript), 비트 연산  (0) 2025.11.21
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Combination Sum (JavaScript), BackTracking
  • LeetCode Count and Say (JavaScript)
  • LeetCode Find First and Last Position of Element in Sorted Array (JavaScript), 이분 탐색
  • LeetCode Next Permutaion (JavaScript), 순열
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (213) N
      • 프론트엔드 (64) N
        • JavaScript (51)
        • HTML (3)
        • React (7) N
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (127) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (38) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Valid Sudoku (JavaScript), Set
상단으로

티스토리툴바