🔥 Day 99 of #100DaysOfCode Today’s problem: LeetCode – Merge Two Sorted Lists 🔗📊 📌 Problem Summary You are given two sorted linked lists. 👉 Merge them into one sorted linked list and return the head. Example: list1 = [1,2,4] list2 = [1,3,4] Output → [1,1,2,3,4,4] 🧠 Approach: Recursion We compare nodes from both lists and recursively build the merged list. ⚙️ Logic 1️⃣ Base cases: If list1 == null → return list2 If list2 == null → return list1 2️⃣ Compare current nodes: If list1.val <= list2.val → attach list1 and recurse Else → attach list2 and recurse 💻 Code Insight if(list1.val <= list2.val){ list1.next = mergeTwoLists(list1.next, list2); return list1; }else{ list2.next = mergeTwoLists(list1, list2.next); return list2; } 💡 Why Recursion Works? Each step: Picks the smaller node Reduces the problem size Eventually reaches base case → builds sorted list naturally. ⏱ Time Complexity: O(n + m) 💾 Space Complexity: O(n + m) (recursion stack) 🚀 Performance Runtime: 0 ms Beats 100% submissions 🔥 Memory: 44.23 MB 🧠 Key Learning This problem is fundamental for: Linked list manipulation Divide & conquer Merge sort logic 🚨 Almost There! Just 1 day left to complete the #100DaysOfCode challenge 🎯🔥 From basics → advanced patterns → consistency. On to the final Day 100 🚀 #100DaysOfCode #LeetCode #LinkedList #Recursion #Java #DSA #InterviewPrep
Merge Two Sorted Linked Lists in Java
More Relevant Posts
-
**Day 110 of #365DaysOfLeetCode Challenge** Today’s problem: **Add Two Numbers II (LeetCode 445)** A very elegant **Linked List + Stack** problem. We are given two numbers stored in linked lists where the **most significant digit comes first**. Example: `7243 + 564 = 7807` Lists: `[7,2,4,3] + [5,6,4] = [7,8,0,7]` 💡 **Core Challenge:** Normally addition starts from the **last digit**… But linked lists are given from the **front**. So how do we add from right to left **without reversing the lists**? 📌 **Approach:** 1️⃣ Push digits of both linked lists into stacks 2️⃣ Pop from stacks → gives digits from right to left 3️⃣ Add with carry 4️⃣ Insert new node at the front of result list This preserves correct order naturally ⚡ **Time Complexity:** O(n + m) ⚡ **Space Complexity:** O(n + m) **What I learned today:** Stacks are incredibly useful when you need to process data in **reverse order**. 💭 **Key Takeaway:** If you can’t move backward easily: 👉 Use a stack 👉 Simulate reverse traversal 👉 Build result from front Clean solution. Smart idea. Great interview problem #LeetCode #DSA #LinkedList #Stack #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 52 of My DSA Journey Today, I solved Reverse Words in a String (LeetCode 151) 💻 This problem tested my understanding of string manipulation, trimming, and efficient traversal. 🔹 Problem Statement: Given a string s, reverse the order of words while removing extra spaces. 🔹 Key Learnings: ✅ Handling leading, trailing, and multiple spaces ✅ Using split() with regex (\\s+) ✅ Efficient use of StringBuilder for better performance ✅ Traversing array in reverse order 🔹 Approach: Trim the string to remove extra spaces Split words using regex Traverse from end to start Append words with single space 🔹 Example: Input: " hello world " Output: "world hello" Another Example: Input: "the sky is blue" Output: "blue is sky the" 🔹 Code Insight (Java): Used StringBuilder to efficiently build the reversed string without extra space issues. Consistency is the key 🔑 — showing up every day and improving step by step. #Day52 #DSA #Java #LeetCode #CodingJourney #100DaysOfCode #Programming #PlacementPreparation 🚀 If you want, I can also create a more viral version (with hooks + storytelling) to get more reach 🔥Here’s a clean and engaging LinkedIn post for your Day 52 of DSA Journey with an example: 🚀 Day 52 of My DSA Journey Today, I solved Reverse Words in a String (LeetCode 151) 💻 This problem tested my understanding of string manipulation, trimming, and efficient traversal. 🔹 Problem Statement: Given a string s, reverse the order of words while removing extra spaces. 🔹 Key Learnings: ✅ Handling leading, trailing, and multiple spaces ✅ Using split() with regex (\\s+) ✅ Efficient use of StringBuilder for better performance ✅ Traversing array in reverse order 🔹 Approach: Trim the string to remove extra spaces Split words using regex Traverse from end to start Append words with single space 🔹 Example: Input: " hello world " Output: "world hello" Another Example: Input: "the sky is blue" Output: "blue is sky the" 🔹 Code Insight (Java): Used StringBuilder to efficiently build the reversed string without extra space issues. Consistency is the key 🔑 — showing up every day and improving step by step. #Day52 #DSA #Java #LeetCode #CodingJourney #100DaysOfCode #Programming #PlacementPreparation 🚀
To view or add a comment, sign in
-
-
🚀 Day 11 – #50DaysLeetCodeChallenge Today I solved the 3Sum problem. 📌 Problem Statement Given an integer array nums, return all the unique triplets [nums[i], nums[j], nums[k]] such that: i ≠ 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]] 💡 Approach I Used – Sorting + Two Pointers 1️⃣ Sort the array 2️⃣ Fix one element i 3️⃣ Use two pointers: left = i + 1 right = end of array 4️⃣ Check the sum: If sum == 0 → add triplet If sum < 0 → move left++ If sum > 0 → move right-- 5️⃣ Skip duplicates to avoid repeated triplets ⚙️ Key Idea Reduce the problem from 3Sum → 2Sum (using two pointers) Sorting helps in efficient traversal and duplicate handling 🧠 What I learned today ✔️ How sorting simplifies complex problems ✔️ Converting problems into smaller subproblems (3Sum → 2Sum) ✔️ Handling duplicates carefully From simple arrays → advanced pointer techniques 🚀 Consistency is making a difference! #LeetCode #Java #DSA #CodingChallenge #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
🔥 Day 100 of #100DaysOfCode — FINAL DAY 🎯 Today’s problem: LeetCode – Reverse Linked List 🔗🔄 📌 Problem Summary You are given the head of a singly linked list. 👉 Reverse the list and return the new head. Example: [1,2,3,4,5] → [5,4,3,2,1] 🧠 Approach: Iterative (Two Pointers) We reverse the list by changing the direction of pointers. ⚙️ Logic We maintain three pointers: prev → previous node (initially null) curr → current node (starts at head) next → temporary pointer to store next node 💻 Code Insight ListNode prev = null; ListNode curr = head; while(curr != null){ ListNode temp = curr.next; curr.next = prev; prev = curr; curr = temp; } return prev; 💡 How It Works At each step: Reverse the link (curr.next = prev) Move both pointers forward Gradually, the entire list gets reversed. ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Beats 100% submissions 🔥 Memory: 44.29 MB 🧠 Key Learning This is one of the most fundamental linked list problems. It teaches: Pointer manipulation In-place operations Iterative thinking 🎉 100 Days Completed! From: Arrays & Strings Sliding Window Stack & Queue Monotonic Stack Binary Search Linked Lists 👉 To building strong problem-solving skills 💪 Consistency > Motivation 🔥 🚀 What’s Next? Start Advanced DSA (Graphs / DP) Build real-world projects Contribute to Open Source (GSoC ready 💪) Practice mock interviews 💬 This journey is just the beginning. #100DaysOfCode #LeetCode #DSA #Java #CodingJourney #Consistency #InterviewPrep
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟒𝟗 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on checking whether a string can be segmented into valid dictionary words. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Word Break 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 – 𝐃𝐅𝐒 + 𝐌𝐞𝐦𝐨𝐢𝐳𝐚𝐭𝐢𝐨𝐧 • Converted the word list into a HashSet for fast lookup • Used recursion to try breaking the string into prefixes • If prefix exists in dictionary, recursively check the remaining string • Stored results in a memo map to avoid recomputation This avoids exponential re-checking of the same substrings. 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Memoization helps optimize recursive solutions • Breaking problems into smaller substrings is a common pattern • HashSet improves lookup efficiency • DP problems often start with recursion and get optimized 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n²) (with memoization) • Space: O(n) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 When recursion feels slow, adding memoization can transform it into an efficient solution. 49 days consistent 🚀 On to Day 50. #DSA #Arrays #DynamicProgramming #Recursion #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 Day 15 – ArrayList vs LinkedList (It’s Not Just About Syntax) Today I explored the real difference between "ArrayList" and "LinkedList". List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new LinkedList<>(); At first glance, both implement "List"… but internally they are very different. --- 💡 ArrayList ✔ Backed by a dynamic array ✔ Fast for random access (get by index) ✔ Slower for insert/delete in middle (shifting required) --- 💡 LinkedList ✔ Uses a doubly linked list ✔ Faster for insert/delete (no shifting) ✔ Slower for access (traversal needed) --- ⚠️ Real insight: In most real-world scenarios, "ArrayList" is preferred due to better cache locality and overall performance. 👉 "LinkedList" is useful only when: - Frequent insertions/deletions in the middle - Less need for random access --- 💡 Takeaway: Don’t choose based on interface—choose based on use case and internal behavior #Java #BackendDevelopment #Collections #ArrayList #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 84/100 – 𝐒𝐞𝐚𝐫𝐜𝐡 𝐢𝐧 𝐑𝐨𝐭𝐚𝐭𝐞𝐝 𝐒𝐨𝐫𝐭𝐞𝐝 𝐀𝐫𝐫𝐚𝐲 𝐈𝐈 🔍 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠: Binary search works great on sorted arrays, but duplicates introduce ambiguity — making it harder to decide which half is sorted. 💡 𝐂𝐨𝐫𝐞 𝐈𝐝𝐞𝐚: Use modified binary search Identify the sorted half Handle duplicates by shrinking the search space ⚡ 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Find 𝐦𝐢𝐝 If 𝐭𝐚𝐫𝐠𝐞𝐭 𝐟𝐨𝐮𝐧𝐝 → 𝐫𝐞𝐭𝐮𝐫𝐧 𝐭𝐫𝐮𝐞 𝐇𝐚𝐧𝐝𝐥𝐞 𝐝𝐮𝐩𝐥𝐢𝐜𝐚𝐭𝐞𝐬 (𝐥𝐨𝐰++) Check which half is sorted Narrow down search accordingly #Day84 #100DaysOfCode #Java #DSA #LeetCode #BinarySearch #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 21/30 – DSA Challenge 📌 LeetCode Problem – Median of Two Sorted Arrays 📝 Problem Statement Given two sorted arrays nums1 and nums2, find the median of the combined array. 📌 Example Input: nums1 = [1,2] nums2 = [3,4] Output: 2.5 💡 My Approach Instead of using complex binary search, I followed a simple and reliable method: 👉 Merge both arrays 👉 Sort the merged array 👉 Find the median This approach is easy to understand and implement. 🚀 Algorithm 1️⃣ Create a new array of size n1 + n2 2️⃣ Copy elements of both arrays 3️⃣ Sort the merged array 4️⃣ If length is odd → return middle element 5️⃣ If even → return average of two middle elements ✅ Java Code import java.util.Arrays; class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int n1 = nums1.length; int n2 = nums2.length; int[] merged = new int[n1 + n2]; for (int i = 0; i < n1; i++) { merged[i] = nums1[i]; } for (int i = 0; i < n2; i++) { merged[n1 + i] = nums2[i]; } Arrays.sort(merged); int n = merged.length; if (n % 2 == 1) { return merged[n / 2]; } else { return (merged[n / 2 - 1] + merged[n / 2]) / 2.0; } } } ⏱ Complexity Time Complexity: O((n + m) log(n + m)) Space Complexity: O(n + m) 📚 Key Learnings – Day 21 ✔ Simple solutions are often easiest to implement ✔ Always understand problem constraints ✔ This problem can be optimized further using binary search ✔ Multiple approaches exist — choose based on context Simple approach. Clear logic. Strong understanding. Day 21 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode
To view or add a comment, sign in
-
-
Day 76/100 Completed ✅ 🚀 Solved LeetCode – Search a 2D Matrix (Java) ⚡ Implemented an optimized binary search approach by treating the 2D matrix as a flattened sorted array. Converted 1D index into 2D coordinates (row = mid / m, col = mid % m) to efficiently locate the target in O(log(m × n)) time. 🧠 Key Learnings: • Applying binary search on a 2D matrix • Converting 1D index to 2D (row & column mapping) • Reducing time complexity from O(m × n) → O(log(m × n)) • Importance of problem observation (matrix behaves like sorted array) 💯 This problem strengthened my understanding of binary search variations and how to apply it beyond simple 1D arrays. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #binarysearch #arrays #optimization #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
From implementing basic arrays to building my own Generic ArrayList from scratch in Java 🚀 Recently, in an interview, I was asked to implement an ArrayList with major operations. Instead of stopping there, I took it as a challenge and went deeper. Here’s what I built: ✔ Dynamic resizing (handled capacity growth) ✔ Generic support using <T> ✔ add(element) and add(index, element) ✔ remove(index) with shifting ✔ get(index) with boundary checks ✔ size() and capacity() methods ✔ Custom toString() for clean output Along the way, I also understood an important concept: 👉 Why Java doesn’t allow new T[] (due to type erasure) 👉 How real ArrayList internally uses Object[] This wasn’t just about coding — it was about understanding how data structures actually work internally. Small improvements daily → big progress over time. #Java #DataStructures #DSA #CodingInterview #Learning #Consistency
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