re: Daily Coding Puzzles VIEW POST

VIEW FULL DISCUSSION

Day 1

const piggy = (str) =>
    str.split(" ")
    .map(word =>
        word[0].match(/\w/) ?
            word.slice(1) + word[0] + 'ay' :
            word
    )
    .join(" ");

console.info(piggy("Pig latin is cool"));
console.info(piggy("Hello world !"));

Time: O(n), Space: O(n)

Day 2

const opposites = {
    "}": "{",
    ")": "(",
    "]": "["
};

function isBalanced(str) {
    if (str.length & 1) {
        return false;
    }
    const openers = [];
    for (const c of str) {
        if (c === "{" || c === "(" || c === "[") {
            openers.push(c);
        }
        else {
            const opener = openers.pop();
            if (opener !== opposites[c]) {
                return false;
            }
        }
    }
    return true;
}

function balance(input) {
    const lines = input.split("\n");
    const testCount = parseInt(lines[0]);
    let index = 1;
    while (index <= testCount) {
        const result = isBalanced(lines[index]);
        console.info(result ? "YES" : "NO");
        index++;
    }
}

balance(`7
{[()]}
{[(])}
{{[[(())]]}}
[]{}()
[({})]{}()
({(){}[]})[]
({(){}[]})[](
`);

Time: O(n), Space: O(n)

Day 3

const esrever = (word) =>
    word.split("").reverse().join("");

const spinWords = (str) =>
    str.split(" ")
    .map(word =>
        word.length > 4 ?
            esrever(word) :
            word
    )
    .join(" ");

console.info(spinWords("Hey fellow warriors"));
console.info(spinWords("This is a test"));
console.info(spinWords("This is another test"));

Time: O(n), Space: O(n)

Day 4

let a = 1, b = 2;
let sum = 0;

while (a <= 4000000) {
    if ((a & 1) === 0) {
        sum += a;
    }

    let nb = a + b;
    a = b;
    b = nb;
}
console.info(sum);

Time: O(n), Space: O(1)

Nice exercise, this also shows how clumsy JS is when dealing with string data. Everything has to be converted to and from arrays. And these exercises do not work with non-BMP Unicode characters, but that was not in the requirement ;)

code of conduct - report abuse