Products of Array Except Self
Problem Information
- Leetcode problem: https://leetcode.com/problems/product-of-array-except-self/description/
- Neetcode problem: https://neetcode.io/problems/products-of-array-discluding-self
- Difficulty: Medium
Material
Solution
Using a similar approach to prefix sum we calculate the prefix and suffix multiplication, so that later we can calculate the multiplication.
class Solution {
public boolean isValidSudoku(char[][] board) {
int boardSize = board.length;
var columns = new ArrayList<HashSet<Character>>(boardSize);
var rows = new ArrayList<HashSet<Character>>(boardSize);
var squares = new HashMap<String, HashSet<Character>>();
for (int i = 0; i < boardSize; i++) {
columns.add(i, new HashSet<Character>());
rows.add(i, new HashSet<Character>());
}
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board.length; c++) {
var num = board[r][c];
if (num != '.') {
var columnSet = columns.get(c);
var rowSet = rows.get(r);
var squareKey = r/3 + "," + c/3;
squares.putIfAbsent(squareKey, new HashSet<Character>());
var squareSet = squares.get(squareKey);
if (columnSet.contains(num))
return false;
else
columnSet.add(num);
if (rowSet.contains(num))
return false;
else
rowSet.add(num);
if (squareSet.contains(num))
return false;
else
squareSet.add(num);
}
}
}
return true;
}
}