🚀 DSA Day — Merge Two Sorted Arrays (LeetCode 88) Today I worked on a classic problem that looks simple but teaches an important optimization technique 👇 🔹 Problem Statement You are given two sorted arrays and need to merge them into one sorted array in-place. Example: nums1 = [1, 7, 8, 0, 0, 0], m = 3 nums2 = [2, 5, 6], n = 3 ✅ Output: [1, 2, 5, 6, 7, 8] 🔸 Approach 1: Brute Force ✔ Copy nums2 into nums1 ✔ Sort the entire array ⏱ Time Complexity: O((m+n) log(m+n)) 👉 Simple but not efficient 🔸 Approach 2: Optimized (Two Pointers) 💡 Key Idea: Start filling from the end ✔ Compare last elements of both arrays ✔ Place the larger one at the end ✔ Move pointers accordingly ⏱ Time Complexity: O(m+n) 📦 Space Complexity: O(1) 🔥 Why this works? Because nums1 already has extra space at the end — we use it smartly without shifting elements. 💻 Code Snippet (Optimized) https://lnkd.in/g9Z7yf3d def merge(nums1, m, nums2, n): i = m - 1 j = n - 1 k = m + n - 1 while i >= 0 and j >= 0: if nums1[i] > nums2[j]: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1 while j >= 0: nums1[k] = nums2[j] j -= 1 k -= 1 🎯 Key Takeaway 👉 Always think from the end when dealing with in-place array problems. #DSA #Python #CodingInterview #LeetCode #ProblemSolving #SoftwareEngineering #LearnInPublic
Merge Two Sorted Arrays in-place with Two Pointers
More Relevant Posts
-
🚀 Solved Another Sliding Window Problem on LeetCode! Today’s problem: Maximum Number of Vowels in a Substring of Given Length (LeetCode #1456) 💡 Problem Summary: Given a string s and an integer k, find the maximum number of vowels in any substring of length k. ❌ Brute Force Approach: Generate all substrings of size k Count vowels in each substring Time Complexity: O(n × k) → not efficient ✅ Optimized Approach: Sliding Window Instead of recalculating everything: Count vowels in the first window Slide the window forward: Add next character Remove previous character Track the maximum count 👉 Core Idea: count = count + new_char - old_char 💻 Clean Code: def maxVowels(s, k): vowels = set("aeiou") count = 0 for i in range(k): if s[i] in vowels: count += 1 max_count = count for i in range(k, len(s)): if s[i] in vowels: count += 1 if s[i - k] in vowels: count -= 1 max_count = max(max_count, count) return max_count ⚡ Complexity: Time: O(n) Space: O(1) 🧠 Key Takeaway: Sliding Window is not just a technique — it’s a mindset. You reuse previous computation instead of recalculating everything. 🔥 This pattern applies to: Strings & Arrays Substring / Subarray problems Real-world streaming data #DSA #LeetCode #Coding #SlidingWindow #InterviewPreparation #Python #ProblemSolving
To view or add a comment, sign in
-
-
💡 Cracking the Maximum Product Subarray Problem (Without Overcomplicating It) Today I worked on a classic DSA problem: Maximum Product Subarray — and found a simple yet powerful approach worth sharing. Most solutions focus on tracking max/min dynamically. But there’s a cleaner trick: 👉 Traverse the array from both directions (prefix & suffix) Why this works: Negative numbers can flip the product sign A single left-to-right pass might miss the optimal answer Scanning from both ends ensures we capture every possibility 🔁 Key Idea: Maintain two running products: Prefix (left → right) Suffix (right → left) Reset when product becomes 0 Track the maximum throughout ⚡ Complexity: Time: O(n) Space: O(1) Python code : https://lnkd.in/gZtCw9_i What I liked about this approach is its simplicity and elegance — no extra arrays, no complex state tracking. Sometimes, the best solutions aren’t the most complicated ones — just the most thoughtful. Have you tried solving this problem using a different approach? Would love to hear your thoughts 👇 #DataStructures #Algorithms #CodingInterview #Python #LeetCode #ProblemSolving Rajan Arora
To view or add a comment, sign in
-
-
Just solved “Reverse Words in a String” — and this time, I focused less on just getting it accepted and more on how clean and efficient my thinking is. 💡 My approach: Broke the problem into 3 simple steps: split → reverse → join Avoided manual looping once I realized Python already gives optimized built-ins Switched from constructing strings step-by-step (costly ⚠️) to using join() for better performance Used reversed() to keep the solution clean and readable ✨ Key learning: Sometimes optimization isn’t about writing more logic — it’s about writing less, but smarter. Leveraging built-in functions can significantly improve both readability and efficiency. 📈 Result: Runtime: 0 ms Cleaner code ✔️ Better understanding ✔️ Still learning, still improving — one problem at a time 🚀 #LeetCode #Python #DataStructures #CodingJourney #ProblemSolving #100DaysOfCode #TechGrowth #CodeOptimization #LearningInPublic #FutureEngineer #WomenInTech #ConsistencyWins
To view or add a comment, sign in
-
-
🔍 Debugging a Graph Problem: Longest Cycle in a Directed Graph Today I worked on an interesting problem — finding the longest cycle in a directed graph using DFS + cycle detection. Initially, my approach was correct, but I ran into errors due to small mistakes like: ❌ Typo in variable name (inCureentDfs) ❌ Wrong operator (. instead of -) ❌ Missing proper cycle detection handling After fixing them, the solution worked perfectly 🚀 💡 Key Concept: To detect a cycle and calculate its length: Use visited[] to track visited nodes Use inCurrentDfs[] to detect cycles Use dist[] to calculate cycle length 👉 Formula used: Cycle Length = dist[current] - dist[cycle_start] + 1 💻 Final Solution: class Solution: def longestCycle(self, V, edges): self.res = -1 self.next = [-1] * V for u, v in edges: if v != -1: self.next[u] = v self.visited = [False] * V self.dist = [0] * V self.inCurrentDfs = [False] * V def dfs(u): self.visited[u] = True self.inCurrentDfs[u] = True v = self.next[u] if v != -1: if not self.visited[v]: self.dist[v] = self.dist[u] + 1 dfs(v) elif self.inCurrentDfs[v]: self.res = max(self.res, self.dist[u] - self.dist[v] + 1) self.inCurrentDfs[u] = False for i in range(V): if not self.visited[i]: dfs(i) return self.res ✨ Learning: Sometimes, it's not about logic — it's about attention to detail. Small bugs can break the entire solution. #DataStructures #Algorithms #Python #CodingJourney #Debugging #GraphTheory #Learning
To view or add a comment, sign in
-
🚀 Minimum Cost to Connect All Houses | Prim’s Algorithm (MST) Today, I solved an interesting graph problem: 👉 How to connect all houses in a city with minimum cost? Each house is connected using Manhattan Distance, and the goal is to minimize the total cost. 💡 Approach Used: Prim’s Algorithm This problem is a classic application of Minimum Spanning Tree (MST). ✔️ Start from any house ✔️ Always connect the nearest unvisited house ✔️ Repeat until all houses are connected 📊 Visual Understanding (Diagram) Houses (Points): (0,0) ● -------- ● (2,2) \ / \ / ● (3,1) Step 1: Start from (0,0) Step 2: Connect nearest → (2,2) Step 3: Connect next nearest → (3,1) Final MST Connections: (0,0) —— (2,2) | (3,1) Minimum Cost = Sum of all edges 🧠 Key Concepts 🔹 Greedy Approach 🔹 Priority Queue (Min Heap) 🔹 Manhattan Distance = |x₁ - x₂| + |y₁ - y₂| 💻 Python Implementation import heapq class Solution: def minCost(self, houses): n = len(houses) visited = [False] * n minDist = [float('inf')] * n minDist[0] = 0 minHeap = [(0, 0)] total_cost = 0 while minHeap: cost, u = heapq.heappop(minHeap) if visited[u]: continue visited[u] = True total_cost += cost for v in range(n): if not visited[v]: new_dist = abs(houses[u][0] - houses[v][0]) + abs(houses[u][1] - houses[v][1]) if new_dist < minDist[v]: minDist[v] = new_dist heapq.heappush(minHeap, (new_dist, v)) return total_cost #DataStructures #Algorithms #Python #Coding #InterviewPrep #GraphTheory #LearningJourney
To view or add a comment, sign in
-
Day 64 of LeetCode Grind ⚡🔥 Two classic Medium problems today — both are interview must-knows and each teaches a pattern you'll reuse constantly. 1️⃣ Top K Frequent Elements (347) <<< return [x for x, _ in Counter(nums).most_common(k)] >>> * Counter.most_common(k) uses a heap internally to find top-k in O(n log k) — better than sorting which is O(n log n). Want true O(n)? Use Bucket Sort: > Create n+1 buckets indexed by frequency. > Elements with frequency f go into bucket[f]. > Scan buckets from highest frequency down, collect until you have k elements. > Since frequency can't exceed n, bucket index is bounded → pure O(n)! 2️⃣ Product of Array Except Self (238) > No division allowed. O(n). O(1) extra space. Classic prefix + suffix product pattern: * nums = [1, 2, 3, 4] * prefix = [1, 1, 2, 6] ← everything LEFT of i * suffix = [24, 12, 4, 1] ← everything RIGHT of i * result = [24, 12, 8, 6] ← multiply both * Two passes, one output array. The trick is reusing the result array itself — store prefix in the first pass, multiply suffix in-place on the second pass. ✨ Reflection: Both problems follow the same meta-pattern: precompute something so each query is O(1). Whether it's frequency counts or prefix products, the "precompute → combine" mindset is fundamental to efficient algorithm design. #LeetCode #Day64 #Python #PrefixProduct #BucketSort #HashMap #Arrays #Medium #100DaysOfCode #DSA
To view or add a comment, sign in
-
-
💡 From Brute Force to Optimal — My Approach to “Subarray Sum Equals K” Cracked this classic problem using an O(n) Prefix Sum + HashMap approach instead of the naive O(n²) brute force. 🔍 Key Idea: Maintain a running prefix sum p If p - k has been seen before, it means a valid subarray exists Store prefix sums in a hashmap with their frequencies ⚡ Why this works: Instead of checking all subarrays, we reuse previous computations to instantly detect valid sums — making it efficient and scalable. 🧠 What I learned: The real power of prefix sums How hashmaps convert time complexity Thinking in terms of patterns, not loops 📈 Result: Runtime: 28 ms (Beats 86% 🔥) Clean and optimized solution 💻 Code Mindset: “Don’t just solve — optimize your thinking.” #DataStructures #Algorithms #LeetCode #CodingJourney #Python #ProblemSolving #TechGrowth #WomenInTech #CodeNewbie #100DaysOfCode #CodingInterview #SoftwareEngineering #AIJourney #DeveloperMindset #CareerGrowth 🚀
To view or add a comment, sign in
-
-
built a research and notetaking agent in the weekend a quick context: the idea came from wanting to automate deep research into obsidian. so i wired together gemini cli, a few python scripts, and a well-written skill file that tells the agent exactly how to behave. you give it a topic, some urls, pdfs, or youtube links — it fetches everything, searches the web for more context, synthesizes across all sources, and writes structured notes directly into your obsidian vault. atomic notes, map of content, citations, mermaid mindmaps and more. the hard part wasn't the code. it was getting the agent to go deep instead of just dumping urls back at you. check it out: https://lnkd.in/gyKbGiBz let's keep building.
To view or add a comment, sign in
-
🚀 Day 10 of DSA Practice: Merge Two Sorted Arrays Today’s problem is a classic and super important for interviews 👇 🧩 Problem Given two sorted arrays, merge them into a single sorted array. 🔍 Example Input: Array 1: [1, 3, 5] Array 2: [2, 4, 6] Output: [1, 2, 3, 4, 5, 6] 💡 Approach 1: Two Pointers (Optimal) Since both arrays are already sorted, we can use a two-pointer technique. 👉 Compare elements from both arrays and pick the smaller one each time. ✅ Time Complexity: O(n + m) ✅ Space Complexity: O(n + m) def merge_sorted_arrays(arr1, arr2): i, j = 0, 0 merged = [] while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: merged.append(arr1[i]) i += 1 else: merged.append(arr2[j]) j += 1 # Add remaining elements merged.extend(arr1[i:]) merged.extend(arr2[j:]) return merged 💡 Approach 2: Using Built-in Sort (Not Optimal) Merge both arrays and then sort. ❌ Time Complexity: O((n+m) log(n+m)) def merge_sorted_arrays(arr1, arr2): return sorted(arr1 + arr2) ⚡ Key Takeaways ✔️ Two-pointer approach is efficient and interview-friendly ✔️ Works because arrays are already sorted ✔️ Foundation for advanced topics like merge sort #Python #CodingJourney #30DaysOfCode #LearnToCode #Programming #Developers #ProblemSolving #PythonBasics
To view or add a comment, sign in
-
I just built a fully working RAG (Retrieval-Augmented Generation) system from scratch. 🚀. Here's what it does and how: 𝗪𝗵𝗮𝘁 𝗶𝘁 𝗱𝗼𝗲𝘀: Upload any PDF → ask questions → get answers with cited sources 𝗛𝗼𝘄 𝗶𝘁 𝘄𝗼𝗿𝗸𝘀: 1. PDF is loaded and split into 500-character chunks 2. Each chunk is converted into embeddings (vectors) 3. Stored in ChromaDB — a vector database 4. At query time, the top 3 relevant chunks are retrieved 5. Chunks + question are sent to a local LLM 6. Answer returned with source citations 𝗡𝗼 𝗵𝗮𝗹𝗹𝘂𝗰𝗶𝗻𝗮𝘁𝗶𝗼𝗻: The LLM is explicitly instructed to answer only from the retrieved context. If the answer isn't in the document, it says so — no fabrication. 𝗧𝗲𝗰𝗵 𝘀𝘁𝗮𝗰𝗸: Python · LangChain · ChromaDB · Sentence Transformers · Ollama · Streamlit Runs fully locally — zero API costs. GitHub: https://lnkd.in/drfgqa-B #AIEngineering #RAG #Python #LLM #MachineLearning #BuildingInPublic
To view or add a comment, sign in
Explore related topics
- LeetCode Array Problem Solving Techniques
- Approaches to Array Problem Solving for Coding Interviews
- Leetcode Problem Solving Strategies
- How to Use Arrays in Software Development
- Solving Sorted Array Coding Challenges
- Common Algorithms for Coding Interviews
- How to Improve Array Iteration Performance in Code
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development