Open In App

Find Sublist with Contiguous Sum Equal to K

Last Updated : 12 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list, you need to determine if there exists a sublist within the list where the sum of elements in the sublist is equal to a given integer K. Your Task is to write a function that takes the head of a linked list and an integer K as input and returns “Yes” if such a sublist exists and “No” otherwise.

Example:

Input: Linked List: 2 -> 4 -> 1 -> 6 -> 7 -> 2 -> 9 -> NULL , K = 15
Output: Yes
Explanation: Sublist with nodes 6 -> 7 -> 2 adds up to K (15).

Input: Linked List: 3 -> 2 -> 1 – > 7 -> 8 -> 5 -> NULL, K = 9
Output: No
Explanation: There is no sublist whose sum is equal to K (9).

Approach: To solve this problem follow below idea:

The approach involves using two pointers, “start” and “end,” to traverse the linked list while maintaining a running sum. As we move the “end” pointer forward, we continuously update the sum of elements in the sublist between the “start” and “end” pointers. If at any point the sum becomes equal to the target value K, we have found a sublist with the desired sum. If the sum exceeds K, we increment the “start” pointer to exclude elements and reduce the sum. This approach efficiently checks for sublists with the given sum without using additional space, making it an optimal solution for this problem.

Steps of this approach:

  • Initialize two pointers, start and end, to the head of the linked list. Also, initialize a variable sum to 0.
  • Iterate through the linked list using the end pointer, moving it one node at a time.
  • At each step, add the value of the current node pointed to by end to the sum.
  • Check if the sum is equal to K. If it is, return true as we have found a sublist with the desired sum.
  • If the sum becomes greater than K, it means the current sublist’s sum is too large. To find a valid sublist with sum K, we need to adjust the sublist’s starting point. So, enter a nested loop.
  • In the nested loop, increment the start pointer, subtracting its value from the sum, and continue this process until sum becomes less than or equal to K.
  • Continue moving the end pointer, updating the sum at each step, and repeating the nested loop if sum becomes too large.
  • If, at any point during this process, the sum becomes equal to K, return true as we have found a sublist with the desired sum.
  • If the end pointer reaches the end of the linked list and no sublist with sum K is found, return false.

Below is the implementation of the above idea:

C++




#include <iostream>
using namespace std;
 
struct Node {
    int data;
    Node* next;
};
 
// Function to check if there exists a sublist with sum
// equal to K
bool hasSublistWithSumK(Node* head, int K)
{
    if (!head)
        return false; // Empty list
 
    Node* start = head; // Initialize the start pointer
    Node* end = head; // Initialize the end pointer
    int sum = 0; // Initialize the sum
 
    while (end != nullptr) {
        sum += end->data; // Add the current node's data to
                          // the sum
 
        while (sum > K) {
            sum -= start->data; // Remove nodes from the
                                // start to adjust the sum
            start = start->next; // Move the start pointer
                                 // to the next node
        }
 
        if (sum == K) {
            return true; // If the sum is equal to K, return
                         // true
        }
 
        end = end->next; // Move the end pointer to the next
                         // node
    }
 
    // If no sublist with sum K is found
    return false;
}
 
// Helper function to create a new Node
Node* createNode(int data)
{
    Node* newNode = new Node;
    newNode->data = data;
    newNode->next = nullptr;
    return newNode;
}
 
int main()
{
    // Example 1
    Node* head1 = createNode(2);
    head1->next = createNode(4);
    head1->next->next = createNode(1);
    head1->next->next->next = createNode(6);
    head1->next->next->next->next = createNode(7);
    head1->next->next->next->next->next = createNode(2);
    head1->next->next->next->next->next->next
        = createNode(9);
 
    int K1 = 15;
 
    if (hasSublistWithSumK(head1, K1)) {
        cout << "Example 1: Yes" << endl;
    }
    else {
        cout << "Example 1: No" << endl;
    }
 
    // Example 2
    Node* head2 = createNode(3);
    head2->next = createNode(2);
    head2->next->next = createNode(1);
    head2->next->next->next = createNode(7);
    head2->next->next->next->next = createNode(8);
    head2->next->next->next->next->next = createNode(5);
 
    int K2 = 9;
 
    if (hasSublistWithSumK(head2, K2)) {
        cout << "Example 2: Yes" << endl;
    }
    else {
        cout << "Example 2: No" << endl;
    }
 
    return 0;
}


