
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check If a String Contains All Binary Codes of Size K in C++
Suppose we have a binary string s and an integer k. We have to check whether every binary code of length k is a substring of s. Otherwise, return False.
So, if the input is like S = "00110110", k = 2, then the output will be true. The binary codes of length 2 are "00", "01", "10" and "11". These are present at indices 0, 1, 3, and 2 respectively.
To solve this, we will follow these steps −
Define one set v
temp := blank string
req := 2^k
for initialize i := 0, when i < size of s, update (increase i by 1), do −
temp := temp + s[i]
if i >= k, then −
delete one character from the first index of temp
if i >= k - 1, then −
insert temp into v
if size of v is same as req, then −
return true
return false
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: lli fastPow(lli b, lli p){ lli ret = 1; while (p) { if (p & 1) { ret *= b; } b *= b; p >>= 1; } return ret; } bool hasAllCodes(string s, int k) { unordered_set<string> v; string temp = ""; lli req = fastPow(2, k); for (lli i = 0; i < s.size(); i++) { temp += s[i]; if (i >= k) { temp.erase(0, 1); } if (i >= k - 1) { v.insert(temp); } if ((lli)v.size() == req) return true; } return false; } }; main(){ Solution ob; cout << (ob.hasAllCodes("00110110",2)); }
Input
"00110110",2
Output
1
- Related Articles
- Check if a binary string contains all permutations of length k in C++
- Check if a Binary Tree contains duplicate subtrees of size 2 or more in C++
- Check if a binary string contains consecutive same or not in C++
- Python program to check if a string contains all unique characters
- Check if a string contains a sub-string in C++
- Check if a string contains numbers in MySQL?
- Check if string contains another string in Swift
- Check if a field contains a string in MongoDB?
- Check if a String Contains a Substring in Linux
- Check if a string contains a palindromic sub-string of even length in Python
- Check if a string contains a palindromic sub-string of even length in C++
- Check if all the 1s in a binary string are equidistant or not in Python
- How to check if a string contains a specific sub string?
- Check if a string contains a number using Java.
- Check if string contains special characters in Swift
