Skip to main content

Posts

Leetcode 47: Permutations II

  1. Problem Statement (Simple Explanation): You’re given an array nums that  may contain duplicates . You must return  all unique permutations  of nums. The order of permutations in the output does not matter. 2. Examples: Example 1: Input: nums = [1,1,2] All permutations (with duplicates): [1,1,2] [1,2,1] [1,1,2] (duplicate) [1,2,1] (duplicate) [2,1,1] [2,1,1] (duplicate) Unique permutations: [   [1,1,2],   [1,2,1],   [2,1,1] ] Example 2: Input: nums = [1,2,3] All permutations are unique: [   [1,2,3],   [1,3,2],   [2,1,3],   [2,3,1],   [3,1,2],   [3,2,1] ] 3. Approach – Backtracking with Duplicate Handling: This is similar to Problem 46 (Permutations) but nums may contain duplicates, so naive permutation will produce duplicate lists. We need to  avoid generating duplicates  instead of removing them afterwards. Standard trick: sor...
Recent posts

Leetcode 46: Permutations

1. Problem Statement (Simple Explanation): You’re given an array nums of  distinct  integers. You must return  all possible permutations  of nums (all possible orderings). The answer can be returned in any order. 2. Examples: Example 1: Input: nums = [1,2,3] Output: [   [1,2,3],   [1,3,2],   [2,1,3],   [2,3,1],   [3,1,2],   [3,2,1] ] Example 2: Input: nums = [0,1] Output: [   [0,1],   [1,0] ] Example 3: Input: nums = [1] Output: [   [1] ] 3. Approach – Backtracking (DFS): This is a classic permutations problem. Intuition: We build permutations one position at a time: At each step, we choose one of the remaining unused numbers to place next. We continue until we have used all numbers → one complete permutation. Then we backtrack and try another choice. Since all integers in nums are distinct, we don’t need special duplicate handling. Two common im...

Leetcode 45: Jump Game II

1. Problem Statement (Simple Explanation): You are given: A 0-indexed array nums of length n. You start at index 0. Each nums[i] tells you the  maximum  forward jump length from index i: From i, you can jump to any index i + j such that: 0 <= j <= nums[i] i + j < n You must return the  minimum number of jumps  needed to reach  index n-1  (the last index). You are guaranteed that this is always possible. 2. Examples: Example 1: Input: nums = [2,3,1,1,4] One optimal strategy: From index 0 (value 2), you can reach indices 1 or 2. If you jump to index 1 (value 3), from there you can jump directly to index 4. Total jumps: 2. Output: 2 Example 2: Input: nums = [2,3,0,1,4] Again: From index 0, jump to index 1. From index 1, you can jump directly to index 4. Total jumps: 2. Output: 2 3. Intuition – Greedy "Level" / Inter...