📖
Coding problems
  • Overview
  • Second time
  • Third time
  • 2 sum
    • 2 sum?
    • 2 Sum All Pair I
    • 2 Sum All Pair II
    • 3 Sum
  • Array
    • Smallest and Largest
    • Largest and second largest
    • Longest Palindromic Substring
  • BFS
    • Array Hopper IV
    • Deep copy graph(possible loops)
    • Kth Smallest With Only 3, 5, 7 As Factors
    • Word Ladder
  • Binary Search
    • Closest in Sorted Array
    • Smallest Element that is larger than target
    • Search in unknown size array
  • Bit Operations
    • Basic Operations
    • Power of two?
    • Different bits
    • Reverse all bits of a number
    • Unique String
  • Deque
    • Deque with 3 stacks
    • Largest Rectangle in histogram
  • DFS Permutations
    • All subsets I
    • All subsets size k
    • Combinations For Telephone Pad I
    • Subsets of all permuations
    • Generate N valid parentheses I
    • Generate N valid parentheses II
    • Generate N valid parentheses III
    • Combinations of Coin
    • All Permutation String
    • All Permutations II
    • Telephone Combinations
  • Dynamic Programming
    • Array Hopper I
    • Array Hopper II
    • Array Hopper III
    • Cut Rope
    • Dictionary Word 1
    • Dictionary Word II
    • Eat Pizza
    • Largest Cross of Ones
    • Largest Square Surrounded By One
    • Largest X of 1s
    • Largest Square of Matches
    • Largest Submatrix Sum
    • Longest Ascending Subsequence I & II
    • Longest Common Sequence between two strings
    • Most with positive slope
    • Palindrome Partition
    • Edit Distance
    • Square of ones
    • Wild card matching
    • Wood Cutting
    • 188. Best Time to Buy and Sell Stock IV
  • Graph Search
    • Kth closest to <0, 0, 0>
    • Largest Product of Length
  • HashTable
    • Top K frequent words
    • Bipartite
  • Heap
  • LinkedList
    • Reverse
    • Merge Sort Linked List
    • Re-Order LinkedList
  • Slow fast pointers
    • Remove duplicate elements in array
  • Problem Solving
    • Water Level I
    • Largest rectangle in histogram
    • Range Addition II
  • Recursion
    • ReverseTree
    • NQueen
    • NQueen optimized
    • Spiral Order Print I
    • Spiral Order Print II
    • String Abbreviation Matching
  • Sliding Window
    • Longest subarray contains only 1s
    • Longest Substring Without Repeating Characters
    • Maximum Number within Window
  • Sorts
    • QuickSort
  • String
    • All Anagrams
    • is substring of string
    • Reverse String
    • Reverse Words on sentence
    • Remove Chars from String in place
    • Right shift N characters
    • Remove Leading/duplicate/trailing spaces
    • Shuffle String
    • String Abbreviation Matching
  • Tree Traversal
    • Check balanced tree
    • Check if complete tree
    • Delete in binary tree
    • LCA of two tree nodes
    • Get Keys In Binary Search Tree In Given Range
    • Height of Tree
    • Symmetric Tree?
    • Tweaked Binary tree
    • Set left node count
    • Greatest difference Left and Right subtree count Node
    • Largest Number Smaller in BST
    • Closest Number in Binary Search Tree II
    • Max Path Sum From Leaf To Root
    • Maximum Path Sum Binary Tree I
    • Maximum Path Sum Binary Tree II
    • Maximum Path Sum Binary Tree III
    • Flatten Binary Tree to Linked List
    • Iterative Post-Order Traversal
  • Unsorted Array
    • Find missing number
Powered by GitBook
On this page

Was this helpful?

  1. Recursion

NQueen optimized

Optimization Method: Improve valid position check to O(1)

High Level: use three boolean[] to check current column , leftDiagonal, and rightDiagonal

  public List<List<Integer>> nqueens(int n) {
    List<List<Integer>> result = new ArrayList<>();
    int[] cur = new int[n];
    boolean[] column = new boolean[n];
    boolean[] leftDiagonal = new boolean[2 * n - 1];
    boolean[] rightDiagonal = new boolean[2 * n - 1];

    helper(n, 0, cur, result, column, leftDiagonal, rightDiagonal);
    return result;
  }

  private void helper(int n, int row, int[] cur, List<List<Integer>> result, boolean[] column, boolean[] leftDiagonal ,boolean[] rightDiagonal){
    if (row == n){
      result.add(toList(cur));
      return;
    }
    for (int i = 0; i < n; i++){
      if (isValid(n, row, i, column, leftDiagonal, rightDiagonal)){
        mark(n, row, i, column, leftDiagonal, rightDiagonal);
        cur[row] = i;
        helper(n, row + 1, cur, result, column, leftDiagonal, rightDiagonal);
        unMark(n, row, i, column, leftDiagonal, rightDiagonal);
      }
    }
  }

  private boolean isValid(int n , int row, int col, boolean[] column, boolean[] leftDiagonal ,boolean[] rightDiagonal){
    return !column[col] && !leftDiagonal[col - row + n -1] && !rightDiagonal[col + row];
  }

  private void mark(int n , int row, int col, boolean[] column, boolean[] leftDiagonal ,boolean[] rightDiagonal){
    column[col] = true;
    leftDiagonal[col - row + n - 1] = true; //column - row range; -{n -1) -> (n - 1)
    rightDiagonal[col + row] = true; //0 -> (n -1) * 2
  }

  private void unMark(int n , int row, int col, boolean[] column, boolean[] leftDiagonal ,boolean[] rightDiagonal){
    column[col] = false;
    leftDiagonal[col - row + n - 1] = false; //column - row range; -{n -1) -> (n - 1)
    rightDiagonal[col + row] = false; //0 -> (n -1) * 2
  }

  private List<Integer> toList(int[] input){
    List<Integer> result = new ArrayList<>();
    for (int x: input){
      result.add(x);
    }
    return result;
  }

Time Complexity: O(N!) helper calls * O(1) valid check = O(N!)

Space Complexity: O(N) List cur * ~O(N) List result = O(N^2)

PreviousNQueenNextSpiral Order Print I

Last updated 4 years ago

Was this helpful?