Reorder the letters of one string to match the order of letters in a second string

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












I have a solution to the following problem that I'd like to know if there's a way I could decrease runtime complexity for.



The directions are: reorder the letters of the first string to match the order of the letters in the second string. If a letter in the first string is not present in the second string, add it to the end of the reordering.



Example input: 'shouts', 'soup'
Example output: 'ssouht'



My code is as follows:



const reOrderLetters = (string1,string2) => 
let tailString = '';
let newString = '';
const mapped = ;

for (let i=0;i<string1.length;i++)
let char = string1[i];
if (string2.indexOf(char) !== -1)
if (!mapped[char])
mapped[char] = char;
else
mapped[char] = mapped[char] += char;

else
tailString += char;


for (let i=0;i<string2.length;i++)
let char = string2[i];
if (mapped[char])
if (mapped[char].length > 1 && string2.slice(i+1).indexOf(char) !== -1)
newString += mapped[char].slice(mapped[char].length-1);
mapped[char] = mapped[char].slice(0,mapped[char].length-1);
else
newString += mapped[char];



return newString += tailString;








share|improve this question





















  • Is the second string guaranteed to not have repeated chars? What is expected behaviour otherwise?
    – juvian
    Apr 3 at 18:28










  • Good question. That's an edge case I didn't think about. It's a question I found on Glassdoor interviews, so though I don't know, for the purpose of this exercise, let's say that if the second string has repeated chars that are present in the first string, that they be split up. So if the above input were instead: 'shouts', 'soups', expected output would be: 'sousht'.
    – Jessie Richardson
    Apr 3 at 18:50










  • I just revised the code to accommodate the edge case mentioned above.
    – Jessie Richardson
    Apr 3 at 19:20










  • If by split you mean distribute the amount of characters in string1 on the positions of that char over string2, your code produces incorrect output for example on "aa", "aaaa"
    – juvian
    Apr 3 at 19:30
















up vote
0
down vote

favorite












I have a solution to the following problem that I'd like to know if there's a way I could decrease runtime complexity for.



The directions are: reorder the letters of the first string to match the order of the letters in the second string. If a letter in the first string is not present in the second string, add it to the end of the reordering.



Example input: 'shouts', 'soup'
Example output: 'ssouht'



My code is as follows:



const reOrderLetters = (string1,string2) => 
let tailString = '';
let newString = '';
const mapped = ;

for (let i=0;i<string1.length;i++)
let char = string1[i];
if (string2.indexOf(char) !== -1)
if (!mapped[char])
mapped[char] = char;
else
mapped[char] = mapped[char] += char;

else
tailString += char;


for (let i=0;i<string2.length;i++)
let char = string2[i];
if (mapped[char])
if (mapped[char].length > 1 && string2.slice(i+1).indexOf(char) !== -1)
newString += mapped[char].slice(mapped[char].length-1);
mapped[char] = mapped[char].slice(0,mapped[char].length-1);
else
newString += mapped[char];



return newString += tailString;








share|improve this question





















  • Is the second string guaranteed to not have repeated chars? What is expected behaviour otherwise?
    – juvian
    Apr 3 at 18:28










  • Good question. That's an edge case I didn't think about. It's a question I found on Glassdoor interviews, so though I don't know, for the purpose of this exercise, let's say that if the second string has repeated chars that are present in the first string, that they be split up. So if the above input were instead: 'shouts', 'soups', expected output would be: 'sousht'.
    – Jessie Richardson
    Apr 3 at 18:50










  • I just revised the code to accommodate the edge case mentioned above.
    – Jessie Richardson
    Apr 3 at 19:20










  • If by split you mean distribute the amount of characters in string1 on the positions of that char over string2, your code produces incorrect output for example on "aa", "aaaa"
    – juvian
    Apr 3 at 19:30












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a solution to the following problem that I'd like to know if there's a way I could decrease runtime complexity for.



The directions are: reorder the letters of the first string to match the order of the letters in the second string. If a letter in the first string is not present in the second string, add it to the end of the reordering.



Example input: 'shouts', 'soup'
Example output: 'ssouht'



My code is as follows:



const reOrderLetters = (string1,string2) => 
let tailString = '';
let newString = '';
const mapped = ;

for (let i=0;i<string1.length;i++)
let char = string1[i];
if (string2.indexOf(char) !== -1)
if (!mapped[char])
mapped[char] = char;
else
mapped[char] = mapped[char] += char;

else
tailString += char;


for (let i=0;i<string2.length;i++)
let char = string2[i];
if (mapped[char])
if (mapped[char].length > 1 && string2.slice(i+1).indexOf(char) !== -1)
newString += mapped[char].slice(mapped[char].length-1);
mapped[char] = mapped[char].slice(0,mapped[char].length-1);
else
newString += mapped[char];



