🚀 #100DaysOfCode – Day 16 | DSA Practice Continuing my 100 Days Data Structures and Algorithms challenge, today I solved a popular problem based on arrays and two-pointer technique. 📌 Problem: Move Zeroes Given an integer array nums, move all 0’s to the end while maintaining the relative order of non-zero elements. The operation must be done in-place. Example: Input: nums = [0,1,0,3,12] Output → [1,3,12,0,0] 🧠 Approach / Logic: 1️⃣ Use two pointers: • i → to traverse the array • j → to track the position for non-zero elements 2️⃣ Traverse the array from left to right. 3️⃣ If the current element is non-zero, swap it with the element at index j. 4️⃣ Increment j to point to the next position. 5️⃣ Continue this process for the entire array. 6️⃣ At the end, all non-zero elements will be at the front, and all zeros will be shifted to the end. 📊 Time Complexity: O(n) 📦 Space Complexity: O(1) 🎯 Key Learning: This problem demonstrates how the two-pointer technique can efficiently solve in-place array problems while maintaining order. Consistency is the key to growth. Let’s keep improving every day! 💪 #100DaysOfCode #DSA #CodingJourney #ProblemSolving #CPP #LearningInPublic
Moving Zeroes to End with Two Pointer Technique
More Relevant Posts
-
Day 16/50 – DSA Challenge Today was about designing something smarter, not just solving. ->Min Stack This problem looks simple… until you realize: “getMin() must be O(1)” That’s where the real thinking starts. What I learned today: • Using an extra stack to track minimums is a design decision, not just coding • Every push/pop must maintain consistency between two stacks • This problem is less about loops and more about data structure design Key Insight: Good programmers solve problems. Better programmers design systems that make problems easier. ⚙️ From brute force → optimized → now smart data structure design That’s real progress. #DSA #LeetCode #DataStructures #CodingJourney #KeepLearning
To view or add a comment, sign in
-
-
🚀 #100DaysOfCode – Day 17 | DSA Practice Continuing my 100 Days Data Structures and Algorithms challenge, today I solved a very important problem based on arrays and the Dutch National Flag Algorithm. 📌 Problem: Sort Colors Given an array nums containing only 0, 1, and 2, sort the array in-place so that all 0’s, 1’s, and 2’s are grouped together in order. Example: Input: nums = [2,0,2,1,1,0] Output → [0,0,1,1,2,2] 🧠 Approach / Logic: 1️⃣ Use three pointers: • low → for placing 0’s • mid → to traverse the array • high → for placing 2’s 2️⃣ Traverse the array while mid <= high. 3️⃣ If the current element is: • 0 → swap with low, move both low and mid forward • 1 → just move mid forward • 2 → swap with high, move high backward 4️⃣ Continue this process until the entire array is sorted. 📊 Time Complexity: O(n) 📦 Space Complexity: O(1) 🎯 Key Learning: This problem demonstrates the power of the Dutch National Flag Algorithm, which helps sort elements efficiently in a single pass without extra space. Consistency is the key to growth. Let’s keep improving every day! 💪 #100DaysOfCode #DSA #CodingJourney #ProblemSolving #CPP #LearningInPublic
To view or add a comment, sign in
-
-
🚀 #100DaysOfCode – Day 15 | DSA Practice Continuing my 100 Days Data Structures and Algorithms challenge, today I solved an interesting problem based on numbers and digit manipulation. 📌 Problem: Check if The Number is Fascinating Given a 3-digit number n, we need to check whether it is fascinating or not. A number is called fascinating if: 👉 Concatenate n, 2*n, and 3*n 👉 The resulting number contains all digits from 1 to 9 exactly once 👉 It should not contain 0 Example: Input: n = 192 Concatenation → 192384576 Output → true 🧠 Approach / Logic: 1️⃣ Convert the numbers n, 2*n, and 3*n into strings and concatenate them. 2️⃣ Check if the total length of the string is 9. 3️⃣ Traverse the string and count the frequency of each digit. 4️⃣ If any digit is 0, return false. 5️⃣ Ensure each digit from 1 to 9 appears exactly once. 6️⃣ If all conditions are satisfied, the number is fascinating. 📊 Time Complexity: O(1) 📦 Space Complexity: O(1) 🎯 Key Learning: This problem highlights how string manipulation and frequency counting can be used to validate patterns in numbers. Consistency is the key to growth. Let’s keep improving every day! 💪 #100DaysOfCode #DSA #CodingJourney #ProblemSolving #CPP #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 114 of My DSA Problem Solving Journey - The Grind Continues! 🎉 After tackling some quick string manipulation yesterday, today I shifted gears to Stack data structures! I took on LeetCode's "Min Stack" (Medium) in C++. The Problem: We need to design a custom stack that supports the usual operations (push, pop, top) BUT with a catch—we also need to retrieve the minimum element in constant O(1) time! My Approach: The tricky part is figuring out how to get the minimum value instantly without scanning the entire stack. To achieve this, I used a classic Two-Stack Approach. 🧠 The Logic: Two Stacks: I initialized a main stack (st) to store all the elements and an auxiliary stack (minSt) specifically to keep track of the minimum values at any given point. Push Operation: When pushing a new value, it always goes into the main stack. If the minSt is empty, OR if the new value is less than or equal to the current minimum (the top element of minSt), I push it onto minSt as well. Pop Operation: When popping, I check if the element being removed from the main stack is exactly the same as the current minimum at the top of the auxiliary stack. If it matches, I pop it from both stacks! Otherwise, just pop from the main stack. Retrieving Min: Because of how we maintained the auxiliary stack, calling getMin() is as simple as returning the top value of minSt. Zero searching required! Takeaway: This problem is a brilliant example of a Space-Time Tradeoff. By sacrificing a little bit of memory to maintain a second stack, we successfully optimized our time complexity to a strict O(1) for every single operation! ⚡ Keep pushing! 💻🔥 #Day114 #CPP #Stack #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices
To view or add a comment, sign in
-
-
💡 “In DSA, the hardest problems often become simple when you transform them into a familiar pattern.” 🚀 #geekstreak60 — Day 39 Day 39 of the streak! Today’s problem was a great example of how mathematical transformation + dynamic programming can simplify a complex problem. 📌 Problem Statement Given an array and an integer diff, the task was to count the number of ways to partition the array into two subsets such that: ➡️ Difference of subset sums = diff 🧠 My Thought Process At first, directly trying all partitions would be inefficient (exponential complexity). Then came the key transformation: Let: S1 = sum of subset 1 S2 = sum of subset 2 We know: S1 - S2 = diff S1 + S2 = totalSum Solving both: 👉 S1 = (totalSum + diff) / 2 🛠️ Optimized Approach The problem reduces to: ✅ Count number of subsets with sum = target Where: target = (totalSum + diff) / 2 Then applied Dynamic Programming (subset sum counting). ⚡ Complexity Analysis Time Complexity: O(n × target) Space Complexity: O(target) Efficient for given constraints. 💡 Key Learning Many DP problems become easier once you convert them into subset sum problems. Today strengthened my understanding of: ✅ Problem transformation techniques ✅ Subset sum DP ✅ Counting-based DP ✅ Optimizing exponential solutions Consistency continues strong 💪 #geekstreak60 #npci #DSA #CPP #DynamicProgramming #ProblemSolving #CodingJourney #ContinuousLearning
To view or add a comment, sign in
-
-
🚀 Day 119 of My DSA Problem Solving Journey - The Grind Continues! 🎉 Today, I tackled an interesting array problem on LeetCode: "Split the Array" in C++. The Problem: We are given an even-length integer array. The goal is to split this array into two equal halves (nums1 and nums2) such that both arrays contain strictly distinct elements. If it's possible, we return true; otherwise, false. My Approach: Instead of sorting or using complex logic, I used an unordered_map to keep track of element frequencies. It's clean, efficient, and gets the job done perfectly! The Logic: Frequency Counting: I iterated through the entire array and stored the frequency of each number using the hash map. The Core Rule: For both nums1 and nums2 to have strictly distinct elements, a specific number can appear a maximum of two times in the entire array (one copy goes to nums1, and the other to nums2). Validation: I looped through the hash map. If any element's frequency is strictly greater than 2, it's impossible to distribute them without creating duplicates in one of the halves. In that case, I immediately return false. If the loop finishes without finding any frequency greater than 2, the split is totally possible, so I return true. Takeaway: Hash maps are incredibly powerful for tracking occurrences and solving frequency-based problems. This approach keeps the time complexity at an optimal O(N) and space complexity at O(N). Keep it simple and logical! ⚡ Keep pushing! 💻🔥 #Day119 #CPP #Arrays #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices
To view or add a comment, sign in
-
-
💡 “In DSA, the beauty lies in finding simple formulas that solve complex patterns.” 🚀 #geekstreak60 — Day 45 Day 45 of the streak! Today’s problem was a perfect mix of bit manipulation and pattern recognition, introducing the elegant concept of Gray Code. 📌 Problem Statement Given an integer n, generate all binary strings of length n such that: ✅ Each successive string differs by exactly one bit ✅ The sequence starts from "0...0" 🧠 My Thought Process At first, generating all binary strings is easy — but ensuring that: Every consecutive pair differs by only one bit is the real challenge. Then I came across the key insight: 👉 Use the formula: gray = i ^ (i >> 1) This guarantees that each number differs from the previous one by only one bit. 🛠️ Optimized Approach ✅ Iterated from 0 to 2ⁿ - 1 ✅ Generated Gray code using bit manipulation ✅ Converted each number to binary string of length n ⚡ Complexity Analysis Time Complexity: O(2ⁿ × n) Space Complexity: O(2ⁿ) Efficient for n ≤ 16. 💡 Key Learning Bit manipulation can turn complex sequence constraints into simple mathematical expressions. Today strengthened my understanding of: ✅ Gray code generation ✅ Bitwise operations (^, >>) ✅ Pattern-based problem solving ✅ Writing efficient and elegant solutions Consistency continues strong 💪🔥 #geekstreak60 #npci #DSA #CPP #BitManipulation #ProblemSolving #CodingJourney #ContinuousLearning
To view or add a comment, sign in
-
-
Week 2 of My DSA Pattern Revision — Two Pointers & Sliding Window 🔁 Most array and string problems initially look like they require O(n²) solutions. But with the right approach, many of them can be optimized to O(n). This week, I focused on two powerful techniques that help achieve this: 👉 Two Pointers 👉 Sliding Window Hello everyone 👋 I’m continuing my pattern-wise revision of Data Structures & Algorithms, inspired by the structured A2Z DSA roadmap by Raj Vikramaditya (Striver). The goal remains the same: 👉 Focus on recognizing patterns, not memorizing solutions. 🔍 What I Covered This Week 1️⃣ Two Pointer Technique Used when we process elements from multiple positions simultaneously. 👉 Core idea: Move pointers based on conditions to reduce unnecessary comparisons. Must-Try Problems • Two Sum (Sorted Array) • Container With Most Water • Remove Duplicates from Sorted Array • 3Sum 2️⃣ Sliding Window — Fixed Size Used when the window size is constant. 👉 Core idea: Slide the window by removing the left element and adding the next right element. Must-Try Problems • Maximum Sum Subarray of Size K 3️⃣ Sliding Window — Variable Size (Most Important) Used when the window size is dynamic. 👉 Pattern: while(condition breaks) shrink window; expand window; 👉 Core idea: Expand to explore, shrink to maintain validity. Must-Try Problems • Longest Substring Without Repeating Characters • Longest Repeating Character Replacement • Minimum Window Substring 🧠 How I Identify These Patterns Over time, I noticed some strong signals: ✔ Contiguous subarray / substring ✔ Need optimal (max/min length or count) ✔ Brute force is too slow (O(n²)) ✔ Sorted array → Two Pointer ✔ Dynamic window → Sliding Window 💡 Key Insights 👉 Two Pointers help convert O(n²) → O(n) by eliminating redundant comparisons 👉 Sliding Window avoids recomputation by reusing previous window calculations 👉 Golden Rule: expand → check → shrink → repeat 🚀 GitHub Repository I’ve implemented all these problems in C++ with explanations: 🔗 https://lnkd.in/gCMuX_zX #DSA #Algorithms #TwoPointers #SlidingWindow #LeetCode #CodingInterview #ProblemSolving #Pattern #A2Z
To view or add a comment, sign in
-
-
Day 22 Today I solved “Missing Number” on LeetCode. The problem is to find the missing number from an array containing distinct numbers in the range [0, n]. At first, we might think of sorting or using a HashSet — but there’s a more elegant approach. 💡 Mathematical Approach (Gauss Formula) Idea: The sum of first n natural numbers = n(n+1)/2 Calculate expected sum Subtract actual sum of array The difference is the missing number Approach: Compute expected sum using formula Iterate through array to get actual sum Return the difference This gives: Time Complexity: O(n) Space Complexity: O(1) 💡 Key takeaway: Sometimes the best solution comes from mathematical observation, not data structures. #LeetCode #DSA #LearnInPublic
To view or add a comment, sign in
-
-
🚀 Day 98 of 100 Days of DSA 📌 LeetCode #279 (Perfect Squares) 📈 "Consistency over motivation, Progress over perfection" A fascinating problem where math + pattern recognition beats traditional DP. 🧩 Problem Statement Given an integer n: Find the minimum number of perfect squares that sum up to n A perfect square = number like 1, 4, 9, 16, ... 🧠 Thought Process Initial thinking: - Try all combinations of perfect squares - Minimize the count But quickly: - Too many combinations - Overlapping subproblems This feels like a DP problem… but there’s more. 🚫 Brute Force Approach 1. Try every square ≤ n 2. Recursively subtract and explore Problems: • Massive recursion tree • Repeated calculations Time Complexity → Exponential ❌ 🔄 Better Approach (Dynamic Programming) Define: dp[i] = minimum number of squares to form i For each i: • Try all squares ≤ i • Take minimum Complexity: • Time → O(n√n) • Works, but not optimal 🔍 Key Insight This problem has a hidden mathematical structure: Every number can be represented as the sum of at most 4 perfect squares This comes from Lagrange’s Four Square Theorem 💡 Observations 1. If n itself is a perfect square → answer = 1 2. If n = a² + b² → answer = 2 3. Reduce n: • Remove factors of 4 • If n % 8 == 7 → answer = 4 4. Otherwise → answer = 3 ✅ Approach Used Math + Number Theory Optimization ⚙️ Strategy 1. Check if n is a perfect square → return 1 2. Check if n can be written as sum of 2 squares → return 2 3. Reduce n by removing powers of 4 4. If n % 8 == 7 → return 4 5. Else → return 3 💡 Intuition Instead of building the answer: Use mathematical guarantees to classify the answer directly This avoids unnecessary computation. ⏱ Complexity Analysis Time Complexity: O(√n) Space Complexity: O(1) 💡 Key Learnings - Some DP problems have mathematical shortcuts - Recognizing patterns can drastically reduce complexity - Number theory can outperform brute force and DP - Always question: “Can this be solved without building everything?” #100DaysOfDSA #Day98 #LeetCode #Math #NumberTheory #DynamicProgramming #Algorithms #DSA #CodingJourney
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