Skip to main content

Posts

Leetcode 33: Search in Rotated Sorted Array

1. Problem Statement (Simple Explanation): You’re given: An array nums, originally  sorted in ascending order with distinct values . It has been  rotated  at some unknown index k (0 ≤ k < n). An integer target. The rotated array looks like: [nums[k], nums[k+1], ..., nums[n-1], nums[0], ..., nums[k-1]] You must: Return the index of target in nums if it exists. Otherwise, return -1. You must achieve  O(log n)  time → so you need a variant of  binary search . 2. Examples: Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 0 is at index 4. Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 3 is not in the array. Output: -1 Example 3: Input: nums = [1], target = 0 0 is not in the array. Output: -1 Constraints: 1 <= nums.length <= 5000 -10 4 <= nums[i] <= 10 4 All nums[i] are  unique . nums is sorted ascending then possibly rotated. -10 4 <=...
Recent posts

Leetcode 32: Longest Valid Parentheses

  1. Problem Statement (Simple Explanation): Yo u are given a string s containing only: '(' ')' You must return the  length  of the  longest valid (well-formed) parentheses substring . A valid substring must be contiguous. It must be a correct parentheses sequence (every '(' has a matching ')' in proper order). 2. Examples: Example 1: Input: s = "(()" Valid substrings: "()" (from index 1 to 2) – length 2 Longest length: 2 Output: 2 Example 2: Input: s = ")()())" Valid substrings: "()()" (from index 1 to 4) – length 4 "()" (from index 1 to 2) "()" (from index 3 to 4) Longest length: 4 Output: 4 Example 3: Input: s = "" No parentheses → no valid substring. Output: 0 Constraints: 0 ≤ ∣s∣ ≤ 3* 10 4 s[i] is '(' or ')'. 3. Approaches Overview: There are three classic approaches: Stack-based  –  O(n)  time,  O(n)  space. Two-pass counters (left-to-right and right-t...