
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.
This implementation iterates over each possible pair of ideas and attempts to swap their first letters. If the new names generated are not found among the original ideas, it counts such pairs as valid. It restores the original names after checking for existence.
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.
1function countValidNamesOptimized(ideas) {
2 const prefixMap = new Map();
3
4 // Create a map of sets based on first character of each idea
5 ideas.forEach(idea => {
6 const firstChar = idea[0];
7 if (!prefixMap.has(firstChar)) {
8 prefixMap.set(firstChar, new Set());
9 }
10 prefixMap.get(firstChar).add(idea);
11 });
12
13 let validNames = 0;
14 const keys = Array.from(prefixMap.keys());
15
16 for (let i = 0; i < keys.length; i++) {
17 for (let j = i + 1; j < keys.length; j++) {
18 const setA = prefixMap.get(keys[i]);
19 const setB = prefixMap.get(keys[j]);
20 for (const ideaA of setA) {
21 for (const ideaB of setB) {
22 const swappedA = ideaB[0] + ideaA.slice(1);
23 const swappedB = ideaA[0] + ideaB.slice(1);
24 if (!setA.has(swappedB) && !setB.has(swappedA)) {
25 validNames++;
26 }
27 }
28 }
29 }
30 }
31
32 return validNames * 2; // Count (a, b) and (b, a)
33}
34
35const ideas = ["coffee", "donuts", "time", "toffee"];
36console.log(countValidNamesOptimized(ideas));JavaScript solution organizes ideas by first character into Map of Sets, thus enabling optimized pair-swappings and reduced duplication during validation checks. Using these prefixed groupings enhances the efficiency.