Searching: Check if all occurrence if a character appear together

Problem Statement:

You are given a string s and key k, you need to check if all the occurrence of k are together

Example:

Input:

s = '112233003344' k = '1'

Output: Yes

Input:

s = '1122330033441122' k = '1'

Output: No

Because all the occurrence of 1 are not together.

Solution : Brute force approach

Traverse the string and we check if the set of strings equal to ‘k’ and keep a bool value.

Then traverse full string and check if any other string with the same as k and return false.

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

Code Solution

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <limits.h>

using namespace std;

bool solution_1 (string s, char c)
{

	bool result = false;

	int i = 0;
	int n = s.length();

	while (i < n) 
	{
	 
		if (s[i] == c) 
		{
			if (result == true)
				return false;

			while (i < n && s[i] == c)
				i++;

			result = true;
		}

		else
			i++;
	}
	return true;
}

int main()
{
	string s = "112233003344";

	if (solution_1(s, '1'))

		cout << "Yes" << endl;
	else
		cout << "No" << endl;
	return 0;
}

Output

Yes
Write a Comment

Leave a Comment

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