Day 27/100 Problem Statement: There is a singly-linked list head and we want to delete a node node in it. You are given the node to be deleted node. You will not be given access to the first node of head. All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: The value of the given node should not exist in the linked list. The number of nodes in the linked list should decrease by one. All the values before node should be in the same order. All the values after node should be in the same order. Custom testing: For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list. We will build the linked list and pass the node to your function. The output will be the entire list after calling your function. Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Solution: https://lnkd.in/gi8zCZUG public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } #100DaysDSA #100DaysOfCode #Java #LeetCode #Neetcode #Neetcode250
Delete a Node in a Singly-Linked List
More Relevant Posts
-
Day 46/100 Problem Statement : You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer. Input: target = [1,2,3,2,1] Output: 3 Solution : https://lnkd.in/gsXFvUr3 public int minNumberOperations(int[] target) { final int n=target.length; int ans=target[0]; for(int i=1; i<n; i++) ans+=Math.max(target[i]-target[i-1], 0); return ans; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
To view or add a comment, sign in
-
Day 43/100 Problem Statement : Given an array nums, you can perform the following operation any number of times: Select the adjacent pair with the minimum sum in nums. If multiple such pairs exist, choose the leftmost one. Replace the pair with their sum. Return the minimum number of operations needed to make the array non-decreasing. An array is said to be non-decreasing if each element is greater than or equal to its previous element (if it exists). Input: nums = [5,2,3,1] Output: 2 Solution : https://lnkd.in/g3Z6NQxN public int minimumPairRemoval(int[] nums) { int length = nums.length - 1; int count = 0; while(length > 0) { boolean increase = true; int minSum = Integer.MAX_VALUE; int minIndex = -1; for(int i = 0; i < length; i++) { if(nums[i] > nums[i + 1]) increase = false; if(nums[i] + nums[i + 1] < minSum) { minSum = nums[i] + nums[i + 1]; minIndex = i; } } if(increase) break; nums[minIndex] = minSum; for(int i = minIndex + 1; i < length; i++) nums[i] = nums[i + 1]; length--; count++; } return count; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
To view or add a comment, sign in
-
🔥 Day 97 of my 100 Days of Code Problem: Binary Tree Inorder Traversal (LeetCode #94) Problem Description: Given the root of a binary tree, return the inorder traversal of its nodes’ values. Inorder means visiting nodes in this order: Left -> Node -> Right Java Solution: class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode current = root; while (current != null || !stack.isEmpty()) { // Reach the leftmost node while (current != null) { stack.push(current); current = current.left; } // Process node current = stack.pop(); result.add(current.val); // Visit right subtree current = current.right; } return result; } } Time Complexity: O(n) Space Complexity: O(n) (for stack in the worst case) #Day97 #LeetCode #100DaysOfCode #Java #BinaryTree #DFS
To view or add a comment, sign in
-
-
🚀 Day 6 of 30 Days of Data Structures Challenge Topics Covered Today: 🔹 Java Collection Framework (JCF) – LinkedList 🔹 Explored in-built LinkedList methods like add(), remove(), get(), addFirst(), addLast() and more. 🔹 Implemented Merge Sort on a LinkedList from Scratch. 📂 Code: https://lnkd.in/gk5-kdKv https://lnkd.in/gfdmpVWf #Java #DataStructures #LinkedList #MergeSort #JCF
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 73 String Manipulation Problem: Valid Anagram (LeetCode #242) Task: Given two strings s and t, return true if t is an anagram of s, otherwise false. Example: Input: s = "anagram", t = "nagaram" → Output: true Input: s = "rat", t = "car" → Output: false My Approach:- Method 1 – Sorting Converted both strings into character arrays. Sorted them and compared if equal, they’re anagrams! Time Complexity: O(n log n) Method 2 – Frequency Count (Optimized) Counted occurrences of each character in s and t. If every count matches, it’s a valid anagram. Time Complexity: O(n) | Space: O(1) String problems may look simple, but optimizing from sorting to counting makes a huge difference. Small logic shifts often lead to big performance gains! #100DaysOfCode #Java #ProblemSolving #LeetCode #CodingJourney #takeUforward #DataStructures #Algorithms #StringManipulation #GeeksForGeeks #CodeNewbie
To view or add a comment, sign in
-
-
💻 Day 03/10 of Linked List Series: Inserting a Node at the Beginning of a Linked List Let’s understand how we can add a new node at the start of a linked list 👇 ⚙️ Algorithm: Insert at Beginning Create a new node with the given data (for example, 'A'). Set the next pointer of this new node to point to the current head of the list. Now, make this new node the new head of the linked list. 💡 In simple terms: you’re placing a new link before the first link in the chain. 🧩 Example Explanation: Initial list: B → C → D We want to insert 'A' at the beginning. Steps: Create a new node 'A'. Point 'A' → 'B'. Return node 'A'. ✅ Final list becomes: A → B → C → D ✨ This operation is one of the most common and easiest insert operations in linked lists — it just needs a few pointer adjustments! 📚 Stay tuned for the next part in this #LinkedListSeries! Follow my Brand 👉 #CodeWithLakkojuEswaraSai #CodeWithLakkojuEswaraSai_LinkedList #DSA #Java #10000coders
To view or add a comment, sign in
-
-
How try-with-resources Handles Dependent Resources in Java Last week, I talked about how try-with-resources made it easier to close connections automatically. But what about when one resource depends on another — like a ResultSet that relies on a PreparedStatement, which relies on a Connection? Before (old way): Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("SELECT * FROM orders WHERE customer_id = ?"); stmt.setInt(1, id); rs = stmt.executeQuery(); while (rs.next()) { process(rs); } } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } After (try-with-resources): try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM orders WHERE customer_id = ?"); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { process(rs); } } Java automatically closes everything in reverse order of creation: ResultSet → Statement → Connection No leaks, no nested finally blocks, no forgotten close calls. It’s small things like this that make Java cleaner every release. 👉 Did you know try-with-resources handled dependencies this neatly? #Java #CleanCode #SoftwareEngineering #Refactoring #Java17 #BestPractices
To view or add a comment, sign in
-
🌱 Day 4 of My Tech Journey — Understanding @PathVariable & @RequestParam in Spring Boot Today I explored how to send data through a REST API in Spring Boot using path parameters and query parameters. Here’s a simple example: @RestController @RequestMapping("/api") public class UserController { @GetMapping("/user/{id}") public String getUser(@PathVariable int id, @RequestParam(required = false) String name) { return "User ID: " + id + ", Name: " + name; } } 👉 Output: User ID: 10, Name: Harshita 🔑 Takeaway: @PathVariable is used to pass values inside the URL, while @RequestParam is used for query parameters. #SpringBoot #Java #RESTAPI #CodingJourney #BackendDevelopment
To view or add a comment, sign in
-
💻 Day 52 of #100DaysOfCodeChallenge Today’s problem: LeetCode 203 – Remove Linked List Elements 🧩 I worked on a Linked List manipulation problem where the goal is to remove all nodes that match a given value. This problem helped strengthen my understanding of pointer handling and dummy node usage in linked lists. 🧠 What I Learned: Handling edge cases where the head itself might need to be removed. Using a dummy node before the head to simplify pointer operations. How current and next pointers work together to modify a linked list safely. 🧩 Java Solution: class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode current = dummy; while (current.next != null) { if (current.next.val == val) current.next = current.next.next; else current = current.next; } return dummy.next; } } ⏱️ Complexity: Time: O(n) Space: O(1) Every day, I’m getting more confident with data structures and linked list traversal logic. On to the next challenge 🚀 #Day52 #LeetCode #Java #100DaysOfCode #CodingChallenge #LinkedList #ProblemSolving
To view or add a comment, sign in
-
-
🔰 𝐃𝐚𝐲 𝟖𝟑/𝟏𝟎𝟎 – 𝟏𝟎𝟎 𝐃𝐚𝐲𝐬 𝐨𝐟 𝐉𝐚𝐯𝐚 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞 📌 𝐓𝐨𝐩𝐢𝐜: 𝐓𝐡𝐫𝐞𝐚𝐝 𝐏𝐨𝐨𝐥 𝐢𝐧 𝐉𝐚𝐯𝐚 – 𝐄𝐟𝐟𝐢𝐜𝐢𝐞𝐧𝐭 𝐓𝐡𝐫𝐞𝐚𝐝 𝐌𝐚𝐧𝐚𝐠𝐞𝐦𝐞𝐧𝐭 After exploring Future and CompletableFuture, it’s time to understand how Java manages multiple threads efficiently using Thread Pools. 🔹 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐚 𝐓𝐡𝐫𝐞𝐚𝐝 𝐏𝐨𝐨𝐥? ✔ A Thread Pool is a group of pre-created threads reused to execute multiple tasks. ✔ Prevents creating new threads every time a task starts. ✔ Part of the Executor Framework, it helps optimize performance and resource usage. 🔹 𝐖𝐡𝐲 𝐔𝐬𝐞 𝐓𝐡𝐫𝐞𝐚𝐝 𝐏𝐨𝐨𝐥𝐬? ✔ Improves performance by reusing threads. ✔ Reduces overhead of thread creation. ✔ Controls concurrency by limiting active threads. ✔ Prevents resource exhaustion caused by too many threads. 🔹 𝐓𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐡𝐫𝐞𝐚𝐝 𝐏𝐨𝐨𝐥𝐬 (𝐯𝐢𝐚 𝐄𝐱𝐞𝐜𝐮𝐭𝐨𝐫𝐬 𝐂𝐥𝐚𝐬𝐬) 1️⃣ newFixedThreadPool(int n) → Fixed number of threads. 2️⃣ newCachedThreadPool() → Creates threads as needed and reuses idle ones. 3️⃣ newSingleThreadExecutor() → Single worker thread for sequential tasks. 4️⃣ newScheduledThreadPool(int n) → Runs tasks with delay or periodically. 🔹 𝐑𝐞𝐚𝐥-𝐋𝐢𝐟𝐞 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 🌐 Imagine a web server handling hundreds of client requests. Instead of creating a new thread per request, a Thread Pool efficiently reuses existing threads — improving speed and stability. 💡 𝐅𝐢𝐧𝐚𝐥 𝐓𝐡𝐨𝐮𝐠𝐡𝐭 Using Thread Pools is a best practice in multithreaded applications. They make your system faster, scalable, and resource-efficient. #Java #CoreJava #ThreadPool #ExecutorFramework #Concurrency #Multithreading #JavaProgramming #PerformanceOptimization #100DaysOfJava #100DaysOfCode #CodingChallenge #JavaDeveloper
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