return newString += tailString;








share|improve this question













I have a solution to the following problem that I'd like to know if there's a way I could decrease runtime complexity for.



The directions are: reorder the letters of the first string to match the order of the letters in the second string. If a letter in the first string is not present in the second string, add it to the end of the reordering.



Example input: 'shouts', 'soup'
Example output: 'ssouht'



My code is as follows:



const reOrderLetters = (string1,string2) => 
let tailString = '';
let newString = '';
const mapped = ;

for (let i=0;i<string1.length;i++)
let char = string1[i];
if (string2.indexOf(char) !== -1)
if (!mapped[char])
mapped[char] = char;
else
mapped[char] = mapped[char] += char;

else
tailString += char;


for (let i=0;i<string2.length;i++)
let char = string2[i];
if (mapped[char])
if (mapped[char].length > 1 && string2.slice(i+1).indexOf(char) !== -1)
newString += mapped[char].slice(mapped[char].length-1);
mapped[char] = mapped[char].slice(0,mapped[char].length-1);
else
newString += mapped[char];



return newString += tailString;










share|improve this question












share|improve this question




share|improve this question








edited Apr 3 at 19:19
























asked Apr 3 at 18:20









Jessie Richardson

1204




1204











  • Is the second string guaranteed to not have repeated chars? What is expected behaviour otherwise?
    – juvian
    Apr 3 at 18:28










  • Good question. That's an edge case I didn't think about. It's a question I found on Glassdoor interviews, so though I don't know, for the purpose of this exercise, let's say that if the second string has repeated chars that are present in the first string, that they be split up. So if the above input were instead: 'shouts', 'soups', expected output would be: 'sousht'.
    – Jessie Richardson
    Apr 3 at 18:50










  • I just revised the code to accommodate the edge case mentioned above.
    – Jessie Richardson
    Apr 3 at 19:20










  • If by split you mean distribute the amount of characters in string1 on the positions of that char over string2, your code produces incorrect output for example on "aa", "aaaa"
    – juvian
    Apr 3 at 19:30
















  • Is the second string guaranteed to not have repeated chars? What is expected behaviour otherwise?
    – juvian
    Apr 3 at 18:28










  • Good question. That's an edge case I didn't think about. It's a question I found on Glassdoor interviews, so though I don't know, for the purpose of this exercise, let's say that if the second string has repeated chars that are present in the first string, that they be split up. So if the above input were instead: 'shouts', 'soups', expected output would be: 'sousht'.
    – Jessie Richardson
    Apr 3 at 18:50










  • I just revised the code to accommodate the edge case mentioned above.
    – Jessie Richardson
    Apr 3 at 19:20










  • If by split you mean distribute the amount of characters in string1 on the positions of that char over string2, your code produces incorrect output for example on "aa", "aaaa"
    – juvian
    Apr 3 at 19:30















Is the second string guaranteed to not have repeated chars? What is expected behaviour otherwise?
– juvian
Apr 3 at 18:28




Is the second string guaranteed to not have repeated chars? What is expected behaviour otherwise?
– juvian
Apr 3 at 18:28












Good question. That's an edge case I didn't think about. It's a question I found on Glassdoor interviews, so though I don't know, for the purpose of this exercise, let's say that if the second string has repeated chars that are present in the first string, that they be split up. So if the above input were instead: 'shouts', 'soups', expected output would be: 'sousht'.
– Jessie Richardson
Apr 3 at 18:50




Good question. That's an edge case I didn't think about. It's a question I found on Glassdoor interviews, so though I don't know, for the purpose of this exercise, let's say that if the second string has repeated chars that are present in the first string, that they be split up. So if the above input were instead: 'shouts', 'soups', expected output would be: 'sousht'.
– Jessie Richardson
Apr 3 at 18:50












I just revised the code to accommodate the edge case mentioned above.
– Jessie Richardson
Apr 3 at 19:20




I just revised the code to accommodate the edge case mentioned above.
– Jessie Richardson
Apr 3 at 19:20












If by split you mean distribute the amount of characters in string1 on the positions of that char over string2, your code produces incorrect output for example on "aa", "aaaa"
– juvian
Apr 3 at 19:30




If by split you mean distribute the amount of characters in string1 on the positions of that char over string2, your code produces incorrect output for example on "aa", "aaaa"
– juvian
Apr 3 at 19:30










1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










Your code is pretty good, except for using indexOf(char), as that can be quite expensive: O(string2.length). Here is how I would do it to avoid using that. Assuming hashmap access is O(1) and n being the max length between both strings, my implementation runs in O(n)






function characterCount (str) 
var chars = ;

