Day 50 of My DSA Journey Today I reached a major milestone—Day 50! To celebrate, I tackled "Design Linked List" on LeetCode using Java. This was a great exercise in understanding the fundamental mechanics of data structures. Problem Summary The task is to manually implement a Singly or Doubly Linked List from scratch. This includes creating functions to: Get the value of a node at a specific index. Add a node at the head and tail. Add a node before a specific index. Delete a node at a specific index. 🛠️ My Approach I chose to implement a Singly Linked List using a Sentinel (Dummy) Node. Sentinel Node: Used a dummy head to simplify edge cases (like adding or deleting at the very beginning of the list). Pointer Management: Carefully tracked the next references to ensure the chain remains intact during insertions and deletions. Size Tracking: Maintained a size variable to perform quick bounds checking for index-based operations. Complexity Analysis Time Complexity: * $O(1)$ for addAtHead. $O(n)$ for get, addAtIndex, and deleteAtIndex (where $n$ is the length of the list). Space Complexity: $O(n)$ to store the $n$ nodes of the linked list. Result Accepted! Successfully handled the zero-indexing and edge cases for an efficient implementation. Key Learning Manual Memory Logic: Implementing your own data structure builds a much deeper intuition than just using ArrayList. Sentinel Power: Using a dummy node is a "pro-tip" that eliminates many if (head == null) checks, making the code much cleaner and less error-prone. Index Precision: Off-by-one errors are the biggest challenge in Linked Lists; tracing the "previous" node is the key to success. #DSA #LeetCode #Java #DataStructures #CodingJourney #100DaysOfCode #Day50
Implementing Linked List in Java for LeetCode Challenge
More Relevant Posts
-
🚀 #100DaysOfCode – Day 20 Today’s problem: Kth Largest Element in an Array 📊 Given an integer array nums and an integer k, return the kth largest element in the array (not necessarily distinct). 🔴 Brute Force Approach Sort the array in descending order Return the element at index k-1 ⛔ Time Complexity: O(n log n) 👉 Sorting the entire array is unnecessary when we only need one element 🟢 Optimized Approach (Min Heap) 💡 Idea: Use a Min Heap of size k Keep only the k largest elements The top of the heap will always be the kth largest ✅ Code: class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int num : nums) { pq.offer(num); if (pq.size() > k) { pq.poll(); } } return pq.peek(); } } 🧠 Key Insight 👉 Instead of sorting everything, maintain only the k largest elements If heap size exceeds k → remove smallest The smallest in heap = kth largest overall ⚡ Complexity Time: O(n log k) Space: O(k) 🔍 Example nums = [3,2,1,5,6,4], k = 2 Step-by-step heap: Add → maintain size k 👉 Final heap → [5,6] 👉 Answer = 5 💡 Learning of the Day When solving problems: 👉 Don’t process everything — process only what’s required #Day20 #100DaysOfCode #DSA #Java #Heap #PriorityQueue #CodingJourney #LeetCode #ProblemSolving
To view or add a comment, sign in
-
🚀 #Day31/300 — Mastering DSA Challenge Continuing my 300-day journey to strengthen my Data Structures & Algorithms skills using Java. 📌 Daily Goals • Solve at least 1 problem every day • Focus on pattern recognition and optimized solutions • Share consistent learning updates along the journey 🧠 Today’s Problem: Smallest Range in K Lists Solved this problem using a Min Heap (Priority Queue) approach along with tracking the current maximum element. The idea is to always consider one element from each list and minimize the range between the minimum and maximum values. 💡 Key Takeaways: • Use Min Heap to track the smallest element among K lists • Keep updating the current maximum to calculate range • Helps in solving multi-pointer problems efficiently • Time Complexity: O(n log k) This problem strengthened my understanding of heap-based merging, range optimization, and handling multiple sorted lists. Staying consistent and improving every day in this 300-day DSA journey. 💪 #DSA #Java #ProblemSolving #BackendDeveloper #FullStackDeveloper #300DaysChallenge #LearningInPublic #Heap #PriorityQueue #Algorithms #SDE #React #ReactNative #JavaFullStack #SpringBoot
To view or add a comment, sign in
-
-
🚀 Day 21/100 – DSA Challenge Today’s problem: Daily Temperatures 🌡️ The task is to find how many days you have to wait for a warmer temperature. If no such day exists, return 0. 🔴 Brute Force Approach (O(n²)) 👉 For each day, check all future days until you find a warmer temperature. 📌 Java Code: class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] result = new int[n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (temperatures[j] > temperatures[i]) { result[i] = j - i; break; } } } return result; } } 🟢 Optimized Approach: Monotonic Stack (O(n)) 👉 Instead of checking every future day, use a stack to store indices and resolve them when a warmer day appears. 📌 Java Code: class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] result = new int[n]; Stack<Integer> st = new Stack<>(); for (int i = 0; i < n; i++) { while (!st.isEmpty() && temperatures[i] > temperatures[st.peek()]) { int prevPos = st.pop(); result[prevPos] = i - prevPos; } st.push(i); } return result; } } ⚡ Complexity Comparison: Brute Force → O(n²) Optimized (Stack) → O(n) 🎯 Key Learning: Whenever you see “next greater element” type problems, think monotonic stack 🔥 📈 Day 21 done—consistency is the real win! #100DaysOfCode #DSA #Java #CodingChallenge #LearningJourney
To view or add a comment, sign in
-
DSA Day 4 – Simple Problem, Important Insight Today I solved the “Contains Duplicate” problem on LeetCode. Problem: Check if any element appears more than once in an array. Initial Thought: -> Use nested loops to compare every pair -> Time Complexity: O(n²) ❌ Optimized Approach: -> Used HashMap to track elements -> While iterating, check if element already exists -> If yes → duplicate found Time Complexity: -> O(n) -> Space Complexity: O(n) Key Learning: -> Not every problem needs complex logic -> Choosing the right data structure makes a big difference -> Hashing is one of the most powerful tools in DSA What I Realized: Sometimes the simplest problems teach the most important concepts. Thanks to Pulkit Aggarwal sir for guiding me in DSA and helping me build strong fundamentals. Staying consistent, one day at a time. #DSA #LeetCode #Java #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 49 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Set Mismatch Problem Insight: Given an array containing numbers from 1 to n, one number is duplicated and one number is missing. The goal is to find both of them. Approach: • Used a frequency array to count occurrences of each number • Traversed the input array and updated frequency • Iterated from 1 to n: – If frequency is 2 → duplicate element – If frequency is 0 → missing element • Returned both values as the final result Time Complexity: O(n) Space Complexity: O(n) Key Learnings: • Frequency array is a simple and powerful technique for counting problems • Helps quickly identify missing and repeating elements • Clean and easy-to-understand approach for beginners Takeaway: Sometimes the simplest approach is the most effective. Mastering basic patterns like counting can solve many problems efficiently! #DSA #Java #LeetCode #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 #100DaysOfCode – Day 19 Today’s challenge: Kth Distinct String in an Array 🔤 You’re given an array of strings and an integer k. Your task is to return the kth distinct string — a string that appears exactly once, while also respecting the original order. 🔴 Brute Force Approach For every string, count its occurrences by scanning the entire array Track distinct elements in order ⛔ Time Complexity: O(n²) 👉 Repeated counting makes it inefficient 🟢 Optimized Approach (HashMap + Order Preservation) 💡 Idea: First, count frequency of each string using a HashMap Then, iterate again to maintain original order Decrease k when a distinct string is found ✅ Code: class Solution { public String kthDistinct(String[] arr, int k) { Map<String, Integer> mp = new HashMap<>(); // Count frequency for (var s : arr) { mp.put(s, mp.getOrDefault(s, 0) + 1); } // Find kth distinct for (var s : arr) { if (mp.get(s) == 1) { k--; } if (k == 0) { return s; } } return ""; } } 🧠 Key Insight 👉 Use HashMap for frequency counting 👉 Use array traversal to preserve order This combination ensures: Efficient lookup Correct ordering ⚡ Complexity Time: O(n) Space: O(n) 🔍 Example arr = ["a","b","a","c","d","c"], k = 2 Distinct elements → ["b", "d"] 👉 Output = "d" 💡 Learning of the Day Efficiency is not just about speed — it’s about combining the right data structures with the right traversal strategy. #Day19 #100DaysOfCode #DSA #Java #HashMap #CodingJourney #LeetCode #ProblemSolving
To view or add a comment, sign in
-
#Day53 of #100DaysDSAChallenge 🚀 Solved #LeetCode328: Odd Even Linked List The problem asks us to rearrange the nodes of a singly linked list such that all odd indexed nodes come first, followed by even indexed nodes, while preserving their relative order. 🔹 Approach: Brute Force Approach First traverse the linked list and store odd and even indexed values separately using an ArrayList. Then rewrite these values back into the linked list in required order. Time Complexity: O(n) Space Complexity: O(n) 🔹 Optimal Approach (Two Pointer Technique) Use two pointers: odd and even. Keep track of the head of even list (evenHead). Traverse the list and rearrange the next pointers such that: odd nodes are linked together even nodes are linked together Finally, connect the odd list with evenHead. Time Complexity: O(n) Space Complexity: O(1) 💡 Key Learning Instead of modifying values, focus on re-linking nodes for better space optimization. 🧠 Example Input: 1 → 2 → 3 → 4 → 5 Output: 1 → 3 → 5 → 2 → 4 Github repo: https://lnkd.in/g_rSFCh8 #100DaysOfDSA #DSA #LeetCode #Java #Algorithms #DataStructures #KunalKushwaha #Striver #GeeksForGeeks #ProblemSolving #CodingJourney #LearningInPublic #InterviewPrep #PlacementPreparation 🚀
To view or add a comment, sign in
-
-
🚀 #Day30/300 — Mastering DSA Challenge Continuing my 300-day journey to strengthen my Data Structures & Algorithms skills using Java. 📌 Daily Goals • Solve at least 1 problem every day • Focus on pattern recognition and optimized solutions • Share consistent learning updates along the journey 🧠 Today’s Problem: Find Median from Data Stream Solved this problem using the Two Heaps approach (Max Heap + Min Heap). Maintained one heap for the smaller half of elements and another for the larger half to efficiently calculate the median at any point. 💡 Key Takeaways: • Use Max Heap for the left half and Min Heap for the right half • Balance both heaps to maintain size difference ≤ 1 • Median can be retrieved in O(1) time • Time Complexity per insertion: O(log n) This problem strengthened my understanding of heap balancing, stream processing, and real-time median calculation. Staying consistent and improving every day in this 300-day DSA journey. 💪 #DSA #Java #ProblemSolving #BackendDeveloper #FullStackDeveloper #300DaysChallenge #LearningInPublic #Heap #PriorityQueue #Algorithms #SDE #React #ReactNative #JavaFullStack #SpringBoot
To view or add a comment, sign in
-
-
🚀 How HashSet Stores Data Without Remembering the Order. ( https://lnkd.in/gUPxBhjX ) ➡️ HashSet is a powerful Java collection that guarantees uniqueness using Hashing — but trades insertion order for blazing-fast O(1) performance. 🔹 Post Office Sorting: Imagine dropping letters into sorted bins based on a code on the envelope. You don't care which order they arrived — you only care that each bin holds the right letter. That's exactly how a hash function places elements into bucket locations. Here are the key takeaways from the HashSet & LinkedHashSet session at TAP Academy by Sharath R sir: 🔹 **Hashing = Hash Table + Hash Function:** The hash function takes your input, computes a unique bucket address, and stores the element there — giving constant O(1) time for add, remove, and search operations. 🔹 **No Duplicates, Ever:** Identical values always produce the same hash → same bucket → bucket already occupied → element rejected. This is why HashSet cannot store duplicates — it's not a rule, it's a mathematical guarantee. 🔹 **Collision Handling is Built In:** When two different values land on the same bucket, a LinkedList is created at that location. If collisions keep growing beyond 8 nodes, Java automatically converts it to a Red-Black Tree for efficiency. 🔹 **Load Factor Controls Resizing:** The default capacity is 16 buckets with a load factor of 0.75. Once 75% of buckets are filled (after the 12th element), HashSet doubles in size and rehashes everything — keeping performance consistent. 🔹 **HashSet vs LinkedHashSet — One Key Difference:** Both offer O(1) performance and reject duplicates. The only difference is that LinkedHashSet maintains insertion order internally using a LinkedList alongside the hash table — a small overhead for a big quality-of-life improvement. #Java #JavaDeveloper #Collections #HashSet #DataStructures #TAPAcademy #LearningEveryDay #SoftwareEngineering #CodingJourney #PlacementPrep
To view or add a comment, sign in
-
-
Beginning this journey to learn in public and stay consistent with Problem :- Contains Duplicate (LeetCode 217) Problem Statement :- Given an integer array, return true if any value appears at least twice, otherwise return false. Approach 1 :- Brute Force (Nested Loops) i - Compare every element with others ii - Time Complexity:- O(n²) => because of nested loops iii - Simple but inefficient for large inputs class Solution { public boolean containsDuplicate(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] == nums[j]) return true; } } return false; } } Approach 2 :- Optimized (Sorting) Sort array → check adjacent elements Time Complexity:- O(n log n) class Solution { public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for (int i = 1; i < nums.length; i++) { if (nums[i] == nums[i - 1]) return true; } return false; } } Key Learning: Start with brute force → then optimize. How would you optimize this further? One problem. Every day. No shortcuts, just consistency. #LeetCode #Java #DSA #CodingChallenge #SoftwareEngineering #Arrays #Sorting
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