Skip to content

Instantly share code, notes, and snippets.

View swarooprath's full-sized avatar

Swaroop swarooprath

  • Palantir
  • Palo Alto, California
View GitHub Profile
@swarooprath
swarooprath / Nqueen.java
Last active March 29, 2023 07:05
NQueen Succint Java Solution
class Solution {
private static final String DOT = ".";
private static final String Q = "Q";
public static void main(String[] args) {
var soln = new Solution().solveNQueens(8);
for (var s : soln) {
for (var r : s) {
System.out.println(r);
@swarooprath
swarooprath / NQueen-optimized.py
Last active March 25, 2023 19:33
NQueen with Optimizations that traverses only half of the tree
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def solve_helper(n, slate, i):
nonlocal result_list
if i >= n:
result_list.append(slate[:])
else:
for j in filter(lambda x: not is_attack(slate, x), range(n)):
slate.append(j)
@swarooprath
swarooprath / NQueen.py
Last active March 30, 2023 03:36
Succint NQueen solution
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def solve_helper(n, slate, new_col):
nonlocal result
if new_col >= n:
result.append(slate[:]) # copy the slate, else we will have empty lists in result as elements are removed from slate
else:
for new_row in filter(lambda nr: not is_attack(slate, nr, new_col), range(n)): # find the position where the new queen in the new column is not being attacked by existing queens on the board
slate.append(new_row)
@swarooprath
swarooprath / tree.py
Created July 31, 2016 18:45
Python class for tree and binary tree. The __str__ function in Tree pretty prints binary tree, making it human readable
class Tree(object):
def __init__(self, val, children=[]):
self.val = val;
self.children = children;
def __str__(self, level=0, depth=0):
if depth == 0:
depth = self.getDepth()
ret = "\t" * level + repr(self.val) + ("____" * depth) + "\n"
for child in self.children: