🚀 Day 35 of #100DaysOfCode — LeetCode + HackerRank Edition! Today’s challenge was all about merging two sorted arrays in-place — no extra space allowed, just clean pointer logic. 📌 Challenge: Merge nums2 into nums1, assuming nums1 has enough trailing space. The final array must be sorted — and the merge must happen in-place. 🔍 Approach: → Used a two-pointer strategy from the back to avoid overwriting values in nums1 → Compared the largest elements from both arrays and placed them at the end → Moved pointers backward (p1, p2, p) until all elements were merged → Handled edge cases like empty nums2 or all elements being smaller than nums1 → Avoided sorting after merge — the logic itself ensures order 💡 What made it click: → Realized that merging from the front causes overwrites — merging from the back preserves data → Visualized the pointer movement with a dry run — that helped me catch off-by-one bugs → Learned that in-place algorithms often rely on reverse traversal and smart indexing 📚 What I learned: ✅ Two-pointer techniques are powerful for in-place operations ✅ Always think about overwrite risks when merging arrays ✅ Dry runs and visual walkthroughs are key to debugging pointer logic Have you tried merging sorted arrays in-place before? Did you use reverse traversal or a different trick? Let’s swap strategies 💬 #Day35 #LeetCode #ArrayProblems #TwoPointerTechnique #ProblemSolving #Python #DebuggingJourney #CleanCode #LearnToCode #CodeNewbie #SoftwareEngineering #TechJourney #100DaysOfCode
Merging sorted arrays in-place with two pointers
More Relevant Posts
-
🚀 Day 32 of #100DaysOfCode — LeetCode + HackerRank Edition! Today’s challenge was all about frequency mapping and subarray logic — solving the Picking Numbers problem from HackerRank. 🔗 Problem: pickingNumbers(a) (HackerRank) 📌 Challenge: Given an array of integers, find the length of the longest subarray where the absolute difference between any two elements is ≤ 1. 🔍 Approach: → Used Python’s Counter to map frequencies of each number → For each number num, calculated freq[num] + freq[num + 1] → Tracked the maximum such sum to find the longest valid subarray → Avoided brute-force by leveraging frequency patterns instead of scanning all subarrays 💡 What made it click: → Realized that valid subarrays must contain only num and num + 1 → Frequency mapping reveals hidden structure in the data → Clean logic with max() and get() made the solution elegant and readable 📚 What I learned: ✅ Frequency-based thinking can simplify subarray problems ✅ Counter is a powerful tool for pattern detection ✅ Avoiding brute-force leads to scalable, efficient solutions ✅ Sharing dry runs and visual walkthroughs helps others grasp the intuition faster Have you tackled Picking Numbers before? Did you go with sorting, brute-force, or frequency mapping like I did? Let’s swap strategies 💬 #Day31 #HackerRank #SubarrayLogic #FrequencyMapping #Python #ProblemSolving #CleanCode #CodeEveryDay #LearnToCode #CodeNewbie #SoftwareEngineering #TechJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 26 of #100DaysOfCode — LeetCode + HackerRank Edition! Today’s challenge was all about string precision and pattern matching: 🔗 Implement strStr() (LeetCode) 📌 Challenge: Given two strings haystack and needle, return the index of the first occurrence of needle in haystack, or -1 if it doesn’t exist. 🔍 Approach: → Skipped the built-in .find() to implement it manually → Iterated through haystack only up to len(haystack) - len(needle) → Compared slices haystack[i:i+len(needle)] with needle → Returned the index on match, -1 otherwise 💡 What made it click: → Realized that checking every possible starting index is enough — no need to build substrings manually → Adjusting the loop range to avoid out-of-bound errors was the key → Removing redundant checks like if needle not in haystack made the code cleaner and faster 📚 What I learned: ✅ Substring search is a great intro to sliding window logic ✅ Clean loop bounds = fewer bugs ✅ Sometimes the simplest approach is the most elegant ✅ Writing your own version of built-ins deepens your understanding of how they work under the hood Have you implemented your own strStr() before? Did you go brute-force or try KMP? Let’s compare strategies 💬🔍 #Day26 #LeetCode #StringMatching #CodingChallenge #Python #ProblemSolving #CleanCode #CodeEveryDay #LearnToCode #CodeNewbie #SoftwareEngineering #TechJourney #geeksforgeeks #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 29 of #100DaysOfCode — LeetCode + HackerRank Edition! Today’s challenge was all about precision and pattern matching — and I stuck to the essentials. 🔗 Problem: findSubstring(s, words) (LeetCode) 📌 Challenge: Given a string s and a list of words (all the same length), find all starting indices where the concatenation of all words appears exactly once and without overlap. 🔍 Approach: → Calculated the total length of the target substring using len(words[0]) * len(words) → Built a frequency map using Counter(words) → Used a sliding window of size total_len to scan through s → At each position, extracted word-sized chunks and tracked their frequency → Compared the seen map with the original word_count to validate matches → Appended valid starting indices to the result list 💡 What made it click: → Realized that permutations aren’t necessary — just match word frequencies → Stepping through s in word-sized chunks keeps the logic clean and efficient → Using Counter for both the target and current window made comparison seamless 📚 What I learned: ✅ Frequency maps are a powerful alternative to brute-force approaches ✅ Matching dictionaries directly (seen == word_count) is a validation trick ✅ Clean logic and early breaks make the code both readable and performant Have you solved findSubstring before? Did you go with permutations or lean into frequency maps like I did? Let’s swap strategies 💬 #Day29 #LeetCode #SlidingWindow #StringAlgorithms #Python #ProblemSolving #CleanCode #CodeEveryDay #LearnToCode #CodeNewbie #SoftwareEngineering #TechJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 52 of #100DaysOfCode — Leetcode + HackerRank Edition! Today’s challenge was all about bringing order to chaos — merging overlapping intervals into clean, non-overlapping ranges 🗂️✨ 🧩 def merge(self, intervals: List[List[int]]) -> List[List[int]]: — Combine overlapping intervals into a simplified list 📌 Challenge: → Implement a function to merge overlapping intervals → Avoid brute-force approaches that check every pair → Optimize for clarity and performance 🔍 Approach: → First, sort intervals by their start time → Keep track of the last merged interval (prev[0]) → If the current interval overlaps, extend the end boundary → Otherwise, add it as a new interval 💡 What made it click: → Realized sorting upfront makes merging straightforward → Saw how prev[1] = max(prev[1], interval[i][1]) elegantly handles overlaps → Practiced dry runs with examples like: [[1,3],[2,6],[8,10],[15,18]] → [[1,6],[8,10],[15,18]] 📚 What I learned: ✅ Why sorting is the key to simplifying interval problems ✅ How greedy merging avoids unnecessary comparisons ✅ How to handle edge cases like single intervals or fully nested ranges Ever felt like your calendar was a mess of overlapping meetings? This algorithm is the perfect organizer 🗓️😎 Let’s swap dry runs, edge cases, and interval insights 💬 #Day51 #Leetcode #Python #MergeIntervals #GreedyAlgorithm #DryRun #LearnInPublic #CodeNewbie #TechJourney #100DaysOfCode #DSA
To view or add a comment, sign in
-
-
🚀 Day 31 of #100DaysOfCode — LeetCode + HackerRank Edition! Today’s challenge was all about tracking structure and resilience — decoding the longest valid parentheses substring in a given string. 🔗 Problem: longestValidParentheses(s) (LeetCode) 📌 Challenge: Given a string of '(' and ')', find the length of the longest well-formed (valid) parentheses substring. 🔍 Approach: → Used a stack to track indices of unmatched '(' characters → Introduced a base index to reset when encountering unmatched ')' → On each valid match, calculated the distance to the last unmatched index → Continuously updated the maximum valid length found so far 💡 What made it click: → Realized that tracking indices, not just characters, is key to measuring valid spans → Using stack[-1] after a pop gives the start of the current valid substring → Resetting with a base index ensures recovery after mismatches 📚 What I learned: ✅ Stack-based tracking is powerful for nested structures ✅ Index math reveals patterns that raw character matching misses ✅ Defensive coding (checking if stack is empty) prevents crashes and improves robustness ✅ Visual walkthroughs and guided hints make debugging intuitive and rewarding Have you tackled longestValidParentheses before? Did you go with dynamic programming, two-pass scanning, or stack-based logic like I did? Let’s swap strategies 💬 #Day30 #LeetCode #StackAlgorithms #ParenthesesMatching #Python #ProblemSolving #CleanCode #CodeEveryDay #LearnToCode #CodeNewbie #SoftwareEngineering #TechJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 46 of #100DaysOfCode — Leetcode + HackerRank Edition! Today’s challenge was a twist on yesterday’s recursion puzzle — this time with duplicates in the mix 🔁🧠 🧩 permuteUnique(self, nums: List[int]) -> List[List[int]] — Generate all unique permutations of a list that may contain duplicate integers. 📌 Challenge: → Given a list nums, return all distinct orderings → Each number must appear exactly once per permutation → Example: nums = [1, 1, 2] ✅ Output: [[1,1,2], [1,2,1], [2,1,1]] 🔍 Approach: → Sort the input to group duplicates → Use recursion + backtracking to build paths → Track visited indices with a used[] array → Skip duplicates using: if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: continue → Backtrack by popping the last element and resetting used[i] 💡 What made it click: → Visualized the decision tree for [1, 1, 2] — saw how pruning avoids duplicate branches → Practiced dry runs to trace how used[] and sorting work together → Realized how skipping nums[i] when nums[i] == nums[i-1] and used[i-1] == False prevents redundant paths → Appreciated how recursion + pruning = clean, efficient, elegant 📚 What I learned: ✅ How to handle duplicates in permutation problems ✅ How sorting + index tracking helps prune recursion ✅ How to visualize branching decisions and avoid redundant paths ✅ The subtle power of used[] and index-based duplicate checks Have you ever debugged a recursive tree with duplicate values? Let’s swap strategies, dry runs, and visual walkthroughs 💬 #Day46 #Leetcode #Python #Recursion #Backtracking #DryRun #LearnInPublic #CodeNewbie #TechJourney #100DaysOfCode #DSA
To view or add a comment, sign in
-
-
Day 33 / 100 – Maximum Average Subarray (LeetCode #643) Today’s challenge was about finding a contiguous subarray of length k with the maximum average. At first glance, it seems simple, but the key is doing it efficiently. By using a sliding window, I avoided recalculating sums for every subarray, which makes the solution both fast and elegant. This problem reminded me that small optimizations in logic can lead to huge improvements in performance, and thinking carefully about how to structure your solution is just as important as solving the problem itself. 🔍 Key Learnings Sliding window technique updates the sum in constant time for each step. Keeping track of the maximum sum while iterating avoids unnecessary computations. Always ensure floating-point division for correct average calculations. 💭 Thought of the Day Efficiency in coding comes from thinking smart, not from brute force. Sliding window allowed me to write clean and readable solutions while handling all edge cases. Today reinforced that solving problems isn’t just about getting a correct answer — it’s about writing solutions that are elegant, efficient, and scalable. 🔗 Problem Link:https://lnkd.in/gCVb4_pu #100DaysOfCode #Day33 #LeetCode #Python #SlidingWindow #ProblemSolving #Algorithms #DataStructures #CodingChallenge #CodeEveryday #LearningJourney #TechGrowth #Efficiency #CleanCode #PythonProgramming
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 101 Problem: Maximum Number of Operations on Binary String ⚙️💡 This problem was an elegant mix of string traversal and logical counting, where understanding the movement of '1's relative to '0's was key to finding the optimal number of operations. 🧠 Problem Summary: You are given a binary string s. You can repeatedly perform the following operation: Choose an index i where s[i] == '1' and s[i + 1] == '0'. Move '1' right until it reaches the end or another '1'. Your goal → Return the maximum number of operations that can be performed. ⚙️ My Approach: 1️⃣ Traverse the string from left to right. 2️⃣ Maintain two counters: ones → counts the number of '1's encountered so far. res → stores the total number of operations. 3️⃣ Every time a '0' is found after some '1's, we can perform operations equal to the number of '1's seen so far. 4️⃣ Continue counting consecutive zeros and repeat the process. 💡 Why This Works: Each '1' can “influence” all the zeros that appear after it — moving right across them. Hence, for every block of zeros, we add all previously counted ones to our result. 📈 Complexity Analysis: Time Complexity: O(n) → Single pass through the string. Space Complexity: O(1) → Constant extra space. ✨ Key Takeaway: Sometimes, all it takes is counting relationships instead of simulating moves — a simple greedy insight leading to an optimal O(n) solution. ⚡ 🔖 #DSA #100DaysOfCode #Day101 #LeetCode #ProblemSolving #GreedyAlgorithm #StringManipulation #Python #CodingChallenge #TechCommunity #EfficientCode #LearnByDoing
To view or add a comment, sign in
-
-
🚀 Product of Array Except Self — LeetCode #238 Today, I solved one of the most elegant problems in array manipulation — “Product of Array Except Self.” 🧩 Problem in short: Given an integer array nums, return an array answer such that answer[i] equals the product of all numbers in nums except nums[i], ✅ Without using division ✅ In O(n) time ✅ With O(1) extra space 💡 Key Insight — Prefix & Suffix Products Instead of recalculating every product, the trick is to use two passes: First pass: Store the product of all elements before each index (prefix). Second pass: Multiply each element by the product of all elements after it (suffix). This way, each position in the output represents the product of all other elements — efficiently and elegantly. ⚙️ Complexity Time: O(n) Space: O(1) (excluding the result array) 📊 Result ✅ Accepted — Runtime: 20 ms ⚡ Beats 74.21% in performance and 55.22% in memory usage Every problem like this reinforces one key principle: In interviews (and real-world problems), pattern recognition always beats rote memorization. This one beautifully highlights the Prefix–Suffix Pattern, seen in problems like Trapping Rain Water and Subarray Product. #LeetCode #DSA #CodingInterview #Python #Arrays #PrefixSuffix #ProblemSolving
To view or add a comment, sign in
-
-
🚀 DSA Progress – Day 100 ✅ Problem #1371: Find the Longest Substring Containing Even Counts of Vowels 🧠 Difficulty: Medium | Topics: String, Bitmasking, HashMap, Prefix State Tracking 🔍 Approach: Implemented a bitmask + hashmap based solution to efficiently track the parity (even/odd) of vowel occurrences while traversing the string. Step 1 (Vowel Encoding): Each vowel (a, e, i, o, u) is assigned a specific bit position in a 5-bit integer mask. Example: a → bit 0, e → bit 1, i → bit 2, o → bit 3, u → bit 4 Step 2 (Bit Flipping): While iterating through the string, flip (XOR) the corresponding bit when a vowel is found: mask ^= (1 << bit_position) This keeps track of whether each vowel has appeared an even or odd number of times. Step 3 (State Tracking with HashMap): Use a dictionary to store the first occurrence of every mask state. If the same mask is seen again, it means the substring between those indices has even counts for all vowels. Step 4 (Result Calculation): For each repeated mask, calculate the substring length i - mp[mask] and keep track of the maximum. This approach smartly transforms the problem into a state parity tracking problem, making it efficient and clean. 🕒 Time Complexity: O(n) → Single traversal of the string 💾 Space Complexity: O(32) → Only 32 possible vowel parity states (2^5) 📁 File: https://lnkd.in/gx-_Trp6 📚 Repo: https://lnkd.in/g8Cn-EwH 💡 Learned: This problem strengthened my understanding of bitmasking and prefix-based logic. I learned how to represent multiple binary conditions using a single integer mask and efficiently find substring properties using hashmaps. It was a great example of combining bit operations with string traversal for optimized solutions. ✅ Day 100 complete — balanced vowels and flipped bits like a pro! ⚙️🔠✨ #LeetCode #DSA #Python #Bitmasking #HashMap #String #PrefixSum #100DaysOfCode #DailyCoding #InterviewPrep #GitHub #LeetCode1371
To view or add a comment, sign in
Explore related topics
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