Given the root node of a tree, return an array where each element is the width of the tree at each level. --- Example Given: 0 / | \ 123 | | 45 Answer: [1, 3, 2]
// --- Directions // Create an 'eventing' library out of the // Events class. The Events class should // have methods 'on', 'trigger', and 'off'.
classEvents { constructor() { this.events = {}; }
// Register an event handler on(eventName, callback) { if (this.events[eventName]) { this.events[eventName].push(callback); } else { this.events[eventName] = [callback]; } }
// Trigger all callbacks associated // with a given eventName trigger(eventName) { if (this.events[eventName]) { for (let cb ofthis.events[eventName]) { cb(); } } }
// Remove all event handlers associated // with the given eventName off(eventName) { deletethis.events[eventName]; } }
// 1) Implement the Node class to create // a binary search tree. The constructor // should initialize values 'data', 'left', // and 'right'. // 2) Implement the 'insert' method for the // Node class. Insert should accept an argument // 'data', then create an insert a new node // at the appropriate location in the tree. // 3) Implement the 'contains' method for the Node // class. Contains should accept a 'data' argument // and return the Node in the tree with the same value. // If the value isn't in the tree return null.
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
functionbinaryGap(num) { let str = num.toString(2).split('') console.log(str) let counter = 0; let max = 0; str.forEach((char) => { if (char === '0') { counter ++; } else { if (counter > max) { max = counter; } counter = 0; } // console.log(counter) }); return max; }
Bug and Sell Stock
You will be given a list of stock prices for a given day and your goal is to return the maximum profit that could have been made by buying a stock at the given price and then selling the stock later on. For example if the input is: [45, 24, 35, 31, 40, 38, 11] then your program should return 16 because if you bought the stock at $24 and sold it at $40, a profit of $16 was made and this is the largest profit that could be made. If no profit could have been made, return -1.