logo

Number Strings and Words (Level 1)

function solution(s) {
    const obj = {'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 'nine':9}
    let stringNum = ''
    let answer = ''
    for(let i=0; i<s.length; i++){
        let temp = +s[i]
        if(isNaN(temp)){
            stringNum += s[i]
              if(obj[stringNum] || obj[stringNum] === 0){ // A counterexample is 'one0zero0'. Since 0 is a falsy value, you need to explicitly handle the value to ensure accuracy. 
            answer += obj[stringNum]
            stringNum = ''
            }   
        } else {
            answer += s[i]
        }
        
    }
    return +answer
}
One minute to read

Combinations

function getCombinations(arr, selectNumber) {
    const results = [];
    
    if (selectNumber === 1) {
        return arr.map((value) => [value]); // Return each element as an array
    }

    arr.forEach((fixed, index, array) => {
        const rest = array.slice(index + 1); // The array after the current element
        const combinations = getCombinations(rest, selectNumber - 1); // Recursive call
        const attached = combinations.map((combination) => [fixed, ...combination]); // Attach the current element to the combinations
        results.push(...attached);
    });

    return results;
}
One minute to read

Valid Parentheses (Level 2)

This exact problem appeared in a live coding test for the company I want to join.

I had solved this problem three years ago while preparing for coding tests as a new graduate, but I couldn’t remember it since it’s been a while.

It was so frustrating that I couldn’t solve it halfway through, so I decided to review it.

function solution(s) {
    let stack = [];
    let obj = { '(': ')', '{':'}', '[':']' };
    
    for (let i = 0; i < s.length; i++) {
        if (Object.keys(obj).includes(s[i])) { 
            stack.push(s[i]); // Only push the left parentheses onto the stack.
        } else {
            let last = stack.pop(); // Pop the last item from the stack.
            if (s[i] !== obj[last]) { // If it doesn't match the correct closing bracket, return false.
                return false;
            }
        }
    }
    if (stack.length !== 0) { // If there's anything left in the stack, it means not all parentheses were closed, so return false.
        return false;
    } else {
        return true; // If the stack is empty, all parentheses were correctly matched, so return true.
    }
}
One minute to read