Reputation: 899
I want to optimize give below program using node js programming language, can anyone help me on that. I tried given code but i want to optimize more
function anagramsArray() { let arr = ["cab", "cz", "abc", "bca", "zc"]; let result = [] for(let i=0; i<arr.length; i++) { let iSortedValue = sortString(arr[i]) let innerResult = [] innerResult.push(arr[i]) for(let j=i+1; j<arr.length; j++) { let jSortedValue = sortString(arr[j]) if(iSortedValue.length == jSortedValue.length && jSortedValue == jSortedValue) { innerResult.push(arr[j]) arr.splice(j,1) j-- } } result.push(innerResult) } return result } console.log(anagramsArray()) function sortString(reqV) { let reqValue = reqV.split("") for(let i=0; i<reqValue.length; i++) { for(let j=i; j<reqValue.length; j++) { if(reqValue[i] > reqValue[j]) { let temp = reqValue[i] reqValue[i] = reqValue[j] reqValue[j] = temp } } } return reqValue.join("") }
Result :: [ [ "abc", "bca", "cab"] , [ "zc", cz"]]
Upvotes: 0
Views: 166
Reputation: 1790
First of all, your sortString
function can be 'simplified' to following:
function sortString(str) {
return Array.from(str) // Converts string to array of characters
.sort() // Sorts them
.join(''); // Creates string again
}
The actual logic of grouping anagrams can actually be done in multiple ways. What you have already done is also valid, but it's very 'C' style code. Following is one such way using available JS features:
function anagramsArray() {
let arr = ["cab", "cz", "abc", "bca", "zc"];
// Following reduction creates a Map from 'sorted string' to list of
// strings that result in same sorted string. i.e. list of anagrams
const resultObj = arr.reduce((accumulator, str) => {
const sortedStr = sortString(str);
if(!accumulator[sortedStr]) {
accumulator[sortedStr] = [];
}
accumulator[sortedStr].push(str);
return accumulator;
}, {});
// Following mapping discards the keys in object above,
// and returns the Array of arrays that the user expects.
return Object.keys(resultObj).map(key => resultObj[key]);
}
Upvotes: 1