I am trying to solve this problem:
Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
https://leetcode.com/problems/maximum-product-of-word-lengths/
You can create a bitmap of char for each word to check if they share chars in common and then calc the max product.
I have two method almost equal but the first pass checks, while the second is too slow, can you understand why?
class Solution { public: int maxProduct2(vector<string>& words) { int len = words.size(); int *num = new int[len]; // compute the bit O(n) for (int i = 0; i < len; i ++) { int k = 0; for (int j = 0; j < words[i].length(); j ++) { k = k | (1 <<(char)(words[i].at(j))); } num[i] = k; } int c = 0; // O(n^2) for (int i = 0; i < len - 1; i ++) { for (int j = i + 1; j < len; j ++) { if ((num[i] & num[j]) == 0) { // if no common letters int x = words[i].length() * words[j].length(); if (x > c) { c = x; } } } } delete []num; return c; } int maxProduct(vector<string>& words) { vector<int> bitmap(words.size()); for(int i=0;i<words.size();++i) { int k = 0; for(int j=0;j<words[i].length();++j) { k |= 1 << (char)(words[i][j]); } bitmap[i] = k; } int maxProd = 0; for(int i=0;i<words.size()-1;++i) { for(int j=i+1;j<words.size();++j) { if ( !(bitmap[i] & bitmap[j])) { int x = words[i].length() * words[j].length(); if ( x > maxProd ) maxProd = x; } } } return maxProd; } }; Why the second function (maxProduct) is too slow for leetcode?
Solution
The second method does repetitive call to words.size(). If you save that in a var than it working fine
vector<int>, not a thing composed of individually adressable bits.