Two Pointers: Given a binary string, check if the string has most number of contiguous segment of one

Problem Statement:

Given a binary string, check if the string has most number of contiguous segment of one

Example:

Input: arr = "110"

Output: true

Input: arr = "11010"

Output: false
The string has 2 different segments of 1

Solution Explanation:

Take a pointer, from index 1 to n-1.

Check each pair (s[i-1], s[i])

if we encounter 0 followed by 1, then there are more than one segment of ones.

if there is no such changes, then return true.

Time Complexity: O(n)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <string>
#include <climits>

using namespace std;

bool solution(string s) 
{
    for (auto i = 1; i < (int)s.size(); i++) 
    {
        if (s[i - 1] == '0' && s[i] == '1')
            return false;
    }

    return true;
}

int main()
{
    string str = "11100";

    if (solution(str))
    {
    	cout<<"True";
    }
    else
    {
    	cout<<"False";
    }

    return 0;
}

Output

True
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *