Open In App

Check Contiguous 1s Sequence in Binary Linked List

Last Updated : 03 Dec, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report

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++
Java Python3 C# JavaScript

Output
True

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