Skip to main content

Posts

Showing posts with the label dsa

LeetCode 26 — Remove Duplicates from Sorted Array

LeetCode 26 — Remove Duplicates from Sorted Array 1)approach 1 (Using extra list — not optimal) Works correctly but uses extra space and has O(n²) behavior because if i not in uniques is an O(n) check for each element. class Solution: def removeDuplicates(self, nums: List[int]) -> int: uniques = [] for i in nums: if i not in uniques: uniques.append(i) k = len(uniques) for i in range(k): nums[i] = uniques[i] return k Complexity: Time O(n²), Space O(n). Not in-place as required by the problem. 2) Optimal two-pointer solution (Front write — O(n), O(1) space) This is the recommended in-place approach for a sorted array: keep a write pointer p that marks the last unique position. class Solution: def removeDuplicates(self, nums: List[int]) -> int: if not nums: return 0 p = 0 for i in range(1, len(nums)): ...

Solution: LeetCode 27 — Remove Element

LeetCode 27 — Remove Element Solution 1 (Optimal) This version is in-place, single-pass, O(n) time and O(1) space. It preserves the relative order of kept elements. class Solution: def removeElement(self, nums: List[int], val: int) -> int: p = 0 for i in nums: if i != val: nums[p] = i p += 1 return p Solution 2(Optimal) This version is in-place, single-pass, O(n) time and O(1) space. It preserves the relative order of kept elements. class Solution: def removeElement(self, nums: List[int], val: int) -> int: l, r = 0, len(nums) - 1 while l return l Common Mistakes Modifying the list while iterating with for x in nums plus remove or pop — this changes indices and skips elements. Returning the modified list instead of the new length . Trying to maintain order with an algorithm designed to minimize writes (e.g., two-pointer-swap) without noting that order...

LeetCode 88 Explained: Four Approaches, Mistakes, Fixes & the Final Optimal Python Solution

Evolving My Solution to “Merge Sorted Array” A practical, beginner-friendly walkthrough showing four versions of my code (from a naive approach to the optimal in-place two-pointer solution). Includes explanations, complexity and ready-to-paste code. Problem Summary You are given two sorted arrays: nums1 with size m + n (first m are valid) nums2 with size n Goal: Merge nums2 into nums1 in sorted order in-place . Version 1 — Beginner Approach (Extra List) I merged into a new list then copied back. Works, but not in-place and uses extra memory. class Solution: def merge(self, nums1, m, nums2, n): result = [] p1 = 0 p2 = 0 for _ in range(m+n): if p1 >= m: result.extend(nums2[p2:n]) break elif p2 >= n: result.extend(nums1[p1:m]) break elif nu...