Algorithm - LeetCode Top Interview Problems

이소라·2022년 12월 12일
0

Algorithm

목록 보기
33/77

Problem : Roman to Integer

  • Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
SymbolValue
I1
V5
X10
L50
C100
D500
M1000
  • For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

  • Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

    • I can be placed before V (5) and X (10) to make 4 and 9.
    • X can be placed before L (50) and C (100) to make 40 and 90.
    • C can be placed before D (500) and M (1000) to make 400 and 900.
  • Given a roman numeral, convert it to an integer.

  • Example 1:

    • Input: s = "LVIII"
    • Output: 58
    • Explanation: L = 50, V= 5, III = 3.
  • Example 2:

    • Input: s = "MCMXCIV"
    • Output: 1994
    • Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Solution

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    let answer = 0;
    const symbolArr = ['I', 'V', 'X', 'L', 'C', 'D', 'M'];
    const valueArr = [1, 5, 10, 50, 100, 500, 1000];
    const symbolMap = new Map();
    symbolArr.forEach((symbol, index) => {
        symbolMap.set(symbol, valueArr[index]);
    });
    
    let prevStrIndex = symbolArr.length - 1;
    let str, prevStr, strIndex;
    for (let i = 0; i < s.length; i++) {
        str = s[i];
        strIndex = symbolArr.indexOf(str);
        
        if (strIndex <= prevStrIndex) {
            answer += symbolMap.get(str);
        } else {
            const value = symbolMap.get(str).toString();
            const digit = value[0] == '1' ? value.length - 2 : value.length - 1;
            answer -= symbolMap.get(prevStr);
            answer += symbolMap.get(str) - (10 ** digit);
        }

        prevStr = str;
        prevStrIndex = strIndex;
    }

    return answer;
};

Problem : Longest Common Prefix

  • Write a function to find the longest common prefix string amongst an array of strings.

  • If there is no common prefix, return an empty string "".

  • Constraints

    • 1 <= strs.length <= 200
    • 0 <= strs[i].length <= 200
    • strs[i] consists of only lowercase English letters.
  • Example 1:

    • Input: strs = ["flower","flow","flight"]
    • Output: "fl"
  • Example 2 :

    • Input: strs = ["dog","racecar","car"]
    • Output: ""
    • Explanation: There is no common prefix among the input strings.

Solution

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    let prefix = '';
    const firstWord = strs[0];
    let hasPrefix = true;
    for (let i = 0; i < firstWord.length; i++) {
        prefix += firstWord[i];
        hasPrefix = strs.every((word) => word.startsWith(prefix));
        if (!hasPrefix) {
            prefix = prefix.slice(0, prefix.length - 1);
            break;
        }
    }
    return prefix.length ? prefix : "";
};

Problem : Remove Duplicates from Sorted Array

  • Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

  • Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

  • Return k after placing the final result in the first k slots of nums.

  • Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

  • Example 1:

    • Input: nums = [1,1,2]
    • Output: 2, nums = [1,2,_]
    • Explanation:
      • Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
      • It does not matter what you leave beyond the returned k (hence they are underscores).
  • Example 2:

    • Input: nums = [0,0,1,1,1,2,2,3,3,4]
    • Output: 5, nums = [0,1,2,3,4,,,,,_]
    • Explanation:
      • Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
      • It does not matter what you leave beyond the returned k (hence they are underscores).

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    let currIndex = 0;
    let prevNum;
    nums.forEach((num) => {
        if (num !== prevNum) {
            nums[currIndex] = num;
            prevNum = num;
            currIndex += 1;
            return; 
        }
    });
    nums.splice(currIndex);
};

Problem : Binary Tree Inorder Traversal

  • Given the root of a binary tree, return the inorder traversal of its nodes' values.

  • Example 1:
    - Input: root = [1,null,2,3]
    Output: [1,3,2]

Solution

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    const data = [];
    const traverse = (node) => {
        if (!node) return;
        if (node.left) traverse(node.left);
        data.push(node.val);
        if (node.right) traverse(node.right);
    }
    traverse(root);
    return data;
};

Problem : Maximum Depth of Binary Tree

  • Given the root of a binary tree, return its maximum depth.
  • A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

  • Example 1:
    • Input: root = [3,9,20,null,null,15,7]
    • Output: 3

Solution

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    const queue = [root];
    let depth = 0;
    let node, length;

    while(queue.length) {
        length = queue.length;

        for (let i = 0; i < length; i++) {
            node = queue.shift();
            if (!node) return 0;
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }

        depth++;
    }
    return depth;
};

0개의 댓글