Skip to main content

Posts

Leetcode 55: Jump Game

1. Problem Statement (Simple Explanation): You’re given an integer array nums where: You start at index 0. Each nums[i] is the  maximum jump length  from position i. From index i, you can jump to any index j such that: i < j <= i + nums[i] You must determine: Return true  if you can reach the  last index  (n - 1). Otherwise  return false . 2. Examples: Example 1: Input: nums = [2,3,1,1,4] Possible path: Start at index 0 (nums[0] = 2): Jump to index 1. From index 1 (nums[1] = 3): Jump directly to index 4 (last index). You can reach the last index ⇒ true. Output: true Example 2: Input: nums = [3,2,1,0,4] Start at index 0: can reach indices 1, 2, or 3. No matter what path you choose, eventually you end at index 3 (nums[3] = 0) → you cannot move further. Index 4 is unreachable. Output: false 3. Approach – Greedy (O(n), Optimal): We want to know if we can “cover” the path to the last index using ...

Leetcode 54: Spiral Matrix

  1. Problem Statement (Simple Explanation): You’re given an m x n matrix. You must return all elements in  spiral order , starting from the top-left corner and spiraling: Right → down → left → up → and so on, layer by layer. 2. Examples: Example 1: Input: matrix = [   [1,2,3],   [4,5,6],   [7,8,9] ] Spiral order: 1 → 2 → 3 → 6 → 9 → 8 → 7 → 4 → 5 Output: [1,2,3,6,9,8,7,4,5] Example 2: Input: matrix = [   [1, 2, 3, 4],   [5, 6, 7, 8],   [9,10,11,12] ] Spiral order: 1 → 2 → 3 → 4 → 8 → 12 → 11 → 10 → 9 → 5 → 6 → 7 Output: [1,2,3,4,8,12,11,10,9,5,6,7] 3. Approach – Boundary Tracking (Layer by Layer): We can simulate walking around the matrix in layers, maintaining four boundaries: top – index of current top row not yet traversed. bottom – index of current bottom row not yet traversed. left – index of current left column not yet traversed. right – index of current right column not yet traver...

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