Count occurrences of a character in a repeated string
Last Updated :
12 Nov, 2023
Given an integer N and a lowercase string. The string is repeated infinitely. The task is to find the No. of occurrences of a given character x in first N letters.
Examples:
Input : N = 10 str = "abcac"
Output : 4
Explanation: "abcacabcac" is the substring from the infinitely repeated string. In first 10 letters 'a' occurs 4 times.
Input: N = 10, str = "aba"
Output : 7
Approach:
1. Find the occurrences of character 'a' in the given string.
2. Find the No. of repetitions which are required to find the 'a' occurrences.
3. Multiply the single string occurrences to the No. of repetitions.
4. If given n is not the multiple of given string size then we will find the 'a' occurrences in the remaining substring.
Below is the implementation of above approach:
C++
// CPP program to find the occurrences of
// character x in the infinite repeated string
// upto length n
#include <bits/stdc++.h>
using namespace std;
// Function to count the character 'a'
int countChar(string str, char x)
{
int count = 0, n = 10;
for (int i = 0; i < str.size(); i++)
if (str[i] == x)
count++;
// atleast k repetition are required
int repetitions = n / str.size();
count = count * repetitions;
// if n is not the multiple of the string size
// check for the remaining repeating character.
for (int i = 0; i < n % str.size(); i++) {
if (str[i] == x)
count++;
}
return count;
}
// Driver code
int main()
{
string str = "abcac";
cout << countChar(str, 'a');
return 0;
}
// This code is contributed by Surendra_Gangwar
Java
// Java program to find the occurrences
// of character x in the infinite
// repeated string upto length n
import java.util.*;
import java.lang.*;
class GFG
{
// Function to count the character 'a'
static int countChar(String str, char x)
{
int count = 0;
int n = 10;
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == x)
count++;
// atleast k repetition are required
int repetitions = n / str.length();
count = count * repetitions;
// if n is not the multiple of the
// string size check for the remaining
// repeating character.
for (int i = 0;
i < n % str.length(); i++)
{
if (str.charAt(i) == x)
count++;
}
return count;
}
// Driver code
public static void main(String args[])
{
String str = "abcac";
System.out.println(countChar(str, 'a'));
}
}
// This code is contributed
// by Akanksha Rai
Python3
# Python3 program to find the occurrences of
# character x in the infinite repeated string
# upto length n
# Function to count the character 'a'
def countChar(str, x):
count = 0
for i in range(len(str)):
if (str[i] == x) :
count += 1
n = 10
# atleast k repetition are required
repetitions = n // len(str)
count = count * repetitions
# if n is not the multiple of the
# string size check for the remaining
# repeating character.
l = n % len(str)
for i in range(l):
if (str[i] == x):
count += 1
return count
# Driver code
str = "abcac"
print(countChar(str, 'a'))
# This code is contributed
# by sahishelangia
C#
// C# program to find the occurrences
// of character x in the infinite
// repeated string upto length n
using System;
class GFG
{
// Function to count the character 'a'
static int countChar(string str, char x)
{
int count = 0;
int n = 10;
for (int i = 0; i < str.Length; i++)
if (str[i] == x)
count++;
// atleast k repetition are required
int repetitions = n / str.Length;
count = count * repetitions;
// if n is not the multiple of the
// string size check for the remaining
// repeating character.
for (int i = 0;
i < n % str.Length; i++)
{
if (str[i] == x)
count++;
}
return count;
}
// Driver code
public static void Main()
{
string str = "abcac";
Console.WriteLine(countChar(str, 'a'));
}
}
// This code is contributed
// by Akanksha Rai
JavaScript
<script>
// JavaScript program to find the occurrences
// of character x in the infinite
// repeated string upto length n
// Function to count the character 'a'
function countChar(str, x)
{
let count = 0;
let n = 10;
for (let i = 0; i < str.length; i++)
if (str[i] == x)
count++;
// atleast k repetition are required
let repetitions = n / str.length;
count = count * repetitions;
// if n is not the multiple of the
// string size check for the remaining
// repeating character.
for (let i = 0; i < n % str.length; i++)
{
if (str[i] == x)
count++;
}
return count;
}
let str = "abcac";
document.write(countChar(str, 'a'));
</script>
PHP
<?php
// PHP program to find the occurrences
// of character x in the infinite
// repeated string upto length n
// Function to count the character 'a'
function countChar($str, $x)
{
$count = 0;
$n = 10;
for ($i = 0; $i < strlen($str); $i++)
if ($str[$i] == $x)
$count++;
// atleast k repetition are required
$repetitions = (int)($n / strlen($str));
$count = $count * $repetitions;
// if n is not the multiple of
// the string size check for the
// remaining repeating character.
for ($i = 0; $i < $n % strlen($str); $i++)
{
if ($str[$i] == $x)
$count++;
}
return $count;
}
// Driver code
$str = "abcac";
echo countChar($str, 'a');
// This code is contributed by Sachin
?>
Time complexity: O(length(str))
Auxiliary space: O(1)
Brute Force:
Approach:
In this approach, we will generate the infinitely repeated string and count the occurrences of the desired character in the first N characters of the string.
- Define a function count_occurrences_brute that takes three parameters: N, s, and c. N is an integer representing the number of characters to consider, s is a string representing the repeated string, and c is a character for which we want to count the occurrences.
- Generate the infinitely repeated string by repeating s enough times to cover at least N characters, and then truncating the result to exactly N characters.
- Initialize a counter variable count to 0.
- Loop over the first N characters of the repeated string, and increment count each time the current character is equal to c.
- Return the value of count.
C++
//C++ Code for above approach
#include <iostream>
#include <string>
int count_occurrences_brute(int N, const std::string &s, char c) {
// generate the infinitely repeated string
std::string repeated = "";
for (int i = 0; i < N; i++) {
repeated += s[i % s.length()];
}
// count the occurrences of the desired character
int count = 0;
for (int i = 0; i < N; i++) {
if (repeated[i] == c) {
count++;
}
}
return count;
}
int main() {
// example usage
std::cout << count_occurrences_brute(10, "abcac", 'a') << std::endl; // output: 4
std::cout << count_occurrences_brute(10, "aba", 'a') << std::endl; // output: 7
return 0;
}
Java
public class Main {
public static int countOccurrencesBrute(int N, String s,
char c)
{
// Generate the infinitely repeated string
StringBuilder repeated = new StringBuilder();
for (int i = 0; i < N; i++) {
repeated.append(s.charAt(i % s.length()));
}
// Count the occurrences of the desired character
int count = 0;
for (int i = 0; i < N; i++) {
if (repeated.charAt(i) == c) {
count++;
}
}
return count;
}
public static void main(String[] args)
{
// Example usage
System.out.println(countOccurrencesBrute(
10, "abcac", 'a')); // Output: 4
System.out.println(countOccurrencesBrute(
10, "aba", 'a')); // Output: 7
}
}
Python3
def count_occurrences_brute(N, s, c):
# generate the infinitely repeated string
repeated = (s * (N // len(s) + 1))[:N]
# count the occurrences of the desired character
count = 0
for i in range(N):
if repeated[i] == c:
count += 1
return count
# example usage
print(count_occurrences_brute(10, 'abcac', 'a')) # output: 4
print(count_occurrences_brute(10, 'aba', 'a')) # output: 7
C#
using System;
class Program {
// Function to count occurrences of a character 'c' in a
// string 's' repeated 'N' times
static int CountOccurrencesBrute(int N, string s,
char c)
{
// Generate the infinitely repeated string
string repeated = "";
for (int i = 0; i < N; i++) {
repeated += s[i % s.Length];
}
// Count the occurrences of the desired character
int count = 0;
for (int i = 0; i < N; i++) {
if (repeated[i] == c) {
count++;
}
}
return count;
}
static void Main()
{
// Example usage
Console.WriteLine(CountOccurrencesBrute(
10, "abcac", 'a')); // Output: 4
Console.WriteLine(CountOccurrencesBrute(
10, "aba", 'a')); // Output: 7
}
}
JavaScript
function countOccurrencesBrute(N, s, c) {
// generate the infinitely repeated string
const repeated = (s.repeat(Math.floor(N / s.length) + 1)).slice(0, N);
// count the occurrences of the desired character
let count = 0;
for (let i = 0; i < N; i++) {
if (repeated[i] === c) {
count++;
}
}
return count;
}
// example usage
console.log(countOccurrencesBrute(10, 'abcac', 'a'));
console.log(countOccurrencesBrute(10, 'aba', 'a'));
Time Complexity: O(N^2)
Space Complexity: O(N)
Similar Reads
Count Occurrences of a Given Character in a String Given a string S and a character 'c', the task is to count the occurrence of the given character in the string.Examples: Input : S = "geeksforgeeks" and c = 'e'Output : 4Explanation: 'e' appears four times in str.Input : S = "abccdefgaa" and c = 'a' Output : 3Explanation: 'a' appears three times in
6 min read
Count occurrences of a sub-string with one variable character Given two strings a and b, and an integer k which is the index in b at which the character can be changed to any other character, the task is to check if b is a sub-string in a and print out how many times b occurs in a in total after replacing the b[k] with every possible lowercase character of Eng
5 min read
Count K-Length Substrings With No Repeated Characters Given a string S and an integer k, the task is to return the number of substrings in S of length k with no repeated characters.Example:Input: S = "geeksforgeeks", k = 5Output: 4Explanation: There are 4 substrings, they are: 'eksfo', 'ksfor', 'sforg', 'forge'.Input: S = "home", k = 5Output: 0Explanat
6 min read
Count of all unique substrings with non-repeating characters Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
6 min read
Find Character Frequencies in Order of Occurrence Given string s containing only lowercase characters, the task is to print the characters along with their frequency in the order of their occurrence and in the given format explained in the examples below.Examples: Input: s = "geeksforgeeks"Output: g2 e4 k2 s2 f1 o1 r1Input: str = "elephant"Output:
13 min read
Count the Number of matching characters in a pair of strings Given a pair of non-empty strings str1 and str2, the task is to count the number of matching characters in these strings. Consider the single count for the character which have duplicates in the strings.Examples: Input: str1 = "abcdef", str2 = "defghia" Output: 4 Matching characters are: a, d, e, fI
7 min read
Count the number of Unique Characters in a String in Python We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8.Using setSet in Python is an unordered collection of unique elements automatically removing du
2 min read
First non-repeating character in a stream Given an input stream s consisting solely of lowercase letters, you are required to identify which character has appeared only once in the stream up to each point. If there are multiple characters that have appeared only once, return the one that first appeared. If no character has appeared only onc
15+ min read
Count substrings made up of a single distinct character Given a string S of length N, the task is to count the number of substrings made up of a single distinct character.Note: For the repetitive occurrences of the same substring, count all repetitions. Examples: Input: str = "geeksforgeeks"Output: 15Explanation: All substrings made up of a single distin
5 min read
Count of substrings having all distinct characters Given a string str consisting of lowercase alphabets, the task is to find the number of possible substrings (not necessarily distinct) that consists of distinct characters only.Examples: Input: Str = "gffg" Output: 6 Explanation: All possible substrings from the given string are, ( "g", "gf", "gff",
7 min read