🚀 Day 23/40 – DSA Challenge 📌 LeetCode Problem – Remove Duplicates from Sorted List 📝 Problem Statement Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the modified linked list. 📌 Example Input: 1 → 1 → 2 → 3 → 3 Output: 1 → 2 → 3 💡 Key Insight Since the list is sorted, 👉 duplicates will always be adjacent. So we don’t need extra space or hashing. 🔥 Optimal Approach – Single Traversal 🧠 Idea Traverse the list and compare: Current node Next node If they are equal → skip the next node Else → move forward 🚀 Algorithm 1️⃣ Start from head 2️⃣ While current != null && current.next != null 3️⃣ If: current.val == current.next.val 👉 Skip duplicate: current.next = current.next.next 4️⃣ Else: Move to next node ✅ Java Code (Optimal O(n)) class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode current = head; while (current != null && current.next != null) { if (current.val == current.next.val) { current.next = current.next.next; } else { current = current.next; } } return head; } } ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) 📚 Key Learnings – Day 23 ✔ Sorted data simplifies problems ✔ Linked list manipulation requires careful pointer handling ✔ No extra space needed when duplicates are adjacent ✔ Always check current.next != null to avoid errors Simple structure. Clean pointer logic. Efficient solution. Day 23 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode
Remove Duplicates from Sorted Linked List
More Relevant Posts
-
Problem :- Two Sum (LeetCode 1) Problem Statement :- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target. Assume exactly one solution exists, and you may not use the same element twice. Approach 1 :- Brute Force => Nested Loop i - Check every pair of elements ii - If nums[i] + nums[j] == target => return indices iii - Time Complexity : O(n²) class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[]{}; } } Approach 2 :- Optimal => HashMap i - Store number and its index in a HashMap ii - For each element, check if (target - current) exists iii - Time Complexity : O(n) class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[]{}; } } Key Takeaway :- Instead of checking every pair, we store previously seen elements and directly find the required complement efficiently. #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #HashMap
To view or add a comment, sign in
-
-
Problem :- Search Insert Position (LeetCode 35) Problem Statement :- Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Approach :- Binary Search i - Uses Binary Search to efficiently find the target or its position in a sorted array. ii - Compares nums[mid] with target and adjusts search range (start or end). iii - Loop ends when target is not found, and correct position is crossed. iv - If target > nums[mid] => mid + 1 Else => mid v - Time Complexity : O(log n) vi - Space Complexity : O(1) class Solution { public int searchInsert(int[] nums, int target) { int start = 0; int end = nums.length - 1; int mid = 0; while (start <= end) { mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { start = mid + 1; } else { end = mid - 1; } } return (target > nums[mid]) ? mid + 1 : mid; } } Key Takeaway :- Binary Search efficiently finds the position (or insertion point) by repeatedly dividing the search space. How would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #BinarySearch
To view or add a comment, sign in
-
-
Day16:- Arrays A Journey with Frontlines EduTech (FLM) and Fayaz S ✒️An array in Java is a data structure used to store multiple values of the same data type in a single variable. ✒️Instead of creating many variables, we store them in one array. Without array:- int a = 10; int b = 20; int c = 30; With array:- int [] numbers = {10,20,30}; Syntax:- dataType[] = new new dataType [size]; Array Initialization and access:- ✒️Arrays can also be initialized with values directly. int[] num = {1,2,3,4,5}; ✒️You can access elements using their index (string Index 0) Looping through arrays:- ✒️You can use loops to traverse arrays. ✒️ Commonly using for or enhanced for loops. ex:- int [] arr = {10,20,30,}; for(int i = 0; i<arr.lenght; i++) { System.out.println(arr[i]); } Advantages of Arrays:- ✒️Arrays allow random access of elements using index. ✒️Arrays are easy to traverse and manipulate using loops. ✒️Arrays help in efficient memory allocation when the size is known. ✒️They store multiple values in a single variable, reducing code complexity. ✒️Arrays are faster in accessing and modifying data compared to some data structures. Two-Dimensional Arrays :- ✒️2D arrays are arrays of arrays. They are useful for matrix-like data representation. Syntax:- dataType[][] arrayName = new dataType[rows][columns]; #arrays #corejava #java #2darrays
To view or add a comment, sign in
-
-
I was building filtering for financial records in my backend. Date range. Category. Amount range. User scope. All optional. All combinable. I started with hardcoded query logic using if-else conditions for different filter cases. It got messy fast. Every new filter meant rewriting existing logic. At one point, the queries looked like they were never meant to be read again. So I scrapped it. I implemented the Specification pattern using Spring Data JPA. Each filter became an isolated, composable predicate. At runtime, only the active ones combine into a single query. No hardcoding. No duplication. Small change in approach. Big impact on scalability and future scope. Now, adding a new filter is just one addition. Existing logic doesn't change. This is the Open/Closed principle from SOLID in practice, open for extension, closed for modification. Each Specification also owns exactly one filter concern. Single Responsibility, naturally enforced. The filtering layer went from something I avoided touching to something I can extend confidently, without regression risk. Interesting how backend complexity shifts as systems grow: performance → security → maintainability. This was firmly the third. #Backend #Java #Maintainability #SOLID #LearningInPublic #SWE
To view or add a comment, sign in
-
🚀 Day 31/40 – DSA Challenge 📌 LeetCode Problem – Mirror Distance of an Integer 📝 Problem Statement Given an integer n, compute its mirror distance: | n - reverse(n) | Where reverse(n) is formed by reversing the digits of n. 📌 Example Input: n = 25 Output: 27 Explanation: reverse(25) = 52 |25 - 52| = 27 💡 Key Insight The main task is correctly reversing the number. 👉 Extract digits one by one 👉 Build the reversed number ⚠️ Important: Do not lose the original value of n while reversing. 🚀 Algorithm 1️⃣ Store original value 2️⃣ Reverse the number using modulo and division 3️⃣ Return absolute difference ✅ Java Code (Correct & Safe) class Solution { public int mirrorDistance(int n) { int original = n; int reversed = 0; while (n != 0) { int digit = n % 10; reversed = reversed * 10 + digit; n /= 10; } return Math.abs(original - reversed); } } ⏱ Complexity Time Complexity: O(d) (d = number of digits) Space Complexity: O(1) ⚠️ Common Mistake (You Had This Earlier) return Math.abs(n - reversed); ❌ 👉 Because n becomes 0 after the loop ✔ Fix: return Math.abs(original - reversed); ✅ 📚 Key Learnings – Day 31 ✔ Preserve original values during transformations ✔ Digit extraction using % and / is fundamental ✔ Small mistakes can break correct logic ✔ Always dry run with simple inputs Simple problem. Careful implementation. Bug fixed, concept clear. Day 31 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Math #LeetCode
To view or add a comment, sign in
-
-
Most developers equate slow APIs with bad code. However, the issue often lies elsewhere. Consider this scenario: You have a query that appears perfectly fine: SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id Yet, the API is painfully slow. Upon checking the execution plan, you find: NESTED LOOP → TABLE ACCESS FULL ORDERS → INDEX SCAN CUSTOMERS At first glance, this seems acceptable. But here's the reality: for each row in orders, the database is scanning and filtering again. If orders contain 1 million rows, that's 1 million loops. The real issue wasn’t the JOIN; it was the database's execution method. After adding an index: CREATE INDEX idx_orders_date ON orders(created_at); The execution plan changed to: INDEX RANGE SCAN ORDERS → INDEX SCAN CUSTOMERS As a result, query time dropped significantly. Key lessons learned include: • Nested Loop is efficient only when: → the outer table is small → the inner table is indexed • Hash Join is preferable when: → both tables are large → there are no useful indexes • Common performance issues stem from: → full table scans → incorrect join order → missing indexes → outdated statistics A common mistake is this Java code: for (Order o : orders) { o.getCustomer(); } This essentially creates a nested loop at the application level (N+1 query problem). Final takeaway: Don’t just write queries; understand how the database executes them. That's where true performance improvements occur. If you've resolved a slow query using execution plans, sharing your experience would be valuable. #BackendDevelopment #DatabaseOptimization #SQLPerformance #QueryOptimization #SystemDesign #SoftwareEngineering #Java #SpringBoot #APIPerformance #TechLearning #Developers #Coding #PerformanceTuning #Scalability #DistributedSystems #DataEngineering #Debugging #TechTips #LearnInPublic #EngineeringLife
To view or add a comment, sign in
-
🔥 Day 552 of #750DaysOfCode 🔥 🔐 LeetCode 2075: Decode the Slanted Ciphertext (Medium) Today’s problem looked tricky at first, but once the pattern clicked, it became super elegant 😄 🧠 Problem Understanding We are given an encoded string that was: Filled diagonally (↘) into a matrix Then read row-wise (→) 👉 Our task is to reverse this process and recover the original text. 💡 Key Insight If encoding is: ➡️ Fill diagonally ➡️ Read row-wise Then decoding is: ➡️ Read diagonally from row-wise string ⚙️ Approach ✅ Step 1: Calculate number of columns cols = encodedText.length() / rows; ✅ Step 2: Traverse diagonals starting from each column for (int startCol = 0; startCol < cols; startCol++) { int row = 0, col = startCol; while (row < rows && col < cols) { result.append(encodedText.charAt(row * cols + col)); row++; col++; } } ✅ Step 3: Remove trailing spaces 🚀 Complexity Time: O(n) Space: O(n) 🧠 What I Learned How to reverse matrix-based encoding patterns Converting 2D traversal → 1D index mapping Importance of pattern recognition in problems 📌 Takeaway Not every problem needs heavy logic. Sometimes, it's just about seeing the pattern correctly 👀 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Algorithms #SoftwareEngineering #100DaysOfCode #750DaysOfCode
To view or add a comment, sign in
-
-
📅 Day 61 out of 100 — Solving LeetCode Problems Daily, Kickstarting My Java + DSA Journey 📘 Course: Data Structures & Algorithms 📈 One Problem a Day: Consistency Compounding. Leetcode Problem_94. Binary Tree Inorder Traversal Given the root of a binary tree, return the inorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [1,3,2] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [4,2,6,5,7,1,3,9,8] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] Constraints: The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100 https://lnkd.in/drecZB7b Solution:- class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; stack<TreeNode*> st; TreeNode* curr = root; while (curr != NULL || !st.empty()) { while (curr != NULL) { st.push(curr); curr = curr->left; } curr = st.top(); st.pop(); result.push_back(curr->val); curr = curr->right; } return result; } };
To view or add a comment, sign in
-
-
🚀 Day 21/40 – 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 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode
To view or add a comment, sign in
-
-
. 🚀 Day 27/40 – DSA Challenge 📌 LeetCode Problem – Middle of the Linked List 📝 Problem Statement Given the head of a singly linked list, return the middle node of the linked list. 👉 If there are two middle nodes, return the second middle node. 📌 Example Input: 1 → 2 → 3 → 4 → 5 Output: 3 📌 Even Case Input: 1 → 2 → 3 → 4 → 5 → 6 Output: 4 💡 My Approach (Counting Method) Instead of using two pointers, I used a two-step approach: 👉 First count total nodes 👉 Then move to the middle 🚀 Algorithm 1️⃣ Traverse the list and count nodes 2️⃣ Calculate middle index: mid = count / 2 3️⃣ Traverse again till mid position 4️⃣ Return that node ✅ Java Code class Solution { public ListNode middleNode(ListNode head) { int count = 0; ListNode temp = head; // Step 1: Count nodes while (temp != null) { count++; temp = temp.next; } // Step 2: Find middle index int mid = count / 2; // Step 3: Traverse to middle temp = head; for (int i = 0; i < mid; i++) { temp = temp.next; } return temp; } } ⏱ Complexity Time Complexity: O(n) (two traversals) Space Complexity: O(1) 📚 Key Learnings – Day 27 ✔ Problems can have multiple valid approaches ✔ Counting method is simple and intuitive ✔ Always think about optimizing further ✔ Same problem can be solved in one pass using fast & slow pointers Simple idea. Clear logic. Solid understanding. Day 27 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode
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