Java




class Node {
    int data;
    Node next;
 
    // Constructor
    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}
 
public class SublistSumJava {
    // Function to check if there exists a sublist with sum equal to K
    static boolean hasSublistWithSumK(Node head, int K) {
        if (head == null) {
            return false; // Empty list
        }
 
        Node start = head; // Initialize the start pointer
        Node end = head; // Initialize the end pointer
        int sum = 0; // Initialize the sum
 
        while (end != null) {
            sum += end.data; // Add the current node's data to the sum
 
            while (sum > K) {
                sum -= start.data; // Remove nodes from the start to adjust the sum
                start = start.next; // Move the start pointer to the next node
            }
 
            if (sum == K) {
                return true; // If the sum is equal to K, return true
            }
 
            end = end.next; // Move the end pointer to the next node
        }
 
        // If no sublist with sum K is found
        return false;
    }
 
    // Helper function to create a new Node
    static Node createNode(int data) {
        Node newNode = new Node(data);
        return newNode;
    }
 
    public static void main(String[] args) {
        // Example 1
        Node head1 = createNode(2);
        head1.next = createNode(4);
        head1.next.next = createNode(1);
        head1.next.next.next = createNode(6);
        head1.next.next.next.next = createNode(7);
        head1.next.next.next.next.next = createNode(2);
        head1.next.next.next.next.next.next = createNode(9);
 
        int K1 = 15;
 
        if (hasSublistWithSumK(head1, K1)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
 
        // Example 2
        Node head2 = createNode(3);
        head2.next = createNode(2);
        head2.next.next = createNode(1);
        head2.next.next.next = createNode(7);
        head2.next.next.next.next = createNode(8);
        head2.next.next.next.next.next = createNode(5);
 
        int K2 = 9;
 
        if (hasSublistWithSumK(head2, K2)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}


Python3




# Define the Node class
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Function to check if there exists a sublist with sum equal to K
def hasSublistWithSumK(head, K):
    if not head:
        return False  # Empty list
 
    start = head  # Initialize the start pointer
    end = head  # Initialize the end pointer
    _sum = 0  # Initialize the sum
 
    while end:
        _sum += end.data  # Add the current node's data to the sum
 
        while _sum > K:
            _sum -= start.data  # Remove nodes from the start to adjust the sum
            start = start.next  # Move the start pointer to the next node
 
        if _sum == K:
            return True  # If the sum is equal to K, return True
 
        end = end.next  # Move the end pointer to the next node
 
    # If no sublist with sum K is found
    return False
 
# Helper function to create a new Node
def createNode(data):
    newNode = Node(data)
    return newNode
 
# Example 1
head1 = createNode(2)
head1.next = createNode(4)
head1.next.next = createNode(1)
head1.next.next.next = createNode(6)
head1.next.next.next.next = createNode(7)
head1.next.next.next.next.next = createNode(2)
head1.next.next.next.next.next.next = createNode(9)
 
K1 = 15
 
if hasSublistWithSumK(head1, K1):
    print("Yes")
else:
    print("No")
 
# Example 2
head2 = createNode(3)
head2.next = createNode(2)
head2.next.next = createNode(1)
head2.next.next.next = createNode(7)
head2.next.next.next.next = createNode(8)
head2.next.next.next.next.next = createNode(5)
 
K2 = 9
 
if hasSublistWithSumK(head2, K2):
    print("Yes")
else:
    print("No")


C#




using System;
 
public class Program
{
    // Node definition for the linked list
    public class Node
    {
        public int Data { get; set; }
        public Node Next { get; set; }
    }
 
    // Function to check if there exists a sublist with sum
    // equal to K
    public static bool HasSublistWithSumK(Node head, int K)
    {
        if (head == null)
            return false; // Empty list
 
        Node start = head; // Initialize the start pointer
        Node end = head; // Initialize the end pointer
        int sum = 0; // Initialize the sum
 
        while (end != null)
        {
            sum += end.Data; // Add the current node's data to the sum
 
            while (sum > K)
            {
                sum -= start.Data; // Remove nodes from the start to adjust the sum
                start = start.Next; // Move the start pointer to the next node
            }
 
            if (sum == K)
            {
                return true; // If the sum is equal to K, return true
            }
 
            end = end.Next; // Move the end pointer to the next node
        }
 
        // If no sublist with sum K is found
        return false;
    }
 
    // Helper function to create a new Node
    public static Node CreateNode(int data)
    {
        return new Node { Data = data, Next = null };
    }
 
    public static void Main()
    {
        // Example 1
        Node head1 = CreateNode(2);
        head1.Next = CreateNode(4);
        head1.Next.Next = CreateNode(1);
        head1.Next.Next.Next = CreateNode(6);
        head1.Next.Next.Next.Next = CreateNode(7);
        head1.Next.Next.Next.Next.Next = CreateNode(2);
        head1.Next.Next.Next.Next.Next.Next = CreateNode(9);
 
        int K1 = 15;
 
        Console.WriteLine(HasSublistWithSumK(head1, K1) ? "Example 1: Yes" : "Example 1: No");
 
        // Example 2
        Node head2 = CreateNode(3);
        head2.Next = CreateNode(2);
        head2.Next.Next = CreateNode(1);
        head2.Next.Next.Next = CreateNode(7);
        head2.Next.Next.Next.Next = CreateNode(8);
        head2.Next.Next.Next.Next.Next = CreateNode(5);
 
        int K2 = 9;
 
        Console.WriteLine(HasSublistWithSumK(head2, K2) ? "Example 2: Yes" : "Example 2: No");
    }
}
 
 
   
  // This code is contributed by akshitaguprzj3


Javascript




<script>
 
// Define the Node class
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 
// Function to check if there exists a sublist with sum equal to K
function hasSublistWithSumK(head, K) {
    if (!head) {
        return false; // Empty list
    }
 
    let start = head; // Initialize the start pointer
    let end = head; // Initialize the end pointer
    let sum = 0; // Initialize the sum
 
    while (end) {
        sum += end.data; // Add the current node's data to the sum
 
        while (sum > K) {
            sum -= start.data; // Remove nodes from the start to adjust the sum
            start = start.next; // Move the start pointer to the next node
        }
 
        if (sum === K) {
            return true; // If the sum is equal to K, return true
        }
 
        end = end.next; // Move the end pointer to the next node
    }
 
    // If no sublist with sum K is found
    return false;
}
 
// Helper function to create a new Node
function createNode(data) {
    return { data: data, next: null };
}
 
// Example 1
let head1 = createNode(2);
head1.next = createNode(4);
head1.next.next = createNode(1);
head1.next.next.next = createNode(6);
head1.next.next.next.next = createNode(7);
head1.next.next.next.next.next = createNode(2);
head1.next.next.next.next.next.next = createNode(9);
 
let K1 = 15;
 
if (hasSublistWithSumK(head1, K1)) {
    console.log("Yes");
} else {
    console.log("No");
}
 
// Example 2
let head2 = createNode(3);
head2.next = createNode(2);
head2.next.next = createNode(1);
head2.next.next.next = createNode(7);
head2.next.next.next.next = createNode(8);
head2.next.next.next.next.next = createNode(5);
 
let K2 = 9;
 
if (hasSublistWithSumK(head2, K2)) {
    console.log("Yes");
} else {
    console.log("No");
}
 
 
</script>


Output

Example 1: Yes
Example 2: No








Time Complexity: O(N), Where N is the number of Nodes in list.
Space Complexity: O(1), As we are not using any extra space.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads