2

I have an associative NxN matrix and a vector containing all columns:

std::map<std::string,std::map<std::string,int>> A;
std::vector<std::string> columns; //this has size n

An element would look like this: A["abc"]["bcd"] = 2

I want to remove the row "abc" (so basically A["abc"]) and the column "abc" (so basically A[*]["abc"]) in O(n)

A.erase("abc"); //this is O(log n)

for (int i = 0; i < words.size(); ++i) //this is O(n*log n)
{
    A[words[i]].erase("abc"); 
}

This has O(n*log n) runtime. Is it possible to do it in O(n)?

Miklos
  • 101
  • 2
  • 11

1 Answers1

1

You could use a std::map<std::pair<std::string, std::string>, int>, where the pair of strings are the row and column values.

Then you can use the custom std::erase_if algorithm that works on a std::map, which runs in O(n) time:

std::erase_if(A, [](const auto& item) {
    auto const& [key, value] = item;
    return key.first == "abc" or key.second == "abc";
});
cigien
  • 57,834
  • 11
  • 73
  • 112
  • But the runtime is linear to the number of elements in the map which is n^2. Is it impossible to remove rows and columns in O(n)? – Miklos Sep 06 '20 at 20:54
  • If you have `O(n^2)` elements, how do you expect to even look at all the elements in less than that time? – cigien Sep 06 '20 at 20:55
  • Because I know the rows and the columns – Miklos Sep 06 '20 at 21:03
  • 1
    Well, a map lets you erase an element with a particular key in `O(log n)`, but you also want to remove other elements, which you can't really do any faster than looking at all the elements. – cigien Sep 06 '20 at 21:09
  • OK, so what I want is basically impossible. I need to pick a data structure which is ordered by the 2nd coordinate as well, so if I know which row and column need to be deleted I can do it without iterating through every other elements as well. – Miklos Sep 06 '20 at 21:22
  • Yes, exactly. You need to find the right data structure for your case. – cigien Sep 06 '20 at 21:22