Attribute Parser – HackerRank Solution

Attribute Parser – HackerRank Solution

Problem :

We have defined our own markup language HRML. In HRML, each element consists of a starting and ending tag, and there are attributes associated with each tag. Only starting tags can have attributes. We can call an attribute by referencing the tag, followed by a tilde, ‘~‘ and the name of the attribute. The tags may also be nested.

The opening tags follow the format:

<tag-name attribute1-name = "value1" attribute2-name = "value2" ...>

The closing tags follow the format:


For example:

<tag1 value = "HelloWorld">
<tag2 name = "Name1">

The attributes are referenced as:


You are given the source code in HRML format consisting of N lines. You have to answer Q queries. Each query asks you to print the value of the attribute specified. Print “Not Found!” if there isn’t any such attribute.

Sample Input :

4 3
<tag1 value = "HelloWorld">
<tag2 name = "Name1">

Sample Output :

Not Found!

Solution :

#include <iostream>
#include <map>
using namespace std;

map <string, string> tagMap;

void createMap(int &n, string pretag) {
    if(!n) return;
    string line, tag, attr, value;
    getline(cin, line);
    int i=1;
    if(line[i]=='/') {           // found closing tag
        while(line[i]!='>') i++;
        if(pretag.size()>(i-2))        // update tag
            tag = pretag.substr(0,pretag.size()-i+1);
            tag = "";
    else {                       // found opening tag
        while(line[i]!=' ' && line[i]!='>') i++;
        tag = line.substr(1,i-1);    // update tag
        if(pretag!="") tag = pretag + "." + tag;
        int j;
        while(line[i]!='>') { // go through attributes
            j = ++i;
            while(line[i]!=' ') i++;
            attr = line.substr(j,i-j);    // attribute name
            while(line[i]!='\"') i++;
            j = ++i;
            while(line[i]!='\"') i++;
            value = line.substr(j,i-j);    // attribute value
            i+= 1;
            tagMap[tag + "~" + attr] = value;
    createMap(--n, tag);

int main() {
    int n, q;
    cin >> n >> q;
    string attr, value;
    while(q--) {
        value = tagMap[attr];
        if(value=="") value = "Not Found!";
        cout << value << endl;
    return 0;

 50 total views,  7 views today

Post Disclaimer

the above hole problem statement is given by but the solution is generated by the SLTECHACADEMY authority if any of the query regarding this post or website fill the following contact form thank you.

Leave a Reply

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