VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-continuous-nodes-with-sum-k-from-a-given-linked-list/

⇱ Delete continuous nodes with sum K from a given linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete continuous nodes with sum K from a given linked list

Last Updated : 12 Jul, 2025

Given a singly linked list and an integer K, the task is to remove all the continuous set of nodes whose sum is K from the given linked list. Print the updated linked list after the removal. If no such deletion can occur, print the original Linked list.

Examples:  

Input: Linked List: 1 -> 2 -> -3 -> 3 -> 1, K = 3 

Output: -3 -> 1 

Explanation: 

The nodes with continuous sum 3 are: 

1) 1 -> 2 

2) 3 

Therefore, after removing these chain of nodes Linked List becomes: -3-> 1

Input: Linked List: 1 -> 1 -> -3 -> -3 -> -2, K = 5 
Output: 1 -> 1 -> -3 -> -3 -> -2 
Explanation: 
No continuous nodes exits with sum K 

Approach:  

  1. Append Node with value zero at the starting of the linked list.
  2. Traverse the given linked list.
  3. During traversal store the sum of the node value till that node with the reference of the current node in an unordered_map.
  4. If there is Node with value (sum - K) present in the unordered_map then delete all the nodes from the node corresponding to value (sum - K) stored in map to the current node and update the sum as (sum - K).
  5. If there is no Node with value (sum - K) present in the unordered_map, then stored the current sum with node in the map.

Below is the implementation of the above approach: 


Output
1 -> 2 -> -3 -> 3 -> 1

Time Complexity: O(N), where N is the number of Node in the Linked List. 
Auxiliary Space Complexity: O(N), where N is the number of Node in the Linked List.

Comment