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.
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);
};
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;
};
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000
Solution 1:
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function(nums) {
let max = 0;
let count = 0;
for (let num of nums) {
if (num === 1) {
count++;
} else {
max = Math.max(max, count);
count = 0;
}
}
max = Math.max(max, count);
return max;
}
Solution 2:
var findMaxConsecutiveOnes = function(nums) {
let max = 0;
let res = 0;
for (let num of nums) {
let sign = 1;
if (num === 0) {
sign = 0;
} else {
sign = 1;
}
max = sign * max + num;
// update max result
if (max > res) res = max;
}
return res;
};
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
Idea:
To solve this in O(1) space and O(n) runtime, we have to do some modification in the original array.
In for loop:
Flipping the index location number (to negative number)
when we meet the duplicate number, we should see index location is negative, save the result
Solution:
/**
* @param {number[]} nums
* @return {number[]}
*/
var findDuplicates = function(nums) {
const res = [];
for (let i = 0; i < nums.length; i++) {
let index = Math.abs(nums[i]) - 1;
// flipping the index location number (to negative number)
// if we found they are negative, save the result
if (nums[index] < 0) res.push(index + 1); // because index = ABS(nums[i]) - 1
nums[index] = -nums[index];
}
return res;
};
You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
Example 1:
Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]
Explanation: Another accepted tree is:
Example 2:
Input: root = [40,20,60,10,30,50,70], val = 25
Output: [40,20,60,10,30,50,70,null,null,25]
Example 3:
Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
Output: [4,2,7,1,3,5]
Constraints:
The number of nodes in the tree will be in the range [0, 104].
-108 <= Node.val <= 108
All the values Node.val are unique.
-108 <= val <= 108
It’s guaranteed that val does not exist in the original BST.
Solution: (Recursion)
Time complexity: O(logn ~ n)
Space complexity: O(logn ~ n)
/**
* 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
* @param {number} val
* @return {TreeNode}
*/
var insertIntoBST = function(root, val) {
// empty tree case:
if (root === null) return new TreeNode(val);
if (val > root.val) {
root.right = insertIntoBST(root.right, val);
} else {
root.left = insertIntoBST(root.left, val);
}
return root;
};
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Follow up: Can you solve it with time complexity O(height of tree)?
Example 1:
Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the above BST.
Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.
Example 2:
Input: root = [5,3,6,2,4,null,7], key = 0
Output: [5,3,6,2,4,null,7]
Explanation: The tree does not contain a node with value = 0.
Example 3:
Input: root = [], key = 0
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 104].
-105 <= Node.val <= 105
Each node has a unique value.
root is a valid binary search tree.
-105 <= key <= 105
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
* @param {number} key
* @return {TreeNode}
*/
var deleteNode = function(root, key) {
if (root === null) return root;
if (key > root.val) {
root.right = deleteNode(root.right, key);
} else if (key < root.val) {
root.left = deleteNode(root.left, key);
} else { // found the key
// has children
if (root.left !== null && root.right !== null) {
let min = new TreeNode();
min = root.right;
while (min.left !== null) min = min.left;
root.val = min.val;
root.right = deleteNode(root.right, min.val);
} else { // no children
let newRoot = new TreeNode();
newRoot = root.left === null ? root.right : root.left;
root.left = root.right = null;
return newRoot;
}
}
return root;
};