Skip to content
Merged

March12 #1574

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:

answer = dict()

for k, v in enumerate(nums):

if v in answer:
return [answer[v], k]
else:
answer[target - v] = k

return []





Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod
import re

class Solution:
def isPalindrome(self, s: str) -> bool:

# To lowercase
s = s.lower()

# Remove non-alphanumeric characters
s = re.sub(pattern=r'[^a-zA-Z0-9]', repl='', string=s)

# Determine if s is palindrome or not
len_s = len(s)

for i in range(len_s//2):

if s[i] != s[len_s - 1 - i]:
return False

return True
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod
from collections import deque, defaultdict

class Solution:
def totalNQueens(self, n: int) -> int:
"""
Given an integer n, return the number of distinct solutions to the n-queens puzzle.

The n-queens puzzle is placing n queens on an n×n chessboard such that
no two queens attack each other (same row, column, or diagonal).

Time Complexity: O(N!)
Space Complexity: O(N)
"""
def backtrack(row: int) -> int:
# Base case: all queens placed successfully
if row == n:
return 1

count = 0
# Try placing queen in each column of current row
for col in range(n):
# Calculate diagonal and anti-diagonal identifiers
diagonal = row - col
anti_diagonal = row + col

# Check if current position is safe
if col in cols or diagonal in diagonals or anti_diagonal in anti_diagonals:
continue

# Place queen
cols.add(col)
diagonals.add(diagonal)
anti_diagonals.add(anti_diagonal)

# Recurse to next row
count += backtrack(row + 1)

# Backtrack: remove queen
cols.remove(col)
diagonals.remove(diagonal)
anti_diagonals.remove(anti_diagonal)

return count

# Track occupied columns, diagonals, and anti-diagonals
cols = set()
diagonals = set() # row - col is constant for each diagonal
anti_diagonals = set() # row + col is constant for each anti-diagonal

return backtrack(0)
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* 52. N-Queens II
*
* Given an integer n, return the number of distinct solutions to the n-queens puzzle.
*
* The n-queens puzzle is placing n queens on an n×n chessboard such that
* no two queens attack each other (same row, column, or diagonal).
*
* Time Complexity: O(N!)
* Space Complexity: O(N)
*/
function totalNQueens(n: number): number {
// Track occupied columns, diagonals, and anti-diagonals
const cols = new Set<number>();
const diagonals = new Set<number>(); // row - col is constant for each diagonal
const antiDiagonals = new Set<number>(); // row + col is constant for each anti-diagonal

function backtrack(row: number): number {
// Base case: all queens placed successfully
if (row === n) {
return 1;
}

let count = 0;
// Try placing queen in each column of current row
for (let col = 0; col < n; col++) {
// Calculate diagonal and anti-diagonal identifiers
const diagonal = row - col;
const antiDiagonal = row + col;

// Check if current position is safe
if (cols.has(col) || diagonals.has(diagonal) || antiDiagonals.has(antiDiagonal)) {
continue;
}

// Place queen
cols.add(col);
diagonals.add(diagonal);
antiDiagonals.add(antiDiagonal);

// Recurse to next row
count += backtrack(row + 1);

// Backtrack: remove queen
cols.delete(col);
diagonals.delete(diagonal);
antiDiagonals.delete(antiDiagonal);
}

return count;
}

return backtrack(0);
}


43 changes: 43 additions & 0 deletions tests/test_150_questions_round_22/test_ex_100_n_queens_round_22.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import unittest
from typing import Optional, List
from src.my_project.interviews.top_150_questions_round_22\
.ex_100_n_queens import Solution


class NQueensTestCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()

def test_example_1(self):
"""Test with n = 4, should return 2 solutions"""
result = self.solution.totalNQueens(4)
self.assertEqual(result, 2)

def test_example_2(self):
"""Test with n = 1, should return 1 solution"""
result = self.solution.totalNQueens(1)
self.assertEqual(result, 1)

def test_n_2(self):
"""Test with n = 2, should return 0 solutions"""
result = self.solution.totalNQueens(2)
self.assertEqual(result, 0)

def test_n_3(self):
"""Test with n = 3, should return 0 solutions"""
result = self.solution.totalNQueens(3)
self.assertEqual(result, 0)

def test_n_5(self):
"""Test with n = 5, should return 10 solutions"""
result = self.solution.totalNQueens(5)
self.assertEqual(result, 10)

def test_n_8(self):
"""Test with n = 8, should return 92 solutions"""
result = self.solution.totalNQueens(8)
self.assertEqual(result, 92)


if __name__ == '__main__':
unittest.main()
Loading