#Day_24 💡 Problem Solved: Intersection of Two Arrays II Today’s challenge tested my ability to handle array manipulation and two-pointer logic efficiently. 🧩 Problem Overview: Given two integer arrays, the task is to find their intersection — meaning the common elements between both arrays, including duplicates. For example: nums1 = [4,9,5] and nums2 = [9,4,9,8,4] 👉 Output should be [4,9] (since both 4 and 9 appear in both arrays). ⚙️ My Approach: Sorting both arrays: By sorting nums1 and nums2, I was able to efficiently compare elements in a linear scan. Two-pointer technique: I used two indices i and j, starting from 0 in each array. If both elements matched → it’s part of the intersection. If one was smaller → move that pointer ahead to catch up. Storing results dynamically: Added all matching elements into an ArrayList. Finally converted it into an integer array for the result. This approach ensures O(n log n) time complexity due to sorting, but O(n) in space — a solid balance between clarity and performance. 🧠 Key Takeaways: Sorting simplifies complex comparison problems. The two-pointer pattern is extremely useful for dealing with sorted arrays. Always remember: clean logic > brute force. 🔥 Every new problem brings a fresh perspective on optimizing logic and learning better ways to handle data structures. #Java #CodingChallenge #LeetCode #100DaysOfCode #ProblemSolving #DSA #ProgrammingJourney #TechWithMudassir
Solved Intersection of Two Arrays II with Java and Two-Pointer Technique
More Relevant Posts
-
#Day_23 💡 Problem Solved: Intersection of Two Arrays Today’s challenge tested my ability to handle array manipulation and two-pointer logic efficiently. 🧩 Problem Overview: Given two integer arrays, the task is to find their intersection — meaning the common elements between both arrays, including duplicates. For example: nums1 = [4,9,5] and nums2 = [9,4,9,8,4] 👉 Output should be [4,9] (since both 4 and 9 appear in both arrays). ⚙️ My Approach: Sorting both arrays: By sorting nums1 and nums2, I was able to efficiently compare elements in a linear scan. Two-pointer technique: I used two indices i and j, starting from 0 in each array. If both elements matched → it’s part of the intersection. If one was smaller → move that pointer ahead to catch up. Storing results dynamically: Added all matching elements into an ArrayList. Finally converted it into an integer array for the result. This approach ensures O(n log n) time complexity due to sorting, but O(n) in space — a solid balance between clarity and performance. 🧠 Key Takeaways: Sorting simplifies complex comparison problems. The two-pointer pattern is extremely useful for dealing with sorted arrays. Always remember: clean logic > brute force. 🔥 Every new problem brings a fresh perspective on optimizing logic and learning better ways to handle data structures. #Java #CodingChallenge #LeetCode #100DaysOfCode #ProblemSolving #DSA #ProgrammingJourney #TechWithMudassir
To view or add a comment, sign in
-
-
🔥 Day 117 of My DSA Challenge – Partition Array According to Given Pivot 🔷 Problem : 2161. Partition Array According to Given Pivot 🔷 Level : Medium 🔷 Goal : Rearrange an array so that — 1️⃣ Elements less than the pivot come first 2️⃣ Elements equal to the pivot come next 3️⃣ Elements greater than the pivot come last …and maintain relative order for smaller and larger elements. 🔷 Key Idea : The problem is a great test of array manipulation and partitioning logic — similar to what we see in the partition step of quicksort, but here the order must be stable (unchanged for equal categories). We can solve it cleanly using extra space and multiple passes: First collect elements < pivot Then elements == pivot Finally elements > pivot 🔷 Approach : 1️⃣ Initialize a result array res of same size. 2️⃣ Keep two pointers — left starts from the beginning for smaller elements. right starts from the end for larger elements. 3️⃣ Fill smaller elements from the start. 4️⃣ Fill larger elements from the end (in reverse order). 5️⃣ Fill the middle portion with the pivot. Time Complexity: O(n) Space Complexity: O(n) This problem strengthens your understanding of partitioning logic, stable ordering, and array construction — all fundamental to sorting algorithms and data arrangement. Small rearrangements. Big insights. Every element has its right place — in arrays and in life. ⚡ #Day117 #DSA #100DaysOfCode #LeetCode #Java #Arrays #ProblemSolving #CodingChallenge #Algorithms #DataStructures #LearningJourney #CodeEveryday #DeveloperMindset #EngineerInProgress
To view or add a comment, sign in
-
-
🚀 Day 62 – In-Place Array Filtering with Clean Two-Pointer Logic 🧩 Problem: 27. Remove Element The task is to remove all occurrences of a given value from the array in-place and return the new valid length. Only the first k elements matter after removal, and we must avoid using extra space making this a good test of controlled index manipulation. 🧠 Approach To solve this efficiently, I used an insertion-based two-pointer strategy, which ensures both clarity and optimal performance. I maintained an insertPos pointer that always marks the next position where a valid element should be placed. As I iterated through the array, every element that wasn’t equal to the given value was copied to this position, and the pointer moved forward. This approach ensures: 👉 A single linear pass through the array 👉 Strict in-place modification 👉 Clean separation of valid and removed elements Full control over the final valid length The resulting length is simply the total size minus the number of removed elements, giving a direct and efficient solution. This method clearly shows structured thinking, control over memory usage, and the ability to simplify a problem into predictable pointer movements — exactly what strong algorithmic reasoning looks like. 🔗 Problem Link: https://lnkd.in/gAakjJqC 🔗 GitHub Link: https://lnkd.in/gCe-A-Ev 💡 Reflection: Working on this problem reminded me how powerful a simple pointer and a clear goal can be. Not every challenge needs complex logic sometimes the cleanest solutions come from knowing exactly how you want the data to look and moving toward it step by step. This problem reinforced the value of in-place changes, memory efficiency, and how clean thinking leads to clean code. #LeetCode #Arrays #TwoPointers #InPlaceAlgorithm #Java #Day62 #CodingJourney #100DaysChallenge #ProblemSolving #LearningEveryday #CleanCode
To view or add a comment, sign in
-
-
🌟 Day 76 of #100DaysOfCodingChallenge 📘 Problem: LeetCode 73 – Set Matrix Zeroes Today, I explored an important array manipulation problem — setting entire rows and columns to zero if any element in a 2D matrix is zero. 🧩 Problem Understanding Given an m x n matrix, if any cell has the value 0, we must make its entire row and column 0. For example: Input: [ [1, 2, 3], [4, 0, 6], [7, 8, 9] ] Output: [ [1, 0, 3], [0, 0, 0], [7, 0, 9] ] 💡 My Approach (Brute Force) To handle this, I used two extra arrays — one to track rows and another to track columns that should become zero. 🪄 Steps followed: 1️⃣ Traverse the matrix and store the indices of rows and columns containing 0. 2️⃣ Loop through the matrix again and make the elements 0 wherever their row or column index is marked. This simple approach helps clearly visualize how matrix updates propagate. 🧠 Concept Learned: How to access and manipulate specific rows and columns in a 2D array. The importance of auxiliary data structures (like boolean arrays) in preserving information during traversal. 🕒 Complexity: Time: O(m × n) Space: O(m + n) 🧵 Next Step: I’ll be optimizing this approach to an O(1) space solution using the matrix itself as a marker — a neat trick in in-place algorithms! #100DaysOfCode #Day75 #LeetCode #Java #CodingChallenge #ProblemSolving #ArrayManipulation #DataStructures #WomenInTech
To view or add a comment, sign in
-
-
✅ Day 75 of LeetCode Medium/Hard Edition Today’s challenge was “Range Add Queries 2D” — a fascinating problem that tests your understanding of grid manipulation, optimization, and prefix-sum based range updates ⚡💡 📦 Problem: You're given an n × n matrix initialized with zeros. Each query specifies a rectangle (r1, c1) to (r2, c2), and you must add +1 to every cell inside this rectangle. Return the final matrix after applying all queries. 🔗 Problem Link: https://lnkd.in/g9ct4VtM ✅ My Submission: https://lnkd.in/gkSe-sP8 💡 Thought Process: A direct brute-force update for each query results in O(q × n²) complexity — too slow for large constraints. The key insight is to replace repeated cell updates with a 2D Difference Array, which allows you to update an entire rectangle using only four operations: Add +1 at the start point Subtract at the boundaries Propagate values through prefix sums After building the difference matrix, we use: Row-wise prefix sums Column-wise prefix sums This reconstructs the final grid efficiently. This method transforms the problem from potentially billions of operations into a neat and fast O(q + n²) solution. 🎯 How the Difference Array Helps: Avoids updating each cell individually Captures changes in a compact form Spreads values using cumulative sums Works perfectly for rectangular range additions ⚙️ Complexity: ⏱ Time: O(q + n²) with prefix sums 💾 Space: O(n²) for the difference matrix #LeetCodeMediumHardEdition #100DaysChallenge #PrefixSum #Optimization #Java #DSA #ProblemSolving #LearnEveryday
To view or add a comment, sign in
-
-
🚀 Today’s DSA Challenge: Vertical Order Traversal of a Binary Tree (LeetCode 987) This problem was quite interesting and taught me how powerful combinations of data structures can be when used smartly. The goal: Given a binary tree, we need to return its vertical order traversal — where nodes are grouped by their column index (left to right), and for each column, nodes are sorted first by row, then by their value. Here’s how I approached it 👇 🔹 I used a TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>> to store nodes in this structure: column -> row -> minHeap of node values This ensures everything stays sorted automatically (both columns and rows). 🔹 I performed a BFS traversal using a Queue<Tuple> where each Tuple stores (node, row, col) coordinates. Whenever I go left, column decreases by 1; when I go right, it increases by 1. 🔹 After traversing the entire tree, I built the final list column by column, row by row. This problem really strengthened my understanding of: ✅ BFS traversal on trees ✅ Nested TreeMaps for maintaining sorted ordering ✅ PriorityQueue usage to resolve same-row value ordering ➡️ Time & Space Complexity Analysis Time Complexity: O(N log N) 👉 Each node is visited once during BFS (O(N)), and every insertion and retrieval in the nested TreeMap + PriorityQueue takes O(log N) time. Space Complexity: O(N) 👉 Because we store all nodes in the map, queue, and result list during traversal. #Java #DSA #LeetCode #BinaryTree #LearningJourney #Coding #Software Engineer #InterviewPreparation #Problem Solving
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟏𝟐 𝐨𝐟 #50DaysOfDSA 𝐏𝐫𝐨𝐛𝐥𝐞𝐦: 𝟑𝟔𝟎𝟕. 𝐏𝐨𝐰𝐞𝐫 𝐆𝐫𝐢𝐝 𝐌𝐚𝐢𝐧𝐭𝐞𝐧𝐚𝐧𝐜𝐞 Level: Medium Topic: Disjoint Set Union (Union-Find), Graphs, PriorityQueue 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐈𝐧𝐬𝐢𝐠𝐡𝐭: We are given a number of power stations connected by cables. Each connection forms part of a power grid. If a station goes offline, it still remains part of its grid. During a maintenance check, if the station is offline, the smallest-id online station in the same grid handles it. If no online station exists, return -1. The challenge was to efficiently manage dynamic connectivity and online/offline status while answering multiple queries. 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: To handle this efficiently: Used Union-Find (Disjoint Set Union) to track connected components. Each component maintains a min-heap (PriorityQueue) to get the smallest online station quickly. For each query: Type [1, x]: Check if station x or another in its grid is online. Type [2, x]: Mark station x as offline. This approach ensures near O(log n) query handling even for large inputs (up to 10⁵). 𝐊𝐞𝐲 𝐂𝐨𝐧𝐜𝐞𝐩𝐭𝐬 𝐔𝐬𝐞𝐝: ✅ Disjoint Set Union (Path Compression & Union by Size) ✅ PriorityQueue for smallest operational station ✅ Efficient offline handling logic #DSA #Java #LeetCode #ProblemSolving #GraphTheory #UnionFind #CodingChallenge #LearnByCoding #TechJourney
To view or add a comment, sign in
-
-
Day 3 — Median of Two Sorted Arrays Today’s focus was on one of the most popular LeetCode problems : "Median of Two Sorted Arrays.” The goal: merge two sorted arrays and find their median. At first glance, it feels simple — but getting it right with edge cases is where the logic truly kicks in. Used a two-pointer merge approach — merging elements in order until both arrays are traversed. Once the merged array is ready, finding the median becomes straightforward. It’s one of those problems that looks basic but builds a strong foundation for array manipulation and binary search-based optimizations later on. Slow progress, steady learning.. Similar problems: 🔹 Merge Sorted Array — LeetCode #88 🔹 Kth Element of Two Sorted Arrays (variation of this problem, often asked in interviews) 🔹 Find the Median from Data Stream — LeetCode #295 #100DaysOfDSA #LeetCode #Java #Arrays #ProblemSolving
To view or add a comment, sign in
-
-
🌊 DSA Day 58 — Number of Enclaves (BFS Approach) Today, I explored another interesting graph + grid traversal problem — finding the number of enclaves in a binary matrix. This problem beautifully combines boundary detection, BFS traversal, and logical filtering — all classic DSA concepts wrapped into one challenge. 🧩 Problem Intuition You’re given a binary grid where: 1 represents land 0 represents water An enclave is a piece of land completely surrounded by water — meaning you can’t reach the boundary from that land by moving up, down, left, or right. So, our task is to count how many such land cells are not connected to the boundary. ⚙️ My Approach — BFS from the Boundaries Instead of starting from every land cell, I reversed the thinking: “If we can remove all lands connected to boundaries, what’s left must be enclaves.” Here’s how I approached it: Traverse all boundary cells (first/last row or column). For every boundary land (1) that’s not visited, perform a BFS traversal and mark all reachable land cells as visited. After marking, count all unvisited land cells — these are the enclaves! 💡 Key Insights The trick lies in starting BFS from the edges, not the center. It’s more efficient than checking every cell individually. Using a simple helper class pair made it easier to manage row–column positions in the queue. 🧠 Concepts Reinforced BFS traversal on 2D grids Boundary-based problem-solving Queue-based implementation Logical reasoning in graph problems 🪄 Today’s Takeaway Sometimes, solving a problem efficiently isn’t about going toward the goal — it’s about clearing out everything else first. This problem is a perfect example of reverse thinking in algorithm design. #DSA #Day58 #GraphTheory #BFS #ProblemSolving #CodingJourney #100DaysOfCode #Java #LearningInPublic #GridTraversal #ReverseThinking
To view or add a comment, sign in
-
-
Day 45/100 — DSA From Scratch (Medium) Problem Solved: Binary Tree Right Side View Task: Given the root of a binary tree, imagine standing on the right side of it — return the list of node values visible from top to bottom. Approach Used: Used DFS (Depth-First Search) with a right-first traversal approach. At each level, the first node we encounter (while going right to left) represents the rightmost visible node. By keeping track of the level during recursion, we can directly capture the visible nodes from the right side. Complexity: Time Complexity: O(n) — visiting each node once. Space Complexity: O(h) — height of the recursion stack. Notes: Learned a new and elegant DFS technique today — just by prioritizing the right subtree, we can capture the right view naturally without using extra data structures. A small but powerful concept that made tree traversal feel intuitive and satisfying to implement. #Day45 #DSAFromScratch #BinaryTree #RightSideView #DFS #LeetCode #Java #ProblemSolving #LearningEveryday #100DaysOfCode
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