DEV Community

codingpineapple
codingpineapple

Posted on

1

LeetCode 791. Custom Sort String (javascript solution)

Description:

order and str are strings composed of lowercase letters. In order, no letter occurs more than once.

order was sorted in some custom order previously. We want to permute the characters of str so that they match the order that order was sorted. More specifically, if x occurs before y in order, then x should occur before y in the returned string.

Return any permutation of str (as a string) that satisfies this property.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

var customSortString = function (order, str) {
    const map = new Map();
    // Count chars in str and save into map
    for(let i=0;i<str.length;i++){
        map.set(str[i],map.get(str[i])+1||1);
    }
    let res=''
    // Add characters common between str and order to the res string
    for(let i=0;i<order.length;i++){
        res += order[i].repeat(map.get(order[i]))
        map.delete(order[i])
    }
    // Add characters from str not found in order to the res string
    for(let [key,value] of map){
        if(value>0){
            res+= key.repeat(value);
            map.delete(key)
        }        
    }
    return res;
};
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay