kirk0201
kirk0201

Reputation: 69

Why can't i get through this algorithm?

// exmaple is passed
// strings = ["sun", "bed", "car"]  n = 1   //["car", "bed", "sun"]
// strings = ["abce", "abcd", "cdx"] n = 2 //["abcd", "abce", "cdx"]

function solution(strings, n) {
    let arr = [];
    let obj = {};
    /* before
    for(let i = 0; i < strings.length; i++) {
        obj[strings[i].slice(n)] = strings[i]
    }
    */
    // after
    for(let i = 0; i < strings.length; i++) {
        if (Object.keys(obj).includes(strings[i].slice(n))) {
            obj[strings[i].slice(n) + 1] = strings[i]
        } else obj[strings[i].slice(n)] = strings[i]

    let temp = Object.keys(obj).sort()
    let x = 0
    while(x < temp.length) {
        arr.push(obj[temp[x]])
        x++
    }
    return arr

To summarize the code

  1. Receives an array of strings and stores the value sliced ​​from n as the key and the value as the strings value.
  2. Sort by extracting the key value in the created object (even if there is the same nth character as in test case 2, the string after slice from the top is also received, so it is automatically sorted to the next value)
  3. Sorted key values ​​are stored in an array in order by running a loop.

I thought of the code in this way, but please give me some advice on where it went wrong.

LINK URL : https://programmers.co.kr/learn/courses/30/lessons/12915?language=javascript#

enter image description here

> My result I don't know the parameters of the test case

enter image description here

Upvotes: 0

Views: 73

Answers (1)

trincot
trincot

Reputation: 350310

Your approach will not work when the letter that becomes the key is not unique, you will overwrite that entry in your obj object, which will lead to an output that has fewer items than the input.

It will be easier to use the sort method directly, putting the logic in the callback function:

function solution(strings, n) {
    return [...strings].sort((a, b) => (a[n]+a).localeCompare(b[n]+b));
}

console.log(solution(["sun", "bed", "car"], 1));
console.log(solution(["abce", "abcd", "cdx"], 2));

Upvotes: 1

Related Questions