Skip to main content

Posts

Leetcode 81: Search in Rotated Sorted Array II

  1. Problem Statement (Simple Explanation) You’re given: A  rotated  array nums that was originally sorted in  non-decreasing  order. The array may contain  duplicates . An integer target. You must return: true if target exists in nums false otherwise. Rotation: Original sorted: e.g. [0,1,2,4,4,4,5,6,6,7] Rotated at pivot k: e.g. [4,5,6,6,7,0,1,2,4,4] Goal: Decrease operations as much as possible (use a  modified binary search ). 2. Examples Example 1: Input: nums = [2,5,6,0,0,1,2], target = 0 0 is in the array. Output: true Example 2: Input: nums = [2,5,6,0,0,1,2], target = 3 3 is not in the array. Output: false 3. Approach – Modified Binary Search (with duplicates) This is similar to  LeetCode 33  but now nums may contain  duplicates . Without duplicates: At each step we could tell which half is sorted and then decide which side to search. With duplicates, ...

Watson asks Does Permutation Exist

You need to  reorder  the array into some permutation B such that for every i: ∣ B i - B i+1 ∣≤1 We must decide if such a permutation exists. Key Insight If we  sort  the array to get C (non-decreasing order): In the sorted array, adjacent numbers are as close as possible. Any other permutation can only make  some adjacent differences bigger , never smaller. So: If the  sorted  array already has some adjacent pair with difference > 1, then  no permutation  can satisfy the condition. If the sorted array has  all  adjacent differences ≤ 1, then the sorted array itself is a valid permutation. Therefore, the check is simple: Sort the array. Check all adjacent pairs: If for any i, C[i+1] - C[i] > 1 → print NO. Otherwise → print YES. Algorithm For each test case: Read N and array A. Sort A. For i from 0 to N-2: If A[i+1] - A...

Leetcode 80: Remove Duplicates from Sorted Array II

  1. Problem Statement (Simple Explanation) You’re given a  sorted  integer array nums (non-decreasing). You must: Remove extra duplicates  in-place  so that  each unique value appears at most twice . Keep the  relative order  of elements. Put the result in the  first k positions  of nums. Return k (the new length). Anything beyond index k-1 can be ignored. Constraints: Do it in-place,  O(1)  extra memory. nums length up to 3 * 10 4 . 2. Examples Example 1: Input: nums = [1,1,1,2,2,3] Allowed counts: at most 2 of each number. Output: k = 5 nums becomes [1,1,2,2,3,_] (the _ denote “don’t care”). Explanation: 1 appears 3 times → keep 2. 2 appears 2 times → keep 2. 3 appears 1 time → keep 1. Example 2: Input: nums = [0,0,1,1,1,1,2,3,3] Output: k = 7 First 7 elements: [0,0,1,1,2,3,3,_,_] Explanation: 0 → keep [0,0] 1...