Skip to main content

Posts

Leetcode 53: Maximum Subarray

  1. Problem Statement (Simple Explanation): You are given an integer array nums. You must find the  contiguous subarray  (containing at least one number) which has the  largest sum , and return that sum. 2. Examples: Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] The subarray [4, -1, 2, 1] has sum 4 + (-1) + 2 + 1 = 6, which is the largest. Output: 6 Example 2: Input: nums = [1] Only one subarray [1], sum = 1. Output: 1 Example 3: Input: nums = [5,4,-1,7,8] Best subarray is the whole array, sum = 5 + 4 + (-1) + 7 + 8 = 23. Output: 23 3. Approach 1 – Kadane’s Algorithm (O(n), Standard): This is the classic linear-time solution. Intuition: As you traverse the array, maintain: currentSum – maximum subarray sum  ending at the current index . maxSum – maximum subarray sum seen so far. For each nums[i], you decide: Either  extend  the previous subarray: currentSum + nums[i] Or  start a new subarray ...

Leetcode 52: N-Queens II

  1. Problem Statement (Simple Explanation): Same puzzle as N-Queens (problem 51): Place n queens on an n x n chessboard so that no two queens attack each other: Not in the same  row Not in the same  column Not on the same  diagonal But now: Instead of returning all boards, you must return the  number of distinct solutions . 2. Examples: Example 1: Input: n = 4 There are exactly 2 valid configurations (same as problem 51’s example). Output: 2 Example 2: Input: n = 1 Only one way to place a queen on 1x1 board. Output: 1 3. Approach – Backtracking with Column & Diagonal Constraints: This is almost identical to  N-Queens (51) , but we: Don’t need to build the actual board strings. Only need a  counter  of valid placements. We still: Place queens  row by row . Use three boolean arrays to track attacked lines: colUsed[c] – column c is under attack. diag1Used[row - col + n - 1] – main diagonal (...

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 ens...