diff --git a/dec_week_4/addDigits/README.md b/dec_week_4/addDigits/README.md new file mode 100644 index 0000000..53fea81 --- /dev/null +++ b/dec_week_4/addDigits/README.md @@ -0,0 +1,8 @@ +### Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. + +### Example: + +Input: 38 +Output: 2 +Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. + Since 2 has only one digit, return it. \ No newline at end of file diff --git a/dec_week_4/addDigits/addDigits.js b/dec_week_4/addDigits/addDigits.js new file mode 100644 index 0000000..5d0f919 --- /dev/null +++ b/dec_week_4/addDigits/addDigits.js @@ -0,0 +1,24 @@ +// const addDigits = (num) => { +// let result = 0; + +// while (num >= 10) { +// result += num % 10; +// num = Math.floor(num / 10); + +// if (num < 10) { +// num += result; +// result = 0; +// } +// } + +// return num; +// }; + +const addDigits = (num) => { + if (isNaN(num) || num === 0) return 0; + if (num < 10) return num; + + return num % 9 === 0 ? 9 : num % 9; +}; + +module.exports = addDigits; diff --git a/dec_week_4/addDigits/addDigits.test.js b/dec_week_4/addDigits/addDigits.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4/flipAndInvertImage/README.md b/dec_week_4/flipAndInvertImage/README.md new file mode 100644 index 0000000..d4b04ca --- /dev/null +++ b/dec_week_4/flipAndInvertImage/README.md @@ -0,0 +1,24 @@ +### Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. + +### To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. + +### To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. + +### Example 1: + +Input: [[1,1,0],[1,0,1],[0,0,0]] +Output: [[1,0,0],[0,1,0],[1,1,1]] +Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. +Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] + +### Example 2: + +Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] +Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] +Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. +Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] + +### Notes: + +1 <= A.length = A[0].length <= 20 +0 <= A[i][j] <= 1 \ No newline at end of file diff --git a/dec_week_4/flipAndInvertImage/flipAndInvertImage.js b/dec_week_4/flipAndInvertImage/flipAndInvertImage.js new file mode 100644 index 0000000..e3a9d8e --- /dev/null +++ b/dec_week_4/flipAndInvertImage/flipAndInvertImage.js @@ -0,0 +1,11 @@ +const flipAndInvertImage = (A) => { + let result = []; + for (let array of A) { + result.push(array.reverse().map((ele) => ele === 1 ? 0 : 1)); + } + return result; +}; + +// const flipAndInvertImage = A => A.map(row => row.map(val => val ^ 1).reverse()); + +module.exports = flipAndInvertImage; diff --git a/dec_week_4/flipAndInvertImage/flipAndInvertImage.test.js b/dec_week_4/flipAndInvertImage/flipAndInvertImage.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4/isUgly/README.md b/dec_week_4/isUgly/README.md new file mode 100644 index 0000000..2f18a30 --- /dev/null +++ b/dec_week_4/isUgly/README.md @@ -0,0 +1,25 @@ +### Write a program to check whether a given number is an ugly number. + +### Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. + +### Example 1: + +Input: 6 +Output: true +Explanation: 6 = 2 × 3 + +### Example 2: + +Input: 8 +Output: true +Explanation: 8 = 2 × 2 × 2 + +### Example 3: + +Input: 14 +Output: false +Explanation: 14 is not ugly since it includes another prime factor 7. +### Note: + +1 is typically treated as an ugly number. +Input is within the 32-bit signed integer range: [−231, 231 − 1]. \ No newline at end of file diff --git a/dec_week_4/isUgly/isUgly.js b/dec_week_4/isUgly/isUgly.js new file mode 100644 index 0000000..e3d85e1 --- /dev/null +++ b/dec_week_4/isUgly/isUgly.js @@ -0,0 +1,16 @@ +const isUgly = (num) => { + if (num <= 0) return false; + if (num < 5) return true; + while (num % 2 == 0) { + num = num / 2; + } + while (num % 3 == 0) { + num = num / 3; + } + while (num % 5 == 0) { + num = num / 5; + } + return (num == 1); +}; + +module.exports = isUgly; diff --git a/dec_week_4/isUgly/isUgly.test.js b/dec_week_4/isUgly/isUgly.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4/minTimeToVisitAllPoints/README.md b/dec_week_4/minTimeToVisitAllPoints/README.md new file mode 100644 index 0000000..b277f8a --- /dev/null +++ b/dec_week_4/minTimeToVisitAllPoints/README.md @@ -0,0 +1,29 @@ +### On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. + +### You can move according to the next rules: + +### In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second). +You have to visit the points in the same order as they appear in the array. + + +### Example 1: + +Input: points = [[1,1],[3,4],[-1,0]] +Output: 7 +Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] +Time from [1,1] to [3,4] = 3 seconds +Time from [3,4] to [-1,0] = 4 seconds +Total time = 7 seconds + +### Example 2: + +Input: points = [[3,2],[-2,2]] +Output: 5 + + +Constraints: + +points.length == n +1 <= n <= 100 +points[i].length == 2 +-1000 <= points[i][0], points[i][1] <= 1000 \ No newline at end of file diff --git a/dec_week_4/minTimeToVisitAllPoints/minTimeToVisitAllPoints.js b/dec_week_4/minTimeToVisitAllPoints/minTimeToVisitAllPoints.js new file mode 100644 index 0000000..59f3640 --- /dev/null +++ b/dec_week_4/minTimeToVisitAllPoints/minTimeToVisitAllPoints.js @@ -0,0 +1,13 @@ +const minTimeToVisitAllPoints = (points) => { + let minTime = 0; + + for (let i = 1; i < points.length; ++i) { + const point0 = points[i - 1]; + const point1 = points[i]; + minTime += Math.max(Math.abs(point1[0] - point0[0]), Math.abs(point1[1] - point0[1])); + } + + return minTime; +}; + +module.exports = minTimeToVisitAllPoints; diff --git a/dec_week_4/minTimeToVisitAllPoints/minTimeToVisitAllPoints.test.js b/dec_week_4/minTimeToVisitAllPoints/minTimeToVisitAllPoints.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4/robotToOrigin/README.md b/dec_week_4/robotToOrigin/README.md new file mode 100644 index 0000000..6ac9c97 --- /dev/null +++ b/dec_week_4/robotToOrigin/README.md @@ -0,0 +1,18 @@ +### There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. + +### The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false. + +### Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move. + +### Example 1: + +Input: "UD" +Output: true +Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. + + +### Example 2: + +Input: "LL" +Output: false +Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves. \ No newline at end of file diff --git a/dec_week_4/robotToOrigin/robotToOrigin.js b/dec_week_4/robotToOrigin/robotToOrigin.js new file mode 100644 index 0000000..27fe561 --- /dev/null +++ b/dec_week_4/robotToOrigin/robotToOrigin.js @@ -0,0 +1,20 @@ +const judgeCircle = (moves) => { + let horizontal = 0; + let vertical = 0; + + for (let i = 0; i < moves.length; i++) { + if (moves[i] === 'U') { + vertical++; + } else if (moves[i] === 'D') { + vertical--; + } else if (moves[i] === 'R') { + horizontal++; + } else if (moves[i] === 'L') { + horizontal--; + } + } + + return (vertical === 0 && horizontal === 0) ? true : false; +}; + +module.exports = judgeCircle; diff --git a/dec_week_4/robotToOrigin/robotToOrigin.test.js b/dec_week_4/robotToOrigin/robotToOrigin.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4/sortedSquares/README.md b/dec_week_4/sortedSquares/README.md new file mode 100644 index 0000000..339d308 --- /dev/null +++ b/dec_week_4/sortedSquares/README.md @@ -0,0 +1,18 @@ +### Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. + +### Example 1: + +Input: [-4,-1,0,3,10] +Output: [0,1,9,16,100] + +### Example 2: + +Input: [-7,-3,2,3,11] +Output: [4,9,9,49,121] + + +Note: + +1 <= A.length <= 10000 +-10000 <= A[i] <= 10000 +A is sorted in non-decreasing order. \ No newline at end of file diff --git a/dec_week_4/sortedSquares/sortedSquares.js b/dec_week_4/sortedSquares/sortedSquares.js new file mode 100644 index 0000000..ecadc86 --- /dev/null +++ b/dec_week_4/sortedSquares/sortedSquares.js @@ -0,0 +1,19 @@ +// const sortedSquares = (A) => { +// const result = []; +// let head = 0; +// let tail = A.length - 1; + +// while (head <= tail) { +// if (A[head] ** 2 > A[tail] ** 2) result.push(A[head++] ** 2); +// else result.push(A[tail--] ** 2); +// } + +// return result.reverse(); +// }; + +const sortedSquares = (A) => + A + .map((number) => Math.abs(number * number)) + .sort((a, b) => a - b); + +module.exports = sortedSquares; diff --git a/dec_week_4/sortedSquares/sortedSquares.test.js b/dec_week_4/sortedSquares/sortedSquares.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4/validAnagram/README.md b/dec_week_4/validAnagram/README.md new file mode 100644 index 0000000..6491531 --- /dev/null +++ b/dec_week_4/validAnagram/README.md @@ -0,0 +1,16 @@ +### Given two strings s and t , write a function to determine if t is an anagram of s. + +### Example 1: + +Input: s = "anagram", t = "nagaram" +Output: true + +### Example 2: + +Input: s = "rat", t = "car" +Output: false +Note: +You may assume the string contains only lowercase alphabets. + +### Follow up: +What if the inputs contain unicode characters? How would you adapt your solution to such case? \ No newline at end of file diff --git a/dec_week_4/validAnagram/validAnagram.js b/dec_week_4/validAnagram/validAnagram.js new file mode 100644 index 0000000..3e4151d --- /dev/null +++ b/dec_week_4/validAnagram/validAnagram.js @@ -0,0 +1,56 @@ +// const getFreq = (s) => s.reduce((acc, curr) => { +// acc[curr] = acc[curr] ? acc[curr] + 1 : 1; +// return acc; +// }, {}); + +// const getSize = (obj) => { +// var size = 0, key; +// for (key in obj) { +// if (obj.hasOwnProperty(key)) size++; +// } +// return size; +// }; + +// const checkEquality = (s, t) => { +// for (let key in s) { +// if (!t.hasOwnProperty(key) || s[key] !== t[key]) { +// return false; +// } +// } +// return true; +// } + +// const eqObject = (s, t) => { +// let sizeS = getSize(s); +// let sizeT = getSize(t); + +// if (sizeS > sizeT) { +// return checkEquality(s, t); +// } + +// return checkEquality(t, s); +// }; + +// const isAnagram = (s, t) => { +// const mapS = getFreq(s.split('')); +// const mapT = getFreq(t.split('')); + +// return eqObject(mapS, mapT); +// }; + +const isAnagram = (s, t) => { + if (s.length !== t.length) { + return false; + } + + let arr = [...Array(26)].fill(0); + let codeA = "a".charCodeAt(0); + for (let i = 0; i < s.length; i++) { + arr[s.charCodeAt(i) - codeA]++; + arr[t.charCodeAt(i) - codeA]--; + } + + return arr.every(el => el === 0); +}; + +module.exports = isAnagram; diff --git a/dec_week_4/validAnagram/validAnagram.test.js b/dec_week_4/validAnagram/validAnagram.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4_2/Encode and Decode TinyURL/index.js b/dec_week_4_2/Encode and Decode TinyURL/index.js new file mode 100644 index 0000000..8120093 --- /dev/null +++ b/dec_week_4_2/Encode and Decode TinyURL/index.js @@ -0,0 +1,14 @@ +let obj = {}; +const origin = "http://tinyurl.com/"; + +const encode = (longUrl) => { + const randomString = Math.random().toString(36).substring(5); + obj[randomString] = longUrl; + return origin + randomString; + +}; + +const decode = (shortUrl) => { + let getKey = shortUrl.split(origin); + return obj[getKey[1]]; +}; \ No newline at end of file diff --git a/dec_week_4_2/FindElements/FindElements.js b/dec_week_4_2/FindElements/FindElements.js new file mode 100644 index 0000000..2768794 --- /dev/null +++ b/dec_week_4_2/FindElements/FindElements.js @@ -0,0 +1,18 @@ +class FindElements { + constructor(root) { + this.set = new Set(); + this.dfs(root, 0); + } + + dfs(node, val) { + this.set.add(val); + node.left && this.dfs(node.left, val * 2 + 1); + node.right && this.dfs(node.right, val * 2 + 2); + } + + find(target) { + return this.set.has(target); + } +} + +module.exports = FindElements; diff --git a/dec_week_4_2/FindElements/README.md b/dec_week_4_2/FindElements/README.md new file mode 100644 index 0000000..d1dbf8d --- /dev/null +++ b/dec_week_4_2/FindElements/README.md @@ -0,0 +1,58 @@ +Given a binary tree with the following rules: + +root.val == 0 +If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1 +If treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2 +Now the binary tree is contaminated, which means all treeNode.val have been changed to -1. + +You need to first recover the binary tree and then implement the FindElements class: + +FindElements(TreeNode* root) Initializes the object with a contamined binary tree, you need to recover it first. +bool find(int target) Return if the target value exists in the recovered binary tree. + +Example 1: + +Input +["FindElements","find","find"] +[[[-1,null,-1]],[1],[2]] +Output +[null,false,true] +Explanation +FindElements findElements = new FindElements([-1,null,-1]); +findElements.find(1); // return False +findElements.find(2); // return True + +Example 2: + +Input +["FindElements","find","find","find"] +[[[-1,-1,-1,-1,-1]],[1],[3],[5]] +Output +[null,true,true,false] +Explanation +FindElements findElements = new FindElements([-1,-1,-1,-1,-1]); +findElements.find(1); // return True +findElements.find(3); // return True +findElements.find(5); // return False + +Example 3: + +Input +["FindElements","find","find","find","find"] +[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]] +Output +[null,true,false,false,true] +Explanation +FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]); +findElements.find(2); // return True +findElements.find(3); // return False +findElements.find(4); // return False +findElements.find(5); // return True + +Constraints: + +TreeNode.val == -1 +The height of the binary tree is less than or equal to 20 +The total number of nodes is between [1, 10^4] +Total calls of find() is between [1, 10^4] +0 <= target <= 10^6 \ No newline at end of file diff --git a/dec_week_4_2/arrayPairSum/README.md b/dec_week_4_2/arrayPairSum/README.md new file mode 100644 index 0000000..62941ad --- /dev/null +++ b/dec_week_4_2/arrayPairSum/README.md @@ -0,0 +1,10 @@ +Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. + +Example 1: +Input: [1,4,3,2] + +Output: 4 +Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). +Note: +n is a positive integer, which is in the range of [1, 10000]. +All the integers in the array will be in the range of [-10000, 10000]. \ No newline at end of file diff --git a/dec_week_4_2/arrayPairSum/arrayPairSum.js b/dec_week_4_2/arrayPairSum/arrayPairSum.js new file mode 100644 index 0000000..9587361 --- /dev/null +++ b/dec_week_4_2/arrayPairSum/arrayPairSum.js @@ -0,0 +1,12 @@ +const arrayPairSum = (nums) => { + let sum = 0; + const sorted = nums.sort((a, b) => a - b); + + for (let i = 0; i < sorted.length; i += 2) { + sum += sorted[i]; + } + + return sum; +}; + +module.exports = arrayPairSum; diff --git a/dec_week_4_2/dayOfTheWeek/README.md b/dec_week_4_2/dayOfTheWeek/README.md new file mode 100644 index 0000000..2d82a2c --- /dev/null +++ b/dec_week_4_2/dayOfTheWeek/README.md @@ -0,0 +1,24 @@ +### Given a date, return the corresponding day of the week for that date. + +### The input is given as three integers representing the day, month and year respectively. + +### Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}. + +### Example 1: + +Input: day = 31, month = 8, year = 2019 +Output: "Saturday" + +### Example 2: + +Input: day = 18, month = 7, year = 1999 +Output: "Sunday" + +### Example 3: + +Input: day = 15, month = 8, year = 1993 +Output: "Sunday" + +### Constraints: + +The given dates are valid dates between the years 1971 and 2100. \ No newline at end of file diff --git a/dec_week_4_2/dayOfTheWeek/dayOfTheWeek.js b/dec_week_4_2/dayOfTheWeek/dayOfTheWeek.js new file mode 100644 index 0000000..e334a3a --- /dev/null +++ b/dec_week_4_2/dayOfTheWeek/dayOfTheWeek.js @@ -0,0 +1,6 @@ +const dayOfTheWeek = (day, month, year) => { + const week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; + return week[new Date(year + '-' + month + '-' + day).getDay()]; +}; + +module.exports = dayOfTheWeek; diff --git a/dec_week_4_2/dayOfTheWeek/dayOfTheWeek.test.js b/dec_week_4_2/dayOfTheWeek/dayOfTheWeek.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4_2/distributeCandies/README.md b/dec_week_4_2/distributeCandies/README.md new file mode 100644 index 0000000..f883231 --- /dev/null +++ b/dec_week_4_2/distributeCandies/README.md @@ -0,0 +1,33 @@ +We distribute some number of candies, to a row of n = num_people people in the following way: + +We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person. + +Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person. + +This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift). + +Return an array (of length num_people and sum candies) that represents the final distribution of candies. + +Example 1: + +Input: candies = 7, num_people = 4 +Output: [1,2,3,1] +Explanation: +On the first turn, ans[0] += 1, and the array is [1,0,0,0]. +On the second turn, ans[1] += 2, and the array is [1,2,0,0]. +On the third turn, ans[2] += 3, and the array is [1,2,3,0]. +On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1]. +Example 2: + +Input: candies = 10, num_people = 3 +Output: [5,2,3] +Explanation: +On the first turn, ans[0] += 1, and the array is [1,0,0]. +On the second turn, ans[1] += 2, and the array is [1,2,0]. +On the third turn, ans[2] += 3, and the array is [1,2,3]. +On the fourth turn, ans[0] += 4, and the final array is [5,2,3]. + +Constraints: + +1 <= candies <= 10^9 +1 <= num_people <= 1000 \ No newline at end of file diff --git a/dec_week_4_2/distributeCandies/distributeCandies.js b/dec_week_4_2/distributeCandies/distributeCandies.js new file mode 100644 index 0000000..6cd272e --- /dev/null +++ b/dec_week_4_2/distributeCandies/distributeCandies.js @@ -0,0 +1,22 @@ +const distributeCandies = (candies, num_people) => { + let count = 0; + let arr = Array(num_people).fill(0); + while (candies > 0) { + for (let i = 0; i < num_people; i++) { + count += 1; + if (candies - count > 0) { + candies -= count; + arr[i] += count; + } else { + arr[i] += candies; + candies = 0; + } + if (candies <= 0) { + break; + } + } + } + return arr; +}; + +module.exports = distributeCandies; diff --git a/dec_week_4_2/findDisappearedNumbers/README.md b/dec_week_4_2/findDisappearedNumbers/README.md new file mode 100644 index 0000000..4f38e91 --- /dev/null +++ b/dec_week_4_2/findDisappearedNumbers/README.md @@ -0,0 +1,13 @@ +Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. + +Find all the elements of [1, n] inclusive that do not appear in this array. + +Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. + +Example: + +Input: +[4,3,2,7,8,2,3,1] + +Output: +[5,6] \ No newline at end of file diff --git a/dec_week_4_2/findDisappearedNumbers/findDisappearedNumbers.js b/dec_week_4_2/findDisappearedNumbers/findDisappearedNumbers.js new file mode 100644 index 0000000..5df12f8 --- /dev/null +++ b/dec_week_4_2/findDisappearedNumbers/findDisappearedNumbers.js @@ -0,0 +1,28 @@ +const findDisappearedNumbers = (nums) => { + // let map = {}; + // let result = []; + + // for (let number of nums) { + // map[number] = map[number] ? map[number] += 1 : 1; + // } + + // for (let i = 1; i <= nums.length; i++) { + // if (!map[i]) { + // result.push(i); + // } + // } + + // return result; + let res = [] + nums.forEach((val, ind, arr) => { + let tmp = Math.abs(arr[ind]) - 1; + if (arr[tmp] > 0) + arr[tmp] *= -1; + }) + console.log(nums); + nums.forEach((val, ind) => { + if (val > 0) + res.push(ind + 1) + }) + return res +}; \ No newline at end of file diff --git a/dec_week_4_2/findOcurrences/README.md b/dec_week_4_2/findOcurrences/README.md new file mode 100644 index 0000000..fd59a64 --- /dev/null +++ b/dec_week_4_2/findOcurrences/README.md @@ -0,0 +1,21 @@ +### Given words first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second. + +### For each such occurrence, add "third" to the answer, and return the answer. + +### Example 1: + +Input: text = "alice is a good girl she is a good student", first = "a", second = "good" +Output: ["girl","student"] + +### Example 2: + +Input: text = "we will we will rock you", first = "we", second = "will" +Output: ["we","rock"] + + +### Note: + +1 <= text.length <= 1000 +text consists of space separated words, where each word consists of lowercase English letters. +1 <= first.length, second.length <= 10 +first and second consist of lowercase English letters. \ No newline at end of file diff --git a/dec_week_4_2/findOcurrences/findOcurrences.js b/dec_week_4_2/findOcurrences/findOcurrences.js new file mode 100644 index 0000000..c7ab58a --- /dev/null +++ b/dec_week_4_2/findOcurrences/findOcurrences.js @@ -0,0 +1,14 @@ +const findOccurrences = (text, first, second) => { + const words = text.split(' '); + let third = []; + + for (let i = 0; i < words.length; i++) { + if (words[i - 1] === second && words[i - 2] === first) { + third.push(words[i]); + } + } + + return third; +}; + +module.exports = findOccurrences; diff --git a/dec_week_4_2/findOcurrences/findOcurrences.test.js b/dec_week_4_2/findOcurrences/findOcurrences.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4_2/findSolution/README.md b/dec_week_4_2/findSolution/README.md new file mode 100644 index 0000000..152a556 --- /dev/null +++ b/dec_week_4_2/findSolution/README.md @@ -0,0 +1,34 @@ +Given a function f(x, y) and a value z, return all positive integer pairs x and y where f(x,y) == z. + +The function is constantly increasing, i.e.: + +f(x, y) < f(x + 1, y) +f(x, y) < f(x, y + 1) +The function interface is defined like this: + +interface CustomFunction { +public: + // Returns positive integer f(x, y) for any given positive integer x and y. + int f(int x, int y); +}; +For custom testing purposes you're given an integer function_id and a target z as input, where function_id represent one function from an secret internal list, on the examples you'll know only two functions from the list. + +You may return the solutions in any order. + +Example 1: + +Input: function_id = 1, z = 5 +Output: [[1,4],[2,3],[3,2],[4,1]] +Explanation: function_id = 1 means that f(x, y) = x + y +Example 2: + +Input: function_id = 2, z = 5 +Output: [[1,5],[5,1]] +Explanation: function_id = 2 means that f(x, y) = x * y + +Constraints: + +1 <= function_id <= 9 +1 <= z <= 100 +It's guaranteed that the solutions of f(x, y) == z will be on the range 1 <= x, y <= 1000 +It's also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 <= x, y <= 1000 \ No newline at end of file diff --git a/dec_week_4_2/findSolution/findSolution.js b/dec_week_4_2/findSolution/findSolution.js new file mode 100644 index 0000000..4b8c57a --- /dev/null +++ b/dec_week_4_2/findSolution/findSolution.js @@ -0,0 +1,31 @@ +/** + * // This is the CustomFunction's API interface. + * // You should not implement it, or speculate about its implementation + * function CustomFunction() { + * + * @param {integer, integer} x, y + * @return {integer} + * this.f = function(x, y) { + * ... + * }; + * + * }; + */ +/** + * @param {CustomFunction} customfunction + * @param {integer} z + * @return {integer[][]} + */ +const findSolution = (f, z) => { + const ret = []; + + for (let x = 1; x <= 1000; x++) { + for (let y = 1; y <= 1000; y++) { + if (f.f(x, y) === z) { ret.push([x, y]); break; } + } + } + + return ret; +}; + +module.exports = findSolution; diff --git a/dec_week_4_2/getAllElements/README.md b/dec_week_4_2/getAllElements/README.md new file mode 100644 index 0000000..0e34846 --- /dev/null +++ b/dec_week_4_2/getAllElements/README.md @@ -0,0 +1,33 @@ +Given two binary search trees root1 and root2. + +Return a list containing all the integers from both trees sorted in ascending order. + +Example 1: + +Input: root1 = [2,1,4], root2 = [1,0,3] +Output: [0,1,1,2,3,4] + +Example 2: + +Input: root1 = [0,-10,10], root2 = [5,1,7,0,2] +Output: [-10,0,0,1,2,5,7,10] + +Example 3: + +Input: root1 = [], root2 = [5,1,7,0,2] +Output: [0,1,2,5,7] + +Example 4: + +Input: root1 = [0,-10,10], root2 = [] +Output: [-10,0,10] + +Example 5: + +Input: root1 = [1,null,8], root2 = [8,1] +Output: [1,1,8,8] + +Constraints: + +Each tree has at most 5000 nodes. +Each node's value is between [-10^5, 10^5]. \ No newline at end of file diff --git a/dec_week_4_2/getAllElements/getAllElements.js b/dec_week_4_2/getAllElements/getAllElements.js new file mode 100644 index 0000000..5cc4779 --- /dev/null +++ b/dec_week_4_2/getAllElements/getAllElements.js @@ -0,0 +1,25 @@ +const getAllElements = (root1, root2) => { + let arr1 = []; + let arr2 = []; + + return merge(extract(root1, arr1), extract(root2, arr2)); +}; + +// Merge from merge sort because initial function returns a sorted array +const merge = (a1, a2) => { + let res = [...a1, ...a2]; + return res.sort((a, b) => a - b); +}; + +// In-order traversal, returns a sorted array on a BST +const extract = (node, array) => { + if (node == null) { + return []; + } + array.push(node.val); + extract(node.left, array); + extract(node.right, array); + return array; +}; + +module.exports = getAllElements; diff --git a/dec_week_4_2/heightChecker/README.md b/dec_week_4_2/heightChecker/README.md new file mode 100644 index 0000000..bb2e811 --- /dev/null +++ b/dec_week_4_2/heightChecker/README.md @@ -0,0 +1,15 @@ +Students are asked to stand in non-decreasing order of heights for an annual photo. + +Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.) + +Example 1: + +Input: [1,1,4,2,1,3] +Output: 3 +Explanation: +Students with heights 4, 3 and the last 1 are not standing in the right positions. + +Note: + +1 <= heights.length <= 100 +1 <= heights[i] <= 100 \ No newline at end of file diff --git a/dec_week_4_2/heightChecker/heightChecker.js b/dec_week_4_2/heightChecker/heightChecker.js new file mode 100644 index 0000000..f8ee7bd --- /dev/null +++ b/dec_week_4_2/heightChecker/heightChecker.js @@ -0,0 +1,13 @@ +const heightChecker = (heights) => { + let sorted = heights.slice().sort((a, b) => a - b); + let count = 0; + + for (let i = 0; i < sorted.length; i++) { + if (heights[i] !== sorted[i]) { + count++; + } + } + return count; +}; + +module.exports = heightChecker; diff --git a/dec_week_4_2/keyboardRow/README.md b/dec_week_4_2/keyboardRow/README.md new file mode 100644 index 0000000..8b2597d --- /dev/null +++ b/dec_week_4_2/keyboardRow/README.md @@ -0,0 +1,11 @@ +### Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. + +### Example: + +Input: ["Hello", "Alaska", "Dad", "Peace"] +Output: ["Alaska", "Dad"] + +### Note: + +You may use one character in the keyboard more than once. +You may assume the input string will only contain letters of alphabet. \ No newline at end of file diff --git a/dec_week_4_2/keyboardRow/keyboardRow.js b/dec_week_4_2/keyboardRow/keyboardRow.js new file mode 100644 index 0000000..97fbcab --- /dev/null +++ b/dec_week_4_2/keyboardRow/keyboardRow.js @@ -0,0 +1,9 @@ +const top = /^[qwertyuiop]+$/i; +const mid = /^[asdfghjkl]+$/i; +const bottom = /^[zxcvbnm]+$/i; +const layouts = [top, mid, bottom]; + +const findWords = words => + words.filter(word => layouts.some(layout => layout.test(word))); + +module.exports = findWords; diff --git a/dec_week_4_2/keyboardRow/keyboardRow.test.js b/dec_week_4_2/keyboardRow/keyboardRow.test.js new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/dec_week_4_2/keyboardRow/keyboardRow.test.js @@ -0,0 +1 @@ + diff --git a/dec_week_4_2/minimumAbsDifference/README.md b/dec_week_4_2/minimumAbsDifference/README.md new file mode 100644 index 0000000..33d0133 --- /dev/null +++ b/dec_week_4_2/minimumAbsDifference/README.md @@ -0,0 +1,29 @@ +### Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. + +### Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows + +a, b are from arr +a < b +b - a equals to the minimum absolute difference of any two elements in arr + + +### Example 1: + +Input: arr = [4,2,1,3] +Output: [[1,2],[2,3],[3,4]] +Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. + +### Example 2: + +Input: arr = [1,3,6,10,15] +Output: [[1,3]] + +### Example 3: + +Input: arr = [3,8,-10,23,19,-4,-14,27] +Output: [[-14,-10],[19,23],[23,27]] + +### Constraints: + +2 <= arr.length <= 10^5 +-10^6 <= arr[i] <= 10^6 \ No newline at end of file diff --git a/dec_week_4_2/minimumAbsDifference/minimumAbsDifference.js b/dec_week_4_2/minimumAbsDifference/minimumAbsDifference.js new file mode 100644 index 0000000..7c3759b --- /dev/null +++ b/dec_week_4_2/minimumAbsDifference/minimumAbsDifference.js @@ -0,0 +1,22 @@ +const minimumAbsDifference = (arr) => { + arr.sort((a, b) => a - b); + let differences = []; + let minDiff = Infinity; + let i = 1; + + while (i < arr.length) { + let currentDiff = Math.abs(arr[i - 1] - arr[i]); + + if (currentDiff < minDiff) { + differences = [[arr[i - 1], arr[i]]]; + minDiff = currentDiff; + } else if (currentDiff === minDiff) { + differences.push([arr[i - 1], arr[i]]); + } + i++; + } + + return differences; +}; + +module.exports = minimumAbsDifference; diff --git a/dec_week_4_2/minimumAbsDifference/minimumAbsDifference.test.js b/dec_week_4_2/minimumAbsDifference/minimumAbsDifference.test.js new file mode 100644 index 0000000..48c8c6c --- /dev/null +++ b/dec_week_4_2/minimumAbsDifference/minimumAbsDifference.test.js @@ -0,0 +1,12 @@ +const minimumAbsDifference = require('./minimumAbsDifference'); + +describe('minimumAbsDifference', () => { + + test('should return pairs with min difference', () => { + expect(minimumAbsDifference([4, 2, 1, 3])).toEqual([[1, 2], [2, 3], [3, 4]]); + expect(minimumAbsDifference([1, 3, 6, 10, 15])).toEqual([[1, 3]]); + expect(minimumAbsDifference([3, 8, -10, 23, 19, -4, -14, 27])) + .toEqual([[-14, -10], [19, 23], [23, 27]]); + }); + +}); \ No newline at end of file diff --git a/dec_week_4_2/nextGreaterElement/README.md b/dec_week_4_2/nextGreaterElement/README.md new file mode 100644 index 0000000..7a8f4e6 --- /dev/null +++ b/dec_week_4_2/nextGreaterElement/README.md @@ -0,0 +1,22 @@ +You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. + +The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. + +Example 1: +Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. +Output: [-1,3,-1] +Explanation: + For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. + For number 1 in the first array, the next greater number for it in the second array is 3. + For number 2 in the first array, there is no next greater number for it in the second array, so output -1. + +Example 2: +Input: nums1 = [2,4], nums2 = [1,2,3,4]. +Output: [3,-1] +Explanation: + For number 2 in the first array, the next greater number for it in the second array is 3. + For number 4 in the first array, there is no next greater number for it in the second array, so output -1. + +Note: +All elements in nums1 and nums2 are unique. +The length of both nums1 and nums2 would not exceed 1000. \ No newline at end of file diff --git a/dec_week_4_2/nextGreaterElement/nextGreaterElement.js b/dec_week_4_2/nextGreaterElement/nextGreaterElement.js new file mode 100644 index 0000000..e6cc1b8 --- /dev/null +++ b/dec_week_4_2/nextGreaterElement/nextGreaterElement.js @@ -0,0 +1,19 @@ +const nextGreaterElement = (nums1, nums2) => { + let nums2NextGrList = {} + + for (let i = 0; i < nums2.length; i += 1) { + let currIndex = i + 1; + while (nums2[currIndex] < nums2[i]) currIndex += 1; + nums2NextGrList[nums2[i]] = currIndex === nums2.length ? -1 : nums2[currIndex]; + } + + let result = []; + + for (let i = 0; i < nums1.length; i += 1) { + result.push(nums2NextGrList[nums1[i]]); + } + + return result; +}; + +module.exports = nextGreaterElement; diff --git a/dec_week_4_2/relativeSortArray/README.md b/dec_week_4_2/relativeSortArray/README.md new file mode 100644 index 0000000..c03b732 --- /dev/null +++ b/dec_week_4_2/relativeSortArray/README.md @@ -0,0 +1,16 @@ +### Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. + +### Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order. + +### Example 1: + +Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] +Output: [2,2,2,1,4,3,3,9,6,7,19] + + +### Constraints: + +arr1.length, arr2.length <= 1000 +0 <= arr1[i], arr2[i] <= 1000 +Each arr2[i] is distinct. +Each arr2[i] is in arr1. \ No newline at end of file diff --git a/dec_week_4_2/relativeSortArray/relativeSortArray.js b/dec_week_4_2/relativeSortArray/relativeSortArray.js new file mode 100644 index 0000000..aa528fe --- /dev/null +++ b/dec_week_4_2/relativeSortArray/relativeSortArray.js @@ -0,0 +1,22 @@ +const relativeSortArray = (arr1, arr2) => { + let frequency = arr1.reduce((acc, num) => { + acc[num] = acc[num] ? acc[num] + 1 : 1; + return acc; + }, {}); + + let len = arr2.length; + let relativeArray = []; + + for (let i = 0; i < len; i++) { + for (let j = 0; j < frequency[arr2[i]]; j++) { + relativeArray.push(arr2[i]); + let index = arr1.indexOf(arr2[i]); + arr1.splice(index, 1); + } + } + + arr1.sort((a, b) => a - b); + return relativeArray.concat(arr1); +}; + +module.exports = relativeSortArray; diff --git a/dec_week_4_2/relativeSortArray/relativeSortArray.test.js b/dec_week_4_2/relativeSortArray/relativeSortArray.test.js new file mode 100644 index 0000000..ad9fe35 --- /dev/null +++ b/dec_week_4_2/relativeSortArray/relativeSortArray.test.js @@ -0,0 +1,12 @@ +const relativeSortArray = require('./relativeSortArray'); + +describe('relativeSortArray', () => { + + test('should return the relative sorted array', () => { + expect(relativeSortArray( + [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], + [2, 1, 4, 3, 9, 6])) + .toEqual([2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19]); + }); + +}); \ No newline at end of file diff --git a/dec_week_4_2/removeDuplicates/README.md b/dec_week_4_2/removeDuplicates/README.md new file mode 100644 index 0000000..c119049 --- /dev/null +++ b/dec_week_4_2/removeDuplicates/README.md @@ -0,0 +1,20 @@ +### Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. + +### We repeatedly make duplicate removals on S until we no longer can. + +### Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. + + + +### Example 1: + +Input: "abbaca" +Output: "ca" +Explanation: +For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". + + +Note: + +1 <= S.length <= 20000 +S consists only of English lowercase letters. \ No newline at end of file diff --git a/dec_week_4_2/removeDuplicates/removeDuplicates.js b/dec_week_4_2/removeDuplicates/removeDuplicates.js new file mode 100644 index 0000000..8fd7361 --- /dev/null +++ b/dec_week_4_2/removeDuplicates/removeDuplicates.js @@ -0,0 +1,34 @@ +const removeDuplicates = (S) => { + let letters = S.split(''); + + for (let i = 1; i < letters.length;) { + if (letters[i - 1] === letters[i]) { + letters.splice(i - 1, 2); + i = 1; + } else { + i++; + } + } + + return letters.join(''); +}; + +// var removeDuplicates = function(S) { +// let stack = [] +// const n = S.length + +// for (let i = 0; i < n; i++) { +// if (stack.top() == S.charAt(i)) { +// stack.pop() +// } else stack.push(S.charAt(i)) +// } + +// return stack.join('') + +// }; + +// Array.prototype.top = function() { +// return this[this.length - 1] +// } + +module.exports = removeDuplicates; diff --git a/dec_week_4_2/removeDuplicates/removeDuplicates.test.js b/dec_week_4_2/removeDuplicates/removeDuplicates.test.js new file mode 100644 index 0000000..e69de29 diff --git a/dec_week_4_2/removeOuterParentheses/README.md b/dec_week_4_2/removeOuterParentheses/README.md new file mode 100644 index 0000000..6ae60fc --- /dev/null +++ b/dec_week_4_2/removeOuterParentheses/README.md @@ -0,0 +1,35 @@ +A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. + +A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings. + +Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings. + +Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. + +Example 1: + +Input: "(()())(())" +Output: "()()()" +Explanation: +The input string is "(()())(())", with primitive decomposition "(()())" + "(())". +After removing outer parentheses of each part, this is "()()" + "()" = "()()()". +Example 2: + +Input: "(()())(())(()(()))" +Output: "()()()()(())" +Explanation: +The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". +After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". +Example 3: + +Input: "()()" +Output: "" +Explanation: +The input string is "()()", with primitive decomposition "()" + "()". +After removing outer parentheses of each part, this is "" + "" = "". + +Note: + +S.length <= 10000 +S[i] is "(" or ")" +S is a valid parentheses string \ No newline at end of file diff --git a/dec_week_4_2/removeOuterParentheses/removeOuterParentheses.js b/dec_week_4_2/removeOuterParentheses/removeOuterParentheses.js new file mode 100644 index 0000000..f3b76a3 --- /dev/null +++ b/dec_week_4_2/removeOuterParentheses/removeOuterParentheses.js @@ -0,0 +1,21 @@ +const removeOuterParentheses = (S) => { + let level = 0; + let res = ""; + + for (let i = 0; i < S.length; ++i) { + + if (S[i - 1] === "(" && S[i] === "(") { + level++; + } else if (S[i - 1] === ")" && S[i] === ")") { + level--; + } + + if (level > 0) { + res += S[i]; + } + } + + return res; +}; + +module.exports = removeOuterParentheses; diff --git a/dec_week_4_2/repeatedNTimes/README.md b/dec_week_4_2/repeatedNTimes/README.md new file mode 100644 index 0000000..edc055e --- /dev/null +++ b/dec_week_4_2/repeatedNTimes/README.md @@ -0,0 +1,25 @@ +### In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. + +### Return the element repeated N times. + +### Example 1: + +Input: [1,2,3,3] +Output: 3 + +### Example 2: + +Input: [2,1,2,5,3,2] +Output: 2 + +### Example 3: + +Input: [5,1,5,2,5,3,5,4] +Output: 5 + + +### Note: + +4 <= A.length <= 10000 +0 <= A[i] < 10000 +A.length is even \ No newline at end of file diff --git a/dec_week_4_2/repeatedNTimes/repeatedNTimes.js b/dec_week_4_2/repeatedNTimes/repeatedNTimes.js new file mode 100644 index 0000000..f3822d9 --- /dev/null +++ b/dec_week_4_2/repeatedNTimes/repeatedNTimes.js @@ -0,0 +1,15 @@ +const repeatedNTimes = (A) => { + let frequency = A.reduce((acc, num) => { + acc[num] = acc[num] ? acc[num] + 1 : 1; + return acc; + }, {}); + + let len = Math.floor(A.length / 2); + for (let num of A) { + if (frequency[num] === len) { + return num; + } + } +}; + +module.exports = repeatedNTimes; diff --git a/dec_week_4_2/repeatedNTimes/repeatedNTimes.test.js b/dec_week_4_2/repeatedNTimes/repeatedNTimes.test.js new file mode 100644 index 0000000..612701d --- /dev/null +++ b/dec_week_4_2/repeatedNTimes/repeatedNTimes.test.js @@ -0,0 +1,11 @@ +const repeatedNTimes = require('./repeatedNTimes'); + +describe('repeatedNTimes', () => { + + test('should return element repeating n times', () => { + expect(repeatedNTimes([1, 2, 3, 3])).toBe(3); + expect(repeatedNTimes([2, 1, 2, 5, 3, 2])).toBe(2); + expect(repeatedNTimes([5, 1, 5, 2, 5, 3, 5, 4])).toBe(5); + }); + +}); \ No newline at end of file diff --git a/dec_week_4_2/replaceElements/README.md b/dec_week_4_2/replaceElements/README.md new file mode 100644 index 0000000..51cf823 --- /dev/null +++ b/dec_week_4_2/replaceElements/README.md @@ -0,0 +1,13 @@ +Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. + +After doing so, return the array. + +Example 1: + +Input: arr = [17,18,5,4,6,1] +Output: [18,6,6,6,1,-1] + +Constraints: + +1 <= arr.length <= 10^4 +1 <= arr[i] <= 10^5 \ No newline at end of file diff --git a/dec_week_4_2/replaceElements/replaceElements.js b/dec_week_4_2/replaceElements/replaceElements.js new file mode 100644 index 0000000..a1b92b5 --- /dev/null +++ b/dec_week_4_2/replaceElements/replaceElements.js @@ -0,0 +1,18 @@ +const replaceElements = (arr) => { + if (arr.length === 1) return [-1]; + + const len = arr.length; + + let currentMax = -1; + let prevMax = Number.MIN_SAFE_INTEGER; + + for (let i = len - 1; i >= 0; i--) { + const currentValue = arr[i]; + arr[i] = currentMax; + currentMax = Math.max(currentMax, currentValue); + } + + return arr; +}; + +module.exports = replaceElements; diff --git a/dec_week_4_2/reverseVowels/README.md b/dec_week_4_2/reverseVowels/README.md new file mode 100644 index 0000000..a0cf66b --- /dev/null +++ b/dec_week_4_2/reverseVowels/README.md @@ -0,0 +1,12 @@ +Write a function that takes a string as input and reverse only the vowels of a string. + +Example 1: + +Input: "hello" +Output: "holle" +Example 2: + +Input: "leetcode" +Output: "leotcede" +Note: +The vowels does not include the letter "y". \ No newline at end of file diff --git a/dec_week_4_2/reverseVowels/reverseVowels.js b/dec_week_4_2/reverseVowels/reverseVowels.js new file mode 100644 index 0000000..2ceb037 --- /dev/null +++ b/dec_week_4_2/reverseVowels/reverseVowels.js @@ -0,0 +1,25 @@ +const reverseVowels = (s) => { + let letters = s.split(''); + let i = 0; + let j = letters.length - 1; + let vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']; + + while (i < j) { + let temp = ''; + if (vowels.includes(letters[i]) && vowels.includes(letters[j])) { + temp = letters[i]; + letters[i] = letters[j]; + letters[j] = temp; + i++; + j--; + } else if (!vowels.includes(letters[i])) { + i++; + } else { + j--; + } + } + + return letters.join(''); +}; + +module.exports = reverseVowels; diff --git a/dec_week_4_2/reverseWords/REAdME.md b/dec_week_4_2/reverseWords/REAdME.md new file mode 100644 index 0000000..270d146 --- /dev/null +++ b/dec_week_4_2/reverseWords/REAdME.md @@ -0,0 +1,7 @@ +### Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. + +### Example 1: + +Input: "Let's take LeetCode contest" +Output: "s'teL ekat edoCteeL tsetnoc" +Note: In the string, each word is separated by single space and there will not be any extra space in the string. \ No newline at end of file diff --git a/dec_week_4_2/reverseWords/reverseWords.js b/dec_week_4_2/reverseWords/reverseWords.js new file mode 100644 index 0000000..0c8b4f1 --- /dev/null +++ b/dec_week_4_2/reverseWords/reverseWords.js @@ -0,0 +1,12 @@ +const reverseWords = (s) => { + let words = s.split(' '); + let reversedWords = []; + + for (let word of words) { + reversedWords.push(word.split('').reverse().join('')); + } + + return reversedWords.join(' '); +}; + +module.exports = reverseWords; diff --git a/dec_week_4_2/reverseWords/reverseWords.test.js b/dec_week_4_2/reverseWords/reverseWords.test.js new file mode 100644 index 0000000..4c74a51 --- /dev/null +++ b/dec_week_4_2/reverseWords/reverseWords.test.js @@ -0,0 +1,9 @@ +const reverseWords = require('./reverseWords'); + +describe('reverseWords', () => { + + test('should return reverse of the words conserving white space', () => { + expect(reverseWords("Let's take LeetCode contest")).toBe("s'teL ekat edoCteeL tsetnoc"); + }); + +}); \ No newline at end of file diff --git a/dec_week_4_2/sortArrayByParityII/README.md b/dec_week_4_2/sortArrayByParityII/README.md new file mode 100644 index 0000000..96c3264 --- /dev/null +++ b/dec_week_4_2/sortArrayByParityII/README.md @@ -0,0 +1,17 @@ +Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. + +Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. + +You may return any answer array that satisfies this condition. + +Example 1: + +Input: [4,2,5,7] +Output: [4,5,2,7] +Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. + +Note: + +2 <= A.length <= 20000 +A.length % 2 == 0 +0 <= A[i] <= 1000 \ No newline at end of file diff --git a/dec_week_4_2/sortArrayByParityII/sortArrayByParityII.js b/dec_week_4_2/sortArrayByParityII/sortArrayByParityII.js new file mode 100644 index 0000000..c4ac971 --- /dev/null +++ b/dec_week_4_2/sortArrayByParityII/sortArrayByParityII.js @@ -0,0 +1,20 @@ +const sortArrayByParityII = (arr) => { + let len = arr.length; + let res = new Array(len); + let evenIndex = 0; + let oddIndex = 1; + + for (let i = 0; i < len; i++) { + if (arr[i] % 2 === 0) { + res[evenIndex] = arr[i]; + evenIndex = evenIndex + 2; + } else { + res[oddIndex] = arr[i]; + oddIndex = oddIndex + 2; + } + } + + return res; +}; + +module.exports = sortArrayByParityII; diff --git a/dec_week_4_2/sumZero/README.md b/dec_week_4_2/sumZero/README.md new file mode 100644 index 0000000..d546fac --- /dev/null +++ b/dec_week_4_2/sumZero/README.md @@ -0,0 +1,37 @@ +Given an integer n, return any array containing n unique integers such that they add up to 0. + +Example 1: + +Input: n = 5 +Output: [-7,-1,1,3,4] +Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. +Example 2: + +Input: n = 3 +Output: [-1,0,1] +Example 3: + +Input: n = 1 +Output: [0] + +Constraints: + +1 <= n <= 1000Given an integer n, return any array containing n unique integers such that they add up to 0. + +Example 1: + +Input: n = 5 +Output: [-7,-1,1,3,4] +Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. +Example 2: + +Input: n = 3 +Output: [-1,0,1] +Example 3: + +Input: n = 1 +Output: [0] + +Constraints: + +1 <= n <= 1000 \ No newline at end of file diff --git a/dec_week_4_2/sumZero/sumZero.js b/dec_week_4_2/sumZero/sumZero.js new file mode 100644 index 0000000..0e33da7 --- /dev/null +++ b/dec_week_4_2/sumZero/sumZero.js @@ -0,0 +1,16 @@ +const sumZero = (n) => { + let num = Math.floor(n / 2); + let res = []; + + for (let i = 1; i <= num; i++) { + res.push(i, -i); + } + + if (n % 2 !== 0) { + res.push(0); + } + + return res; +}; + +module.exports = sumZero; diff --git a/jan_week_2/binaryGap/README.md b/jan_week_2/binaryGap/README.md new file mode 100644 index 0000000..7631dd8 --- /dev/null +++ b/jan_week_2/binaryGap/README.md @@ -0,0 +1,40 @@ +Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N. + +If there aren't two consecutive 1's, return 0. + + + +Example 1: + +Input: 22 +Output: 2 +Explanation: +22 in binary is 0b10110. +In the binary representation of 22, there are three ones, and two consecutive pairs of 1's. +The first consecutive pair of 1's have distance 2. +The second consecutive pair of 1's have distance 1. +The answer is the largest of these two distances, which is 2. +Example 2: + +Input: 5 +Output: 2 +Explanation: +5 in binary is 0b101. +Example 3: + +Input: 6 +Output: 1 +Explanation: +6 in binary is 0b110. +Example 4: + +Input: 8 +Output: 0 +Explanation: +8 in binary is 0b1000. +There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0. + + +Note: + +1 <= N <= 10^9 \ No newline at end of file diff --git a/jan_week_2/binaryGap/binaryGap.js b/jan_week_2/binaryGap/binaryGap.js new file mode 100644 index 0000000..3e0a897 --- /dev/null +++ b/jan_week_2/binaryGap/binaryGap.js @@ -0,0 +1,18 @@ +const binaryGap = (N) => { + const binary = N.toString(2); + let max = 0; + + let i = 0; + let j = 1; + + while(j < binary.length) { + if (binary[j] === '1' && binary[i] === '1') { + let distance = j - i; + max = Math.max(max, distance); + i = j; + } + j++; + } + + return max; +}; \ No newline at end of file diff --git a/jan_week_2/binaryGap/binaryGap.test.js b/jan_week_2/binaryGap/binaryGap.test.js new file mode 100644 index 0000000..e69de29 diff --git a/jan_week_2/minAddToMakeValid/README.md b/jan_week_2/minAddToMakeValid/README.md new file mode 100644 index 0000000..9ec0b7d --- /dev/null +++ b/jan_week_2/minAddToMakeValid/README.md @@ -0,0 +1,33 @@ +Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. + +Formally, a parentheses string is valid if and only if: + +It is the empty string, or +It can be written as AB (A concatenated with B), where A and B are valid strings, or +It can be written as (A), where A is a valid string. +Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid. + + + +Example 1: + +Input: "())" +Output: 1 +Example 2: + +Input: "(((" +Output: 3 +Example 3: + +Input: "()" +Output: 0 +Example 4: + +Input: "()))((" +Output: 4 + + +Note: + +S.length <= 1000 +S only consists of '(' and ')' characters. \ No newline at end of file diff --git a/jan_week_2/minAddToMakeValid/minAddToMakeValid.js b/jan_week_2/minAddToMakeValid/minAddToMakeValid.js new file mode 100644 index 0000000..d8b0900 --- /dev/null +++ b/jan_week_2/minAddToMakeValid/minAddToMakeValid.js @@ -0,0 +1,16 @@ +const minAddToMakeValid = (S) => { + let result = 0; + let balance = 0; + let i = 0; + + while (i < S.length) { + (S[i] === '(') ? balance++ : balance--; + if (balance === -1) { + result++; + balance++; + } + i++; + } + + return result + balance; +}; \ No newline at end of file diff --git a/jan_week_2/minAddToMakeValid/minAddToMakeValid.test.js b/jan_week_2/minAddToMakeValid/minAddToMakeValid.test.js new file mode 100644 index 0000000..e69de29