for (var i = 0; i < str.length; i ++)
chars[str[i]] = (chars[str[i]]

return chars;




function reOrderLetters (str1, str2)
var count1 = characterCount(str1); // O(n)
var count2 = characterCount(str2); // O(n)
var result = ;
var seenCount =

for (var i = 0; i < str2.length; i++) 0) + 1;

if (count1.hasOwnProperty(char))
var remaining = count1[char] % count2[char];
var toRepeat = Math.floor(count1[char] / count2[char]);

if (seenCount[char] <= remaining)
toRepeat = Math.ceil(count1[char] / count2[char]);


result.push(char.repeat(toRepeat));



for (var i = 0; i < str1.length; i++)
var char = str1[i];

if (count2.hasOwnProperty(char) == false)
result.push(char.repeat(count1[char]));
count2[char] = true;



return result.join("");



console.log(reOrderLetters("shouts", "soups") == "sousht")
console.log(reOrderLetters("aa", "aaaa") == "aa")
console.log(reOrderLetters("aabbbba", "abab") == "aabbabb")








share|improve this answer





















    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f191186%2freorder-the-letters-of-one-string-to-match-the-order-of-letters-in-a-second-stri%23new-answer', 'question_page');

    );

    Post as a guest






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    Your code is pretty good, except for using indexOf(char), as that can be quite expensive: O(string2.length). Here is how I would do it to avoid using that. Assuming hashmap access is O(1) and n being the max length between both strings, my implementation runs in O(n)






    function characterCount (str) 
    var chars = ;

    for (var i = 0; i < str.length; i ++)
    chars[str[i]] = (chars[str[i]]

    return chars;




    function reOrderLetters (str1, str2)
    var count1 = characterCount(str1); // O(n)
    var count2 = characterCount(str2); // O(n)
    var result = ;
    var seenCount =

    for (var i = 0; i < str2.length; i++) 0) + 1;

    if (count1.hasOwnProperty(char))
    var remaining = count1[char] % count2[char];
    var toRepeat = Math.floor(count1[char] / count2[char]);

    if (seenCount[char] <= remaining)
    toRepeat = Math.ceil(count1[char] / count2[char]);


    result.push(char.repeat(toRepeat));



    for (var i = 0; i < str1.length; i++)
    var char = str1[i];

    if (count2.hasOwnProperty(char) == false)
    result.push(char.repeat(count1[char]));
    count2[char] = true;



    return result.join("");



    console.log(reOrderLetters("shouts", "soups") == "sousht")
    console.log(reOrderLetters("aa", "aaaa") == "aa")
    console.log(reOrderLetters("aabbbba", "abab") == "aabbabb")








    share|improve this answer

























      up vote
      1
      down vote



      accepted










      Your code is pretty good, except for using indexOf(char), as that can be quite expensive: O(string2.length). Here is how I would do it to avoid using that. Assuming hashmap access is O(1) and n being the max length between both strings, my implementation runs in O(n)






      function characterCount (str) 
      var chars = ;

      for (var i = 0; i < str.length; i ++)
      chars[str[i]] = (chars[str[i]]

      return chars;




      function reOrderLetters (str1, str2)
      var count1 = characterCount(str1); // O(n)
      var count2 = characterCount(str2); // O(n)
      var result = ;
      var seenCount =

      for (var i = 0; i < str2.length; i++) 0) + 1;

      if (count1.hasOwnProperty(char))
      var remaining = count1[char] % count2[char];
      var toRepeat = Math.floor(count1[char] / count2[char]);

      if (seenCount[char] <= remaining)
      toRepeat = Math.ceil(count1[char] / count2[char]);


      result.push(char.repeat(toRepeat));



      for (var i = 0; i < str1.length; i++)
      var char = str1[i];

      if (count2.hasOwnProperty(char) == false)
      result.push(char.repeat(count1[char]));
      count2[char] = true;



      return result.join("");



      console.log(reOrderLetters("shouts", "soups") == "sousht")
      console.log(reOrderLetters("aa", "aaaa") == "aa")
      console.log(reOrderLetters("aabbbba", "abab") == "aabbabb")








      share|improve this answer























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        Your code is pretty good, except for using indexOf(char), as that can be quite expensive: O(string2.length). Here is how I would do it to avoid using that. Assuming hashmap access is O(1) and n being the max length between both strings, my implementation runs in O(n)






        function characterCount (str) 
        var chars = ;

        for (var i = 0; i < str.length; i ++)
        chars[str[i]] = (chars[str[i]]

        return chars;




        function reOrderLetters (str1, str2)
        var count1 = characterCount(str1); // O(n)
        var count2 = characterCount(str2); // O(n)
        var result = ;
        var seenCount =

        for (var i = 0; i < str2.length; i++) 0) + 1;

        if (count1.hasOwnProperty(char))
        var remaining = count1[char] % count2[char];
        var toRepeat = Math.floor(count1[char] / count2[char]);

        if (seenCount[char] <= remaining)
        toRepeat = Math.ceil(count1[char] / count2[char]);


        result.push(char.repeat(toRepeat));



        for (var i = 0; i < str1.length; i++)
        var char = str1[i];

        if (count2.hasOwnProperty(char) == false)
        result.push(char.repeat(count1[char]));
        count2[char] = true;



        return result.join("");



        console.log(reOrderLetters("shouts", "soups") == "sousht")
        console.log(reOrderLetters("aa", "aaaa") == "aa")
        console.log(reOrderLetters("aabbbba", "abab") == "aabbabb")








        share|improve this answer













        Your code is pretty good, except for using indexOf(char), as that can be quite expensive: O(string2.length). Here is how I would do it to avoid using that. Assuming hashmap access is O(1) and n being the max length between both strings, my implementation runs in O(n)






        function characterCount (str) 
        var chars = ;

        for (var i = 0; i < str.length; i ++)
        chars[str[i]] = (chars[str[i]]

        return chars;




        function reOrderLetters (str1, str2)
        var count1 = characterCount(str1); // O(n)
        var count2 = characterCount(str2); // O(n)
        var result = ;
        var seenCount =

        for (var i = 0; i < str2.length; i++) 0) + 1;

        if (count1.hasOwnProperty(char))
        var remaining = count1[char] % count2[char];
        var toRepeat = Math.floor(count1[char] / count2[char]);

        if (seenCount[char] <= remaining)
        toRepeat = Math.ceil(count1[char] / count2[char]);


        result.push(char.repeat(toRepeat));



        for (var i = 0; i < str1.length; i++)
        var char = str1[i];

        if (count2.hasOwnProperty(char) == false)
        result.push(char.repeat(count1[char]));
        count2[char] = true;



        return result.join("");



        console.log(reOrderLetters("shouts", "soups") == "sousht")
        console.log(reOrderLetters("aa", "aaaa") == "aa")
        console.log(reOrderLetters("aabbbba", "abab") == "aabbabb")








        function characterCount (str) 
        var chars = ;

        for (var i = 0; i < str.length; i ++)
        chars[str[i]] = (chars[str[i]]

        return chars;




        function reOrderLetters (str1, str2)
        var count1 = characterCount(str1); // O(n)
        var count2 = characterCount(str2); // O(n)
        var result = ;
        var seenCount =

        for (var i = 0; i < str2.length; i++) 0) + 1;

        if (count1.hasOwnProperty(char))
        var remaining = count1[char] % count2[char];
        var toRepeat = Math.floor(count1[char] / count2[char]);

        if (seenCount[char] <= remaining)
        toRepeat = Math.ceil(count1[char] / count2[char]);


        result.push(char.repeat(toRepeat));



        for (var i = 0; i < str1.length; i++)
        var char = str1[i];

        if (count2.hasOwnProperty(char) == false)
        result.push(char.repeat(count1[char]));
        count2[char] = true;



        return result.join("");



        console.log(reOrderLetters("shouts", "soups") == "sousht")
        console.log(reOrderLetters("aa", "aaaa") == "aa")
        console.log(reOrderLetters("aabbbba", "abab") == "aabbabb")





        function characterCount (str) 
        var chars = ;

        for (var i = 0; i < str.length; i ++)
        chars[str[i]] = (chars[str[i]]

        return chars;




        function reOrderLetters (str1, str2)
        var count1 = characterCount(str1); // O(n)
        var count2 = characterCount(str2); // O(n)
        var result = ;
        var seenCount =

        for (var i = 0; i < str2.length; i++) 0) + 1;

        if (count1.hasOwnProperty(char))
        var remaining = count1[char] % count2[char];
        var toRepeat = Math.floor(count1[char] / count2[char]);

        if (seenCount[char] <= remaining)
        toRepeat = Math.ceil(count1[char] / count2[char]);


        result.push(char.repeat(toRepeat));



        for (var i = 0; i < str1.length; i++)
        var char = str1[i];

        if (count2.hasOwnProperty(char) == false)
        result.push(char.repeat(count1[char]));
        count2[char] = true;



        return result.join("");



        console.log(reOrderLetters("shouts", "soups") == "sousht")
        console.log(reOrderLetters("aa", "aaaa") == "aa")
        console.log(reOrderLetters("aabbbba", "abab") == "aabbabb")






        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered Apr 3 at 19:36









        juvian

        85838




        85838






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f191186%2freorder-the-letters-of-one-string-to-match-the-order-of-letters-in-a-second-stri%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Chat program with C++ and SFML

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            Will my employers contract hold up in court?