Day 36 of LeetCoding everyday until I get a J-O-B: Search a 2D Matrix. Today’s secret: The Matrix is fake, and we need to escape it. You are given a grid of numbers and a target. Here is the truth LeetCode doesn't want you to know: If you look at the constraints, the end of one row connects perfectly to the start of the next. It’s not actually a 2D grid. It’s just a single, sorted 1D array that got folded up to intimidate you. The Strategy: The 1D Illusion Because it's technically sorted from top-left to bottom-right, we don't need two binary searches. We just do one. 1. The Bounds: Our pointers are 0 and (ROWS * COLS) - 1. 2. The Math Translation: We find our 1D mid index, but to check the actual value, we have to translate it back to a 2D coordinate: - row = mid // COLS - col = mid % COLS ⚠️ Python Pro-Tip (A Warning): Do NOT name your row variable r if your right pointer is also named r. You will overwrite your boundary, skip your target, and question the validity of your CS degree. Name them row and col. See more: https://lnkd.in/gUki2imQ #LeetCode #Python #BinarySearch #Algorithms #SoftwareEngineering #JobSearch
More Relevant Posts
-
🚀 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
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
-
-
🚀 Day 8 – DSA Daily Series Today’s Problem: Search Insert Position (LeetCode 35) Today I solved another interesting problem that uses the concept of Binary Search on a sorted array. 🧠 Problem Given a sorted array of distinct integers and a target value, return the index if the target is found. If the target is not found, return the index where it should be inserted to maintain the sorted order. Example: Input: nums = [1,3,5,6], target = 5 Output: 2 Example: Input: nums = [1,3,5,6], target = 2 Output: 1 💡 Approach I solved this using Binary Search. Steps followed: • Initialize two pointers low and high • Calculate the middle index mid • Compare nums[mid] with the target • If target is greater → move to the right half • If target is smaller → move to the left half • If not found, the low pointer gives the correct insert position ⏱ Complexity Time Complexity: O(log n) Space Complexity: O(1) 🔎 Key Learning Binary Search is not just for searching — it can also help determine the correct position to insert elements efficiently in a sorted array. Continuing the DSA Daily Series — improving problem-solving skills one problem at a time. 🚀 #DSA #LeetCode #Python #Algorithms #BinarySearch #CodingJourney
To view or add a comment, sign in
-
-
Binary Search on Rotated Arrays: Adapting Logarithmic Search to Broken Invariants Standard binary search requires sorted data. When an array is rotated (e.g., [4,5,6,7,0,1,2]), the sorted property breaks globally but persists locally — one half is always properly sorted. The adaptation: determine which half is sorted by comparing endpoints, then check if the target falls within that sorted range. This preserves O(log n) complexity despite the rotation disrupting global order. The Design Lesson: When invariants break, look for partial invariants. Here, global sorting is lost but local sorting remains. This "find the preserved property" approach applies broadly — searching in nearly-sorted data, handling corrupted indices with known structure, or working with time-series data with periodic gaps. The algorithm adapts to what guarantees still hold. Time: O(log n) | Space: O(1) #BinarySearch #AdaptiveAlgorithms #RotatedArrays #InvariantPreservation #Python #AlgorithmDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 9 – DSA Daily Series Today’s Problem: Merge Sorted Array (LeetCode 88) Today I solved an interesting problem that involves merging two sorted arrays efficiently. 🧠 Problem You are given two sorted arrays nums1 and nums2. nums1 has enough extra space at the end to hold elements from nums2. The goal is to merge both arrays into a single sorted array inside nums1. Example: Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] 💡 Approach Instead of creating a new array, I solved this using the two-pointer technique from the end. Steps followed: • Start pointers from the end of both arrays • Compare the elements from nums1 and nums2 • Place the larger element at the end of nums1 • Move the pointers accordingly until all elements are merged This approach avoids unnecessary shifting of elements. ⏱ Complexity Time Complexity: O(m + n) Space Complexity: O(1) 🔎 Key Learning Working from the end of the array is a smart trick that helps avoid overwriting elements while merging. Continuing the DSA Daily Series — improving problem-solving skills one problem at a time. 🚀 #DSA #LeetCode #Python #Algorithms #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Most people solve the Palindrome Number problem by converting the integer to a string and reversing it. It’s simple, readable, and honestly works perfectly in many real-world situations. But there’s another fast method that doesn’t use strings at all. Instead, you reverse the number mathematically — extracting digits one by one using division and modulo, then rebuilding the number in reverse order. This approach uses constant extra space and is often preferred in algorithm-focused environments. Both methods are efficient. The difference is mostly about tradeoffs: • String reversal → cleaner and more readable • Mathematical reversal → more optimal and lower-level Nice reminder that sometimes there’s a straightforward solution… and a slightly more “algorithmic” one — and knowing both makes you a stronger problem solver. 🚀 #Algorithms #ProblemSolving #Python #LeetCode #SoftwareEngineering
To view or add a comment, sign in
-
🧩 How Do YOU Solve This ❓ ❓ ❓ 👉 You must find the smallest missing positive integer in an unsorted array. 👉 Your Time Complexity must be O(n) and your Space Complexity O(1). 👉 No sorting allowed, no hash maps. Before coding, YOU must understand these key insights: 1️⃣ For an array of size n, the answer is always between 1 and n+1. This is crucial! 2️⃣ Use the array itself as storage: Since we know valid numbers are only 1 to n, we can use array indices as a "hash". Position 0 represents number 1, position 1 represents number 2, and so on. e.g: [1, 2, 3, 4, 5] => positions are: [0, 1, 2, 3, 4] 3️⃣ Clean before processing: Replace all invalid numbers (≤ 0 or > n) with n+1. They can't be the answer anyway. 4️⃣ Swap into place: Use a while loop to keep swapping each number to its correct position (number k goes to index k-1) until everything that can be placed is placed. 5️⃣ Scan through and return the first index where the expected number is missing. 💡 Making sure the while loop doesn't become O(n²). It stays O(n) because each number gets swapped at most once to its final position across the entire algorithm. #Python #AlgorithmPractice #ProblemSolving #CodingChallenge #DataStructures
To view or add a comment, sign in
-
-
🚀 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
-
-
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 78 of 100 Days LeetCode Challenge Problem: 🔹 #3110 – Score of a String 🔗 https://lnkd.in/g9jgxcdK Learning Journey: 🔹 Today’s problem involved calculating the score of a string based on the absolute differences between ASCII values of adjacent characters. 🔹 I iterated through the string starting from index 1 and computed the difference between the current and previous character using ord(). 🔹 For each pair, I added the absolute difference to a running total. 🔹 This approach efficiently accumulates the score in a single pass. Concepts Used: 🔹 String Traversal 🔹 ASCII Value Conversion (ord()) 🔹 Absolute Difference Calculation Key Insight: 🔹 The problem reduces to comparing adjacent elements, making it a straightforward linear scan. 🔹 Using ord() allows direct access to ASCII values, simplifying the computation. Complexity: 🔹 Time: O(n) 🔹 Space: O(1) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
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