Day 1 of problem solving: 🚀 Solved 4 interesting DSA problems today — sharing quick approaches + core logic 👇 1️⃣ Detect Cycles in 2D Grid Used DFS + parent tracking. The key idea is to traverse only same-valued adjacent cells and detect whether we revisit an already visited cell that is not the immediate parent. 🔹 Algorithm: Graph Traversal (DFS) 🔹 Logic: visited[][] + previous cell coordinates 2️⃣ Common Elements in 3 Sorted Arrays Applied the 3-pointer technique. Since all arrays are sorted, we move the pointer pointing to the smallest value until all three values match. 🔹 Algorithm: Two/Three Pointers 🔹 Logic: linear scan in O(n1 + n2 + n3) 3️⃣ Smallest Window Containing 0, 1 and 2 Solved using the Sliding Window approach. Expand the right pointer until the window contains all 3 digits, then shrink from the left to find the minimum valid window. 🔹 Algorithm: Sliding Window 🔹 Logic: frequency count + two pointers 4️⃣ Halloumi Boxes (Codeforces) A beautiful observation-based problem. If k = 1, no movement is possible, so the array must already be sorted. If k > 1, adjacent swaps become possible through reversal, meaning any array can be sorted. 🔹 Algorithm: Greedy / Observation 🔹 Logic: reversal length property 💡 Today’s takeaway: Not every problem needs heavy coding — sometimes the strongest solution comes from the right observation and choosing the correct algorithmic pattern. #DSA #Java #LeetCode #Codeforces #ProblemSolving #Algorithms #DataStructures #CodingInterview #SoftwareEngineer #100DaysOfCode Follow for more problem solving content and stay updated 🚀
Solved 4 DSA problems with DFS, 3-pointers, Sliding Window & Greedy Algorithms
More Relevant Posts
-
🔥 DSA Challenge – Day 126/360 🚀 📌 Topic: Array + Backtracking (Recursion) 🧩 Problem: Combination Sum II Problem Statement: Find all unique combinations in an array where numbers sum up to a target. Each number can be used only once, and duplicate combinations are not allowed. 🔍 Example: Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [[1,1,6], [1,2,5], [1,7], [2,6]] 💡 Approach: Backtracking + Pruning 1️⃣ Step 1 – Sort the array to handle duplicates easily 2️⃣ Step 2 – Use recursion to pick elements and reduce target 3️⃣ Step 3 – Skip duplicates & backtrack after each recursive call 👉 Use condition to skip duplicates: if(i > ind && arr[i] == arr[i-1]) continue; 👉 Stop early if element exceeds target (pruning) ⏱ Complexity: Time: O(2^n) Space: O(k * x) (for storing combinations) 📚 Key Learning: Sorting + duplicate skipping is the key trick to avoid repeated combinations in backtracking problems. #DSA #Java #Coding #InterviewPrep #ProblemSolving #TechJourney #360DaysOfCode #LeetCode
To view or add a comment, sign in
-
-
📌 Strengthening DSA Concepts through Problem Solving - Cracking the 3Sum Problem (LeetCode #15) Problem Statement Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that: i != j, i != k, and j != k nums[i] + nums[j] + nums[k] == 0 👉 The solution must not contain duplicate triplets. 🧠 Example Input: [-1, 0, 1, 2, -1, -4] Output: [[-1, -1, 2], [-1, 0, 1]] 🔴 Naive Approach (Brute Force) 👉 Check all possible triplets 🔹 Pseudocode 1. Initialize an empty set 2. Loop i from 0 to n-1: Loop j from i+1 to n-1: Loop k from j+1 to n-1: IF arr[i] + arr[j] + arr[k] == 0: Create triplet Sort it Add to set 3. Return result ⏱ Time Complexity: O(n³) 🟢 Optimized Approach (Two Pointers) 👉 Reduce one loop using sorting + two pointers 🔹 Pseudocode 1. Sort the array 2. Initialize an empty set 3. Loop i from 0 to n-1: - Skip duplicates j = i + 1 k = n - 1 While j < k: sum = arr[i] + arr[j] + arr[k] IF sum == 0: Add triplet j++ k-- ELSE IF sum > 0: k-- ELSE: j++ 4. Return result ⚡ Time Complexity: O(n²) 📌 Key Insight Sorting + Two Pointers is a powerful combo to reduce complexity in many problems! #LeetCode #Algorithms #DSA #CodingInterview #Java #ProblemSolving
To view or add a comment, sign in
-
🚀 Day 23 of My DSA Journey – Clean & Efficient Deduplication Today I solved a classic and very important problem: 👉 Remove Duplicates from Sorted Array 🔍 Problem Understanding Given a sorted array, we need to remove duplicates in-place such that each element appears only once and return the new length. ⚠️ Constraints: No extra space allowed Maintain relative order 🧠 Brute Force Approach Use a Set or ArrayList to store unique elements Copy back to array ❌ Not optimal due to O(n) extra space ⚡ Optimized Approach (Two Pointer Technique) 💡 Key Idea: Since the array is sorted, duplicates are adjacent. We can maintain a pointer j to track the position of unique elements. 🪜 Steps Initialize j = 0 Traverse array using i If nums[j] != nums[i] Increment j Assign nums[j] = nums[i] Return j + 1 🧪 Example Walkthrough Input: [0,0,1,1,1,2,2,3,3,4] Process: Keep only unique elements Final array: [0,1,2,3,4] Output: 5 ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) ✅ 💡 Key Learning Sorted arrays simplify many problems Two-pointer approach is 🔑 for in-place operations Writing clean and minimal code matters in interviews 🙏 Gratitude Consistency is paying off. Small daily wins are building strong fundamentals 💪 📈 Consistency Note Discipline > Motivation. Showing up daily 🚀 #DSA #LeetCode #Java #CodingJourney #100DaysOfCode #ProblemSolving #TechJourney #InterviewPreparation
To view or add a comment, sign in
-
-
🚀 Day 22/40 – DSA Challenge 📌 LeetCode Problem – Divide Two Integers 📝 Problem Statement Given two integers dividend and divisor, divide them without using multiplication, division, or mod operator. Return the quotient after dividing. 📌 Example Input: dividend = 10 divisor = 3 Output: 3 📌 Edge Case Input: dividend = -2147483648 divisor = -1 Output: 2147483647 (Integer.MAX_VALUE) 💡 Key Insight We simulate division using bit shifting (doubling). 👉 Instead of subtracting one by one 👉 Subtract largest possible multiples using powers of 2 🔥 Optimized Approach – Bit Manipulation 🧠 Idea Convert numbers to long (avoid overflow) Work with absolute values Keep doubling divisor using: temp << 1 Subtract largest chunk each time 🚀 Algorithm 1️⃣ Handle overflow case 2️⃣ Convert to long and take absolute values 3️⃣ While dividend ≥ divisor: Keep doubling divisor Subtract largest possible multiple Add to result 4️⃣ Apply sign ✅ Java Code (Optimal O(log n)) class Solution { public int divide(int dividend, int divisor) { if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } long dvd = Math.abs((long) dividend); long dvs = Math.abs((long) divisor); int result = 0; while (dvd >= dvs) { long temp = dvs; int multiple = 1; while (dvd >= (temp << 1)) { temp <<= 1; multiple <<= 1; } dvd -= temp; result += multiple; } if ((dividend < 0) ^ (divisor < 0)) { result = -result; } return result; } } ⏱ Complexity Time Complexity: O(log n) Space Complexity: O(1) 📚 Key Learnings – Day 22 ✔ Bit manipulation can replace division ✔ Doubling strategy reduces time drastically ✔ Handle overflow carefully ✔ Use long to avoid integer issues Classic problem. Bit-level thinking. Edge cases mastered. Day 22 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #BitManipulation #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 75 — Slow & Fast Pointer (Happy Number Detection) Extending the slow‑fast pointer pattern beyond linked lists — today I applied it to a mathematical problem involving cycles. 📌 Problem Solved: - LeetCode 202 – Happy Number 🧠 Key Learnings: 1️⃣ The Problem in a Nutshell A number is happy if repeatedly replacing it with the sum of squares of its digits eventually reaches 1. If it enters a cycle that doesn’t include 1, it’s unhappy. 2️⃣ Why Slow‑Fast Pointer Works - The sequence of numbers (n → sum of squares of digits → ...) will eventually either reach 1 or enter a cycle. - This is exactly like detecting a cycle in a linked list — except the “next” is defined mathematically. - Slow moves one step: `slow = sq(slow)` - Fast moves two steps: `fast = sq(sq(fast))` - If they meet at a value other than 1 → cycle exists → unhappy number. - If fast reaches 1 → happy number. 3️⃣ The sq() Helper Computes sum of squares of digits. Clean and reusable. 4️⃣ Edge Cases - n = 1 → returns true immediately (loop condition `fast != 1` fails, returns true). - Numbers like 2, 3, 4 eventually cycle (4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4). 💡 Takeaway: The slow‑fast pointer pattern isn’t just for linked lists — it’s a general cycle detection tool that works for any sequence with a deterministic “next” step. Recognizing this abstraction is what makes a great problem solver. No guilt about past breaks — just one problem at a time, one pattern at a time. #DSA #SlowFastPointer #HappyNumber #CycleDetection #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
❌ I used to ignore Time & Space Complexity… Until my code started failing on large inputs. That’s when I realized: 👉 Writing code is easy 👉 Writing efficient code is what actually matters 🚀 Time & Space Complexity — Simplified ⏱️ Time Complexity (How fast your code runs) O(1) → Constant O(log n) → Binary Search O(n) → Linear traversal O(n log n) → Efficient sorting O(n²) → Nested loops O(2ⁿ) → Exponential (avoid if possible) 💾 Space Complexity (How much memory your code uses) O(1) → No extra memory O(n) → Extra storage O(n²) → Matrix O(2ⁿ) → Recursive explosion 🔥 Why it actually matters? ✔️ Your code should handle millions of inputs, not just 10 ✔️ Top companies test efficiency, not just correctness ✔️ Better complexity = faster + cheaper systems 🛠️ How I’m improving daily: ✅ Picking the right data structures ✅ Replacing brute force with optimized approaches ✅ Using Binary Search & Hashing wherever possible ✅ Practicing DSA problems consistently ✅ Analyzing time + space after every solution 🎯 Big lesson: 👉 Don’t just solve problems 👉 Solve them efficiently If you're learning DSA, remember: Small optimizations today → Big impact tomorrow 🚀 #DSA #Algorithms #CodingInterview #SoftwareEngineering #Java #LearningInPublic #100DaysOfCode #TechJou
To view or add a comment, sign in
-
-
✳️Day 35 of #100DaysOfCode✳️ 📌 Cracking the "Redundant Connection" Problem with DSU! 🛠️ My Approach: The DSU Strategy The Disjoint Set Union (or Union-Find) algorithm is perfect here because it allows us to track connected components efficiently as we iterate through the edges. ✨The Steps in my Code: 1️⃣Initialization: Created a parent array where every node is initially its own parent (representing n independent sets). 2️⃣Iterative Union: For every edge (u, v) in the input: Find the root (representative) of u. Find the root (representative) of v. Cycle Detection: * If find(u) == find(v), it means u and v are already part of the same connected component. Adding this edge would create a cycle. 🚩 Since the problem asks for the last edge that causes the cycle, I return this edge immediately. 3️⃣Union: If they are in different sets, I perform a union by setting the parent of one root to the other. 4️⃣Optimization: I used Path Compression in the find function to keep the tree flat, ensuring almost constant time complexity. 💡 When should you use DSU? 🔅DSU is a powerhouse for specific graph scenarios. Reach for it when: Cycle Detection: You need to check if adding an edge creates a cycle in an undirected graph. 🔅Connected Components: You need to count or manage groups of connected nodes dynamically. 🔅Minimum Spanning Trees: It’s the backbone of Kruskal’s Algorithm. Grid Problems: Identifying "islands" or connected regions in a 2D matrix. #DataStructures #Algorithms #LeetCode #Java #GraphTheory #CodingLife #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 11/60 This graph illustrates how different algorithms perform as the input size (n) increases. The x-axis represents input size, and the y-axis represents time (or operations). 💡 Explanation of Each Complexity: 🔹 O(1) — Constant Time Execution time remains the same regardless of input size. ➡️ Example: Accessing an element in an array 🔹 O(log n) — Logarithmic Time Time increases slowly as input grows. ➡️ Example: Binary Search 🔹 O(n) — Linear Time Execution time grows proportionally with input size. ➡️ Example: Iterating through a list 🔹 O(n log n) — Linearithmic Time Efficient for sorting large datasets. ➡️ Example: Merge Sort, Quick Sort 🔹 O(n²) — Quadratic Time Time increases rapidly due to nested operations. ➡️ Example: Nested loops (Bubble Sort) 🔹 O(2ⁿ) — Exponential Time Time doubles with each additional input. ➡️ Example: Recursive problems (subsets, Fibonacci) 🔹 O(n!) — Factorial Time Extremely slow growth; impractical for large inputs. ➡️ Example: Generating all permutations ⚠️ Key Insight As input size increases: Lower complexity algorithms scale efficiently Higher complexity algorithms become impractical 📌 Summary Order (Best → Worst) O(1) → O(log n) → O(n) → O(n log n) → O(n²) → O(2ⁿ) → O(n!) #DataStructures #Algorithms #BigO #TimeComplexity #Java #Programming #SoftwareEngineering #BackendDevelopment #DSA #Coding
To view or add a comment, sign in
-
-
𝗠𝗼𝘀𝘁 𝗣𝗲𝗼𝗽𝗹𝗲 𝗨𝘀𝗲 𝗔𝗜. 𝗙𝗲𝘄 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝗧𝗵𝗲 𝗖𝗼𝗱𝗲 𝗔𝗜 𝗰𝗮𝗻 𝗴𝗲𝗻𝗲𝗿𝗮𝘁𝗲 𝗰𝗼𝗱𝗲. 𝗕𝘂𝘁 𝗶𝗳 𝘆𝗼𝘂 𝗱𝗼𝗻’𝘁 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝗣𝘆𝘁𝗵𝗼𝗻 𝗱𝗲𝗲𝗽𝗹𝘆, 𝘆𝗼𝘂 𝘄𝗼𝗻’𝘁 𝗸𝗻𝗼𝘄 𝘄𝗵𝗮𝘁 𝗶𝘁’𝘀 𝗱𝗼𝗶𝗻𝗴, 𝘄𝗵𝘆 𝗶𝘁 𝗯𝗿𝗲𝗮𝗸𝘀, 𝗼𝗿 𝗵𝗼𝘄 𝘁𝗼 𝘀𝗰𝗮𝗹𝗲 𝗶𝘁. 𝗧𝗵𝗮𝘁’𝘀 𝘄𝗵𝗲𝗿𝗲 𝗿𝗲𝗮𝗹 𝗲𝗻𝗴𝗶𝗻𝗲𝗲𝗿𝗶𝗻𝗴 𝘀𝘁𝗮𝗿𝘁𝘀. 𝗕𝗲𝗹𝗼𝘄 𝗮𝗿𝗲 𝘁𝗵𝗲 𝗰𝗼𝗿𝗲 𝘁𝗼𝗽𝗶𝗰𝘀 𝘆𝗼𝘂 𝘀𝗵𝗼𝘂𝗹𝗱 𝗸𝗻𝗼𝘄: 1. Object-Oriented Programming (OOP) 2. Decorators 3. Generators & Iterators 4. Context Managers 5. Async Programming (async/await) 6. Multithreading & Multiprocessing 7. WebSockets 8. Data Structures & Algorithms 9. Memory Management & Garbage Collection 10. File Handling & Serialization 11. List/Dict/Set Comprehensions 12. Exception Handling (advanced patterns) 13. Functional Programming (map, filter, lambda) 14. Modules & Packaging 15. Virtual Environments & Dependency Management 16. Type Hinting & Static Typing 17. Testing (unit tests, mocking, pytest) 18. Logging & Debugging 19. API Development (FastAPI/Flask) 20. Database Handling (SQL/ORMs) Master these, and you’re not just using AI you’re actually building with it. #Python #AI #SoftwareEngineering #Developers #Coding #MachineLearning #Programming #Tech #LearnToCode
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