Check Contiguous 1s Sequence in Binary Linked List
Last Updated :
03 Dec, 2023
Given a binary linked list and integer K, the task is to check whether the binary linked list contains a contiguous sequence of 1s of K length.
Examples:
Input: 0 -> 1 -> 1 -> 1 -> 0 -> 1 -> 1 -> 0 -> 1 -> 1, K = 3
Output: True
Explanation: In the given binary linked list, there is a contiguous sequence of three 1s between the second and fourth nodes (1 -> 1 -> 1). Therefore, the output is return True.
Input: 0 -> 0 -> 1 -> 0 -> 1 -> 1 -> 1 -> 1 -> 0, K = 4
Output: True
Explanation: In the given binary linked list, there is a contiguous sequence of four 1s between the fifth and eight nodes (1 -> 1 -> 1). Therefore, the output is return True.
Input: 0 -> 1 -> 0 -> 0-> 0-> 1, K = 5
Output: False
Explanation: In the given binary linked list, there is no contiguous sequence of five 1s so the output is False.
Approach: To solve the problem follow the below idea:
To solve this problem idea is to iterating through the linked list and keeping track of a counter variable count that increments whenever a 1 is encountered and resets to 0 whenever a 0 is encountered.
Here is steps of above approach:
- Initialize variable count to 0.
- Traverse the linked list using a while loop. Inside the loop, we check whether the current node contains a 1 or a 0.
- If the current node contains a 1, we increment a counter variable count by 1.
- If the value of count becomes equal to K, it means we have found a contiguous sequence of 1s of length K, so we set the Boolean flag variable flag to true and break out of the loop.
- the current node contains a 0, we reset the value of count to 0, since a contiguous sequence of 1s has been broken.
- Finally, we return the value of flag, which indicates whether we found a contiguous sequence of 1s of length K in the linked list.
Below is the implementation of the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Defining the structure of a node
// in a binary linked list
struct Node {
int data;
Node* next;
};
// Function to create a new node
Node* newNode(int data)
{
Node* node = new Node();
node->data = data;
node->next = NULL;
return node;
}
// Function to determine whether the
// given binary linked list contains a
// contiguous sequence of 1s of length K
bool containsContiguousSequence(Node* head, int K)
{
// Initialize a counter for consecutive 1s
int count = 0;
// Initialize a flag to indicate if
// the contiguous sequence is found
bool flag = false;
while (head) {
// Increment the count if the current
// node contains 1
if (head->data == 1) {
count++;
if (count == K) {
// Set the flag to true if the
// contiguous sequence of
// length K is found
flag = true;
// Exit the loop early since the
// sequence has been found
break;
}
}
// Reset the count if the current
// node contains 0
else {
count = 0;
}
// Move to the next node in the
// linked list
head = head->next;
}
// Return true if a contiguous sequence of
// 1s of length K was found, otherwise
// false
return flag;
}
// Driver code
int main()
{
// Creating a sample binary linked list
Node* head = newNode(0);
head->next = newNode(1);
head->next->next = newNode(1);
head->next->next->next = newNode(1);
head->next->next->next->next = newNode(0);
head->next->next->next->next->next = newNode(1);
head->next->next->next->next->next->next = newNode(1);
head->next->next->next->next->next->next->next
= newNode(0);
head->next->next->next->next->next->next->next->next
= newNode(1);
head->next->next->next->next->next->next->next->next
->next
= newNode(1);
bool result = containsContiguousSequence(head, 3);
// Printing the result
if (result) {
cout << "True";
}
else {
cout << "False";
}
return 0;
}
Java
// Defining the structure of a node in a binary linked list
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class Main {
// Function to determine whether the given binary linked list contains
// a contiguous sequence of 1s of length K
public static boolean containsContiguousSequence(Node head, int K) {
// Initialize a counter for consecutive 1s
int count = 0;
// Initialize a flag to indicate if the contiguous sequence is found
boolean flag = false;
while (head != null) {
// Increment the count if the current node contains 1
if (head.data == 1) {
count++;
if (count == K) {
// Set the flag to true if the contiguous sequence of length K is found
flag = true;
// Exit the loop early since the sequence has been found
break;
}
} else {
// Reset the count if the current node contains 0
count = 0;
}
// Move to the next node in the linked list
head = head.next;
}
// Return true if a contiguous sequence of 1s of length K was found, otherwise false
return flag;
}
public static void main(String[] args) {
// Creating a sample binary linked list
Node head = new Node(0);
head.next = new Node(1);
head.next.next = new Node(1);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(0);
head.next.next.next.next.next = new Node(1);
head.next.next.next.next.next.next = new Node(1);
head.next.next.next.next.next.next.next = new Node(0);
head.next.next.next.next.next.next.next.next = new Node(1);
head.next.next.next.next.next.next.next.next.next = new Node(1);
boolean result = containsContiguousSequence(head, 3);
// Printing the result
if (result) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
//Contributed by Aditi Tyagi
Python3
class Node:
def __init__(self, data):
self.data = data
self.next = None
def contains_contiguous_sequence(head, K):
# Initialize a counter for consecutive 1s
count = 0
# Initialize a flag to indicate if the contiguous sequence is found
flag = False
while head:
# Increment the count if the current node contains 1
if head.data == 1:
count += 1
if count == K:
# Set the flag to true if the contiguous sequence of
# length K is found
flag = True
# Exit the loop early since the sequence has been found
break
else:
# Reset the count if the current node contains 0
count = 0
# Move to the next node in the linked list
head = head.next
# Return True if a contiguous sequence of 1s of length K was found, otherwise False
return flag
# Driver code
if __name__ == "__main__":
# Creating a sample binary linked list
head = Node(0)
head.next = Node(1)
head.next.next = Node(1)
head.next.next.next = Node(1)
head.next.next.next.next = Node(0)
head.next.next.next.next.next = Node(1)
head.next.next.next.next.next.next = Node(1)
head.next.next.next.next.next.next.next = Node(0)
head.next.next.next.next.next.next.next.next = Node(1)
head.next.next.next.next.next.next.next.next.next = Node(1)
result = contains_contiguous_sequence(head, 3)
# Printing the result
if result:
print("True")
else:
print("False")
C#
// C# Code
using System;
// Defining the structure of a node in a binary linked list
public class Node
{
public int Data { get; set; }
public Node Next { get; set; }
public Node(int data)
{
Data = data;
Next = null;
}
}
public class GFG
{
// Function to determine whether the given binary linked list contains
// a contiguous sequence of 1s of length K
public static bool ContainsContiguousSequence(Node head, int K)
{
// Initialize a counter for consecutive 1s
int count = 0;
// Initialize a flag to indicate if the contiguous sequence is found
bool flag = false;
while (head != null)
{
// Increment the count if the current node contains 1
if (head.Data == 1)
{
count++;
if (count == K)
{
// Set the flag to true if the contiguous sequence of length K is found
flag = true;
// Exit the loop early since the sequence has been found
break;
}
}
else
{
// Reset the count if the current node contains 0
count = 0;
}
// Move to the next node in the linked list
head = head.Next;
}
// Return true if a contiguous sequence of 1s of length K was found, otherwise false
return flag;
}
public static void Main()
{
// Creating a sample binary linked list
Node head = new Node(0);
head.Next = new Node(1);
head.Next.Next = new Node(1);
head.Next.Next.Next = new Node(1);
head.Next.Next.Next.Next = new Node(0);
head.Next.Next.Next.Next.Next = new Node(1);
head.Next.Next.Next.Next.Next.Next = new Node(1);
head.Next.Next.Next.Next.Next.Next.Next = new Node(0);
head.Next.Next.Next.Next.Next.Next.Next.Next = new Node(1);
head.Next.Next.Next.Next.Next.Next.Next.Next.Next = new Node(1);
bool result = ContainsContiguousSequence(head, 3);
// Printing the result
if (result)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
}
}
// This code is contributed by guptapratik
JavaScript
// Definition of a node in a binary linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to determine whether the given binary linked list contains a contiguous sequence of 1s of length K
function containsContiguousSequence(head, K) {
// Initialize a counter for consecutive 1s
let count = 0;
// Initialize a flag to indicate if the contiguous sequence is found
let flag = false;
while (head) {
// Increment the count if the current node contains 1
if (head.data === 1) {
count++;
if (count === K) {
// Set the flag to true if the contiguous sequence of length K is found
flag = true;
// Exit the loop early since the sequence has been found
break;
}
} else {
// Reset the count if the current node contains 0
count = 0;
}
// Move to the next node in the linked list
head = head.next;
}
// Return true if a contiguous sequence of 1s of length K was found, otherwise false
return flag;
}
// Main function
function main() {
// Creating a sample binary linked list
const head = new Node(0);
head.next = new Node(1);
head.next.next = new Node(1);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(0);
head.next.next.next.next.next = new Node(1);
head.next.next.next.next.next.next = new Node(1);
head.next.next.next.next.next.next.next = new Node(0);
head.next.next.next.next.next.next.next.next = new Node(1);
head.next.next.next.next.next.next.next.next.next = new Node(1);
const result = containsContiguousSequence(head, 3);
// Printing the result
console.log(result ? "True" : "False");
}
// Call the main function
main();
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1), since we are only using a constant amount of extra space to store the counter variable count and the Boolean flag variable flag.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read