NEWYR21 - Editorial

PROBLEM LINK:

Practice
Div-2 Contest

Author: Dharanendra L V
Tester: Dharanendra L V
Editorialist: Dharanendra L V

DIFFICULTY:

Easy

PREREQUISITES:

Basic observations, Strings, Substring

PROBLEM:

Given a string S which may contain the two substrings “newyear” and “2021” and some random characters. We need to find the count of the pairs containing the substring “newyear” as the first substring and “2021” as the second substring.

QUICK EXPLANATION:

We can search for the substring “new year” and keep the track of the count. And search for the substring “2021” and update the answer by adding the count to it.

EXPLANATION:

We need to traverse the string S starting from the index 0, and need to search for the substring “newyear” if we found it then we need to update the count by adding 1 to it. And parallelly we have to search for the substring “2021” if we found it then we need to update the answer by adding the count value to it. We need to repeat this procedure until the end of the string. And finally print the value of the answer.

SOLUTIONS:

Setter's Solution
#include <bits/stdc++.h>
#define FIO ios::sync_with_stdio(0); cin.tie(0)
#define test ll t = 1; while (t--)
#define REP(x) for (ll i = 0; i < x; i++) 
typedef long long ll;
using namespace std;

int main()
{
    FIO;
    test
    {

        string str, str1 = "newyear", str2 = "2021";
        cin >> str;

        int count = 0, ans = 0;
        REP(str.length())
        {
            if (str.substr(i, str1.length()) == str1)
            {
                count++;
            }
            else if (str.substr(i, str2.length()) == str2)
            {
                ans += count;
            }
        }

        cout << ans << endl;
    }

    return 0;
}

Feel free to share your approach here. Suggestions are always welcomed. :slight_smile: