I am trying to solve a problem with lower time complexity which in this case O(n)
.
Here is the problem:
let arr = ['dog', 'come', 'ogd', 'something', 'emoc'];
It should return
[['dog', 'ogd], ['come', 'emoc']]; // which same using letters
So far I solved this problem using two functions it is working great but mine is nested loop will give me O(n2)
Here is my code
const isSameChars = (str1, str2) => {
let str1sorted = str1.split("").sort().join("");
let str2sorted = str2.split("").sort().join("");
if (str1.length !== str2.length) {
return false;
}
for (var i = 0; i < str1sorted.length; i++) {
let char1 = str1sorted[i];
let char2 = str2sorted[i];
if (char1 !== char2) {
return false;
}
}
return true;
}
const isSameCharElements = (arr) => {
let result = [];
for(var i = 0; i < arr.length; i++) {
for(var j = 0; j < i; j++) {
if (isSameChars(arr[i], arr[j]) === true) {
result.push(arr[j])
}
}
}
return result;
}
console.log(isSameCharElements(['dog', 'come', 'ogd', 'something',
'emoc'])) // [['dog', 'ogd], ['come', 'emoc']]
Is there any way to solve this with O(n)
time complexity?
Thank you an advance!
You can have a 'bag of letters' representation of any String by sorting the letters:
function sortLetters(word){
return word.split('').sort().join('');
}
You can then iterate over your input, grouping words that have the same bag of letters representation into an object:
const grouped = arr.reduce(function (m, word) {
var bagRepr = sortLetters(word);
var withSameLetters = m[bagRepr] || [];
withSameLetters.push(word);
m[bagRepr] = withSameLetters;
return m;
}, {});
const result = Object.values(grouped)
.filter(function (arr) {
return arr.length > 1;
});
This is O(n), provided that sortLetters()
is O(1), which is the case if the words lengths are bounded by a constant.
Disclaimer: note that we're only talking about asymptotic complexity here - this does not mean at all that this approach is the most efficient from a practical standpoint!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.