Given a string S, return the “reversed” string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Example 4:
Input: nums = [1,3,5,6], target = 0
Output: 0
Example 5:
Input: nums = [1], target = 0
Output: 0
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums contains distinct values sorted in ascending order.
-104 <= target <= 104
Idea:
Use Binary Search
Time complexity: O(logn)
Space complexity: O(1)
Solution:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var searchInsert = function(nums, target) {
let l = 0;
let r = nums.length;
while (l < r) {
let mid = l + Math.floor((r - l) / 2);
if (nums[mid] === target) {
return mid;
} else if (nums[mid] > target) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
let res = [];
if (digits.length === 0) return res;
// you can use array or use hashmap
const nums = [];
nums[2] = ['a','b','c'];
nums[3] = ['d','e','f'];
nums[4] = ['g','h','i'];
nums[5] = ['j','k','l'];
nums[6] = ['m','n','o'];
nums[7] = ['p','q','r','s'];
nums[8] = ['t','u','v'];
nums[9] = ['w','x','y','z'];
dfs(res, 0, "", nums, digits);
return res;
};
function dfs(res, start, cur, nums, digits) {
// exit recursive conditon
if (cur.length === digits.length) {
res.push(cur);
return;
}
// possible solution
let possibleLetters = nums[digits[start]];
for (let letter of possibleLetters) {
// modify: add the letter to our current solution
cur += letter;
dfs(res, start + 1, cur, nums, digits);
// recover: backtrack by removing the letter
// before moving onto the next
cur = cur.substring(0, cur.length - 1);
}
}
Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity sake, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on. The graph is represented in the test case using an adjacency list.
Adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
Example 1:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
Example 2:
Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
Example 3:
Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.
Example 4:
Input: adjList = [[2],[1]]
Output: [[2],[1]]
Constraints:
1 <= Node.val <= 100
Node.val is unique for each node.
Number of Nodes will not exceed 100.
There is no repeated edges and no self-loops in the graph.
The Graph is connected and all nodes can be visited starting from the given node.
/**
* // Definition for a Node.
* function Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {Node} node
* @return {Node}
*/
var cloneGraph = function(node) {
if (node === null) return null;
let map = new Map();
map.set(node, new Node(node.val));
let q = []; // queue
q.push(node);
while (q.length !== 0) {
let cur = q.shift();
for (let n of cur.neighbors) {
if (!map.has(n)) {
map.set(n, new Node(n.val));
q.push(n);
}
map.get(cur).neighbors.push(map.get(n));
}
}
return map.get(node);
};
Solution 2:
var cloneGraph = function(node) {
if (node === null) return null;
let visited = new Map();
let map = new Map();
let q = []; // queue
q.push(node);
while (q.length !== 0) {
let cur = q.shift();
if (visited.has(cur)) continue;
visited.set(cur, true);
if (!map.has(cur)) map.set(cur, new Node(cur.val));
let temp = map.get(cur);
for (let n of cur.neighbors) {
if (!map.has(n)) map.set(n, new Node(n.val));
q.push(n);
temp.neighbors.push(map.get(n));
}
}
return map.get(node);
};
We are given the head node root of a binary tree, where additionally every node’s value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)
Example 1:Input: [1,null,0,0,1]
Output: [1,null,0,null,1]
Explanation:
Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.
Example 2:Input: [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]
Example 3:Input: [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]
Note:
The binary tree will have at most 200 nodes.
The value of each node will only be 0 or 1.
Solution: (Recursion)
/**
* 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 {TreeNode}
*/
var pruneTree = function(root) {
// basic case:
if (root === null) return root;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
// found 1 or has children then no need to remove
if (root.val === 1 || root.left || root.right)
return root;
else // remove node
return null;
};
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
SymbolValue
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two one’s 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 = "III"
Output: 3
Example 2:
Input: s = "IV"
Output: 4
Example 3:
Input: s = "IX"
Output: 9
Example 4:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
Idea:
Accumulate the value of each symbol.
If the current symbol is greater than the previous one, substract twice of the previous value. e.g. IX, 1 + 10 – 2 * 1 = 9
Solution:
Time complexity: O(n)
Space complexity: O(1)
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
let conversion = {"I": 1, "V":5,"X":10,"L":50,"C":100,"D":500,"M":1000};
let total = 0;
for (var i = 0; i < s.length; i++) {
// first symbol
total += conversion[s[i]];
// if current symbol is bigger than previous symbol
// subtract 2 times of the previous value
if (i > 0 && conversion[s[i]] > conversion[s[i - 1]])
total -= 2 * conversion[s[i - 1]];
}
return total;
};