├── 0001. Two Sum ├── 2-sum.js └── README.md ├── 0002. Add Two Numbers ├── README.md └── add-two-numbers.js ├── 0003. Longest Substring Without Repeating Characters ├── README.md └── longest-substring-without-repeating-characters.js ├── 0004. Median of Two Sorted Arrays ├── README.md └── median-of-two-sorted-arrays.js ├── 0005. Longest Palindromic Substring ├── README.md └── longest-palindromic-substring.js ├── 0006. Zigzag Conversion ├── README.md └── zigzag-conversion.js ├── 0007. Reverse Integer ├── README.md └── reverse-integer.js ├── 0008. String to Integer (atoi) ├── README.md └── string-to-integer.js ├── 0009. Palindrome Number ├── README.md └── palindrome.js ├── 0011. Container With Most Water ├── README.md └── container-with-most-water.js ├── 0012. Integer to Roman ├── README.md └── integer-to-roman.js ├── 0013. Roman to Integer ├── README.md └── roman-to-integer.js ├── 0014. Longest Common Prefix ├── README.md └── longest-common-prefix.js ├── 0015. 3Sum ├── 3-sum.js └── README.md ├── 0016. 3Sum Closest ├── 3sum-closest.js └── README.md ├── 0020. Valid Parentheses ├── README.md └── valid-parentheses.js ├── 0033. Search in Rotated Sorted Array ├── README.md └── search-in-rotated-sorted-array.js ├── 0048. Rotate Image ├── README.md └── rotate-image.js ├── 0053. Maximum Subarray ├── README.md └── maximum-subarray.js ├── 0054. Spiral Matrix ├── README.md └── spiral-matrix.js ├── 0059. Spiral Matrix II ├── README.md └── spiral-matrix-ii.js ├── 0069. Sqrt(x) ├── README.md └── sqrtx.js ├── 0073. Set Matrix Zeroes ├── README.md └── set-matrix-zeroes.js ├── 0074. Search a 2D Matrix ├── README.md └── search-a-2d-matrix.js ├── 0075. Sort Colors ├── README.md └── sort-colors.js ├── 0081. Search in Rotated Sorted Array II ├── README.md └── search-in-rotated-sorted-array-ii.js ├── 0088. Merge Sorted Array ├── README.md └── merge-sorted-array.js ├── 0091. Decode Ways ├── README.md └── decode-ways.js ├── 0113. Path Sum II ├── README.md └── path-sum-ii.js ├── 0146. LRU Cache ├── README.md └── lru-cache.js ├── 0151. Reverse Words in a String ├── README.md └── reverse-words-in-a-string.js ├── 0153. Find Minimum in Rotated Sorted Array ├── README.md └── find-minimum-in-rotated-sorted-array.js ├── 0167. Two Sum II - Input Array Is Sorted ├── README.md └── two-sum-ii-input-array-is-sorted.js ├── 0175. Combine Two Tables ├── README.md └── combine-two-tables.sql ├── 0176. Second Highest Salary ├── README.md └── second-highest-salary.sql ├── 0178. Rank Scores ├── README.md └── rank-scores.sql ├── 0189. Rotate Array ├── README.md └── rotate-array.js ├── 0192. Word Frequency ├── README.md ├── word-frequency.bash └── word-frequency.sh ├── 0193. Valid Phone Numbers ├── README.md └── valid-phone-numbers.sh ├── 0194. Transpose File ├── README.md └── transpose-file.sh ├── 0195. Tenth Line ├── README.md └── tenth-line.sh ├── 0203. Remove Linked List Elements ├── README.md └── remove-linked-list-elements.js ├── 0206. Reverse Linked List ├── README.md └── reverse-linked-list.js ├── 0214. Shortest Palindrome ├── README.md └── shortest-palindrome.js ├── 0215. Kth Largest Element in an Array ├── README.md └── kth-largest-element-in-an-array.js ├── 0219. Contains Duplicate II ├── README.md └── contains-duplicate-ii.js ├── 0220. Contains Duplicate III ├── README.md └── contains-duplicate-iii.js ├── 0228. Summary Ranges ├── README.md └── summary-ranges.js ├── 0234. Palindrome Linked List ├── README.md └── palindrome-linked-list.js ├── 0240. Search a 2D Matrix II ├── README.md └── search-a-2d-matrix-ii.js ├── 0258. Add Digits ├── README.md └── add-digits.js ├── 0268. Missing Number ├── README.md └── missing-number.js ├── 0278. First Bad Version ├── README.md └── first-bad-version.js ├── 0283. Move Zeroes ├── README.md ├── move-zeroes.cpp └── move-zeroes.js ├── 0344. Reverse String ├── README.md └── reverse-string.js ├── 0349. Intersection of Two Arrays ├── README.md └── intersection-of-two-arrays.js ├── 0371. Sum of Two Integers ├── README.md └── sum-of-two-integers.js ├── 0387. First Unique Character in a String ├── README.md └── first-unique-character-in-a-string.js ├── 0414. Third Maximum Number ├── README.md └── third-maximum-number.js ├── 0448. Find All Numbers Disappeared in an Array ├── README.md └── find-all-numbers-disappeared-in-an-array.js ├── 0456. 132 Pattern ├── 132-pattern.js └── README.md ├── 0485. Max Consecutive Ones ├── README.md └── max-consecutive-ones.js ├── 0557. Reverse Words in a String III ├── README.md └── reverse-words-in-a-string-iii.js ├── 0566. Reshape the Matrix ├── README.md └── reshape-the-matrix.js ├── 0622. Design Circular Queue ├── README.md └── design-circular-queue.js ├── 0658. Find K Closest Elements ├── README.md └── find-k-closest-elements.js ├── 0680. Valid Palindrome II ├── README.md └── valid-palindrome-ii.js ├── 0766. Toeplitz Matrix ├── README.md └── toeplitz-matrix.js ├── 0804. Unique Morse Code Words ├── README.md └── unique-morse-code-words.js ├── 0838. Push Dominoes ├── README.md └── push-dominoes.js ├── 0852. Peak Index in a Mountain Array ├── README.md └── peak-index-in-a-mountain-array.js ├── 0867. Transpose Matrix ├── README.md └── transpose-matrix.js ├── 0912. Sort an Array ├── README.md └── sort-an-array.js ├── 0941. Valid Mountain Array ├── README.md ├── valid-mountain-array.cpp └── valid-mountain-array.js ├── 0967. Numbers With Same Consecutive Differences ├── README.md └── numbers-with-same-consecutive-differences.js ├── 0990. Satisfiability of Equality Equations ├── README.md └── satisfiability-of-equality-equations.js ├── 1011. Capacity To Ship Packages Within D Days ├── README.md ├── allocate-books.cpp ├── capacity-to-ship-packages-within-d-days.js └── painter-s-partition-problem.cpp ├── 1021. Remove Outermost Parentheses ├── README.md └── remove-outermost-parentheses.js ├── 1155. Number of Dice Rolls With Target Sum ├── README.md └── number-of-dice-rolls-with-target-sum.js ├── 1207. Unique Number of Occurrences ├── README.md └── unique-number-of-occurrences.js ├── 1337. The K Weakest Rows in a Matrix ├── README.md └── the-k-weakest-rows-in-a-matrix.js ├── 1380. Lucky Numbers in a Matrix ├── README.md └── lucky-numbers-in-a-matrix.js ├── 1470. Shuffle the Array ├── README.md └── shuffle-the-array.js ├── 1482. Minimum Number of Days to Make m Bouquets ├── README.md └── minimum-number-of-days-to-make-m-bouquets.js ├── 1502. Can Make Arithmetic Progression From Sequence ├── README.md └── can-make-arithmetic-progression-from-sequence.js ├── 1539. Kth Missing Positive Number ├── README.md └── kth-missing-positive-number.js ├── 1544. Make The String Great ├── README.md └── make-the-string-great.js ├── 1552. Magnetic Force Between Two Balls ├── 109-aggressive-cows-codingninjas.cpp ├── README.md └── magnetic-force-between-two-balls.js ├── 1572. Matrix Diagonal Sum ├── README.md └── matrix-diagonal-sum.js ├── 1668. Maximum Repeating Substring ├── README.md └── maximum-repeating-substring.js ├── 1700. Number of Students Unable to Eat Lunch ├── README.md └── number-of-students-unable-to-eat-lunch.js ├── 1752. Check if Array Is Sorted and Rotated ├── README.md └── check-if-array-is-sorted-and-rotated.js ├── 1910. Remove All Occurrences of a Substring ├── README.md └── remove-all-occurrences-of-a-substring.js ├── 2022. Convert 1D Array Into 2D Array ├── README.md └── convert-1d-array-into-2d-array.js ├── 2073. Time Needed to Buy Tickets ├── README.md └── time-needed-to-buy-tickets.js ├── 2091. Removing Minimum and Maximum From Array ├── README.md └── removing-minimum-and-maximum-from-array.js ├── 2133. Check if Every Row and Column Contains All Numbers ├── README.md └── check-if-every-row-and-column-contains-all-numbers.js ├── 2319. Check if Matrix Is X-Matrix ├── README.md └── check-if-matrix-is-x-matrix.js ├── 300. Longest Increasing Subsequence ├── README.md └── longest-increasing-subsequence.js └── README.md /0001. Two Sum/2-sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number[]} 5 | */ 6 | var twoSum = function(nums, target) { 7 | const result = []; 8 | for(let i=0;i 0){ 19 | if(l1 != null){ 20 | sum+=l1.val; 21 | l1 = l1.next; 22 | } 23 | if(l2 != null){ 24 | sum+=l2.val; 25 | l2 = l2.next; 26 | } 27 | 28 | carry = Math.floor(sum / 10);; 29 | sum = sum%10; 30 | currentNode.next = new ListNode(sum); 31 | currentNode = currentNode.next; 32 | 33 | sum = carry; 34 | carry = 0; 35 | 36 | } 37 | return list.next; 38 | }; 39 | -------------------------------------------------------------------------------- /0003. Longest Substring Without Repeating Characters/README.md: -------------------------------------------------------------------------------- 1 | ### [3. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) 2 | 3 | ##### Level Medium 4 | 5 | Given a string s, find the length of the longest substring without repeating characters. 6 | 7 | Example 1: 8 | 9 | Input: 10 | ```JS 11 | s = "abcabcbb" 12 | ``` 13 | 14 | Output: 15 | ```JS 16 | 3 17 | ``` 18 | 19 | Explanation: 20 | ```JS 21 | The answer is "abc", with the length of 3. 22 | ``` 23 | 24 | Example 2: 25 | 26 | Input: 27 | ```JS 28 | s = "bbbbb" 29 | ``` 30 | 31 | Output: 32 | ```JS 33 | 1 34 | ``` 35 | 36 | Explanation: 37 | ```JS 38 | The answer is "b", with the length of 1. 39 | ``` 40 | 41 | Example 3: 42 | 43 | Input: 44 | ```JS 45 | s = "pwwkew" 46 | ``` 47 | 48 | Output: 49 | ```JS 50 | 3 51 | ``` 52 | 53 | Explanation: 54 | ```JS 55 | The answer is "wke", with the length of 3. 56 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 57 | ``` 58 | 59 | ### Constraints: 60 | 61 | ```JS 62 | 0 <= s.length <= 5 * 104 63 | s consists of English letters, digits, symbols and spaces. 64 | ``` 65 | -------------------------------------------------------------------------------- /0003. Longest Substring Without Repeating Characters/longest-substring-without-repeating-characters.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var lengthOfLongestSubstring = function(s) { 6 | const subArray = []; 7 | let counter = 0; 8 | for(let i=0;i counter){ 12 | counter = subArray.length; 13 | } 14 | }else{ 15 | // remove till s[i] if match 16 | let index = subArray.indexOf(s[i]); 17 | subArray.splice(0, index+1); 18 | subArray.push(s[i]); 19 | } 20 | } 21 | return counter; 22 | }; 23 | -------------------------------------------------------------------------------- /0004. Median of Two Sorted Arrays/README.md: -------------------------------------------------------------------------------- 1 | ### [4. Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) 2 | 3 | ##### Level Hard 4 | 5 | 6 | Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. 7 | The overall run time complexity should be O(log (m+n)). 8 | 9 | 10 | Example 1: 11 | 12 | Input: 13 | ```JS 14 | nums1 = [1,3], nums2 = [2] 15 | ``` 16 | 17 | Output: 18 | ```JS 19 | 2.00000 20 | ``` 21 | 22 | Explanation: 23 | ```JS 24 | merged array = [1,2,3] and median is 2. 25 | ``` 26 | 27 | Example 2: 28 | 29 | Input: 30 | ```JS 31 | nums1 = [1,2], nums2 = [3,4] 32 | ``` 33 | 34 | Output: 35 | ```JS 36 | 2.50000 37 | ``` 38 | 39 | Explanation: 40 | ```JS 41 | merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. 42 | ``` 43 | 44 | ### Constraints: 45 | 46 | ```JS 47 | nums1.length == m 48 | nums2.length == n 49 | 0 <= m <= 1000 50 | 0 <= n <= 1000 51 | 1 <= m + n <= 2000 52 | -106 <= nums1[i], nums2[i] <= 106 53 | ``` 54 | -------------------------------------------------------------------------------- /0004. Median of Two Sorted Arrays/median-of-two-sorted-arrays.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums1 3 | * @param {number[]} nums2 4 | * @return {number} 5 | */ 6 | var findMedianSortedArrays = function(nums1, nums2) { 7 | let mergedArray = []; 8 | let left = 0, right = 0, counter = 0; 9 | 10 | while(nums1.length > left && nums2.length > right){ 11 | if(nums1[left] > nums2[right]){ 12 | mergedArray.push(nums2[right]); 13 | right++; 14 | }else if(nums1[left] <= nums2[right]){ 15 | mergedArray.push(nums1[left]); 16 | left++; 17 | } 18 | } 19 | 20 | 21 | for(let i=left;i=0 && end<=s.length && s[start] == s[end]){ 8 | start--; 9 | end++; 10 | } 11 | return s.substring(start+1, end) 12 | } 13 | 14 | let longestPalindrome = function(s) { 15 | if(!s || s.length<=1){ 16 | return s 17 | } 18 | let longestSubstring = s.substring(0,1); 19 | for(let i=0;i ",i, i+1, temp); 27 | if(longestSubstring.length <= temp.length){ 28 | longestSubstring = temp; 29 | } 30 | } 31 | return longestSubstring; 32 | }; 33 | 34 | /* 35 | Runtime: 251 ms 36 | */ 37 | -------------------------------------------------------------------------------- /0006. Zigzag Conversion/README.md: -------------------------------------------------------------------------------- 1 | ### [6. Zigzag Conversion](https://leetcode.com/problems/zigzag-conversion/) 2 | 3 | ##### Level Medium 4 | 5 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 6 | 7 | ```JS 8 | P A H N 9 | A P L S I I G 10 | Y I R 11 | And then read line by line: "PAHNAPLSIIGYIR" 12 | ```` 13 | 14 | Write the code that will take a string and make this conversion given a number of rows: 15 | 16 | string convert(string s, int numRows); 17 | 18 | 19 | ##### Example 1: 20 | 21 | ```JS 22 | Input: s = "PAYPALISHIRING", numRows = 3 23 | Output: "PAHNAPLSIIGYIR" 24 | ``` 25 | 26 | ##### Example 2: 27 | ```JS 28 | Input: s = "PAYPALISHIRING", numRows = 4 29 | Output: "PINALSIGYAHRPI" 30 | ``` 31 | 32 | Explanation: 33 | ```JS 34 | P I N 35 | A L S I G 36 | Y A H R 37 | P I 38 | ``` 39 | 40 | ##### Example 3: 41 | ```JS 42 | Input: s = "A", numRows = 1 43 | Output: "A" 44 | ``` 45 | 46 | ##### Constraints: 47 | ```JS 48 | 1 <= s.length <= 1000 49 | s consists of English letters (lower-case and upper-case), ',' and '.'. 50 | 1 <= numRows <= 1000 51 | ``` 52 | -------------------------------------------------------------------------------- /0006. Zigzag Conversion/zigzag-conversion.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {number} numRows 4 | * @return {string} 5 | */ 6 | var convert = function(s, numRows) { 7 | if(s == null || numRows <= 0){ 8 | return; 9 | } 10 | if(numRows ==1){ 11 | return s 12 | } 13 | 14 | let result = ""; 15 | let steps = 2 * numRows - 2; 16 | for(let i=0; i 6 —> 12) and last rows (3 —> 9). 40 | 41 | Iteration 42 | For i = 0 => j = 0, 6, 12 43 | For i = 1 => j = 1, 7, 13 44 | For i = 2 => j = 2, 8 45 | For i = 3 => j = 3, 9 46 | 47 | */ 48 | 49 | Runtime: 433 ms 50 | Memory Usage: 51.6 MB 51 | -------------------------------------------------------------------------------- /0007. Reverse Integer/README.md: -------------------------------------------------------------------------------- 1 | ### [7. Reverse Integer](https://leetcode.com/problems/reverse-integer/) 2 | 3 | ##### Level Medium 4 | 5 | Given a signed 32-bit integer x, return x with its digits reversed. 6 | If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. 7 | 8 | Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 9 | 10 | Example 1: 11 | ```JS 12 | Input: x = 123 13 | Output: 321 14 | ``` 15 | 16 | Example 2: 17 | ```JS 18 | Input: x = -123 19 | Output: -321 20 | ``` 21 | 22 | 23 | Example 3: 24 | ```JS 25 | Input: x = 120 26 | Output: 21 27 | ``` 28 | 29 | Constraints: 30 | ```JS 31 | -231 <= x <= 231 - 1 32 | ``` 33 | -------------------------------------------------------------------------------- /0007. Reverse Integer/reverse-integer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @return {number} 4 | */ 5 | var reverse = function(x) { 6 | let result = 0; 7 | let counter = 0; 8 | let isNeg = false; 9 | if(x < 0){ 10 | isNeg = true; 11 | x = -(x); 12 | } 13 | while(x >= 1){ 14 | let temp = Math.floor(x % 10); 15 | result =`${result}`+temp; 16 | x = Math.floor(x/10); 17 | } 18 | if (result >= Math.pow(2, 31) - 1 || result <= Math.pow(-2, 31)) { 19 | return 0; 20 | } 21 | return isNeg ? -result : result; 22 | }; 23 | 24 | /* 25 | Runtime: 151 ms 26 | Memory Usage: 44 MB 27 | */ 28 | -------------------------------------------------------------------------------- /0009. Palindrome Number/README.md: -------------------------------------------------------------------------------- 1 | ### [9. Palindrome Number](https://leetcode.com/problems/palindrome-number/) 2 | 3 | ###### Level Easy 4 | 5 | Given an integer x, return true if x is palindrome integer. 6 | 7 | An integer is a palindrome when it reads the same backward as forward. 8 | 9 | For example, 121 is a palindrome while 123 is not. 10 | 11 | 12 | Example 1: 13 | 14 | Input: 15 | ```JS 16 | x = 121 17 | ``` 18 | Output: 19 | ```JS 20 | true 21 | ``` 22 | 23 | Explanation: 24 | ```JS 25 | 121 reads as 121 from left to right and from right to left. 26 | ``` 27 | 28 | Example 2: 29 | 30 | Input: 31 | ```JS 32 | x = -121 33 | ``` 34 | Output: 35 | ```JS 36 | false 37 | ``` 38 | 39 | Explanation: 40 | ```JS 41 | From left to right, it reads -121. 42 | From right to left, it becomes 121-. Therefore it is not a palindrome. 43 | ``` 44 | 45 | 46 | Example 3: 47 | 48 | Input: 49 | ```JS 50 | x = 10 51 | ``` 52 | Output: 53 | ```JS 54 | false 55 | ``` 56 | 57 | Explanation: 58 | ```JS 59 | Reads 01 from right to left. Therefore it is not a palindrome. 60 | ``` 61 | 62 | ##### Constraints: 63 | ```JS 64 | -231 <= x <= 231 - 1 65 | ``` 66 | -------------------------------------------------------------------------------- /0009. Palindrome Number/palindrome.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @return {boolean} 4 | */ 5 | 6 | var flip = function(num){ 7 | let rev = ''; 8 | let isNeg = false; 9 | if(num < 0){ 10 | isNeg = true; 11 | num = -num; 12 | } 13 | while(num){ 14 | let temp = Math.floor(num % 10); 15 | rev = `${rev}${temp}`; 16 | num = Math.floor(num / 10); 17 | } 18 | return isNeg ? `${rev}${'-'}` : rev; 19 | } 20 | 21 | var isPalindrome = function(x) { 22 | let rev = flip(x); 23 | if(rev == x){ 24 | return true 25 | } 26 | return false 27 | }; 28 | -------------------------------------------------------------------------------- /0011. Container With Most Water/README.md: -------------------------------------------------------------------------------- 1 | ### [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/) 2 | 3 | ##### Level Medium 4 | 5 | You are given an integer array height of length n. 6 | There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). 7 | 8 | Find two lines that together with the x-axis form a container, such that the container contains the most water. 9 | 10 | Return the maximum amount of water a container can store. 11 | 12 | Notice that you may not slant the container. 13 | 14 | 15 | Example 1: 16 | 17 | ```JS 18 | Input: height = [1,8,6,2,5,4,8,3,7] 19 | Output: 49 20 | ``` 21 | 22 | Explanation: 23 | ```JS 24 | The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. 25 | In this case, the max area of water (blue section) the container can contain is 49. 26 | ``` 27 | 28 | Example 2: 29 | ```JS 30 | Input: height = [1,1] 31 | Output: 1 32 | ``` 33 | 34 | Constraints: 35 | ```JS 36 | n == height.length 37 | 2 <= n <= 105 38 | 0 <= height[i] <= 104 39 | ``` 40 | -------------------------------------------------------------------------------- /0011. Container With Most Water/container-with-most-water.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} height 3 | * @return {number} 4 | */ 5 | var maxArea = function(height) { 6 | if(!height || height.length <= 1){ 7 | return 0; 8 | } 9 | 10 | let len = height.length; 11 | let start = 0; 12 | let end = len-1; 13 | let max_water = -1; 14 | while(start < end){ 15 | if(height[start] < height[end]){ 16 | let waterLevel = (height[start] * (end - start)); 17 | if(waterLevel > max_water){ 18 | max_water = waterLevel; 19 | } 20 | start++; 21 | }else{ 22 | let waterLevel = (height[end] * (end - start)); 23 | if(waterLevel > max_water){ 24 | max_water = waterLevel; 25 | } 26 | end--; 27 | } 28 | } 29 | 30 | return max_water; 31 | 32 | }; 33 | 34 | 35 | /* 36 | Runtime: 118 ms 37 | Memory Usage: 49.6 MB 38 | */ 39 | -------------------------------------------------------------------------------- /0012. Integer to Roman/README.md: -------------------------------------------------------------------------------- 1 | ### [12. Integer to Roman](https://leetcode.com/problems/integer-to-roman/) 2 | 3 | ###### Level Medium 4 | 5 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 6 | 7 | ```JS 8 | Symbol Value 9 | I 1 10 | V 5 11 | X 10 12 | L 50 13 | C 100 14 | D 500 15 | M 1000 16 | ``` 17 | 18 | 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. 19 | 20 | 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: 21 | 22 | I can be placed before V (5) and X (10) to make 4 and 9. 23 | X can be placed before L (50) and C (100) to make 40 and 90. 24 | C can be placed before D (500) and M (1000) to make 400 and 900. 25 | Given an integer, convert it to a roman numeral. 26 | 27 | 28 | Example 1: 29 | ```JS 30 | Input: num = 3 31 | Output: "III" 32 | ``` 33 | 34 | Explanation: 3 is represented as 3 ones. 35 | 36 | 37 | Example 2: 38 | ```JS 39 | Input: num = 58 40 | Output: "LVIII" 41 | ``` 42 | 43 | Explanation: L = 50, V = 5, III = 3. 44 | 45 | 46 | Example 3: 47 | ```JS 48 | Input: num = 1994 49 | Output: "MCMXCIV" 50 | ``` 51 | 52 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 53 | 54 | 55 | Constraints: 56 | ```JS 57 | 1 <= num <= 3999 58 | ``` 59 | -------------------------------------------------------------------------------- /0012. Integer to Roman/integer-to-roman.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} num 3 | * @return {string} 4 | */ 5 | 6 | 7 | /** 8 | * @param {number} num 9 | * @return {string} 10 | */ 11 | var intToRoman = function(num) { 12 | let result = ''; 13 | let array = []; 14 | while(num > 0){ 15 | if(num >= 1000){ 16 | array.push('M'); 17 | num -=1000; 18 | }else if(num < 1000 && num >= 900){ 19 | array.push('CM'); 20 | num -=900; 21 | }else if(num < 900 && num >= 500){ 22 | array.push('D'); 23 | num -=500; 24 | }else if(num < 500 && num >= 400){ 25 | array.push('CD'); 26 | num -=400; 27 | }else if(num < 400 && num >= 100){ 28 | array.push('C'); 29 | num -=100; 30 | }else if(num < 100 && num >= 90){ 31 | array.push('XC'); 32 | num -=90; 33 | }else if(num < 90 && num >= 50){ 34 | array.push('L'); 35 | num -=50; 36 | }else if(num < 50 && num >= 40){ 37 | array.push('XL'); 38 | num -=40; 39 | }else if(num < 40 && num >= 10){ 40 | array.push('X'); 41 | num -=10; 42 | }else if(num < 10 && num >= 9){ 43 | array.push('IX'); 44 | num -=9; 45 | }else if(num < 9 && num >= 5){ 46 | array.push('V'); 47 | num -=5; 48 | }else if(num < 5 && num >= 4){ 49 | array.push('IV'); 50 | num -=4; 51 | }else if(num < 4 && num >= 1){ 52 | array.push('I'); 53 | num -=1; 54 | } 55 | } 56 | return array.join(""); 57 | }; 58 | 59 | /* 60 | Runtime: 554 ms 61 | */ 62 | 63 | // OR 64 | 65 | 66 | var intToRoman = function(num) { 67 | const val = [1000,900,500,400,100,90,50,40,10,9,5,4,1] 68 | const rom = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] 69 | let ans = "" 70 | for(let i=0; num > 0;i++){ 71 | while (num >= val[i]) { 72 | ans += rom[i]; 73 | num -= val[i]; 74 | } 75 | } 76 | return ans 77 | }; 78 | 79 | /* 80 | Runtime: 67 ms 81 | Memory Usage: 46.8 MB 82 | */ 83 | -------------------------------------------------------------------------------- /0013. Roman to Integer/README.md: -------------------------------------------------------------------------------- 1 | ### [13. Roman to Integer](https://leetcode.com/problems/roman-to-integer/) 2 | 3 | ###### Easy 4 | 5 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 6 | 7 | ```JS 8 | Symbol Value 9 | I 1 10 | V 5 11 | X 10 12 | L 50 13 | C 100 14 | D 500 15 | M 1000 16 | ``` 17 | 18 | For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. 19 | 20 | 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: 21 | 22 | I can be placed before V (5) and X (10) to make 4 and 9. 23 | X can be placed before L (50) and C (100) to make 40 and 90. 24 | C can be placed before D (500) and M (1000) to make 400 and 900. 25 | Given a roman numeral, convert it to an integer. 26 | 27 | 28 | 29 | Example 1: 30 | ```JS 31 | Input: s = "III" 32 | Output: 3 33 | ``` 34 | 35 | Explanation: III = 3. 36 | 37 | 38 | Example 2: 39 | ```JS 40 | Input: s = "LVIII" 41 | Output: 58 42 | ``` 43 | 44 | Explanation: 45 | ```JS 46 | L = 50, V= 5, III = 3. 47 | ``` 48 | 49 | Example 3: 50 | ```JS 51 | Input: s = "MCMXCIV" 52 | Output: 1994 53 | ``` 54 | 55 | Explanation: 56 | ```JS 57 | M = 1000, CM = 900, XC = 90 and IV = 4. 58 | ``` 59 | 60 | Constraints: 61 | ```JS 62 | 1 <= s.length <= 15 63 | s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). 64 | It is guaranteed that s is a valid roman numeral in the range [1, 3999]. 65 | ``` 66 | -------------------------------------------------------------------------------- /0013. Roman to Integer/roman-to-integer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var romanToInt = function(s) { 6 | if(!s && !s.length){ 7 | return; 8 | } 9 | const hash= { 10 | 'I': 1, 11 | 'V': 5, 12 | 'X': 10, 13 | 'L': 50, 14 | 'C': 100, 15 | 'D': 500, 16 | 'M': 1000, 17 | }; 18 | let result = hash[s[s.length-1]]; 19 | for(let i=s.length-2; i>=0; i--){ 20 | if(!s[i] || !s[i+1] || !hash[s[i]] || !hash[s[i+1]]){ 21 | return result; 22 | } 23 | 24 | if(hash[s[i]] >= hash[s[i+1]]){ 25 | result += hash[s[i]]; 26 | }else{ 27 | result -= hash[s[i]]; 28 | } 29 | } 30 | return result; 31 | }; 32 | 33 | /* 34 | Runtime: 199 ms 35 | */ 36 | 37 | -------------------------------------------------------------------------------- /0014. Longest Common Prefix/README.md: -------------------------------------------------------------------------------- 1 | ### [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) 2 | 3 | ##### Easy 4 | 5 | Write a function to find the longest common prefix string amongst an array of strings. 6 | If there is no common prefix, return an empty string "". 7 | 8 | Example 1: 9 | 10 | Input: 11 | ```JS 12 | strs = ["flower","flow","flight"] 13 | Output: 14 | "fl" 15 | ``` 16 | 17 | Example 2: 18 | 19 | Input: 20 | ```JS 21 | strs = ["dog","racecar","car"] 22 | Output: 23 | "" 24 | ``` 25 | 26 | Explanation: 27 | ```JS 28 | There is no common prefix among the input strings. 29 | ``` 30 | 31 | ##### Constraints: 32 | ```JS 33 | 1 <= strs.length <= 200 34 | 0 <= strs[i].length <= 200 35 | strs[i] consists of only lowercase English letters. 36 | ``` 37 | -------------------------------------------------------------------------------- /0014. Longest Common Prefix/longest-common-prefix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} strs 3 | * @return {string} 4 | */ 5 | var longestCommonPrefix = function(strs) { 6 | let len = strs.length; 7 | let l=0; 8 | let r= len-1; 9 | 10 | return findPrefix(strs,l,r) 11 | }; 12 | 13 | 14 | var findPrefix = function(strs, l, r){ 15 | if(l===r){ 16 | return strs[l] 17 | } 18 | if(l 0){ 36 | e--; 37 | }else{ 38 | s++; 39 | } 40 | } 41 | } 42 | 43 | return result; 44 | }; 45 | 46 | 47 | /* 48 | Runtime: 1947 ms 49 | Memory Usage: 61.4 MB 50 | */ 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /0015. 3Sum/README.md: -------------------------------------------------------------------------------- 1 | ### [15. 3Sum](https://leetcode.com/problems/3sum/) 2 | 3 | ###### Level Medium 4 | 5 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 6 | 7 | Notice that the solution set must not contain duplicate triplets. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: 14 | ```JS 15 | nums = [-1,0,1,2,-1,-4] 16 | ``` 17 | 18 | Output: 19 | ```JS 20 | [[-1,-1,2],[-1,0,1]] 21 | ``` 22 | ###### Explanation: 23 | ```JS 24 | nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. 25 | nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. 26 | nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. 27 | The distinct triplets are [-1,0,1] and [-1,-1,2]. 28 | Notice that the order of the output and the order of the triplets does not matter. 29 | ``` 30 | 31 | Example 2: 32 | 33 | Input: 34 | ```JS 35 | nums = [0,1,1] 36 | ``` 37 | 38 | Output: 39 | ```JS 40 | [] 41 | ``` 42 | 43 | Explanation: 44 | ```JS 45 | The only possible triplet does not sum up to 0. 46 | ``` 47 | 48 | 49 | Example 3: 50 | 51 | Input: 52 | ```JS 53 | nums = [0,0,0] 54 | ``` 55 | 56 | Output: 57 | ```JS 58 | [[0,0,0]] 59 | ``` 60 | 61 | 62 | Explanation: 63 | ```JS 64 | The only possible triplet sums up to 0. 65 | ``` 66 | 67 | ###### Constraints: 68 | ```JS 69 | 3 <= nums.length <= 3000 70 | -105 <= nums[i] <= 105 71 | ``` 72 | -------------------------------------------------------------------------------- /0016. 3Sum Closest/3sum-closest.js: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: Brute Force 3 | */ 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {number} target 8 | * @return {number} 9 | */ 10 | 11 | var threeSumClosest = function(nums, target) { 12 | if(nums.length < 3) { 13 | return 0; 14 | } 15 | 16 | nums.sort(function(a,b) { 17 | return a-b; 18 | }) 19 | 20 | let i = 0, minDiff = Number.MAX_VALUE; 21 | let sum; 22 | 23 | while( i < nums.length - 2 ){ 24 | let left = i + 1; 25 | let right = nums.length - 1 26 | 27 | while( right > left ){ 28 | let temp = nums[i] + nums[left] + nums[right]; 29 | let diff = Math.abs(temp - target); 30 | 31 | if( diff == 0 ){ 32 | return temp; 33 | } 34 | 35 | if( diff < minDiff ){ 36 | minDiff = diff; 37 | sum = temp; 38 | } 39 | if( temp < target ){ 40 | left++; 41 | } else { 42 | right--; 43 | } 44 | } 45 | i++; 46 | } 47 | 48 | return sum; 49 | }; 50 | 51 | 52 | -------------------------------------------------------------------------------- /0016. 3Sum Closest/README.md: -------------------------------------------------------------------------------- 1 | ### [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/) 2 | 3 | ##### Level Medium 4 | 5 | Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. 6 | Return the sum of the three integers. 7 | You may assume that each input would have exactly one solution. 8 | 9 | 10 | 11 | Example 1: 12 | ```JS 13 | Input: 14 | nums = [-1,2,1,-4], target = 1 15 | ``` 16 | 17 | ```JS 18 | Output: 19 | 2 20 | ``` 21 | 22 | Explanation: 23 | ```JS 24 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 25 | ``` 26 | 27 | Example 2: 28 | ```JS 29 | Input: 30 | nums = [0,0,0], target = 1 31 | ``` 32 | ```JS 33 | Output: 34 | 0 35 | ``` 36 | 37 | ##### Constraints: 38 | ```JS 39 | 3 <= nums.length <= 1000 40 | -1000 <= nums[i] <= 1000 41 | -104 <= target <= 104 42 | ``` 43 | -------------------------------------------------------------------------------- /0020. Valid Parentheses/README.md: -------------------------------------------------------------------------------- 1 | ### [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) 2 | 3 | ##### Level Easy 4 | 5 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 6 | 7 | An input string is valid if: 8 | 9 | Open brackets must be closed by the same type of brackets. 10 | Open brackets must be closed in the correct order. 11 | 12 | 13 | Example 1: 14 | 15 | Input: 16 | ```JS 17 | s = "()" 18 | ``` 19 | 20 | Output: 21 | ```JS 22 | true 23 | ``` 24 | 25 | 26 | Example 2: 27 | 28 | Input: 29 | ```JS 30 | s = "()[]{}" 31 | ``` 32 | 33 | Output: 34 | ```JS 35 | true 36 | ``` 37 | 38 | Example 3: 39 | 40 | Input: 41 | ```JS 42 | s = "(]" 43 | ``` 44 | 45 | Output: 46 | ```JS 47 | false 48 | ``` 49 | 50 | Constraints: 51 | ```JS 52 | 1 <= s.length <= 104 53 | s consists of parentheses only '()[]{}'. 54 | ``` -------------------------------------------------------------------------------- /0020. Valid Parentheses/valid-parentheses.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {boolean} 4 | */ 5 | var isValid = function(s) { 6 | if(!s || s.length <= 1){ 7 | return false; 8 | } 9 | 10 | let stack = []; 11 | let map = { 12 | '(':')', 13 | '[':']', 14 | '{':'}', 15 | } 16 | 17 | for(let i=0;i< s.length;i++){ 18 | if(map[s[i]]){ 19 | stack.push(map[s[i]]) 20 | }else{ 21 | if(stack.pop() != s[i]){ 22 | return false 23 | } 24 | } 25 | } 26 | 27 | return stack.length > 0 ? false : true; 28 | }; 29 | 30 | /* 31 | Runtime: 74 ms 32 | Memory Usage: 42 MB 33 | */ -------------------------------------------------------------------------------- /0033. Search in Rotated Sorted Array/README.md: -------------------------------------------------------------------------------- 1 | ### [33. Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) 2 | 3 | ##### Level Medium 4 | 5 | There is an integer array nums sorted in ascending order (with distinct values). 6 | 7 | Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. 8 | 9 | Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. 10 | 11 | You must write an algorithm with O(log n) runtime complexity. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: 18 | ```JS 19 | nums = [4,5,6,7,0,1,2], target = 0 20 | ``` 21 | 22 | Output: 23 | ```JS 24 | 4 25 | ``` 26 | 27 | 28 | Example 2: 29 | 30 | Input: 31 | ```JS 32 | nums = [4,5,6,7,0,1,2], target = 3 33 | ``` 34 | 35 | Output: 36 | ```JS 37 | -1 38 | ``` 39 | 40 | 41 | Example 3: 42 | 43 | Input: 44 | ```JS 45 | nums = [1], target = 0 46 | ``` 47 | 48 | Output: 49 | ```JS 50 | -1 51 | ``` 52 | 53 | 54 | ##### Constraints: 55 | ```JS 56 | 1 <= nums.length <= 5000 57 | -104 <= nums[i] <= 104 58 | All values of nums are unique. 59 | nums is an ascending array that is possibly rotated. 60 | -104 <= target <= 104 61 | ``` -------------------------------------------------------------------------------- /0033. Search in Rotated Sorted Array/search-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number} 5 | */ 6 | 7 | /* 8 | mid = left + ((right - left)/2) 9 | */ 10 | 11 | // Approach : Recursion + Binary Search 12 | 13 | let binarySearch = function(nums, left, right, target){ 14 | let mid = Math.floor(left+((right-left)/2)); 15 | if(left > right){ 16 | return -1; 17 | } 18 | 19 | if(nums[mid]==target){ 20 | return mid; 21 | } 22 | 23 | if(nums[left] <= nums[mid] && target <= nums[mid] && target >= nums[left]){ 24 | return binarySearch(nums, left, right -1, target); 25 | } 26 | else if(nums[mid] <= nums[right] && target >= nums[mid] && target <= nums[right]){ 27 | return binarySearch(nums, left + 1, right, target); 28 | } 29 | else if (nums[right] <= nums[mid]) { 30 | return binarySearch(nums, mid+1, right, target); 31 | } 32 | else if (nums[left] >= nums[mid]) { 33 | return binarySearch(nums, left, mid-1, target); 34 | } 35 | else{ 36 | return -1; 37 | } 38 | 39 | } 40 | 41 | var search = function(nums, target) { 42 | let left = 0; 43 | let right = nums.length-1; 44 | if(!nums){ return -1;} 45 | return binarySearch(nums, left, right, target); 46 | }; 47 | 48 | /* 49 | Runtime: 237 ms 50 | */ -------------------------------------------------------------------------------- /0048. Rotate Image/README.md: -------------------------------------------------------------------------------- 1 | ### [48. Rotate Image](https://leetcode.com/problems/rotate-image/) 2 | 3 | ##### Medium 4 | 5 | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 6 | 7 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 8 | 9 | 10 | 11 | Example 1: 12 | ```JS 13 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 14 | Output: [[7,4,1],[8,5,2],[9,6,3]] 15 | ``` 16 | 17 | 18 | Example 2: 19 | ```JS 20 | Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] 21 | Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] 22 | ``` 23 | 24 | 25 | ##### Constraints: 26 | ```JS 27 | n == matrix.length == matrix[i].length 28 | 1 <= n <= 20 29 | -1000 <= matrix[i][j] <= 1000 30 | ``` -------------------------------------------------------------------------------- /0048. Rotate Image/rotate-image.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {void} Do not return anything, modify matrix in-place instead. 4 | */ 5 | var rotate = function(matrix) { 6 | let n = matrix.length; 7 | for(let x=0; x= colBeg; i--) { 28 | result.push(matrix[rowEnd][i]) 29 | } 30 | rowEnd-- 31 | } 32 | 33 | if (colBeg <= colEnd) { 34 | for (let i = rowEnd;i >= rowBeg; i--) { 35 | result.push(matrix[i][colBeg]) 36 | } 37 | colBeg++ 38 | } 39 | } 40 | return result 41 | }; 42 | 43 | /* 44 | Runtime: 136 ms, faster than 5.34% of JavaScript online submissions for Spiral Matrix. 45 | Memory Usage: 41.9 MB, less than 61.83% of JavaScript online submissions for Spiral Matrix. 46 | */ 47 | 48 | 49 | -------------------------------------------------------------------------------- /0059. Spiral Matrix II/README.md: -------------------------------------------------------------------------------- 1 | ### [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) 2 | 3 | ##### Medium 4 | 5 | Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. 6 | 7 | Example 1: 8 | ```JS 9 | Input: n = 3 10 | Output: [[1,2,3],[8,9,4],[7,6,5]] 11 | ``` 12 | 13 | 14 | Example 2: 15 | ```JS 16 | Input: n = 1 17 | Output: [[1]] 18 | ``` 19 | 20 | ##### Constraints: 21 | ```JS 22 | 1 <= n <= 20 23 | ``` -------------------------------------------------------------------------------- /0059. Spiral Matrix II/spiral-matrix-ii.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {number[][]} 4 | */ 5 | var generateMatrix = function(n) { 6 | let result = []; 7 | // creating two dimensional array 8 | for (var i = 0; i < n; i++) { 9 | result[i] = new Array(n); 10 | } 11 | let val = 1; 12 | 13 | let rowBeg = 0 14 | let rowEnd = n - 1 15 | let colBeg = 0 16 | let colEnd = n - 1 17 | 18 | while (rowBeg <= rowEnd && colBeg <= colEnd) { 19 | for (let i = colBeg; i <= colEnd; i++) { 20 | result[rowBeg][i] = val++; 21 | } 22 | rowBeg++ 23 | for (let i = rowBeg; i <= rowEnd; i++) { 24 | result[i][colEnd] = val++; 25 | } 26 | colEnd-- 27 | if (rowBeg <= rowEnd) { 28 | for (let i = colEnd; i >= colBeg; i--) { 29 | result[rowEnd][i] = val++; 30 | } 31 | rowEnd-- 32 | } 33 | 34 | if (colBeg <= colEnd) { 35 | for (let i = rowEnd;i >= rowBeg; i--) { 36 | result[i][colBeg] = val++; 37 | } 38 | colBeg++ 39 | } 40 | } 41 | return result 42 | }; 43 | 44 | /* 45 | 46 | */ -------------------------------------------------------------------------------- /0069. Sqrt(x)/README.md: -------------------------------------------------------------------------------- 1 | ### [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/) 2 | 3 | ##### Level Easy 4 | 5 | Given a non-negative integer x, compute and return the square root of x. 6 | 7 | Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. 8 | 9 | ***Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.*** 10 | 11 | 12 | 13 | Example 1: 14 | ```JS 15 | Input: x = 4 16 | Output: 2 17 | ``` 18 | 19 | Example 2: 20 | ```JS 21 | Input: x = 8 22 | Output: 2 23 | ``` 24 | 25 | Explanation: 26 | ```JS 27 | The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. 28 | ``` 29 | 30 | ##### Constraints: 31 | ```JS 32 | 0 <= x <= 231 - 1 33 | ``` -------------------------------------------------------------------------------- /0069. Sqrt(x)/sqrtx.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @return {number} 4 | */ 5 | var mySqrt = function(x) { 6 | // Base cases 7 | if (x == 0 || x == 1) 8 | return x; 9 | 10 | // Starting from 1, try all 11 | // numbers until i*i is 12 | // greater than or equal to x. 13 | let i = 1; 14 | let result = 1; 15 | 16 | while (result <= x) 17 | { 18 | i++; 19 | result = i * i; 20 | } 21 | return i - 1; 22 | }; 23 | 24 | 25 | /* 26 | Runtime: 136 ms 27 | Memory: 43.2 MB 28 | */ 29 | 30 | -------------------------------------------------------------------------------- /0073. Set Matrix Zeroes/README.md: -------------------------------------------------------------------------------- 1 | ### [73. Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) 2 | 3 | ##### Medium 4 | 5 | Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. 6 | 7 | You must do it in place. 8 | 9 | 10 | 11 | Example 1: 12 | ```JS 13 | Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] 14 | Output: [[1,0,1],[0,0,0],[1,0,1]] 15 | ``` 16 | 17 | 18 | Example 2: 19 | ```JS 20 | Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] 21 | Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]] 22 | ``` 23 | 24 | 25 | ##### Constraints: 26 | ```JS 27 | m == matrix.length 28 | n == matrix[0].length 29 | 1 <= m, n <= 200 30 | -231 <= matrix[i][j] <= 231 - 1 31 | ``` 32 | 33 | ***Follow up:*** 34 | - A straightforward solution using O(mn) space is probably a bad idea. 35 | - A simple improvement uses O(m + n) space, but still not the best solution. 36 | - Could you devise a constant space solution? -------------------------------------------------------------------------------- /0073. Set Matrix Zeroes/set-matrix-zeroes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {void} Do not return anything, modify matrix in-place instead. 4 | */ 5 | var setZeroes = function(matrix) { 6 | const m = matrix.length;//row 7 | const n = matrix[0].length;//col 8 | let rowZeroIndx = []; 9 | let colZeroIndx = []; 10 | 11 | const map = {}; 12 | 13 | const getAllIndicesOfZero = (row) => { // get all index with value 0 - column 14 | return row.map((e, i) => e === 0 ? i : '').filter(String) 15 | } 16 | for(let i=0;i target){ 21 | end = mid-1; 22 | }else{ 23 | start = mid+1; 24 | } 25 | mid = start + parseInt((end - start)/2); 26 | } 27 | return false; 28 | }; 29 | 30 | /* 31 | 32 | */ 33 | 34 | 35 | // B) UP - DOWN Approach 36 | 37 | 38 | /** 39 | * @param {number[][]} matrix 40 | * @param {number} target 41 | * @return {boolean} 42 | */ 43 | var searchMatrix = function(matrix, target) { 44 | let m = matrix[0].length; // column length 45 | let n = matrix.length; // row length 46 | 47 | let i = 0; // first row 48 | let j = m-1; // last column 49 | 50 | // till i < n (row o to n) AND j >= 0 (col m to 0) 51 | while(i=0){ 52 | if(matrix[i][j] == target){ 53 | return true; 54 | } 55 | if(matrix[i][j] > target){ 56 | // we'll be moving towards left if the value of target is smaller 57 | j--; 58 | }else{ 59 | // otherwise we'll be moving downwards if the target is greater than 60 | i++; 61 | } 62 | } 63 | return false; 64 | }; 65 | 66 | /* 67 | 68 | */ -------------------------------------------------------------------------------- /0075. Sort Colors/README.md: -------------------------------------------------------------------------------- 1 | ### [75. Sort Colors](https://leetcode.com/problems/sort-colors/) 2 | 3 | ##### Level Medium 4 | 5 | Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. 6 | 7 | We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. 8 | 9 | You must solve this problem without using the library's sort function. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: 16 | ```JS 17 | nums = [2,0,2,1,1,0] 18 | ``` 19 | Output: 20 | ```JS 21 | [0,0,1,1,2,2] 22 | ``` 23 | 24 | 25 | Example 2: 26 | 27 | Input: 28 | ```JS 29 | nums = [2,0,1] 30 | ``` 31 | Output: 32 | ```JS 33 | [0,1,2] 34 | ``` 35 | 36 | 37 | ##### Constraints: 38 | ```JS 39 | n == nums.length 40 | 1 <= n <= 300 41 | nums[i] is either 0, 1, or 2. 42 | ``` 43 | 44 | ***Follow up: Could you come up with a one-pass algorithm using only constant extra space?*** 45 | -------------------------------------------------------------------------------- /0075. Sort Colors/sort-colors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {void} Do not return anything, modify nums in-place instead. 4 | */ 5 | var sortColors = function(nums) { 6 | let i, cnt0 = 0, cnt1 = 0, cnt2 = 0, n = nums.length; 7 | for (i = 0; i < n; i++) { 8 | switch (nums[i]) { 9 | case 0: 10 | cnt0++; 11 | break; 12 | case 1: 13 | cnt1++; 14 | break; 15 | case 2: 16 | cnt2++; 17 | break; 18 | } 19 | } 20 | i = 0; 21 | while (cnt0 > 0) { 22 | nums[i++] = 0; 23 | cnt0--; 24 | } 25 | while (cnt1 > 0) { 26 | nums[i++] = 1; 27 | cnt1--; 28 | } 29 | while (cnt2 > 0) { 30 | nums[i++] = 2; 31 | cnt2--; 32 | } 33 | }; 34 | 35 | /* 36 | Runtime: 84 ms, faster than 61.86% of JavaScript online submissions for Sort Colors. 37 | Memory Usage: 42 MB, less than 64.67% of JavaScript online submissions for Sort Colors. 38 | */ 39 | 40 | // OR 41 | 42 | // Binary Search Approach 43 | 44 | /** 45 | * @param {number[]} nums 46 | * @return {void} Do not return anything, modify nums in-place instead. 47 | */ 48 | var sortColors = function(nums) { 49 | if(nums.length < 2){ 50 | return nums; 51 | } 52 | let start = 0; 53 | let mid = 0; 54 | let end = nums.length-1; 55 | while(mid <= end){ 56 | if(nums[mid] == 0){ 57 | let temp = nums[mid]; 58 | nums[mid] = nums[start]; 59 | nums[start] = temp; 60 | start++; 61 | mid++; 62 | }else if(nums[mid] == 1){ 63 | mid++; 64 | }else if(nums[mid] == 2){ 65 | let temp = nums[mid]; 66 | nums[mid] = nums[end]; 67 | nums[end] = temp; 68 | end--; 69 | } 70 | } 71 | return nums; 72 | }; 73 | 74 | /* 75 | Runtime: 84 ms, faster than 61.86% of JavaScript online submissions for Sort Colors. 76 | Memory Usage: 42.2 MB, less than 52.31% of JavaScript online submissions for Sort Colors. 77 | */ -------------------------------------------------------------------------------- /0081. Search in Rotated Sorted Array II/README.md: -------------------------------------------------------------------------------- 1 | ### [81. Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) 2 | 3 | ##### Level Medium 4 | 5 | There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). 6 | 7 | Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. 8 | 9 | Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. 10 | 11 | You must decrease the overall operation steps as much as possible. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: 18 | ```JS 19 | nums = [2,5,6,0,0,1,2], target = 0 20 | ``` 21 | 22 | Output: 23 | ```JS 24 | true 25 | ``` 26 | 27 | 28 | Example 2: 29 | 30 | Input: 31 | ```JS 32 | nums = [2,5,6,0,0,1,2], target = 3 33 | ``` 34 | 35 | Output: 36 | ```JS 37 | false 38 | ``` 39 | 40 | ##### Constraints: 41 | ```JS 42 | 1 <= nums.length <= 5000 43 | -104 <= nums[i] <= 104 44 | nums is guaranteed to be rotated at some pivot. 45 | -104 <= target <= 104 46 | ``` -------------------------------------------------------------------------------- /0081. Search in Rotated Sorted Array II/search-in-rotated-sorted-array-ii.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {boolean} 5 | */ 6 | var search = function(nums, target) { 7 | let start = 0; 8 | let end = nums.length - 1; 9 | 10 | while (start <= end) { 11 | let mid = parseInt((start + end) / 2); 12 | if (nums[mid] == target) return true; 13 | 14 | if (nums[mid] < nums[start]) { 15 | if (nums[mid] < target && nums[end] >= target) start = mid + 1; 16 | else end = mid - 1; 17 | } else if (nums[mid] > nums[start]) { 18 | if (nums[mid] > target && nums[start] <= target) end = mid - 1; 19 | else start = mid + 1; 20 | } else { 21 | start++; 22 | } 23 | } 24 | return false; 25 | }; 26 | 27 | /* 28 | Runtime: 85 ms, faster than 70.45% of JavaScript online submissions for Search in Rotated Sorted Array II. 29 | Memory Usage: 42.5 MB, less than 57.69% of JavaScript online submissions for Search in Rotated Sorted Array II. 30 | */ -------------------------------------------------------------------------------- /0088. Merge Sorted Array/README.md: -------------------------------------------------------------------------------- 1 | ### [88. Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) 2 | 3 | ##### Level Easy 4 | 5 | You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. 6 | 7 | Merge nums1 and nums2 into a single array sorted in non-decreasing order. 8 | 9 | The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: 16 | ```JS 17 | nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 18 | ``` 19 | Output: 20 | ```JS 21 | [1,2,2,3,5,6] 22 | ``` 23 | 24 | Explanation: 25 | ```JS 26 | The arrays we are merging are [1,2,3] and [2,5,6]. 27 | The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. 28 | ``` 29 | 30 | 31 | Example 2: 32 | 33 | Input: 34 | ```JS 35 | nums1 = [1], m = 1, nums2 = [], n = 0 36 | ``` 37 | Output: 38 | ```JS 39 | [1] 40 | ``` 41 | Explanation: 42 | ```JS 43 | The arrays we are merging are [1] and []. 44 | The result of the merge is [1]. 45 | ``` 46 | 47 | 48 | 49 | Example 3: 50 | 51 | Input: 52 | ```JS 53 | nums1 = [0], m = 0, nums2 = [1], n = 1 54 | ``` 55 | Output: 56 | ```JS 57 | [1] 58 | ``` 59 | Explanation: 60 | ```JS 61 | The arrays we are merging are [] and [1]. 62 | The result of the merge is [1]. 63 | Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. 64 | ``` 65 | 66 | ##### Constraints: 67 | ```JS 68 | nums1.length == m + n 69 | nums2.length == n 70 | 0 <= m, n <= 200 71 | 1 <= m + n <= 200 72 | -109 <= nums1[i], nums2[j] <= 109 73 | ``` -------------------------------------------------------------------------------- /0088. Merge Sorted Array/merge-sorted-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums1 3 | * @param {number} m 4 | * @param {number[]} nums2 5 | * @param {number} n 6 | * @return {void} Do not return anything, modify nums1 in-place instead. 7 | */ 8 | 9 | let merge = function(nums1, m, nums2, n) { 10 | let arr = [...nums1] 11 | let i = 0; 12 | let j = 0; 13 | let k = 0; 14 | 15 | while(i "1" 8 | 'B' -> "2" 9 | ... 10 | 'Z' -> "26" 11 | To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: 12 | 13 | "AAJF" with the grouping (1 1 10 6) 14 | "KJF" with the grouping (11 10 6) 15 | Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". 16 | 17 | Given a string s containing only digits, return the number of ways to decode it. 18 | 19 | The test cases are generated so that the answer fits in a 32-bit integer. 20 | 21 | 22 | 23 | Example 1: 24 | ```JS 25 | Input: s = "12" 26 | Output: 2 27 | 28 | Explanation: 29 | "12" could be decoded as "AB" (1 2) or "L" (12). 30 | 31 | ``` 32 | 33 | Example 2: 34 | ```JS 35 | Input: s = "226" 36 | Output: 3 37 | Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 38 | ``` 39 | 40 | Example 3: 41 | ```JS 42 | Input: s = "06" 43 | Output: 0 44 | Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). 45 | ``` 46 | 47 | Constraints: 48 | ```JS 49 | 1 <= s.length <= 100 50 | s contains only digits and may contain leading zero(s). 51 | ``` 52 | 53 | ***[For proper Explanation and other approaches Please ref](https://leet-codes.blogspot.com/2022/09/decode-ways.html.html)*** -------------------------------------------------------------------------------- /0091. Decode Ways/decode-ways.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | 6 | // DP solution 7 | var numDecodings = function(s) { 8 | // Create dp array 9 | const dp = Array(s.length+1).fill(0); 10 | // If the first number is 0 then return we cannot decode this string 11 | if(s[0]==='0') return 0 12 | // Base cases 13 | dp[0] = 1; 14 | dp[1] = 1 15 | 16 | for(let i = 2; i <= s.length; i++) { 17 | // Get values for one and two digit numbers 18 | const oneDigit = +s.slice(i-1, i); 19 | const twoDigits = +s.slice(i-2, i); 20 | // Check if one digit and/or two digit numbers are valid 21 | if(oneDigit > 0) dp[i] = dp[i-1]; 22 | if(twoDigits >= 10 && twoDigits <= 26) dp[i] += dp[i-2] 23 | } 24 | return dp[s.length]; 25 | }; -------------------------------------------------------------------------------- /0113. Path Sum II/README.md: -------------------------------------------------------------------------------- 1 | ### [113. Path Sum II](https://leetcode.com/problems/path-sum-ii/) 2 | 3 | ##### Medium 4 | 5 | Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. 6 | 7 | A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. 8 | 9 | 10 | 11 | Example 1: 12 | ```JS 13 | Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 14 | Output: [[5,4,11,2],[5,8,4,5]] 15 | ``` 16 | 17 | Explanation: 18 | ```JS 19 | There are two paths whose sum equals targetSum: 20 | 5 + 4 + 11 + 2 = 22 21 | 5 + 8 + 4 + 5 = 22 22 | ``` 23 | 24 | 25 | Example 2: 26 | ```JS 27 | Input: root = [1,2,3], targetSum = 5 28 | Output: [] 29 | ``` 30 | 31 | Example 3: 32 | ```JS 33 | Input: root = [1,2], targetSum = 0 34 | Output: [] 35 | ``` 36 | 37 | Constraints: 38 | ```JS 39 | The number of nodes in the tree is in the range [0, 5000]. 40 | -1000 <= Node.val <= 1000 41 | -1000 <= targetSum <= 1000 42 | ``` -------------------------------------------------------------------------------- /0113. Path Sum II/path-sum-ii.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @param {number} sum 12 | * @return {number[][]} 13 | */ 14 | var pathSum = function(root, sum) { 15 | var result = []; 16 | 17 | if (!root) { 18 | return result; 19 | } 20 | 21 | genPath(result, root, [], 0, sum); 22 | 23 | return result; 24 | }; 25 | 26 | function genPath(result, root, curArr, curSum, target) { 27 | curArr.push(root.val); 28 | curSum += root.val; 29 | 30 | if ((curSum === target) && !root.left && !root.right) { 31 | result.push(curArr); 32 | return; 33 | } 34 | 35 | if (root.left) { 36 | genPath(result, root.left, curArr.concat(), curSum, target); 37 | } 38 | 39 | if (root.right) { 40 | genPath(result, root.right, curArr.concat(), curSum, target); 41 | } 42 | } -------------------------------------------------------------------------------- /0146. LRU Cache/README.md: -------------------------------------------------------------------------------- 1 | ### [146. LRU Cache](https://leetcode.com/problems/lru-cache/) 2 | 3 | ##### Medium 4 | 5 | Design a data structure that follows the constraints of a [Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU). 6 | 7 | Implement the LRUCache class: 8 | 9 | LRUCache(int capacity) Initialize the LRU cache with positive size capacity. 10 | int get(int key) Return the value of the key if the key exists, otherwise return -1. 11 | void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. 12 | The functions get and put must each run in O(1) average time complexity. 13 | 14 | 15 | 16 | Example 1: 17 | ```JS 18 | Input 19 | ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] 20 | [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] 21 | Output 22 | [null, null, null, 1, null, -1, null, -1, 3, 4] 23 | ``` 24 | 25 | Explanation 26 | ```JS 27 | LRUCache lRUCache = new LRUCache(2); 28 | lRUCache.put(1, 1); // cache is {1=1} 29 | lRUCache.put(2, 2); // cache is {1=1, 2=2} 30 | lRUCache.get(1); // return 1 31 | lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} 32 | lRUCache.get(2); // returns -1 (not found) 33 | lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} 34 | lRUCache.get(1); // return -1 (not found) 35 | lRUCache.get(3); // return 3 36 | lRUCache.get(4); // return 4 37 | ``` 38 | 39 | Constraints: 40 | ```JS 41 | 1 <= capacity <= 3000 42 | 0 <= key <= 104 43 | 0 <= value <= 105 44 | At most 2 * 105 calls will be made to get and put. 45 | ``` 46 | 47 | ***[For details explanation](https://sudomistry.blogspot.com/)*** -------------------------------------------------------------------------------- /0151. Reverse Words in a String/README.md: -------------------------------------------------------------------------------- 1 | ### [151. Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) 2 | 3 | ##### Medium 4 | 5 | Given an input string s, reverse the order of the words. 6 | 7 | A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. 8 | 9 | Return a string of the words in reverse order concatenated by a single space. 10 | 11 | Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. 12 | 13 | 14 | 15 | Example 1: 16 | ```JS 17 | Input: s = "the sky is blue" 18 | Output: "blue is sky the" 19 | ``` 20 | 21 | 22 | 23 | Example 2: 24 | ```JS 25 | Input: s = " hello world " 26 | Output: "world hello" 27 | ``` 28 | 29 | Explanation: 30 | ```JS 31 | Your reversed string should not contain leading or trailing spaces. 32 | ``` 33 | 34 | 35 | Example 3: 36 | ```JS 37 | Input: s = "a good example" 38 | Output: "example good a" 39 | ``` 40 | 41 | Explanation: 42 | ```JS 43 | You need to reduce multiple spaces between two words to a single space in the reversed string. 44 | ``` 45 | 46 | 47 | ##### Constraints: 48 | ```JS 49 | 1 <= s.length <= 104 50 | s contains English letters (upper-case and lower-case), digits, and spaces ' '. 51 | There is at least one word in s. 52 | ``` 53 | 54 | ***Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?*** -------------------------------------------------------------------------------- /0151. Reverse Words in a String/reverse-words-in-a-string.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | 6 | var reverseWords = function(s) { 7 | s = s.replace(/\s+/g, ' ').trim(); 8 | let words = s.split(" "); 9 | let start = 0; 10 | let end = words.length-1; 11 | while(start < end){ 12 | if(words[start] == ""){ 13 | start++; 14 | }else if(words[end] == ""){ 15 | end--; 16 | }else { 17 | console.log("start",start,end) 18 | let temp = words[start]; 19 | words[start] = words[end]; 20 | words[end] = temp; 21 | start++; 22 | end--; 23 | } 24 | } 25 | return words.join(" "); 26 | }; 27 | 28 | /* 29 | Runtime: 171 ms, faster than 5.46% of JavaScript online submissions for Reverse Words in a String. 30 | Memory Usage: 48.2 MB, less than 5.05% of JavaScript online submissions for Reverse Words in a String. 31 | */ 32 | 33 | // B) JS 34 | 35 | /** 36 | * @param {string} s 37 | * @return {string} 38 | */ 39 | 40 | var reverseWords = function(s) { 41 | let splitted =s.trim().split(" ").filter((val)=>val!=''); 42 | return splitted.reverse().join(" "); 43 | }; 44 | 45 | /* 46 | Runtime: 95 ms, faster than 52.70% of JavaScript online submissions for Reverse Words in a String. 47 | Memory Usage: 43.9 MB, less than 76.52% of JavaScript online submissions for Reverse Words in a String. 48 | */ -------------------------------------------------------------------------------- /0153. Find Minimum in Rotated Sorted Array/README.md: -------------------------------------------------------------------------------- 1 | ### [153. Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) 2 | 3 | ##### Level Medium 4 | 5 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: 6 | 7 | ```JS 8 | [4,5,6,7,0,1,2] if it was rotated 4 times. 9 | [0,1,2,4,5,6,7] if it was rotated 7 times. 10 | Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. 11 | ``` 12 | 13 | Given the sorted rotated array nums of unique elements, return the minimum element of this array. 14 | You must write an algorithm that runs in O(log n) time. 15 | 16 | 17 | 18 | Example 1: 19 | 20 | Input: 21 | ```JS 22 | nums = [3,4,5,1,2] 23 | ``` 24 | 25 | Output: 26 | ```JS 27 | 1 28 | ``` 29 | 30 | Explanation: 31 | The original array was [1,2,3,4,5] rotated 3 times. 32 | 33 | 34 | Example 2: 35 | 36 | Input: 37 | ```JS 38 | nums = [4,5,6,7,0,1,2] 39 | ``` 40 | 41 | Output: 42 | ```JS 43 | 0 44 | ``` 45 | 46 | Explanation: 47 | The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. 48 | 49 | 50 | Example 3: 51 | 52 | Input: 53 | ```JS 54 | nums = [11,13,15,17] 55 | ``` 56 | 57 | Output: 58 | ```JS 59 | 11 60 | ``` 61 | 62 | Explanation: 63 | The original array was [11,13,15,17] and it was rotated 4 times. 64 | 65 | 66 | 67 | Constraints: 68 | ```JS 69 | n == nums.length 70 | 1 <= n <= 5000 71 | -5000 <= nums[i] <= 5000 72 | All the integers of nums are unique. 73 | nums is sorted and rotated between 1 and n times. 74 | ``` 75 | -------------------------------------------------------------------------------- /0153. Find Minimum in Rotated Sorted Array/find-minimum-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var findMin = function(nums) { 6 | let start =0; 7 | let end = nums.length-1; 8 | let mid = start + parseInt((end - start)/2); 9 | let min = Number.MAX_VALUE; 10 | while(start <= end){ 11 | if(min > nums[mid]){ 12 | min = nums[mid]; 13 | } 14 | if(nums[mid] > nums[nums.length-1]){ 15 | start = mid + 1; 16 | }else{ 17 | end = mid -1; 18 | } 19 | mid = start + parseInt((end - start)/2) 20 | } 21 | return min == Number.MAX_VALUE ? -1 : min; 22 | }; 23 | 24 | /* 25 | 26 | Approach: Binary Search 27 | Runtime: 124 ms, faster than 5.88% of JavaScript online submissions for Find Minimum in Rotated Sorted Array. 28 | Memory Usage: 42.4 MB, less than 23.35% of JavaScript online submissions for Find Minimum in Rotated Sorted Array. 29 | 30 | */ -------------------------------------------------------------------------------- /0167. Two Sum II - Input Array Is Sorted/README.md: -------------------------------------------------------------------------------- 1 | ### [167. Two Sum II - Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) 2 | 3 | ##### Level Medium 4 | 5 | Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. 6 | 7 | Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. 8 | 9 | The tests are generated such that there is exactly one solution. You may not use the same element twice. 10 | 11 | Your solution must use only constant extra space. 12 | 13 | 14 | 15 | Example 1: 16 | ```JS 17 | Input: numbers = [2,7,11,15], target = 9 18 | Output: [1,2] 19 | ``` 20 | Explanation: 21 | ```JS 22 | The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. 23 | ``` 24 | 25 | 26 | 27 | Example 2: 28 | ```JS 29 | Input: numbers = [2,3,4], target = 6 30 | Output: [1,3] 31 | ``` 32 | 33 | Explanation: 34 | ```JS 35 | The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. 36 | ``` 37 | 38 | 39 | 40 | Example 3: 41 | ```JS 42 | Input: numbers = [-1,0], target = -1 43 | Output: [1,2] 44 | ``` 45 | 46 | Explanation: 47 | ```JS 48 | The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. 49 | ``` 50 | 51 | 52 | Constraints: 53 | ```JS 54 | 2 <= numbers.length <= 3 * 104 55 | -1000 <= numbers[i] <= 1000 56 | numbers is sorted in non-decreasing order. 57 | -1000 <= target <= 1000 58 | The tests are generated such that there is exactly one solution. 59 | ``` -------------------------------------------------------------------------------- /0167. Two Sum II - Input Array Is Sorted/two-sum-ii-input-array-is-sorted.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} numbers 3 | * @param {number} target 4 | * @return {number[]} 5 | */ 6 | var twoSum = function(numbers, target) { 7 | let map = new Map(); 8 | for(let i=0;i (translate) from to here ' ' to '\n' (space to new line) 8 | # < words.txt => for input 9 | # grep -E => Grep by pattern (grep char / string) 10 | # sort => Sort 11 | # uniq -c => count uniq char 12 | # sort -nr => again sort based on count 13 | # sed -E => it can perform lots of functions on file like searching, find and replace, insertion or deletion -------------------------------------------------------------------------------- /0192. Word Frequency/word-frequency.sh: -------------------------------------------------------------------------------- 1 | # Read from the file words.txt and output the word frequency list to stdout. 2 | 3 | tr ' ' '\n' < words.txt | grep -E '^[a-z]+$' | sort | uniq -c | sort -nr | sed -E 's/ +(.*) (.*)/\2 \1/' 4 | 5 | # egrep "[a-z]+" -o words.txt | sort | uniq -c | sort -r | awk '{print $2, $1}' 6 | 7 | # tr => (translate) from to here ' ' to '\n' (space to new line) 8 | # < words.txt => for input 9 | # grep -E => Grep by pattern (grep char / string) 10 | # sort => Sort 11 | # uniq -c => count uniq char 12 | # sort -nr => again sort based on count 13 | # sed -E => it can perform lots of functions on file like searching, find and replace, insertion or deletion -------------------------------------------------------------------------------- /0193. Valid Phone Numbers/README.md: -------------------------------------------------------------------------------- 1 | ### [193. Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/) 2 | 3 | ##### Easy 4 | 5 | Given a text file file.txt that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers. 6 | 7 | You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit) 8 | 9 | You may also assume each line in the text file must not contain leading or trailing white spaces. 10 | 11 | Example: 12 | ```Bash 13 | Assume that file.txt has the following content: 14 | 15 | 987-123-4567 16 | 123 456 7890 17 | (123) 456-7890 18 | Your script should output the following valid phone numbers: 19 | 20 | 987-123-4567 21 | (123) 456-7890 22 | ``` -------------------------------------------------------------------------------- /0193. Valid Phone Numbers/valid-phone-numbers.sh: -------------------------------------------------------------------------------- 1 | # Read from the file file.txt and output all valid phone numbers to stdout. 2 | 3 | grep -E '(^[0-9]{3}-|^\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$' file.txt 4 | 5 | 6 | # The construction is as follows 7 | 8 | # ^: indicates the starting of the string 9 | # |: or 10 | # $: indicates the end of the string 11 | # [0-9]\{3\} : represent 3 numbers (\{3\}) between the range 0-9 ([0-9] a digit in the range) 12 | # \: suppresses the specialness of the character 13 | # -E: to include multiple regex -------------------------------------------------------------------------------- /0194. Transpose File/README.md: -------------------------------------------------------------------------------- 1 | ### [194. Transpose File](https://leetcode.com/problems/transpose-file/) 2 | 3 | ##### Medium 4 | 5 | Given a text file file.txt, transpose its content. 6 | 7 | You may assume that each row has the same number of columns, and each field is separated by the ' ' character. 8 | 9 | Example: 10 | ```Bash 11 | If file.txt has the following content: 12 | 13 | name age 14 | alice 21 15 | ryan 30 16 | Output the following: 17 | 18 | name alice ryan 19 | age 21 30 20 | ``` -------------------------------------------------------------------------------- /0194. Transpose File/transpose-file.sh: -------------------------------------------------------------------------------- 1 | # Read from the file file.txt and print its transposed content to stdout. 2 | seq "$(awk '{print NF}' file.txt | head -n 1)" | 3 | xargs -r -I {} sh -c "awk '{print \${}}' file.txt | xargs -r" 4 | 5 | -------------------------------------------------------------------------------- /0195. Tenth Line/README.md: -------------------------------------------------------------------------------- 1 | ### [195. Tenth Line](https://leetcode.com/problems/tenth-line/) 2 | 3 | ##### Easy 4 | 5 | Given a text file file.txt, print just the 10th line of the file. 6 | 7 | Example: 8 | ```Bash 9 | Assume that file.txt has the following content: 10 | 11 | Line 1 12 | Line 2 13 | Line 3 14 | Line 4 15 | Line 5 16 | Line 6 17 | Line 7 18 | Line 8 19 | Line 9 20 | Line 10 21 | Your script should output the tenth line, which is: 22 | 23 | Line 10 24 | ``` 25 | 26 | ***Note:*** 27 | ```Bash 28 | 1. If the file contains less than 10 lines, what should you output? 29 | 2. There's at least three different solutions. Try to explore all possibilities. 30 | ``` -------------------------------------------------------------------------------- /0195. Tenth Line/tenth-line.sh: -------------------------------------------------------------------------------- 1 | # Read from the file file.txt and output the tenth line to stdout. 2 | 3 | tail -n+10 file.txt | head -n1 4 | 5 | # tail command used to print last lines 6 | # head command used to print top lines 7 | # -n is flag (nth line) -------------------------------------------------------------------------------- /0203. Remove Linked List Elements/README.md: -------------------------------------------------------------------------------- 1 | ### [203. Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) 2 | 3 | ##### Easy 4 | 5 | 6 | Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. 7 | 8 | 9 | 10 | Example 1: 11 | ```JS 12 | Input: head = [1,2,6,3,4,5,6], val = 6 13 | Output: [1,2,3,4,5] 14 | ``` 15 | 16 | Example 2: 17 | ```JS 18 | Input: head = [], val = 1 19 | Output: [] 20 | ``` 21 | 22 | Example 3: 23 | ```JS 24 | Input: head = [7,7,7,7], val = 7 25 | Output: [] 26 | ``` 27 | 28 | Constraints: 29 | ```JS 30 | The number of nodes in the list is in the range [0, 104]. 31 | 1 <= Node.val <= 50 32 | 0 <= val <= 50 33 | ``` 34 | 35 | ***[For proper Explanation and other approaches Please ref](https://leet-codes.blogspot.com/2022/09/203-remove-linked-list-elements.html)*** -------------------------------------------------------------------------------- /0203. Remove Linked List Elements/remove-linked-list-elements.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @param {number} val 11 | * @return {ListNode} 12 | */ 13 | var removeElements = function(head, val) { 14 | if (head === null) { 15 | return head; 16 | } 17 | let currentNode = head; 18 | let previousNode; 19 | while(currentNode != null){ 20 | if(currentNode.val == val){ 21 | if(currentNode == head){ 22 | currentNode = head.next; 23 | head.next = null; 24 | head = currentNode; 25 | continue; 26 | }else{ 27 | previousNode.next = currentNode.next; 28 | currentNode.next = null; 29 | currentNode = previousNode.next; 30 | continue; 31 | } 32 | } 33 | previousNode = currentNode; 34 | currentNode = currentNode.next; 35 | } 36 | 37 | return head; 38 | }; 39 | 40 | /* 41 | 42 | */ -------------------------------------------------------------------------------- /0206. Reverse Linked List/README.md: -------------------------------------------------------------------------------- 1 | ### [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) 2 | 3 | ##### Easy 4 | 5 | Given the head of a singly linked list, reverse the list, and return the reversed list. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | 12 | Input: head = [1,2,3,4,5] 13 | Output: [5,4,3,2,1] 14 | Example 2: 15 | 16 | 17 | Input: head = [1,2] 18 | Output: [2,1] 19 | Example 3: 20 | 21 | Input: head = [] 22 | Output: [] 23 | 24 | 25 | Constraints: 26 | 27 | The number of nodes in the list is the range [0, 5000]. 28 | -5000 <= Node.val <= 5000 29 | 30 | 31 | ***Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?*** 32 | ***[For proper Explanation and other approaches Please ref](https://leet-codes.blogspot.com/2022/09/206-reverse-linked-list.html)*** -------------------------------------------------------------------------------- /0206. Reverse Linked List/reverse-linked-list.js: -------------------------------------------------------------------------------- 1 | // Approach 1: Iterative 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * function ListNode(val, next) { 6 | * this.val = (val===undefined ? 0 : val) 7 | * this.next = (next===undefined ? null : next) 8 | * } 9 | */ 10 | /** 11 | * @param {ListNode} head 12 | * @return {ListNode} 13 | */ 14 | var reverseList = function(head) { 15 | if(head==null || head.next==null){ 16 | return head; 17 | } 18 | let p = head ,q = head.next; 19 | head.next = null; 20 | while(q!=null){ 21 | let temp = q; 22 | q = q.next; 23 | temp.next = p; 24 | p = temp; 25 | } 26 | return p; 27 | }; 28 | 29 | // Another way to write code 30 | 31 | /** 32 | * Definition for singly-linked list. 33 | * function ListNode(val, next) { 34 | * this.val = (val===undefined ? 0 : val) 35 | * this.next = (next===undefined ? null : next) 36 | * } 37 | */ 38 | /** 39 | * @param {ListNode} head 40 | * @return {ListNode} 41 | */ 42 | var reverseList = function(head) { 43 | if(head==null || head.next==null){ 44 | return head; 45 | } 46 | let prev = null; 47 | while (head) { 48 | let next = head.next; 49 | head.next = prev; 50 | prev = head; 51 | head = next; 52 | } 53 | 54 | return prev; 55 | }; 56 | 57 | // Approach 1: Recursion 58 | 59 | /** 60 | * Definition for singly-linked list. 61 | * function ListNode(val, next) { 62 | * this.val = (val===undefined ? 0 : val) 63 | * this.next = (next===undefined ? null : next) 64 | * } 65 | */ 66 | /** 67 | * @param {ListNode} head 68 | * @return {ListNode} 69 | */ 70 | var reverseList = function(head) { 71 | if (!head || !head.next) 72 | return head; 73 | 74 | let newHead = reverseList(head.next); 75 | head.next.next = head; 76 | head.next = null; 77 | return newHead; 78 | }; 79 | 80 | -------------------------------------------------------------------------------- /0214. Shortest Palindrome/README.md: -------------------------------------------------------------------------------- 1 | ### [214. Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) 2 | 3 | ##### Level Hard 4 | 5 | You are given a string s. You can convert s to a palindrome by adding characters in front of it. 6 | Return the shortest palindrome you can find by performing this transformation. 7 | 8 | 9 | 10 | Example 1: 11 | ```JS 12 | Input: s = "aacecaaa" 13 | Output: "aaacecaaa" 14 | ``` 15 | 16 | Example 2: 17 | ```JS 18 | Input: s = "abcd" 19 | Output: "dcbabcd" 20 | ``` 21 | 22 | ##### Constraints: 23 | ```JS 24 | 0 <= s.length <= 5 * 104 25 | s consists of lowercase English letters only. 26 | ``` -------------------------------------------------------------------------------- /0214. Shortest Palindrome/shortest-palindrome.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | var shortestPalindrome = function(s) { 6 | const originalString = s; 7 | const originalReversed = s.split('').reverse().join('') 8 | let reversed = originalReversed; 9 | while(reversed !== s) { 10 | s = s.slice(0,-1); 11 | reversed = reversed.slice(1); 12 | } 13 | return originalReversed.slice(0,-s.length) + originalString; 14 | }; 15 | 16 | /* 17 | Runtime: 124 ms, faster than 32.20% of JavaScript online submissions for Shortest Palindrome. 18 | Memory Usage: 45 MB, less than 63.56% of JavaScript online submissions for Shortest Palindrome. 19 | */ 20 | 21 | /* 22 | The idea is when we put a reversed string next to the string it was reversed from, then we'd get a palindrome 23 | 24 | word = 'abcd' 25 | reversed = 'dcba' 26 | reversed + word = 'dcbaabcd' 27 | It's now a palindrome but it's not the shortest palindrome. 28 | The shortest palindrome for abcd is dcbabcd 29 | If you notice we just need to add dcb in front of the stringabcd to accomplish it. 30 | 31 | Also notice that dcb is a prefix of the reversed string dcba. 32 | The solution is really just a matter of prepending the prefix of the reversed string so now we just have to find out which prefix we'll be grabbing from the reversed string. 33 | 34 | Luckily, it's very easy to find the prefix 35 | 36 | word = 'abcd' 37 | reversed = 'dcba' 38 | // now all we have to do is keep removing one character from the end of word 39 | // and remove one character from the beginning of the reversed word 40 | // We keep doing this until both words become equal 41 | 'abcd' 'dcba' 42 | 'abc' 'cba' 43 | 'ab' 'ba' 44 | 'a' 'a' 45 | // Now they're equal 46 | // The length remaining is 1 47 | // Which means removing 1 character from the end of dcba will give us our prefix 48 | // 'dcba' -> 'dcb' 49 | // dcb + abcd = dcbabcd //shortest palindrome 50 | */ -------------------------------------------------------------------------------- /0215. Kth Largest Element in an Array/README.md: -------------------------------------------------------------------------------- 1 | ### [215. Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) 2 | 3 | ##### Level Medium 4 | 5 | Given an integer array nums and an integer k, return the kth largest element in the array. 6 | 7 | Note that it is the kth largest element in the sorted order, not the kth distinct element. 8 | 9 | ***You must solve it in O(n) time complexity.*** 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: 16 | ```JS 17 | nums = [3,2,1,5,6,4], k = 2 18 | ``` 19 | Output: 20 | ```JS 21 | 5 22 | ``` 23 | 24 | 25 | Example 2: 26 | 27 | Input: 28 | ```JS 29 | nums = [3,2,3,1,2,4,5,5,6], k = 4 30 | ``` 31 | Output: 32 | ```JS 33 | 4 34 | ``` 35 | 36 | ##### Constraints: 37 | ```JS 38 | 1 <= k <= nums.length <= 105 39 | -104 <= nums[i] <= 104 40 | ``` -------------------------------------------------------------------------------- /0215. Kth Largest Element in an Array/kth-largest-element-in-an-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} k 4 | * @return {number} 5 | */ 6 | var findKthLargest = function(nums, k) { 7 | // find the largest element 8 | let largest = -Infinity; 9 | 10 | for(let i=0;i largest) largest = nums[i]; 12 | } 13 | 14 | // construct a hash map of difference between nums[i] and largest 15 | const hash = {}; 16 | 17 | for(let i=0;ib" if a != b 14 | "a" if a == b 15 | ``` 16 | 17 | Example 1: 18 | ```JS 19 | Input: nums = [0,1,2,4,5,7] 20 | Output: ["0->2","4->5","7"] 21 | Explanation: The ranges are: 22 | [0,2] --> "0->2" 23 | [4,5] --> "4->5" 24 | [7,7] --> "7" 25 | ``` 26 | 27 | 28 | Example 2: 29 | ```JS 30 | Input: nums = [0,2,3,4,6,8,9] 31 | Output: ["0","2->4","6","8->9"] 32 | Explanation: The ranges are: 33 | [0,0] --> "0" 34 | [2,4] --> "2->4" 35 | [6,6] --> "6" 36 | [8,9] --> "8->9" 37 | ``` 38 | 39 | ##### Constraints: 40 | ```JS 41 | 0 <= nums.length <= 20 42 | -231 <= nums[i] <= 231 - 1 43 | All the values of nums are unique. 44 | nums is sorted in ascending order. 45 | ``` -------------------------------------------------------------------------------- /0228. Summary Ranges/summary-ranges.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {string[]} 4 | */ 5 | var summaryRanges = function(nums) { 6 | for(let i=1;i0) { 13 | nums[i-1] = `${nums[i-1] - times}->${nums[i-1]}` 14 | } 15 | } 16 | return nums.map(e=>String(e)) 17 | }; 18 | 19 | /* 20 | 21 | */ -------------------------------------------------------------------------------- /0234. Palindrome Linked List/README.md: -------------------------------------------------------------------------------- 1 | ### [234. Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) 2 | 3 | ##### Easy 4 | 5 | Given the head of a singly linked list, return true if it is a palindrome or false otherwise. 6 | 7 | 8 | Example 1: 9 | ```JS 10 | Input: head = [1,2,2,1] 11 | Output: true 12 | ``` 13 | 14 | Example 2: 15 | ```JS 16 | Input: head = [1,2] 17 | Output: false 18 | ``` 19 | 20 | Constraints: 21 | ```JS 22 | The number of nodes in the list is in the range [1, 105]. 23 | 0 <= Node.val <= 9 24 | ``` 25 | 26 | ***Follow up: Could you do it in O(n) time and O(1) space?*** 27 | 28 | ***[For details explanation](https://sudomistry.blogspot.com/)*** -------------------------------------------------------------------------------- /0234. Palindrome Linked List/palindrome-linked-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @return {boolean} 11 | */ 12 | var isPalindrome = function (head) { 13 | // Pass empty or single-item linked lists 14 | if (!head || !head.next) return true; 15 | 16 | // Traverse the linked list in order to find the mid-point (slow) 17 | let slow = head, 18 | fast = head; 19 | while (fast.next && fast.next.next) { 20 | slow = slow.next; 21 | fast = fast.next.next; 22 | } 23 | 24 | // Reverse the second half of the linked list 25 | slow.next = reverseLinkedList(slow.next); 26 | slow = slow.next; 27 | 28 | // Compare the original linked list with the reversed second half 29 | while (slow) { 30 | if (head.val !== slow.val) { 31 | // If a mismatch is detected, break out 32 | return false; 33 | } 34 | head = head.next; 35 | slow = slow.next; 36 | } 37 | 38 | return true; 39 | }; 40 | 41 | var reverseLinkedList = function (head) { 42 | let nextNode = null; 43 | let previousNode = null; 44 | while (head) { 45 | nextNode = head.next; 46 | head.next = previousNode; 47 | previousNode = head; 48 | head = nextNode; 49 | } 50 | return previousNode; 51 | }; 52 | 53 | 54 | /* 55 | Runtime: 243 ms 56 | Memory Usage: 77.6 MB 57 | */ -------------------------------------------------------------------------------- /0240. Search a 2D Matrix II/README.md: -------------------------------------------------------------------------------- 1 | ### [240. Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) 2 | 3 | ##### Medium 4 | 5 | Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: 6 | 7 | Integers in each row are sorted in ascending from left to right. 8 | Integers in each column are sorted in ascending from top to bottom. 9 | 10 | 11 | Example 1: 12 | ```JS 13 | Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 14 | Output: true 15 | ``` 16 | 17 | 18 | Example 2: 19 | ```JS 20 | Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 21 | Output: false 22 | ``` 23 | 24 | 25 | ### Constraints: 26 | ```JS 27 | m == matrix.length 28 | n == matrix[i].length 29 | 1 <= n, m <= 300 30 | -109 <= matrix[i][j] <= 109 31 | All the integers in each row are sorted in ascending order. 32 | All the integers in each column are sorted in ascending order. 33 | -109 <= target <= 109 34 | ``` -------------------------------------------------------------------------------- /0240. Search a 2D Matrix II/search-a-2d-matrix-ii.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @param {number} target 4 | * @return {boolean} 5 | */ 6 | var searchMatrix = function(matrix, target) { 7 | let m = matrix[0].length; // column length 8 | let n = matrix.length; // row length 9 | 10 | let i = 0; // first row 11 | let j = m-1; // last column 12 | 13 | // till i < n (row o to n) AND j >= 0 (col m to 0) 14 | while(i=0){ 15 | if(matrix[i][j] == target){ 16 | return true; 17 | } 18 | if(matrix[i][j] > target){ 19 | // we'll be moving towards left if the value of target is smaller 20 | j--; 21 | }else{ 22 | // otherwise we'll be moving downwards if the target is greater than 23 | i++; 24 | } 25 | } 26 | return false; 27 | }; 28 | 29 | /* 30 | 31 | */ -------------------------------------------------------------------------------- /0258. Add Digits/README.md: -------------------------------------------------------------------------------- 1 | ### [258. Add Digits](https://leetcode.com/problems/add-digits/) 2 | 3 | ##### Easy 4 | 5 | Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. 6 | 7 | Example 1: 8 | 9 | ```JS 10 | Input: num = 38 11 | Output: 2 12 | ``` 13 | 14 | Explanation: 15 | ```JS 16 | The process is 17 | 38 --> 3 + 8 --> 11 18 | 11 --> 1 + 1 --> 2 19 | Since 2 has only one digit, return it. 20 | ``` 21 | 22 | Example 2: 23 | ```JS 24 | Input: num = 0 25 | Output: 0 26 | ``` 27 | 28 | Constraints: 29 | ```JS 30 | 0 <= num <= 231 - 1 31 | ``` -------------------------------------------------------------------------------- /0258. Add Digits/add-digits.js: -------------------------------------------------------------------------------- 1 | /* 2 | A) Brute force 3 | */ 4 | 5 | /** 6 | * @param {number} num 7 | * @return {number} 8 | */ 9 | var addDigits = function(num) { 10 | while(num > 9){ 11 | let str = num+""; 12 | let sum = 0; 13 | for(let i=0;i false 22 | call isBadVersion(5) -> true 23 | call isBadVersion(4) -> true 24 | Then 4 is the first bad version. 25 | ``` 26 | 27 | Example 2: 28 | ```JS 29 | Input: n = 1, bad = 1 30 | Output: 1 31 | ``` 32 | 33 | ##### Constraints: 34 | ```JS 35 | 1 <= bad <= n <= 231 - 1 36 | ``` -------------------------------------------------------------------------------- /0278. First Bad Version/first-bad-version.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for isBadVersion() 3 | * 4 | * @param {integer} version number 5 | * @return {boolean} whether the version is bad 6 | * isBadVersion = function(version) { 7 | * ... 8 | * }; 9 | */ 10 | 11 | /** 12 | * @param {function} isBadVersion() 13 | * @return {function} 14 | */ 15 | var solution = function(isBadVersion) { 16 | /** 17 | * @param {integer} n Total versions 18 | * @return {integer} The first bad version 19 | */ 20 | return function(n) { 21 | let start =1; 22 | let end = n; 23 | let mid = start + parseInt((end - start)/2); 24 | let ans = -1; 25 | while(start <= end){ 26 | if(isBadVersion(mid)){ 27 | ans = mid; 28 | end = mid - 1; 29 | }else{ 30 | start = mid + 1; 31 | } 32 | mid = start + parseInt((end - start)/2); 33 | } 34 | return ans; 35 | }; 36 | }; 37 | 38 | /* 39 | Runtime: 82 ms, faster than 60.48% of JavaScript online submissions for First Bad Version. 40 | Memory Usage: 42.4 MB, less than 5.11% of JavaScript online submissions for First Bad Version. 41 | */ -------------------------------------------------------------------------------- /0283. Move Zeroes/README.md: -------------------------------------------------------------------------------- 1 | ### [283. Move Zeroes](https://leetcode.com/problems/move-zeroes/) 2 | 3 | ##### Level Easy 4 | 5 | Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 6 | Note that you must do this in-place without making a copy of the array. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: 13 | ```JS 14 | nums = [0,1,0,3,12] 15 | ``` 16 | Output: 17 | ```JS 18 | [1,3,12,0,0] 19 | ``` 20 | 21 | 22 | Example 2: 23 | 24 | Input: 25 | ```JS 26 | nums = [0] 27 | ``` 28 | Output: 29 | ```JS 30 | [0] 31 | ``` 32 | 33 | Constraints: 34 | ```JS 35 | 1 <= nums.length <= 104 36 | -231 <= nums[i] <= 231 - 1 37 | ``` 38 | 39 | ***Follow up: Could you minimize the total number of operations done?*** 40 | -------------------------------------------------------------------------------- /0283. Move Zeroes/move-zeroes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution { 5 | public: 6 | void moveZeroes(vector& nums) { 7 | int counter = 0; 8 | vector temp (nums.size(), 0); 9 | for(int i=0;i maxValue){ 13 | thirdMaxValue = secondMaxValue; 14 | secondMaxValue = maxValue; 15 | maxValue = num; 16 | } 17 | else if(secondMaxValue == null || num > secondMaxValue){ 18 | thirdMaxValue = secondMaxValue; 19 | secondMaxValue = num; 20 | } 21 | else if(thirdMaxValue == null || num > thirdMaxValue) 22 | thirdMaxValue = num; 23 | } 24 | if(thirdMaxValue == null){ 25 | thirdMaxValue = maxValue 26 | } 27 | return thirdMaxValue; 28 | }; 29 | 30 | /* 31 | Runtime: 101 ms, faster than 47.91% of JavaScript online submissions for Third Maximum Number. 32 | Memory Usage: 42.7 MB, less than 78.07% of JavaScript online submissions for Third Maximum Number. 33 | */ -------------------------------------------------------------------------------- /0448. Find All Numbers Disappeared in an Array/README.md: -------------------------------------------------------------------------------- 1 | ### [448. Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) 2 | 3 | ##### Easy 4 | 5 | Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. 6 | 7 | 8 | 9 | Example 1: 10 | ```JS 11 | Input: nums = [4,3,2,7,8,2,3,1] 12 | Output: [5,6] 13 | ``` 14 | 15 | Example 2: 16 | ```JS 17 | Input: nums = [1,1] 18 | Output: [2] 19 | ``` 20 | 21 | Constraints: 22 | ```JS 23 | n == nums.length 24 | 1 <= n <= 105 25 | 1 <= nums[i] <= n 26 | ``` 27 | 28 | ***Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.*** -------------------------------------------------------------------------------- /0448. Find All Numbers Disappeared in an Array/find-all-numbers-disappeared-in-an-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | var findDisappearedNumbers = function(nums) { 6 | let result = Array.from({length: nums.length}, (item, index) => index+1); 7 | for(let i=0;i -1){ 10 | result.splice(index, 1); 11 | } 12 | } 13 | return result; 14 | }; -------------------------------------------------------------------------------- /0456. 132 Pattern/132-pattern.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {boolean} 4 | */ 5 | var find132pattern = function(nums) { 6 | let len = nums.length; 7 | if (len < 3) { 8 | return false; 9 | } 10 | 11 | let stk = new Stack(); 12 | let k = -1; 13 | for (let i = len - 1; i >= 0; i--) { 14 | if (k > -1 && nums[k] > nums[i]) { 15 | return true; 16 | } 17 | 18 | while (!stk.isEmpty() && nums[i] > nums[stk.peek()]) { 19 | k = stk.pop(); 20 | } 21 | 22 | stk.push(i); 23 | } 24 | 25 | return false; 26 | 27 | }; 28 | 29 | class Stack { 30 | constructor() { 31 | this.stack = [] 32 | } 33 | push(a) { 34 | this.stack.push(a) 35 | } 36 | pop() { 37 | return this.stack.pop() 38 | } 39 | peek() { 40 | return this.stack[this.stack.length - 1] 41 | } 42 | size() { 43 | return this.stack.length 44 | } 45 | isEmpty() { 46 | return this.stack.length == 0 47 | } 48 | } 49 | 50 | /* 51 | Runtime: 112 ms, faster than 61.47% of JavaScript online submissions for 132 Pattern. 52 | Memory Usage: 53.4 MB, less than 58.72% of JavaScript online submissions for 132 Pattern. 53 | */ -------------------------------------------------------------------------------- /0456. 132 Pattern/README.md: -------------------------------------------------------------------------------- 1 | ### [456. 132 Pattern](https://leetcode.com/problems/132-pattern/) 2 | 3 | ##### Medium 4 | 5 | 6 | Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. 7 | 8 | Return true if there is a 132 pattern in nums, otherwise, return false. 9 | 10 | 11 | 12 | Example 1: 13 | ```JS 14 | Input: nums = [1,2,3,4] 15 | Output: false 16 | ``` 17 | 18 | Explanation: 19 | ```JS 20 | There is no 132 pattern in the sequence. 21 | ``` 22 | 23 | 24 | Example 2: 25 | ```JS 26 | Input: nums = [3,1,4,2] 27 | Output: true 28 | ``` 29 | 30 | Explanation: 31 | ```JS 32 | There is a 132 pattern in the sequence: [1, 4, 2]. 33 | ``` 34 | 35 | 36 | 37 | Example 3: 38 | ```JS 39 | Input: nums = [-1,3,2,0] 40 | Output: true 41 | ``` 42 | 43 | Explanation: 44 | ```JS 45 | There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. 46 | ``` 47 | 48 | ##### Constraints: 49 | 50 | n == nums.length 51 | 1 <= n <= 2 * 105 52 | -109 <= nums[i] <= 109 -------------------------------------------------------------------------------- /0485. Max Consecutive Ones/README.md: -------------------------------------------------------------------------------- 1 | ### [485. Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) 2 | 3 | ##### Level Easy 4 | 5 | Given a binary array nums, return the maximum number of consecutive 1's in the array. 6 | 7 | 8 | 9 | Example 1: 10 | ```JS 11 | Input: nums = [1,1,0,1,1,1] 12 | Output: 3 13 | ``` 14 | 15 | Explanation: 16 | ```JS 17 | The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. 18 | ``` 19 | 20 | 21 | 22 | Example 2: 23 | ```JS 24 | Input: nums = [1,0,1,1,0,1] 25 | Output: 2 26 | ``` 27 | 28 | ##### Constraints: 29 | ```JS 30 | 1 <= nums.length <= 105 31 | nums[i] is either 0 or 1. 32 | ``` -------------------------------------------------------------------------------- /0485. Max Consecutive Ones/max-consecutive-ones.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var findMaxConsecutiveOnes = function(nums) { 6 | let ans = 0; 7 | let sum = 0; 8 | 9 | for (let i=0;i { 13 | return reverse(w); 14 | }).join(" "); 15 | }; 16 | 17 | /* 18 | Runtime: 139 ms, faster than 23.52% of JavaScript online submissions for Reverse Words in a String III. 19 | Memory Usage: 48.3 MB, less than 73.45% of JavaScript online submissions for Reverse Words in a String III. 20 | */ -------------------------------------------------------------------------------- /0566. Reshape the Matrix/README.md: -------------------------------------------------------------------------------- 1 | ### [566. Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/) 2 | 3 | ##### Easy 4 | 5 | In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. 6 | 7 | You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. 8 | 9 | The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. 10 | 11 | If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. 12 | 13 | 14 | 15 | Example 1: 16 | ```JS 17 | Input: mat = [[1,2],[3,4]], r = 1, c = 4 18 | Output: [[1,2,3,4]] 19 | ``` 20 | 21 | Example 2: 22 | ```JS 23 | Input: mat = [[1,2],[3,4]], r = 2, c = 4 24 | Output: [[1,2],[3,4]] 25 | ``` 26 | 27 | ##### Constraints: 28 | ```JS 29 | m == mat.length 30 | n == mat[i].length 31 | 1 <= m, n <= 100 32 | -1000 <= mat[i][j] <= 1000 33 | 1 <= r, c <= 300 34 | ``` -------------------------------------------------------------------------------- /0566. Reshape the Matrix/reshape-the-matrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} mat 3 | * @param {number} r 4 | * @param {number} c 5 | * @return {number[][]} 6 | */ 7 | var matrixReshape = function(mat, r, c) { 8 | let len = r * c -1; 9 | if(len != mat.length * mat[0].length -1){ 10 | return mat; 11 | } 12 | let res = []; 13 | // creating two dimensional array 14 | for (var i = 0; i < r; i++) { 15 | res[i] = new Array(c); 16 | } 17 | let rowIndex = 0; 18 | let colIndex = 0; 19 | let count = 0; 20 | for(let i=0;i> 1); 18 | if (x - arr[mid] > arr[mid + k] - x) { 19 | left = mid + 1; 20 | } else { 21 | right = mid; 22 | } 23 | } 24 | return arr.slice(left, left + k); 25 | }; -------------------------------------------------------------------------------- /0680. Valid Palindrome II/README.md: -------------------------------------------------------------------------------- 1 | ### [680. Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) 2 | 3 | ##### Level Easy 4 | 5 | Given a string s, return true if the s can be palindrome after deleting at most one character from it. 6 | 7 | 8 | Example 1: 9 | ```JS 10 | Input: s = "aba" 11 | Output: true 12 | ``` 13 | 14 | 15 | Example 2: 16 | ```JS 17 | Input: s = "abca" 18 | Output: true 19 | ``` 20 | 21 | Explanation: 22 | ```JS 23 | You could delete the character 'c'. 24 | ``` 25 | 26 | 27 | Example 3: 28 | ```JS 29 | Input: s = "abc" 30 | Output: false 31 | ``` 32 | 33 | ##### Constraints: 34 | ```JS 35 | 1 <= s.length <= 105 36 | s consists of lowercase English letters. 37 | ``` -------------------------------------------------------------------------------- /0680. Valid Palindrome II/valid-palindrome-ii.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {boolean} 4 | */ 5 | const isPalindrome = function(s,i,j){ 6 | while(i "--...-." 41 | "zen" -> "--...-." 42 | "gig" -> "--...--." 43 | "msg" -> "--...--." 44 | There are 2 different transformations: "--...-." and "--...--.". 45 | ``` 46 | 47 | 48 | Example 2: 49 | 50 | Input: 51 | ```JS 52 | words = ["a"] 53 | ``` 54 | 55 | Output: 56 | ```JS 57 | 1 58 | ``` 59 | 60 | ##### Constraints: 61 | ```JS 62 | 1 <= words.length <= 100 63 | 1 <= words[i].length <= 12 64 | words[i] consists of lowercase English letters. 65 | ``` -------------------------------------------------------------------------------- /0804. Unique Morse Code Words/unique-morse-code-words.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} words 3 | * @return {number} 4 | */ 5 | var uniqueMorseRepresentations = function(words) { 6 | let morse = [ 7 | ".-", 8 | "-...", 9 | "-.-.", 10 | "-..", 11 | ".", 12 | "..-.", 13 | "--.", 14 | "....", 15 | "..", 16 | ".---", 17 | "-.-", 18 | ".-..", 19 | "--", 20 | "-.", 21 | "---", 22 | ".--.", 23 | "--.-", 24 | ".-.", 25 | "...", 26 | "-", 27 | "..-", 28 | "...-", 29 | ".--", 30 | "-..-", 31 | "-.--", 32 | "--..", 33 | ]; 34 | let alpha = "abcdefghijklmnopqrstuvwxyz"; 35 | let aTom = []; 36 | words.forEach((v,i) => { 37 | let temp = ''; 38 | for(let j = 0; j < words[i].length; j++){ 39 | let turned = words[i].charCodeAt(j) - 97; 40 | temp += morse[turned] 41 | } 42 | 43 | if (aTom.indexOf(temp) === -1) aTom.push(temp) 44 | }) 45 | 46 | return aTom.length 47 | }; 48 | 49 | /* 50 | Runtime: 127 ms, faster than 11.86% of JavaScript online submissions for Unique Morse Code Words. 51 | Memory Usage: 42.7 MB, less than 82.30% of JavaScript online submissions for Unique Morse Code Words. 52 | */ -------------------------------------------------------------------------------- /0838. Push Dominoes/README.md: -------------------------------------------------------------------------------- 1 | ### [838. Push Dominoes](https://leetcode.com/problems/push-dominoes/) 2 | 3 | ##### Medium 4 | 5 | 6 | There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. 7 | 8 | After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. 9 | 10 | When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. 11 | 12 | For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. 13 | 14 | You are given a string dominoes representing the initial state where: 15 | ```JS 16 | dominoes[i] = 'L', if the ith domino has been pushed to the left, 17 | dominoes[i] = 'R', if the ith domino has been pushed to the right, and 18 | dominoes[i] = '.', if the ith domino has not been pushed. 19 | Return a string representing the final state. 20 | ``` 21 | 22 | 23 | Example 1: 24 | ```JS 25 | Input: dominoes = "RR.L" 26 | Output: "RR.L" 27 | ``` 28 | 29 | Explanation: 30 | ```JS 31 | The first domino expends no additional force on the second domino. 32 | ``` 33 | 34 | Example 2: 35 | ```JS 36 | Input: dominoes = ".L.R...LR..L.." 37 | Output: "LL.RR.LLRRLL.." 38 | ``` 39 | 40 | Constraints: 41 | ```JS 42 | n == dominoes.length 43 | 1 <= n <= 105 44 | dominoes[i] is either 'L', 'R', or '.'. 45 | ``` 46 | 47 | 48 | ***[For more detail](https://leet-codes.blogspot.com/2022/09/838-push-dominoes.html)*** -------------------------------------------------------------------------------- /0838. Push Dominoes/push-dominoes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} dominoes 3 | * @return {string} 4 | */ 5 | var pushDominoes = function (dominoes) { 6 | const arr = new Array(dominoes.length) 7 | let c = 0 8 | for (let i = 0; i < dominoes.length; i++) { 9 | if (c > 0 && dominoes[i] === '.') { 10 | c-- 11 | } else if (dominoes[i] === 'R') { 12 | c = dominoes.length 13 | } else { 14 | c = 0 15 | } 16 | arr[i] = c 17 | } 18 | c = 0 19 | for (let j = dominoes.length - 1; j >= 0; j--) { 20 | if (c > 0 && dominoes[j] === '.') { 21 | c-- 22 | } else if (dominoes[j] === 'L') { 23 | c = dominoes.length 24 | } else { 25 | c = 0 26 | } 27 | arr[j] -= c 28 | } 29 | return arr.map(n => n > 0 ? 'R' : n < 0 ? 'L' : '.').join('') 30 | } -------------------------------------------------------------------------------- /0852. Peak Index in a Mountain Array/README.md: -------------------------------------------------------------------------------- 1 | ### [852. Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) 2 | 3 | ##### Level Medium 4 | 5 | An array arr a mountain if the following properties hold: 6 | 7 | ```JS 8 | arr.length >= 3 9 | There exists some i with 0 < i < arr.length - 1 such that: 10 | arr[0] < arr[1] < ... < arr[i - 1] < arr[i] 11 | arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 12 | Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. 13 | ``` 14 | 15 | ***You must solve it in O(log(arr.length)) time complexity.*** 16 | 17 | 18 | Example 1: 19 | ```JS 20 | Input: arr = [0,1,0] 21 | Output: 1 22 | ``` 23 | 24 | Example 2: 25 | ```JS 26 | Input: arr = [0,2,1,0] 27 | Output: 1 28 | ``` 29 | 30 | Example 3: 31 | ```JS 32 | Input: arr = [0,10,5,2] 33 | Output: 1 34 | ``` 35 | 36 | ### Constraints: 37 | ```JS 38 | 3 <= arr.length <= 105 39 | 0 <= arr[i] <= 106 40 | arr is guaranteed to be a mountain array. 41 | ``` -------------------------------------------------------------------------------- /0852. Peak Index in a Mountain Array/peak-index-in-a-mountain-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @return {number} 4 | */ 5 | var peakIndexInMountainArray = function(arr) { 6 | let start = 0; 7 | let end = arr.length-1; 8 | let mid = start + parseInt((end - start)/2); 9 | let ans = -1; 10 | while(start < end){ 11 | if(arr[mid] > arr[mid + 1] && arr[mid] > arr[mid - 1]) { 12 | ans = mid; 13 | break; 14 | } 15 | 16 | if(arr[mid] < arr[mid + 1]) 17 | start = mid + 1; 18 | else 19 | end = mid; 20 | 21 | mid = start + parseInt((end - start)/2); 22 | } 23 | return ans; 24 | }; 25 | 26 | /* 27 | Runtime: 86 ms, faster than 74.88% of JavaScript online submissions for Peak Index in a Mountain Array. 28 | Memory Usage: 51.4 MB, less than 30.88% of JavaScript online submissions for Peak Index in a Mountain Array. 29 | */ -------------------------------------------------------------------------------- /0867. Transpose Matrix/README.md: -------------------------------------------------------------------------------- 1 | ### [867. Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) 2 | 3 | ##### Easy 4 | 5 | Given a 2D integer array matrix, return the transpose of matrix. 6 | 7 | The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. 8 | 9 | 10 | Example 1: 11 | ```JS 12 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 13 | Output: [[1,4,7],[2,5,8],[3,6,9]] 14 | ``` 15 | 16 | 17 | Example 2: 18 | ```JS 19 | Input: matrix = [[1,2,3],[4,5,6]] 20 | Output: [[1,4],[2,5],[3,6]] 21 | ``` 22 | 23 | 24 | ##### Constraints: 25 | ```JS 26 | m == matrix.length 27 | n == matrix[i].length 28 | 1 <= m, n <= 1000 29 | 1 <= m * n <= 105 30 | -109 <= matrix[i][j] <= 109 31 | ``` -------------------------------------------------------------------------------- /0867. Transpose Matrix/transpose-matrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {number[][]} 4 | */ 5 | var transpose = function(matrix) { 6 | let row = matrix.length; 7 | let col = matrix[0].length; 8 | let res = []; 9 | 10 | // creating two dimensional array 11 | for (var i = 0; i < col; i++) { 12 | res[i] = new Array(row); 13 | } 14 | 15 | for(let i=0;i= 3 10 | There exists some i with 0 < i < arr.length - 1 such that: 11 | arr[0] < arr[1] < ... < arr[i - 1] < arr[i] 12 | arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 13 | ``` 14 | 15 | 16 | Example 1: 17 | ```JS 18 | Input: arr = [2,1] 19 | Output: false 20 | ``` 21 | 22 | 23 | Example 2: 24 | ```JS 25 | Input: arr = [3,5,5] 26 | Output: false 27 | ``` 28 | 29 | 30 | Example 3: 31 | ```JS 32 | Input: arr = [0,3,2,1] 33 | Output: true 34 | ``` 35 | 36 | 37 | ##### Constraints: 38 | ```JS 39 | 1 <= arr.length <= 104 40 | 0 <= arr[i] <= 104 41 | ``` -------------------------------------------------------------------------------- /0941. Valid Mountain Array/valid-mountain-array.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public: 5 | bool validMountainArray(vector& arr) { 6 | int len = arr.size(); 7 | int i = 0; 8 | 9 | // walk up 10 | while (i+1 < len && arr[i] < arr[i+1]) 11 | i++; 12 | 13 | // peak can't be first or last 14 | if (i == 0 || i == len-1) 15 | return false; 16 | 17 | // walk down 18 | while (i+1 < len && arr[i] > arr[i+1]) 19 | i++; 20 | 21 | return i == len-1; 22 | } 23 | }; 24 | /* 25 | 26 | */ -------------------------------------------------------------------------------- /0941. Valid Mountain Array/valid-mountain-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @return {boolean} 4 | */ 5 | var validMountainArray = function(arr) { 6 | if(arr.length <= 2 ) return false; 7 | 8 | 9 | let isIncreasing = true; 10 | let isDecreasing = false; 11 | 12 | for(let i = 0; i < arr.length - 1; i++) { 13 | if(isIncreasing) { 14 | if(arr[i] < arr[i+1]) { 15 | continue; 16 | } 17 | else if(arr[i] == arr[i+1]) { 18 | return false; 19 | } 20 | else { 21 | // If Array is in decreasing order from start 22 | if(i == 0) { 23 | return false; 24 | } 25 | isDecreasing = true; 26 | isIncreasing = false; 27 | continue; 28 | } 29 | } 30 | 31 | if(isDecreasing) { 32 | if(arr[i] > arr[i+1]) { 33 | continue; 34 | } 35 | else { 36 | return false; 37 | } 38 | } 39 | } 40 | 41 | return (isDecreasing) ? true: false; 42 | 43 | }; 44 | 45 | /* 46 | 47 | */ 48 | 49 | // B) Two Pointer 50 | 51 | /** 52 | * @param {number[]} arr 53 | * @return {boolean} 54 | */ 55 | var validMountainArray = function(arr) { 56 | if(arr.length <= 2 ) return false; 57 | 58 | let n = arr.length; 59 | let left = 0, right = n -1; 60 | while(left + 1 < n - 1 && arr[left + 1] > arr[left]){ 61 | left += 1 62 | } 63 | 64 | while(right - 1> 0 && arr[right - 1] > arr[right]){ 65 | right -= 1 66 | } 67 | return left == right ? true : false; 68 | }; 69 | 70 | 71 | /* 72 | 73 | */ 74 | -------------------------------------------------------------------------------- /0967. Numbers With Same Consecutive Differences/README.md: -------------------------------------------------------------------------------- 1 | ### [967. Numbers With Same Consecutive Differences](https://leetcode.com/problems/numbers-with-same-consecutive-differences/) 2 | 3 | ##### Medium 4 | 5 | 6 | Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k. 7 | 8 | Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid. 9 | 10 | You may return the answer in any order. 11 | 12 | 13 | 14 | Example 1: 15 | ```JS 16 | Input: n = 3, k = 7 17 | Output: [181,292,707,818,929] 18 | ``` 19 | 20 | Explanation: 21 | ```JS 22 | Note that 070 is not a valid number, because it has leading zeroes. 23 | ``` 24 | 25 | 26 | Example 2: 27 | ```JS 28 | Input: n = 2, k = 1 29 | Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98] 30 | ``` 31 | 32 | ##### Constraints: 33 | ```JS 34 | 2 <= n <= 9 35 | 0 <= k <= 9 36 | ``` -------------------------------------------------------------------------------- /0967. Numbers With Same Consecutive Differences/numbers-with-same-consecutive-differences.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @param {number} k 4 | * @return {number[]} 5 | */ 6 | var numsSameConsecDiff = function(n, k) { 7 | let list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // integers list 8 | while(--n > 0){ 9 | let tmp = []; 10 | for(let val of list){ 11 | let rem = val % 10; 12 | if(rem + k < 10){ // map digit by digit 13 | tmp.push(val * 10 + rem + k); 14 | } 15 | if(k != 0 && rem - k >= 0) { // map digit by digit 16 | tmp.push(val * 10 + rem - k) 17 | } 18 | } 19 | list = tmp; 20 | } 21 | return list 22 | }; 23 | 24 | /* 25 | Runtime: 77 ms, faster than 88.89% of JavaScript online submissions for Numbers With Same Consecutive Differences. 26 | Memory Usage: 43.8 MB, less than 61.11% of JavaScript online submissions for Numbers With Same Consecutive Differences. 27 | */ -------------------------------------------------------------------------------- /0990. Satisfiability of Equality Equations/README.md: -------------------------------------------------------------------------------- 1 | ### [990. Satisfiability of Equality Equations](https://leetcode.com/problems/satisfiability-of-equality-equations/) 2 | 3 | ##### Medium 4 | 5 | You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names. 6 | 7 | Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise. 8 | 9 | 10 | 11 | Example 1: 12 | ```JS 13 | Input: equations = ["a==b","b!=a"] 14 | Output: false 15 | ``` 16 | 17 | Explanation: 18 | ```JS 19 | If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. 20 | There is no way to assign the variables to satisfy both equations. 21 | ``` 22 | 23 | Example 2: 24 | ```JS 25 | Input: equations = ["b==a","a==b"] 26 | Output: true 27 | ``` 28 | 29 | Explanation: 30 | ```JS 31 | We could assign a = 1 and b = 1 to satisfy both equations. 32 | ``` 33 | 34 | Constraints: 35 | ```JS 36 | 1 <= equations.length <= 500 37 | equations[i].length == 4 38 | equations[i][0] is a lowercase letter. 39 | equations[i][1] is either '=' or '!'. 40 | equations[i][2] is '='. 41 | equations[i][3] is a lowercase letter. 42 | ``` 43 | 44 | ***[For details explanation](https://leet-codes.blogspot.com/2022/09/990-satisfiability-of-equality-equations.html)*** -------------------------------------------------------------------------------- /0990. Satisfiability of Equality Equations/satisfiability-of-equality-equations.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} equations 3 | * @return {boolean} 4 | */ 5 | var equationsPossible = function(equations) { 6 | const map = new Map(), 7 | find = item => { 8 | map.set(item, map.get(item) || item); 9 | return item === map.get(item) ? item : find(map.get(item)); 10 | }; 11 | 12 | equations.forEach(([a, eq, , b]) => { 13 | if (eq === '=') { 14 | map.set(find(a), find(b)); 15 | } 16 | }); 17 | 18 | let complies = true; 19 | equations.forEach(([a, eq, , b]) => { 20 | if (eq === '!') { 21 | if (find(a) === find(b)) complies = false; 22 | } 23 | }); 24 | 25 | return complies; 26 | } 27 | 28 | /* 29 | 30 | */ -------------------------------------------------------------------------------- /1011. Capacity To Ship Packages Within D Days/allocate-books.cpp: -------------------------------------------------------------------------------- 1 | bool isPossible(vector arr,int mid,int m){ 2 | int studentCount = 1; 3 | int pageSum = 0; 4 | for(int i=0;i m || arr[i] > mid){ 10 | return false; 11 | } 12 | pageSum = arr[i]; 13 | } 14 | } 15 | return true; 16 | } 17 | 18 | int allocateBooks(vector arr, int n, int m) { 19 | // Write your code here. 20 | int start = 0; 21 | int sum = 0; 22 | for(int i=0;i days || weights[i] > mid){ 15 | return false; 16 | } 17 | capacity = weights[i]; 18 | } 19 | } 20 | return true; 21 | } 22 | 23 | var shipWithinDays = function(weights, days) { 24 | let start = 0 25 | let end = 0; 26 | let ans = -1; 27 | for(let i=0;i &boards, int k, int mid){ 2 | int painterCount = 1; 3 | int boardsPained = 0; 4 | for(int i=0;i < boards.size();i++){ 5 | if(boards[i]+boardsPained <= mid){ 6 | boardsPained+=boards[i]; 7 | }else{ 8 | painterCount++; 9 | if(painterCount > k || boards[i] > mid){ 10 | return false; 11 | } 12 | boardsPained = boards[i]; 13 | } 14 | } 15 | return true; 16 | } 17 | 18 | int findLargestMinDistance(vector &boards, int k) 19 | { 20 | // Write your code here. 21 | int start = 0; 22 | int sum = 0; 23 | for(int i=0;i { 9 | let dp = initialize2DArrayNew(d + 1, target + 1); 10 | dp[0][0] = 1; 11 | for (let i = 1; i <= d; i++) { 12 | for (let j = 1; j <= f; j++) { 13 | for (let k = j; k <= target; k++) { 14 | dp[i][k] = (dp[i][k] + dp[i - 1][k - j]) % mod; 15 | } 16 | } 17 | } 18 | return dp[d][target]; 19 | }; 20 | 21 | const initialize2DArrayNew = (m, n) => { 22 | let data = []; 23 | for (let i = 0; i < m; i++) { 24 | let tmp = new Array(n).fill(0); 25 | data.push(tmp); 26 | } 27 | return data; 28 | }; 29 | 30 | /* 31 | */ -------------------------------------------------------------------------------- /1207. Unique Number of Occurrences/README.md: -------------------------------------------------------------------------------- 1 | ### [1207. Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) 2 | 3 | #####Level Easy 4 | 5 | Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise. 6 | 7 | 8 | Example 1: 9 | 10 | Input: 11 | ```JS 12 | arr = [1,2,2,1,1,3] 13 | ``` 14 | Output: 15 | ```JS 16 | true 17 | ``` 18 | Explanation: 19 | ```JS 20 | The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. 21 | ``` 22 | 23 | 24 | 25 | Example 2: 26 | 27 | Input: 28 | ```JS 29 | arr = [1,2] 30 | ``` 31 | Output: 32 | ```JS 33 | false 34 | ``` 35 | 36 | 37 | 38 | Example 3: 39 | 40 | Input: 41 | ```JS 42 | arr = [-3,0,1,-3,1,1,1,-3,10,0] 43 | ``` 44 | Output: 45 | ```JS 46 | true 47 | ``` 48 | 49 | Constraints: 50 | ```JS 51 | 1 <= arr.length <= 1000 52 | -1000 <= arr[i] <= 1000 53 | ``` -------------------------------------------------------------------------------- /1207. Unique Number of Occurrences/unique-number-of-occurrences.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @return {boolean} 4 | */ 5 | var uniqueOccurrences = function(arr) { 6 | let hash = {}; 7 | let occurrences = new Set(); 8 | for(let i=0;i previousValue + currentValue,0); 14 | } 15 | let entries = Object.entries(countHash); 16 | let sorted = entries.sort((a, b) => a[1] - b[1]); 17 | let result = []; 18 | for(let i=0;i= matrix[i][j]) { 13 | minRow[i] = matrix[i][j]; 14 | } 15 | } 16 | } 17 | for(let i=0;i= m; 22 | } 23 | 24 | var minDays = function(bloomDay, m, k) { 25 | 26 | // case 2 27 | if(m * k > bloomDay.length){ 28 | return -1; 29 | } 30 | 31 | let start = 0; 32 | let end = Math.max(...bloomDay); 33 | let mid = start + parseInt((end - start)/2); 34 | let ans =-1; 35 | while(start <= end){ 36 | mid = start + parseInt((end - start)/2); 37 | if(isPossible(bloomDay, m, k, mid)){ 38 | ans = mid; 39 | end = mid - 1; 40 | }else{ 41 | start = mid + 1; 42 | } 43 | } 44 | return ans; 45 | }; 46 | 47 | /* 48 | Runtime: 170 ms, faster than 54.05% of JavaScript online submissions for Minimum Number of Days to Make m Bouquets. 49 | Memory Usage: 52.6 MB, less than 47.75% of JavaScript online submissions for Minimum Number of Days to Make m Bouquets. 50 | */ -------------------------------------------------------------------------------- /1502. Can Make Arithmetic Progression From Sequence/README.md: -------------------------------------------------------------------------------- 1 | ### [1502. Can Make Arithmetic Progression From Sequence](https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/) 2 | 3 | ##### Easy 4 | 5 | A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. 6 | 7 | Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false. 8 | 9 | 10 | 11 | Example 1: 12 | ```JS 13 | Input: arr = [3,5,1] 14 | Output: true 15 | ``` 16 | Explanation: 17 | ```JS 18 | We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. 19 | ``` 20 | 21 | 22 | Example 2: 23 | ```JS 24 | Input: arr = [1,2,4] 25 | Output: false 26 | ``` 27 | 28 | Explanation: 29 | ```JS 30 | There is no way to reorder the elements to obtain an arithmetic progression. 31 | ``` 32 | 33 | ##### Constraints: 34 | ```JS 35 | 2 <= arr.length <= 1000 36 | -106 <= arr[i] <= 106 37 | ``` -------------------------------------------------------------------------------- /1502. Can Make Arithmetic Progression From Sequence/can-make-arithmetic-progression-from-sequence.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @return {boolean} 4 | */ 5 | var canMakeArithmeticProgression = function(arr) { 6 | arr.sort(function(a, b) { 7 | if( a === Infinity ) 8 | return 1; 9 | else if( isNaN(a)) 10 | return -1; 11 | else 12 | return a - b; 13 | }); 14 | let diff = arr[1] - arr[0]; 15 | for(let i=1;i=arr[i]) k++; 9 | else break; 10 | } 11 | return k; 12 | }; 13 | 14 | 15 | /* 16 | 17 | O(n) 18 | 19 | Runtime: 93 ms, faster than 56.82% of JavaScript online submissions for Kth Missing Positive Number. 20 | Memory Usage: 41.9 MB, less than 95.45% of JavaScript online submissions for Kth Missing Positive Number. 21 | */ 22 | 23 | 24 | // Binary Search Approach 25 | 26 | /** 27 | * @param {number[]} arr 28 | * @param {number} k 29 | * @return {number} 30 | */ 31 | var findKthPositive = function(arr, k) { 32 | let s = 0; 33 | let e = arr.length-1; 34 | 35 | while(s<=e){ 36 | let mid = s + parseInt((e-s) / 2); 37 | if(arr[mid] - (mid+1) >= k){ 38 | e = mid-1; 39 | }else{ 40 | s = mid+1; 41 | } 42 | 43 | } 44 | return s+k; 45 | }; 46 | 47 | /* 48 | Runtime: 88 ms, faster than 66.36% of JavaScript online submissions for Kth Missing Positive Number. 49 | Memory Usage: 42.4 MB, less than 57.27% of JavaScript online submissions for Kth Missing Positive Number. 50 | */ -------------------------------------------------------------------------------- /1544. Make The String Great/README.md: -------------------------------------------------------------------------------- 1 | ### [1544. Make The String Great](https://leetcode.com/problems/make-the-string-great/) 2 | 3 | ##### Easy 4 | 5 | Given a string s of lower and upper case English letters. 6 | 7 | ```JS 8 | A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 9 | 10 | 0 <= i <= s.length - 2 11 | s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa. 12 | To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good. 13 | ``` 14 | 15 | Return the string after making it good. The answer is guaranteed to be unique under the given constraints. 16 | 17 | Notice that an empty string is also good. 18 | 19 | Example 1: 20 | ```JS 21 | Input: s = "leEeetcode" 22 | Output: "leetcode" 23 | ``` 24 | 25 | Explanation: 26 | ```JS 27 | In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode". 28 | ``` 29 | 30 | 31 | Example 2: 32 | ```JS 33 | Input: s = "abBAcC" 34 | Output: "" 35 | ``` 36 | 37 | Explanation: 38 | ```JS 39 | We have many possible scenarios, and all lead to the same answer. For example: 40 | "abBAcC" --> "aAcC" --> "cC" --> "" 41 | "abBAcC" --> "abBA" --> "aA" --> "" 42 | ``` 43 | 44 | 45 | Example 3: 46 | ```JS 47 | Input: s = "s" 48 | Output: "s" 49 | ``` 50 | 51 | ##### Constraints: 52 | ```JS 53 | 1 <= s.length <= 100 54 | s contains only lower and upper case English letters. 55 | ``` -------------------------------------------------------------------------------- /1544. Make The String Great/make-the-string-great.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | const makeGood = function (s) { 6 | if (s.length == 1) return s; 7 | let stack = [s[0]]; 8 | for (let i = 1; i < s.length; i++) { 9 | if (stack.length == 0){ 10 | stack.push(s[i]); 11 | } else { 12 | let end = stack[stack.length - 1]; 13 | if ((isUpperCase(end) && isLowerCase(s[i]) && isEqual(end, s[i])) || (isLowerCase(end) && isUpperCase(s[i]) && isEqual(end, s[i]))) { 14 | stack.pop(); 15 | continue; 16 | } 17 | stack.push(s[i]); 18 | } 19 | } 20 | return stack.join(""); 21 | }; 22 | 23 | 24 | const isEqual = (s1, s2) => { 25 | if (s1.toLowerCase() == s2.toLowerCase()) { 26 | return true; 27 | } 28 | return false; 29 | }; 30 | 31 | const isUpperCase = (character) => { 32 | if (character == character.toUpperCase()) { 33 | return true; 34 | } 35 | return false; 36 | }; 37 | 38 | const isLowerCase = (character) => { 39 | if (character == character.toLowerCase()) { 40 | return true; 41 | } 42 | return false; 43 | }; 44 | 45 | 46 | /** 47 | Runtime: 129 ms, faster than 23.65% of JavaScript online submissions for Make The String Great. 48 | Memory Usage: 45.8 MB, less than 17.73% of JavaScript online submissions for Make The String Great. 49 | **/ -------------------------------------------------------------------------------- /1552. Magnetic Force Between Two Balls/109-aggressive-cows-codingninjas.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Aggressive Cows 3 | 4 | bool canAssign(int minDist, vector &stalls, int k){ 5 | int n = stalls.size(); 6 | int prevBallLoc = stalls[0]; 7 | int ballCount = 1; 8 | for(int i=1; i= minDist) 11 | { 12 | ballCount++; 13 | prevBallLoc = stalls[i]; 14 | } 15 | if(ballCount == k) return true; 16 | } 17 | return false; 18 | } 19 | 20 | int aggressiveCows(vector &stalls, int k) 21 | { 22 | int start = 0; 23 | sort(stalls.begin(), stalls.end()); 24 | int end = *max_element(stalls.begin(), stalls.end()); 25 | int mid = start + (end - start)/2; 26 | int ans = -1; 27 | 28 | while(start <= end){ 29 | if(canAssign(mid, stalls, k)){ 30 | ans = mid; 31 | start = mid + 1; 32 | }else{ 33 | end = mid -1; 34 | } 35 | mid = start + (end - start)/2; 36 | } 37 | return ans; 38 | } 39 | 40 | /* 41 | Runtime: 164ms 42 | */ -------------------------------------------------------------------------------- /1552. Magnetic Force Between Two Balls/magnetic-force-between-two-balls.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} position 3 | * @param {number} m 4 | * @return {number} 5 | */ 6 | const canPlaceMBalls = function(minDist, position, m){ 7 | let ballCount = 1; 8 | let prevBallLoc = position[0]; 9 | for(let i=1;i= minDist){ 11 | ballCount++; 12 | prevBallLoc = position[i]; 13 | } 14 | if(ballCount == m){ 15 | return true; 16 | } 17 | } 18 | return false; 19 | } 20 | 21 | var maxDistance = function(position, m) { 22 | let start = 0; 23 | position.sort(function(a,b) { return a-b }); 24 | let end = position[position.length-1]; 25 | let ans = -1; 26 | let mid = start + parseInt((end-start)/2); 27 | while(start <= end){ 28 | if(canPlaceMBalls(mid, position, m)){ 29 | ans = mid; 30 | start = mid + 1; 31 | }else{ 32 | end = mid - 1; 33 | } 34 | mid = start + parseInt((end-start)/2); 35 | } 36 | return ans; 37 | }; 38 | 39 | /* 40 | Runtime: 305 ms, faster than 77.94% of JavaScript online submissions for Magnetic Force Between Two Balls. 41 | Memory Usage: 54.1 MB, less than 36.76% of JavaScript online submissions for Magnetic Force Between Two Balls. 42 | */ 43 | 44 | -------------------------------------------------------------------------------- /1572. Matrix Diagonal Sum/README.md: -------------------------------------------------------------------------------- 1 | ### [1572. Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum/) 2 | 3 | ##### Easy 4 | 5 | Given a square matrix mat, return the sum of the matrix diagonals. 6 | 7 | Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. 8 | 9 | 10 | 11 | Example 1: 12 | ```JS 13 | Input: mat = [[1,2,3], 14 | [4,5,6], 15 | [7,8,9]] 16 | Output: 25 17 | ``` 18 | 19 | Explanation: 20 | ```JS 21 | Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 22 | Notice that element mat[1][1] = 5 is counted only once. 23 | ``` 24 | 25 | 26 | Example 2: 27 | ```JS 28 | Input: mat = [[1,1,1,1], 29 | [1,1,1,1], 30 | [1,1,1,1], 31 | [1,1,1,1]] 32 | Output: 8 33 | ``` 34 | 35 | 36 | Example 3: 37 | ```JS 38 | Input: mat = [[5]] 39 | Output: 5 40 | ``` 41 | 42 | ##### Constraints: 43 | ```JS 44 | n == mat.length == mat[i].length 45 | 1 <= n <= 100 46 | 1 <= mat[i][j] <= 100 47 | ``` -------------------------------------------------------------------------------- /1572. Matrix Diagonal Sum/matrix-diagonal-sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} mat 3 | * @return {number} 4 | */ 5 | var diagonalSum = function(mat) { 6 | let sum=0; 7 | let n= mat.length; 8 | 9 | for(let i=0;i nums[i]){ 10 | count++; 11 | } 12 | if(count > 1){ 13 | return false; 14 | } 15 | } 16 | 17 | if(nums[n-1] > nums[0]){ 18 | count++; 19 | } 20 | if(count <= 1){ 21 | return true 22 | } 23 | return false; 24 | }; 25 | 26 | /* 27 | Runtime: 66 ms, faster than 90.63% of JavaScript online submissions for Check if Array Is Sorted and Rotated. 28 | Memory Usage: 41.7 MB, less than 91.41% of JavaScript online submissions for Check if Array Is Sorted and Rotated. 29 | */ -------------------------------------------------------------------------------- /1910. Remove All Occurrences of a Substring/README.md: -------------------------------------------------------------------------------- 1 | ### [1910. Remove All Occurrences of a Substring](https://leetcode.com/problems/remove-all-occurrences-of-a-substring/) 2 | 3 | ##### Medium 4 | 5 | Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: 6 | 7 | Find the leftmost occurrence of the substring part and remove it from s. 8 | Return s after removing all occurrences of part. 9 | 10 | A substring is a contiguous sequence of characters in a string. 11 | 12 | Example 1: 13 | ```JS 14 | Input: s = "daabcbaabcbc", part = "abc" 15 | Output: "dab" 16 | ``` 17 | 18 | Explanation: 19 | The following operations are done: 20 | 21 | ```JS 22 | - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". 23 | - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc". 24 | - s = "dababc", remove "abc" starting at index 3, so s = "dab". 25 | Now s has no occurrences of "abc". 26 | ``` 27 | 28 | Example 2: 29 | ```JS 30 | Input: s = "axxxxyyyyb", part = "xy" 31 | Output: "ab" 32 | ``` 33 | 34 | Explanation: 35 | The following operations are done: 36 | 37 | ```JS 38 | - s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb". 39 | - s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb". 40 | - s = "axxyyb", remove "xy" starting at index 2 so s = "axyb". 41 | - s = "axyb", remove "xy" starting at index 1 so s = "ab". 42 | Now s has no occurrences of "xy". 43 | ``` 44 | 45 | ##### Constraints: 46 | 47 | ```JS 48 | 1 <= s.length <= 1000 49 | 1 <= part.length <= 1000 50 | s​​​​​​ and part consists of lowercase English letters. 51 | ``` -------------------------------------------------------------------------------- /1910. Remove All Occurrences of a Substring/remove-all-occurrences-of-a-substring.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} part 4 | * @return {string} 5 | */ 6 | var removeOccurrences = function(s, part) { 7 | let index = s.indexOf(part) 8 | if(index < 0){ 9 | return s; 10 | } 11 | s = s.substring(0, index) + s.substring(index+part.length, s.length); 12 | return removeOccurrences(s, part); 13 | }; 14 | 15 | /* 16 | Runtime: 93 ms, faster than 62.69% of JavaScript online submissions for Remove All Occurrences of a Substring. 17 | Memory Usage: 42.4 MB, less than 73.88% of JavaScript online submissions for Remove All Occurrences of a Substring. 18 | */ 19 | -------------------------------------------------------------------------------- /2022. Convert 1D Array Into 2D Array/README.md: -------------------------------------------------------------------------------- 1 | ### [2022. Convert 1D Array Into 2D Array](https://leetcode.com/problems/convert-1d-array-into-2d-array/) 2 | 3 | ##### Easy 4 | 5 | 6 | You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. 7 | 8 | The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. 9 | 10 | Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible. 11 | 12 | 13 | 14 | Example 1: 15 | ```JS 16 | Input: original = [1,2,3,4], m = 2, n = 2 17 | Output: [[1,2],[3,4]] 18 | ``` 19 | 20 | Explanation: 21 | ```JS 22 | The constructed 2D array should contain 2 rows and 2 columns. 23 | The first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array. 24 | The second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array. 25 | ``` 26 | 27 | 28 | Example 2: 29 | ```JS 30 | Input: original = [1,2,3], m = 1, n = 3 31 | Output: [[1,2,3]] 32 | ``` 33 | 34 | Explanation: 35 | ```JS 36 | The constructed 2D array should contain 1 row and 3 columns. 37 | Put all three elements in original into the first row of the constructed 2D array. 38 | ``` 39 | 40 | 41 | Example 3: 42 | ```JS 43 | Input: original = [1,2], m = 1, n = 1 44 | Output: [] 45 | ``` 46 | 47 | Explanation: 48 | ```JS 49 | There are 2 elements in original. 50 | It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array. 51 | ``` 52 | 53 | ##### Constraints: 54 | ```JS 55 | 1 <= original.length <= 5 * 104 56 | 1 <= original[i] <= 105 57 | 1 <= m, n <= 4 * 104 58 | ``` -------------------------------------------------------------------------------- /2022. Convert 1D Array Into 2D Array/convert-1d-array-into-2d-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} original 3 | * @param {number} m 4 | * @param {number} n 5 | * @return {number[][]} 6 | */ 7 | var construct2DArray = function(original, m, n) { 8 | let len = original.length-1; 9 | if(len != (m * n) -1){ 10 | return []; 11 | } 12 | let res = []; 13 | // creating two dimensional array 14 | for (var i = 0; i < m; i++) { 15 | res[i] = new Array(n); 16 | } 17 | let rowIndex = 0; 18 | let colIndex = 0; 19 | let count = 0; 20 | for(let i=0;i 0){ 12 | for(let i=0;i 0){ 17 | count++; 18 | tickets[i]--; 19 | } 20 | } 21 | if(tickets[k] == 0){ 22 | break; 23 | } 24 | } 25 | return count; 26 | }; 27 | 28 | 29 | 30 | /* 31 | Runtime: 192 ms, faster than 5.21% of JavaScript online submissions for Time Needed to Buy Tickets. 32 | Memory Usage: 45.8 MB, less than 6.16% of JavaScript online submissions for Time Needed to Buy Tickets. 33 | */ 34 | 35 | 36 | // Better Approach One Liner 37 | 38 | /** 39 | * @param {number[]} tickets 40 | * @param {number} k 41 | * @return {number} 42 | */ 43 | var timeRequiredToBuy = function(tickets, k) { 44 | return tickets.reduce((x, v, i)=>x + Math.min(v, tickets[k] - (i > k)), 0); 45 | } -------------------------------------------------------------------------------- /2091. Removing Minimum and Maximum From Array/README.md: -------------------------------------------------------------------------------- 1 | ### [2091. Removing Minimum and Maximum From Array](https://leetcode.com/problems/removing-minimum-and-maximum-from-array/) 2 | 3 | ##### Level Medium 4 | 5 | You are given a 0-indexed array of distinct integers nums. 6 | 7 | There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. 8 | 9 | A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. 10 | 11 | Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: 18 | ```JS 19 | nums = [2,10,7,5,4,1,8,6] 20 | ``` 21 | 22 | Output: 23 | ```JS 24 | 5 25 | ``` 26 | 27 | Explanation: 28 | ```JS 29 | The minimum element in the array is nums[5], which is 1. 30 | The maximum element in the array is nums[1], which is 10. 31 | We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back. 32 | This results in 2 + 3 = 5 deletions, which is the minimum number possible. 33 | ``` 34 | 35 | Example 2: 36 | 37 | Input: 38 | ```JS 39 | nums = [0,-4,19,1,8,-2,-3,5] 40 | ``` 41 | 42 | Output: 43 | ```JS 44 | 3 45 | ``` 46 | 47 | Explanation: 48 | ```JS 49 | The minimum element in the array is nums[1], which is -4. 50 | The maximum element in the array is nums[2], which is 19. 51 | We can remove both the minimum and maximum by removing 3 elements from the front. 52 | This results in only 3 deletions, which is the minimum number possible. 53 | ``` 54 | 55 | Example 3: 56 | 57 | Input: 58 | ```JS 59 | nums = [101] 60 | ``` 61 | 62 | Output: 63 | ```JS 64 | 1 65 | ``` 66 | 67 | Explanation: 68 | ```JS 69 | There is only one element in the array, which makes it both the minimum and maximum element. 70 | We can remove it with 1 deletion. 71 | ``` 72 | 73 | ##### Constraints: 74 | ```JS 75 | 1 <= nums.length <= 105 76 | -105 <= nums[i] <= 105 77 | The integers in nums are distinct. 78 | ``` 79 | -------------------------------------------------------------------------------- /2091. Removing Minimum and Maximum From Array/removing-minimum-and-maximum-from-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var minimumDeletions = function(nums) { 6 | let len = nums.length; 7 | if(len == 1){ 8 | return 1; 9 | } 10 | let min_index = 0; 11 | let max_index = 0; 12 | 13 | for(let i=0;i nums[max_index]){ 15 | max_index = i; 16 | } 17 | if(nums[i] < nums[min_index]){ 18 | min_index = i; 19 | } 20 | } 21 | 22 | let left = Math.min(min_index,max_index);// left position 23 | let right = Math.max(min_index,max_index);// right position 24 | 25 | 26 | // There are three case 27 | // case 1- remove both from front. 28 | let ans1=right+1; 29 | 30 | // case 2- remove both from back. 31 | let ans2=len-left; 32 | 33 | // case 3- remove from front and back. 34 | let ans3=len-(right-left-1); 35 | 36 | return Math.min(ans1,Math.min(ans2,ans3)); 37 | }; 38 | /* 39 | Runtime: 79 ms, faster than 100.00% of JavaScript online submissions for Removing Minimum and Maximum From Array. 40 | Memory Usage: 53.5 MB, less than 100.00% of JavaScript online submissions for Removing Minimum and Maximum From Array 41 | */ 42 | 43 | -------------------------------------------------------------------------------- /2133. Check if Every Row and Column Contains All Numbers/README.md: -------------------------------------------------------------------------------- 1 | ### [2133. Check if Every Row and Column Contains All Numbers](https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/) 2 | 3 | ##### Easy 4 | 5 | An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). 6 | 7 | Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false. 8 | 9 | 10 | 11 | Example 1: 12 | ```JS 13 | Input: matrix = [[1,2,3],[3,1,2],[2,3,1]] 14 | Output: true 15 | ``` 16 | 17 | Explanation: 18 | ```JS 19 | In this case, n = 3, and every row and column contains the numbers 1, 2, and 3. 20 | Hence, we return true. 21 | ``` 22 | 23 | 24 | 25 | Example 2: 26 | ```JS 27 | Input: matrix = [[1,1,1],[1,2,3],[1,2,3]] 28 | Output: false 29 | ``` 30 | 31 | Explanation: 32 | ```JS 33 | In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3. 34 | Hence, we return false. 35 | ``` 36 | 37 | ##### Constraints: 38 | ```JS 39 | n == matrix.length == matrix[i].length 40 | 1 <= n <= 100 41 | 1 <= matrix[i][j] <= n 42 | ``` -------------------------------------------------------------------------------- /2133. Check if Every Row and Column Contains All Numbers/check-if-every-row-and-column-contains-all-numbers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {boolean} 4 | */ 5 | var checkValid = function(matrix) { 6 | let r=matrix.length; 7 | let c=matrix[0].length; 8 | 9 | for(let i=0;i 0) { 42 | return false; 43 | } 44 | } 45 | } 46 | return true; 47 | }; 48 | 49 | -------------------------------------------------------------------------------- /300. Longest Increasing Subsequence/README.md: -------------------------------------------------------------------------------- 1 | ### 300. Longest Increasing Subsequence 2 | 3 | ##### Level Medium 4 | 5 | Given an integer array nums, return the length of the longest strictly increasing subsequence. 6 | 7 | A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: 14 | ```JS 15 | nums = [10,9,2,5,3,7,101,18] 16 | ``` 17 | 18 | Output: 19 | ```JS 20 | 4 21 | ``` 22 | 23 | ##### Explanation: 24 | The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 25 | 26 | 27 | Example 2: 28 | 29 | Input: 30 | ```JS 31 | nums = [0,1,0,3,2,3] 32 | ``` 33 | 34 | Output: 35 | ```JS 36 | 4 37 | ``` 38 | 39 | Example 3: 40 | 41 | Input: 42 | 43 | ```JS 44 | nums = [7,7,7,7,7,7,7] 45 | ``` 46 | 47 | Output: 48 | ```JS 49 | 1 50 | ``` 51 | 52 | ##### Constraints: 53 | ```JS 54 | 1 <= nums.length <= 2500 55 | -104 <= nums[i] <= 104 56 | ``` -------------------------------------------------------------------------------- /300. Longest Increasing Subsequence/longest-increasing-subsequence.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | 6 | // Complexcity: O(n*n) 7 | 8 | var lengthOfLIS = function(nums) { 9 | let list = Array(nums.length).fill(1); 10 | for(let i=0;i