Skip to main content

Posts

Leetcode 75: Sort Colors

1. Problem Statement (Simple Explanation) You’re given an array nums of length n, where each element is: 0 → red 1 → white 2 → blue You must  sort the array in-place  so that: all 0s come first, then all 1s, then all 2s No library sort is allowed. Goal: one pass, O(1) extra space. 2. Examples Example 1: Input: nums = [2,0,2,1,1,0] Output: [0,0,1,1,2,2] Example 2: Input: nums = [2,0,1] Output: [0,1,2] 3. Approach 1 – Counting (Two Passes, O(1) extra) Simple, but 2 passes: Count how many 0s, 1s, and 2s. Overwrite array: First count0 elements → 0 Next count1 elements → 1 Remaining count2 elements → 2 This is valid, O(n) time, O(1) space, but  two passes . 4. Approach 2 – Dutch National Flag (One Pass, O(1) extra) – Recommended We maintain three regions using pointers: low: boundary for the end of the 0-region. mid: current index scanning the array. high: boundary for the start of the 2-regi...

Leetcode 74: Search a 2D Matrix

1. Problem Statement (Simple Explanation) You’re given an m x n integer matrix with these properties: Each row is sorted in  non-decreasing  order. The first integer of each row is  greater than  the last integer of the previous row. This means if you read the matrix row by row, it behaves like a  sorted 1D array . You must determine if a given target exists in the matrix, and you must do it in: O(log(m * n))  // logarithmic in total number of elements Return true if target is found, otherwise false. 2. Examples Example 1: Input: matrix = [   [ 1,  3,  5,  7],   [10, 11, 16, 20],   [23, 30, 34, 60] ] target = 3 3 is present at (0,1). Output: true Example 2: Input: matrix = [   [ 1,  3,  5,  7],   [10, 11, 16, 20],   [23, 30, 34, 60] ] target = 13 13 is not in the matrix. Output: false 3. Approach – Binary Sear...

Maximum Expressions

  You’re given a string S containing digits 0–9 and operators '+' and '-', and it is a valid expression. You must  rearrange all characters  of S to form another  valid expression  that, when evaluated (left to right with normal arithmetic), has  maximum possible value . If multiple answers yield the same maximum value, any one is acceptable. Valid Expression Rules A string S is valid if: First character is  not  + or - (must be a digit). Last character is  not  + or - (must be a digit). No + or - are adjacent. ⇒ Operators strictly alternate with numbers. Numbers may have leading zeros; +0 and -0 are allowed. Core Idea We can rearrange  all characters  freely: Let total digit count be D. Let operator count (number of + and -) be O. For a valid expression, operators and numbers alt...