while I was cracking the leet code task I bumped into some unexpected behavior of the .sort function, so I couldn't finish my task until I implemented the insertion sorting function myself which helped me to sort an array of chars properly.
So the question: why this function doesn't compare with all the array members?
function customSortString(order: string, s: string): string {
const map={};
for(let i=0;i<order.length;i++){
map[order[i]]=i;
}
const newStr=[...s].sort((a,b)=>{
if(map[a]===undefined || map[b]===undefined || a===b){
return 0;
}
if(map[a]<map[b]){
return -1;
}
return 1;
})
return newStr.join('');
};
if I call
customSortString("exv","xwvee")
it will return 'xweev', but expected "eexvw"
here is a description of the problem

If I put console.log into to sorting function
w x
v w
e v
e w
e v
e e
e v
So I can see, that "x" is not compared with "e". But if it did compare it would return 1 and would display "e" first then "x"
I hope I explained clearly, but ask questions if you didn't
You need to move unknown characters to the end, with a large value.
function customSortString(order, s) {
const map = {};
for (let i = 0; i < order.length; i++) map[order[i]] = i + 1;
return [...s]
.sort((a, b) => (map[a] || Infinity) - (map[b] || Infinity))
.join('');
};
console.log(customSortString("exv", "xwvee"));
Another, more efficient answer,I use the map to record the frequency of every letters appearance,if a letter not in the map I will add it ,finally, I use repeat() to calculate all the letters in the map
function sortStr(order, s) {
console.time('test')
const map = {};
for (const i of order) {
map[i] = 0
}
for (const i of s) {
const num = map[i]
map[i] = (num || 0) + 1
}
let res = '';
for (const i in map) {
res += i.repeat(map[i])
}
console.timeEnd('test')
return res
}
const str = 'sdlfjsdifsdkfnweoosdfopdkmfndweoddfjosdfopdkmfndweoddfjosdfopdkmfndweoddfosdfopdkmfndweosdfopdkmfndweoddfjsdigklwjroddfjsdigklwjrjsdigklwjrsdigklwjrsdigklwjrdjlfgjsnfklgosdfopdkmfndweoddfjsdosdfopdkmfndweoddfjsdigklwjrigklwjroskfosdfopdkmfndweoddfjsdigklwjrgmcjbdlsmclgeosdfopdkmfndweoddfjsdigklwjrriciogiodfklsdgi'
console.log(sortStr('iskgupoeqvxzlafrdmn', str))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With