Skip to main content

Posts

Leetcode 57: Insert Interval

1. Problem Statement (Simple Explanation) You are given: A sorted array of  non-overlapping  intervals: intervals[i] = [start_i, end_i] sorted by start_i ascending. A new interval: newInterval = [start, end]. You must: Insert newInterval into intervals. Keep the array: sorted by start non-overlapping  (merge where necessary) Return the resulting list (you can allocate a new array). 2. Examples Example 1: Input: intervals = [[1,3],[6,9]] newInterval = [2,5] [1,3] and [2,5] overlap → merge into [1,5]. [6,9] does not overlap. Output: [[1,5],[6,9]] Example 2: Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]] newInterval = [4,8] Overlaps: [3,5] with [4,8] [6,7] with [4,8] [8,10] with [4,8] All merged into one interval [3,10]. Output: [[1,2],[3,10],[12,16]] 3. Approach – Linear Scan with Three Phases Since intervals is sorted and non-overlapping, we can insert and merge in  o...

Leetcode 56: Merge Intervals

1. Problem Statement (Simple Explanation) You’re given an array of intervals: intervals[i] = [start_i, end_i] You must: Merge all overlapping intervals . Return the resulting list of  non-overlapping intervals  that cover all intervals in the input. Two intervals [a,b] and [c,d]  overlap  if: c <= b   (i.e., start of the next is ≤ end of the current) Note: intervals touching at a point (like [1,4] and [4,5]) are considered overlapping and should be merged. 2. Examples Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] [1,3] and [2,6] overlap → merge to [1,6]. [8,10] and [15,18] do not overlap with others. Output: [[1,6],[8,10],[15,18]] Example 2: Input: intervals = [[1,4],[4,5]] [1,4] and [4,5] overlap (end of first equals start of second) → merge to [1,5]. Output: [[1,5]] Example 3: Input: intervals = [[4,7],[1,4]] After sorting → [[1,4], [4,7]], which overlap →...

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