Leetcode Algorithm



Today(3/31) Algorithm


1720. Decode XORed Array


Example 1:
Input: encoded = [1,2,3], first = 1
Output: [1,0,2,1]
Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]
Example 2:
Input: encoded = [6,2,7,3], first = 4
Output: [4,2,0,7,4]

code

var decode = function(encoded, first) {
    let arr = []
    let count = first;
    arr.push(first);
    for(let i =0; i<encoded.length; i++){
      count = encoded[i] ^ count;
      arr.push(count);
    }
  return arr;
};

1678. Goal Parser Interpretation


Example 1:
Input: command = "G()(al)"
Output: "Goal"
Explanation: The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal".
Example 2:
Input: command = "G()()()()(al)"
Output: "Gooooal"
Example 3:
Input: command = "(al)G(al)()()G"
Output: "alGalooG"

code

var interpret = function(command) {
  let abc = command.replace(/\(\)/g, "o");
  return abc.replace(/\(al\)/g, "al");
};

1773. Count Items Matching a Rule


Example 1:
Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].
Example 2:
Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
Output: 2
Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match.

code

var countMatches = function(items, ruleKey, ruleValue) {
  let count = 0;
  let type = {
    "type" : 0,
    "color" : 1,
    "name" : 2,
  }
  
  for(let i=0; i<items.length; i++){
   if(items[i][type[ruleKey]] === ruleValue ){
     count++
   }
  }
  return count;
};

1313. Decompress Run-Length Encoded List


Example 1:
Input: nums = [1,2,3,4]
Output: [2,4,4,4]
Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
At the end the concatenation [2] + [4,4,4] is [2,4,4,4].
Example 2:
Input: nums = [1,1,2,3]
Output: [1,3,3]

code

var decompressRLElist = function(nums) {
    let arr = [];

    for(let i=0; i < nums.length; i+=2){
      for(let j = 0; j < nums[i]; j++){
        arr.push(nums[i+1]);
      }
    }
    return arr;
};