Skip to main content

Posts

Leetcode 51: N-Queens

1. Problem Statement (Simple Explanation) You must place n queens on an n x n chessboard such that: No two queens attack each other: Not in the same  row Not in the same  column Not on the same  diagonal You must return  all distinct solutions . Each solution is an n-element array of strings, where: 'Q' is a queen '.' is an empty cell Each string represents one row of the board. 2. Examples Example 1: Input: n = 4 Output: [   [".Q..","...Q","Q...","..Q."],   ["..Q.","Q...","...Q",".Q.."] ] These represent the two valid 4-queens solutions. Example 2: Input: n = 1 Output: [["Q"]] One queen on a 1x1 board. 3. Approach – Backtracking with Column & Diagonal Constraints We place queens  row by row : For each row r, we choose a column c where: No queen in the same  column . No queen in the same  diagonal . We track which columns and diagonals are already under attack to ensure...
Recent posts

Leetcode 50: Pow(x, n)

  1. Problem Statement (Simple Explanation): You must implement: pow(x, n) = x n where: x is a double (-100 < x < 100). n is a 32-bit signed integer (-2 31 <= n <= 2 31 - 1). Either x != 0 or n > 0. Result x n  is guaranteed to be in range [-10 4 , 10 4 ]. You should handle  negative exponents : x (-n) = 1 / (x n ) 2. Examples: Example 1: Input: x = 2.00000, n = 10 2 10 = 1024 Output: 1024.00000 Example 2: Input: x = 2.10000, n = 3 2.1 3 = 2.1 * 2.1 * 2.1 = 9.261 Output: 9.26100 Example 3: Input: x = 2.00000, n = -2 2 (-2) = 1 / 2 2 = 1 / 4 = 0.25 Output: 0.25000 3. Approach – Fast Exponentiation (Binary Exponentiation): We want an efficient algorithm, better than multiplying x |n| times. Key Idea: Use  Exponentiation by Squaring : For integer n: If n == 0: return 1 If n is even: x n = (x 2 ) (n/2) If n is odd: x n = x*x (n-1) We can implement this  ite...