💡
Seb's Whiteboard
  • 👨‍💻Welcome, I'm Sebastien St Vil
  • Extras
    • Gradient Descent
    • How I learned Java
    • Machine Learning by Andrew Ng
  • Projects
    • 📉Backtest Equity Trading with SMA Strategy
    • Wellington GA Lab
    • Stock analysis
    • 📈Time Series Regression-based Trading Strategy
  • Arrays & Strings
    • Best Time to Buy and Sell Stock II
    • Online Stock Span
    • Implement strStr()
    • 2Sum
    • 3Sum
    • 3Sum Closest
    • 4Sum II
    • Set Matrix Zeroes
    • Group Anagrams
    • Longest Substring Without Repeating Characters
    • Remove Duplicates from Sorted Array
    • Move Zeroes
    • Valid Sudoku
    • Rotate Image
    • First Unique Character in a String
    • Design a Circular Queue
    • Longest Common Prefix
  • Binary Tree
  • Second Minimum Node In a Binary Tree (671)
  • Design
  • LRU Cache
  • Min Stack (155)
  • Sorting & Searching
    • Merge Sorted Array (88)
    • First Bad Version
  • Math
    • Power of Three (326)
    • Power of Two (231)
    • Count Prime (204)
    • Roman to Integer (13)
    • Fizz Buzz (412)
    • Count-and-Say
  • Dynamic Programming
    • Pascal's Triangle (118)
  • Linked List
    • Copy List with Random Pointer
    • Remove Nth Node From End of List
    • Remove Duplicated from Sorted List II
  • Tips
    • Finding dups
  • Sliding Window
    • Subarray Product Less Than K
Powered by GitBook
On this page
  • Approach1:
  • Approach1: Java Version
  • Approach2: Coordinates

Was this helpful?

  1. Arrays & Strings

Valid Sudoku

PreviousMove ZeroesNextRotate Image

Last updated 4 years ago

Was this helpful?

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: Empty cells consists of '.'(dot) character

Approach1:

We first take note of the above specified properties of a Sudoku. Intuitively, we're thinking about using a Set here since we might have to implement some sort of solution that accounts for duplicates.

The logic is as a follow, if we encode each element that we encounter with their corresponding row -> column -> 3x3 box, we would be able to later verify by using a Set whether they are unique.

For example: (credit: )

  • '4' in row 7 is encoded as "(4)7".

  • '4' in column 7 is encoded as "7(4)".

  • '4' in the top-right block is encoded as "0(4)2".

Scream false if we ever fail to add something because it was already added (i.e., seen before).

  • We iterate thorugh the matrix (board) and we store each non-empty cells values into a set along with their column. row, 3X3 information

  • The set contains unique values, if the element is already found within the set, by virtue of the above prorperties, the Sudoke in question is not valid.

class Solution(object):
    def isValidSudoku(self, board):
        seen = set()
        for i, row in enumerate(board):
            for j, e in enumerate(row):
                if e !='.':
                    if (i,e) in seen or (e,j) in seen or (i/3,j/3,e) in seen:
                        return False
                    seen.add((i,e))
                    seen.add((e,j))
                    seen.add((i/3,j/3,e))
        return True

Time: O(n2) Space: O(distinct(k) k = elements

Approach1: Java Version

class Solution {
    public boolean isValidSudoku(char[][] board) {
        Set<String> set = new HashSet<>();
        
        for(int row = 0; row < board.length; row++){
            for(int col = 0; col < board[row].length; col++){
                char val = board[row][col];
                if(val != '.'){
                    if(!set.add(val + " in row " + row)
                    || !set.add(val + " in column " + col)
                    || !set.add(val + " in sub-box " + row/3 + " " + col/3)) return false;
                }
            }
        }
        return true;
    }
}

Approach2: Coordinates

Time: O(n2) Space: O(distinct(k) k = elements

A different approach we can use if by implementing a method isValid which takes in coordinates and ensures that the elements within the coordinates are unique. This approach is very intuitive however it can be bit delicate as we have to make sure that the passed coordinates are accurates.

Note: We use ther modulo operator% for 3*3. Because % increments and resets back by staying within the box constraints.

class Solution {
    public boolean isValidSudoku(char[][] board) {
        
        for(int i = 0; i < board.length; i++){
            if(!isValid(board, i, i, 0, 8) || !isValid(board, 0, 8, i, i) || !isValid(board, i/3*3, i/3*3+2,i%3*3, i%3*3+2)) return false;
        }
        return true;
    }
    private boolean isValid(char[][]board, int x1, int x2, int y1, int y2){
        Set<Integer> set = new HashSet<>();
        
        for(int row = x1; row <= x2; row++){
            for(int col = y1; col <= y2; col++){
                if(board[row][col] != '.' && !set.add(board[row][col] - '0')) return false;
            }
        }
        return true;
    }
}

StefanPochmann