Skip to main content

Posts

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

Leetcode 79: Word Search

  1. Problem Statement (Simple Explanation) You’re given: A 2D grid of characters board (size m x n). A string word. You must determine if word  exists  in the grid. Rules: The word must be constructed from letters of  sequentially adjacent cells . Adjacent cells are  horizontally or vertically  neighboring (no diagonals). The same cell cannot be used more than once  in a given word path. Return true if word exists in board, otherwise false. 2. Examples Example 1: Input: board = [   ["A","B","C","E"],   ["S","F","C","S"],   ["A","D","E","E"] ] word = "ABCCED" One possible path: (0,0)A → (0,1)B → (0,2)C → (1,2)C → (2,2)E → (2,1)D Output: true Example 2: Input: board = [   ["A","B","C","E"],   ["S","F","C","S"],   ["A","D","E","E"] ] word = ...