Skip to main content

Posts

Showing posts with the label software

Best Time to Buy and Sell Stock – LeetCode 121

Best Time to Buy and Sell Stock – LeetCode 121 (O(n) One-Pass Solution) The Best Time to Buy and Sell Stock problem from LeetCode 121 is a classic array and greedy problem frequently asked in coding interviews. The goal is to maximize profit by choosing a single day to buy and a later day to sell. Problem Statement You are given an array prices , where prices[i] represents the price of a stock on day i . You may complete at most one transaction (buy once and sell once). Input: prices = [7,1,5,3,6,4] Output: 5 Input: prices = [7,6,4,3,1] Output: 0 If no profit is possible, return 0 . Key Observations You must buy before you sell Only one transaction is allowed The selling day must come after the buying day Approach 1: Brute Force (Not Optimal) The brute force approach checks every possible pair of buying and selling days and calculates the profit. for i in range(n): for j in range(i+1, n): profit = max(profit, prices[j] - prices...

LeetCode 189: Rotate Array Explained (In-Place O(1) Space Solution)

Rotate Array – LeetCode 189 (In-Place O(1) Space Solution) The Rotate Array problem from LeetCode 189 is a classic array manipulation question frequently asked in coding interviews. The goal is to rotate an array to the right by k steps while modifying the array in-place . This problem helps build a strong understanding of array indexing, space optimization, and algorithmic thinking. Problem Statement Given an integer array nums , rotate the array to the right by k steps. The rotation must be done in-place, meaning no new array should be returned. Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Key Observations If k is greater than the array length, rotation repeats We can optimize using k = k % n Extra memory usage should be minimized Approach 1: Brute Force Rotation A simple solution is to move the last element to the front, repeating the process k times. class Solution: def rotate(self, nums, k): n = len(nums) ...

Majority Element in an Array

Majority Element in an Array Given an integer array nums of size n , the task is to find the majority element . A majority element is defined as the element that appears more than ⌊n / 2⌋ times in the array. It is guaranteed that the majority element always exists. Problem Example Input: nums = [3, 2, 3] Output: 3 Input: nums = [2,2,1,1,1,2,2] Output: 2 Approach 1: Using Counter (Easy to Understand) A straightforward approach is to count the frequency of each element and return the one with the maximum count. Python Code from collections import Counter class Solution: def majorityElement(self, nums): freq = Counter(nums) max_count = max(freq.values()) for key in freq: if freq[key] == max_count: return key Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) Although this solution is simple and readable, it us...

Soultion with intutions - #LeetCode 80 — Remove Duplicates from Sorted Array II

LeetCode 80 — Remove Duplicates from Sorted Array II 1) my first approach (Counter + new list) — why it fails the constraints this code correctly computes the desired result but violates the problem requirements: Uses extra memory: Counter(nums) and the temporary list n both use O(n) space. Not strictly in-place: The problem requires modifying nums in-place with O(1) extra space. Order risk: Using a frequency map is unnecessary and could break the required stable relative order depending on iteration (avoid it). from collections import Counter class Solution: def removeDuplicates(self, nums: List[int]) -> int: c = Counter(nums) n = [] for i in c: if c[i] >= 2: n.append(i) n.append(i) elif c[i] < 2: n.append(i) for i in range(len(n)): nums[i] = n[i] return len(n) 2) Optimal in-pla...

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

Introducing CodeMad: Your Ultimate Universal IDE with Custom Shortcuts

Introducing CodeMad: Your Ultimate Multi-Language IDE with Custom Shortcuts Welcome to the world of CodeMad, your all-in-one Integrated Development Environment (IDE) that simplifies coding and boosts productivity. Developed in Python, CodeMad is designed to make your coding experience smoother and more efficient across a variety of programming languages, including C, C++, Java, Python, and HTML. Whether you're a beginner or an experienced programmer, CodeMad is your go-to tool. In this blog, we'll dive deep into the workings of CodeMad, highlighting its unique features and easy installation process. The Power of Shortcuts CodeMad's intuitive interface is built around a set of powerful keyboard shortcuts that make coding a breeze. Here are some of the key shortcuts you'll find in CodeMad: Copy (Ctrl+C) : Duplicate text with ease. Paste (Ctrl+V) : Quickly insert copied content into your code. Undo (Ctrl+Z) and Redo (Ctrl+Y) : Correct mistakes and s...