Question

Write a program (O(n), where n is the number of words) that takes as input a...

Write a program (O(n), where n is the number of words) that takes as input a set of words and returns groups of anagrams for those words. Complete your code here -

For example, if the list is "debitcard", "elvis", "silent", "badcredit", "lives", "freedom", "listen", "levis",

the output should be

silent listen
debitcard badcredit
elvis lives levis

Note that freedom has no anagram, and hence is not printed.

///////////////////////////////////////////////$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

anagram.cpp

#include <iostream>

#include <unordered_map>

#include <vector>

#include <algorithm>

using namespace std;

vector<vector<string>> findAnagrams(const vector<string>& dict);

vector<vector<string>> findAnagrams(const vector<string>& dict)

{

// Your code here...

}

////////////////////////////////////////$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

anagram_test.cpp

#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>

using namespace std;
vector<vector<string>> findAnagrams(const vector<string>& dict);

int main()
{
vector<string> word_list = {"debitcard", "elvis", "silent", "badcredit", "lives", "freedom", "listen", "levis"};
vector<vector<string>> result = findAnagrams(word_list);
for (auto anagrams: result) {
for (auto words: anagrams)
cout << words << " ";
cout << endl;
}
return 0;
  
/* Output should be -
  
silent listen
debitcard badcredit
elvis lives levis
  
*/
}

Words that are anagrams are identical when sorted by characters. Use this as the key to a hashtable (unordered_map STL) with key as string, and value as vector<string>

PLEASE KEEP THE TEST FILE SEPERATE.

Thank you for your help.

Homework Answers

Answer #1

ALGORITHM

  • Using Unordered map and Count sort we can solve it in O(M*N) Time complexity.
  • There is no approach that can solve it in O(N) Time. Even Trie also Take O(M*NlogN) time.
  • After applying count sort on each string fill it in map of string,vector<string> and then print it.

CODE

#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;

// Count Sort Takes O(n+k) time to Sort
// where n is the number of elements in input array and k is the range of input.

string Sort(string s) {
        int counter[26] = {0};
        for (char c : s) {
            counter[c - 'a']++;
        }
        string t;
        for (int c = 0; c < 26; c++) {
            t += string(counter[c], c + 'a');
        }
        return t;
}

// Finding the Anagrams using unordered map and sorting technique.
vector<vector<string>> findAnagrams(const vector<string>& dict)
{
        unordered_map<string, vector<string>> m;
        for (string s : dict) {
            m[Sort(s)].push_back(s);
        }
        vector<vector<string>> res;
        for (auto p : m) { 
                if(p.second.size()>1)
            res.push_back(p.second);
        }
        return res;

}

int main()
{
vector<string> word_list = {"debitcard", "elvis", "silent", "badcredit", "lives", "freedom", "listen", "levis"};
vector<vector<string>> result = findAnagrams(word_list);
for (auto anagrams: result) {
for (auto words: anagrams)
cout << words << " ";
cout << endl;
}
return 0;
  
/* Output should be -
  
silent listen
debitcard badcredit
elvis lives levis
  
*/
}

OUTPUT

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Write a program that prompts the user to input a string and outputs the string in...
Write a program that prompts the user to input a string and outputs the string in uppercase letters. (Use dynamic arrays to store the string.) my code below: /* Your code from Chapter 8, exercise 5 is below. Rewrite the following code to using dynamic arrays. */ #include <iostream> #include <cstring> #include <cctype> using namespace std; int main() { //char str[81]; //creating memory for str array of size 80 using dynamic memory allocation char *str = new char[80]; int len;...
Please provide answer in the format that I provided, thank you Write a program that prompts...
Please provide answer in the format that I provided, thank you Write a program that prompts the user to input a string. The program then uses the function substr to remove all the vowels from the string. For example, if str=”There”, then after removing all the vowels, str=”Thr”. After removing all the vowels, output the string. Your program must contain a function to remove all the vowels and a function to determine whether a character is a vowel. You must...
Write a program that reads a string and outputs the number of lowercase vowels in the...
Write a program that reads a string and outputs the number of lowercase vowels in the string. Your program must contain a function with a parameter of a char variable that returns an int. The function will return a 1 if the char being passed in is a lowercase vowel, and a 0 for any other character. The output for your main program should be: There are XXXX lowercase vowels in string yyyyyyyyyyyyyyyyyyyyyy Where XXXX is the count of lowercase...
Lab 6    -   Program #2   -   Write one number to a text file. Use the write()...
Lab 6    -   Program #2   -   Write one number to a text file. Use the write() and read() functions with binary                                                        data, where the data is not char type.              (Typecasting is required) Fill in the blanks, then enter the code and run the program. Note:   The data is int type, so typecasting is            required in the write() and read() functions. #include <iostream> #include <fstream> using namespace std; int main() {    const int SIZE = 10;   ...
Write a C++ program that processes orders for our company Widgets and More. Your program will...
Write a C++ program that processes orders for our company Widgets and More. Your program will read the product code and quantity for all the products in an order from a file, order.txt. You will be given a sample order.txt with the starter code. There are two items on each line of the file the first is a letter that represents the product and the second is an integer representing the number bought. Based on the product and quantity, you...
Write a program that accepts as input the mass, in grams, and density, in grams per...
Write a program that accepts as input the mass, in grams, and density, in grams per cubic centimeters, and outputs the volume of the object using the formula: volume = mass / density. Format your output to two decimal places. ** Add Comments ** Print Name and Assignment on screen ** Date ** Submit .cpp file. Demo // This program uses a type cast to avoid an integer division. #include <iostream> // input - output stream #include <fstream> //working file...
Using a for Loop visual c++ Summary In this lab the completed program should print the...
Using a for Loop visual c++ Summary In this lab the completed program should print the numbers 0 through 10, along with their values multiplied by 2 and by 10. You should accomplish this using a for loop instead of a counter-controlled while loop. Instructions Write a for loop that uses the loop control variable to take on the values 0 through 10. In the body of the loop, multiply the value of the loop control variable by 2 and...
The program shown below reads in (N) values of time (hours, minutes, and seconds). If the...
The program shown below reads in (N) values of time (hours, minutes, and seconds). If the values for hours, minutes and seconds are a legal military time (i.e. 00 00 00 to 23 59 59) the program should display the formatted results (i.e. 12 34 56 should be displayed as 12:34:56). If there's an error for any of the entered values, an exception should be thrown and an error message should be displayed. Note, there are three exception conditions, one...
C++ programming Write a program that reads a comma-separated file (CSV) with integer values and prints...
C++ programming Write a program that reads a comma-separated file (CSV) with integer values and prints the number of integer values in the file. Your program's input will be a string with the name of the file. If the file does not exist, then the program must print: Error opening the file For example, given the following CSV file input1.csv: 1,10,20,30,40 The output of your program must be: 5 You can safely assume that the input file will be a...
// This program prints a table to convert numbers from one unit to another. // The...
// This program prints a table to convert numbers from one unit to another. // The program illustrates some implementation techniques. //Include the header file ostream for including all stream. ---------------------------------------------------------*/ #include <iostream> //Provides cout <v1.0> //Include iomanip that is used for set precision. #include <iomanip> //Provides setw function for setting output width <v1.1> //Header file for EXIT_SUCCESS. #include <stdlib.h>// Provides EXIT_SUCCESS <v1.2> //Header file for assert. #include <assert.h>// Provides assert function <1.3> using namespace std; // Allows all standard...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT