Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Please help me to know what is happening in this code

string kthDistinct(vector<string>& arr, int k) {
    unordered_map<string, int> m;
    for (auto &s : arr)
        ++m[s];
//Frome here
    for (auto &s : arr)
        if (m[s] == 1 && --k == 0)
            return s;
    return "";
//to here 
}

Especially in this part
for (auto &s : arr)
if (m[s] == 1 && –k == 0)
return s;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

That block of code is a bit on the dense side. If we rewrite the same logic in a more verbose manner, we get:

for (auto &s : arr) {
  if( m[s] == 1 ) {
    k -= 1;
    if( k == 0 ) {
      return s;
    } 
  }

Since m contains the number of time a string appears within arr, we can interpret this as:

"Return the kth string of arr that appears only once within arr."

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading