Sponsored
Sponsored
In this approach, we will iterate over all possible pairs of ideas and attempt to swap their first letters to form new names. We will then check if these new names are unique by not being present in the original list of ideas. This approach straightforwardly uses nested loops to examine each pair, which results in an O(n^2) time complexity for the pair-wise name generation.
Time Complexity: O(n^2 * m), where n is the number of ideas, and m is the average length of the ideas, due to the nested loop and string comparison.
Space Complexity: O(1) as we are not using any additional space proportional to input size beyond function parameters.
1#include <iostream>
2#include <vector>
3#include <string>
4#include <unordered_set>
5
6bool isValidName(std::string &a, std::string &b, std::unordered_set<std::string> &ideaSet) {
7 char temp = a[0];
8 a[0] = b[0];
9 b[0] = temp;
10
11 bool valid = ideaSet.find(a) == ideaSet.end() && ideaSet.find(b) == ideaSet.end();
12
13 // Swap back the first letters
14 a[0] = temp;
15 b[0] = a[0];
16
17 return valid;
18}
19
20int countValidNames(std::vector<std::string> &ideas) {
21 int validNames = 0;
22 std::unordered_set<std::string> ideaSet(ideas.begin(), ideas.end());
23 int ideasSize = ideas.size();
24
25 for (int i = 0; i < ideasSize; i++) {
26 for (int j = i + 1; j < ideasSize; j++) {
27 if (isValidName(ideas[i], ideas[j], ideaSet)) {
28 validNames++;
29 }
30 }
31 }
32
33 return validNames * 2; // Since (a,b) and (b,a) both should be counted
34}
35
36int main() {
37 std::vector<std::string> ideas = {"coffee", "donuts", "time", "toffee"};
38 std::cout << countValidNames(ideas) << std::endl;
39 return 0;
40}
This C++ solution uses unordered_set for fast existence checks after swapping the first letters of each pair. It leverages standard string manipulation and set operations to determine valid names.
This improved approach seeks to avoid redundant swaps by organizing names into groups based on their prefix letters. If two sets have no overlap with original names when swapping the first characters of the names from those sets, we count the combinations. By limiting unnecessary swaps, this method reduces repetitive calculations.
Time Complexity: O(n^2 * m) but more efficient than brute force due to reduced checking within grouped sets.
Space Complexity: O(n) since we store ideas organized by prefix.
This C solution organizes names by their starting letters and checks pairwise swapping between distinct prefix sets. By checking overlapping only within sets of the same initial character, it reduces redundant checks and improves efficiency over brute force.