Posts

Showing posts from February, 2025

167. Two Sum 2 - Input Array is Sorted - Medium

 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. Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space. Example: Input: numbers = [2,7,11,15], target = 9 Output: [1.2] Explanation: The sum of 2 and 7 is 0. There index1 = 1 and index2 = 2. We return [1,2] Constraints: 2 <= numbers.length <= 3 * 10**4 -1000 <= numbers[i] <= 1000 numbers is sorted in non-decreasing order. -1000 <= target <= 1000 Solution: var twoSum = function(numbers, target) {     const map = new Map();          for (let i...

392. Is Subsequence - Easy

 Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original characters without disturbing the relative positions of the remaining characters e.g "ace" is a subsequence of "abcde" while "aec" is not. Example: Input: s = "abc", t = "ahbgdc" Output: true Constraints: 0 <= s.length <= 100 0 <= t.length <= 10**4 s and t consist only of lowercase English letters Solution: var isSubsequence = function(s, t) {     let index = 0;     let string = '';     for (let i = 0; i < t.length; i++) {          if (s[index] === t[i]) {               string += t[i];               index++;          }     }       return string === s; } Thoughts: Figured out the solution on my own, which is great. It's not th...

125. Valid Palindrome - Easy

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome or false otherwise. Example: Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome. Constraints: 1 <= s.length <= 2 * 10**5 s consists only of printable ASCII characters Solution: var isPalindorme = function(s) {     const string = s.toLowerCase().replace(/[a-z0-9]/g, '');     const reverse = string.split('').reverse().join('');     return string === reverse } Thoughts: 9/10 using all the built-in js methods.

28. Find the Index of the First Occurence in a String - Easy

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if the needle is not part of haystack. Example: Input: haystack = 'sadbutsad', needle = 'sad' Output: 0 Explanation: 'sad' occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. Constraints: 1 <= haystack.length, needle.length <= 10**4 haystack and needle consist of only lowercase English characters. Solution: var strStr = function(haystack, needle) {          return haystack.indexOf(needle); } Thoughts: 10/10 easy.

151. Reverse Words in a String - Medium

 Given an input string s, reverse the order of the words. Return a string of the words in reverse order concatenated by a single space. Example:  Input: s = "a good    example" Output: "example good a" Explanation: You need to reduce multiple spaces in the reversed string. Constraints: 1 <= s.length <= 10**4 s contains English letters There is at least one word in s. Solution: var reverseWords = function(s) {          return s.split(' ').reverse().filter(x => x !== '').join(' ');  } Thoughts: Happy with the one-line solution. I would struggle to solve this if I couldn't use the built-in js methods (reverse especially). The solution beats 49% of solutions, which is better than I thought. I did need to debug what s looked like after I split on all the spaces and then that's when I clocked so we could filter out the empty array values. I'd give my understanding an 8/10. Happy that it's a medium.

14. Longest Common Prefix - Easy

Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example: Input: strs = ["flower","flow","flight"] Output: "fl" Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lowercase English letters if it is non-empty Solution: var longestCommonPrefix = function(strs) {     let res = '';      let prefix = strs[0];     for (let i = 0; i < prefix.length; i++) {               if (strs.some(str => str[i] !== prefix[i])) {                    break;                  }               res += prefix[i];          }     return res; } Thoughts: This was a difficult one and I gave up after 30 minutes. The s...

58. Length of Last Word - Easy

Given a string s consisting of words and spaces, return the length of the last word in the string. A word is. a maximal substring consisting of non-space characters only. Example: Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5. Constraints: 1 <= s.length <= 10**4 s consists of only English letters and spaces ' '. There will be at least one word in s. Solution: var lenghtOfLastWord = function(s) {       return s.trim().split(' ').pop().length; } Thoughts: Super simple. 10/10 for confidence and understanding.

13. Roman to Integer - Easy

 Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 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. Roman numerals are usually written from 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 is making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V(5) and X(10) to make 4 and 9 X can be placed before L(50) and C(100) to. make 40 and 90 C can be placed before D(500) and M(1000) to make 400 and 900 Given a roman numeral, convert it to an integer. Example: Input: s = "III" Output: 3 Explanation: III = 3 Constraints: 1 <= s.length <= 15 s contains only the characters ('I', 'V...

55. Jump Game - Medium

 You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index or false otherwise. Example: Input: nums = [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: nums = [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter wht. Its maximum jump length is 0, which makes it impossible to reach the last index. Constraints: 1 <= nums.length <= 10**4 0 <= nums[i] <= 10**5 Solution: var canJump = function(nums) {     let goal = nums.length - 1;     for (let i = nums.length - 2; i >= 0; i--) {          if (i + nums[i] >= goal) {               goal = i;          }     return goal === 0; } Thoughts: Too diff...

122. Best Time to Buy and Sell Stock 2 - Medium

 You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve. Example: Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (prices = 1) and sell on day 3 (prices = 5), profit = 5-1=4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit. = 6-3 = 3. Total profit is 4 + 3 = 7. Constraints: 1 <= prices.length <= 3 * 10**4 0 <= prices[i] <= 10**4 Solution: var maxProfit = function(prices) {     let profit = 0;     for (let i = 1; i < prices.length; i++) {          if (prices[i] > prices[i-1]) {               profit += prices[i] - prices[i-1];           ...

121. Best Time to Buy and Sell Stock - Easy

You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximise your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0 Example: Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. Constraints: 1 <= prices.length <= 10**5 0 <= prices[i] <= 10**4 Solution: var maxProfit = function(prices) {     let buyPrice = prices[0];     let profit = 0;     for (let i = 1; i < prices.length; i++) {          if (buyPrice > prices[i]) {               buyPrice = prices[i];         ...

189. Rotate Array - Medium

Given an integer array nums, rotate the array to the right by k steps, where k is a non-negative. Example: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Constraints: 1 <= nums.length <= 10**5 -2**31 <= nums[i] <= 2**31 - 1 0 <= k <= 10**5 My solution: var rotate = function(nums, k) {     while(k > 0) {          nums.unshift(nums.pop());          k--;     } } It passes most test cases except it exceeds the time limit for the second to last test case so its not very fast. I am happy with it and I think an interviewer would be satisfied. Here is a simple one liner solution that uses js built in method splice. var rotate = function(nums, k) {     return nums.unshift(...nums.splice(-k % nums.length)); } The splice method changes the...

169. Majority Element - Easy

Given an array nums of size n, return the majority element. The majority element is the element that appears more than [n / 2] times. You may assume that the majority element always exists in the array. Example: Input: nums [3,2,3] Output: 3 Constraints: n == nums.length; 1 <= n <= 5 * 10**4 -10**9 <= nums[i] <= 10**9 Solution: var majorityElement = function(nums) {     const sortedNums = nums.sort();     return sortedNums.length > 1 ? sortedNums[Math.floor(nums.length / 2)] : sortedNums[0]; } Thoughts: Got the answer pretty quickly but struggled to pass the last couple test cases for a while so thats when I had to use the if statement to check the length of the array is greater than 1 or else we can just return the first index value as the answer. I believe it solves the problem in linear time and 0(1) space because sorted it is in 0(n) and then because its an array we can do 0(1) lookup. I'd give my confidence rating a 7.5/10 out of 10.

80. Remove Duplicates from Sorted Array 2 - Medium

Given an integer array nums sorted in non-decreasing order, remove some duplicates in place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of the nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in place with O(1) extra memory. Example: Input: nums = [1,1,1,2,2,3] Output: 5, nums = [1,1,2,2,3,_] Explanation: Your function should return k = 5, with the first five elements of nums being 1,1,2,2 and 3, respectively. It does not matter what you leave beyond the returned k ...

26. Remove Duplicates from Sorted Array - Easy

Given an integer array nums sorted in non-decreasing order, remove the duplicates in place such that each unique element appears only once. The relative order of the elements should be kept the same. Then, return the number of unique elements in nums. Consider the number of unique elements of nums to be k. To get accepted, you need to do the following things: Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. Return k; Example: Input: nums = [1,1,2] Output: 2, nums = [1,2,_] Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2, respectively. It does not matter what you leave beyond the returned k (hence, they are underscores). Constraints: 1 <= nums.length <= 3 * 10**4 -10**4 <= nums[i] <= 10**4 nums is sorted in non-decreasing order Solution: var removeDuplicates = ...

27. Remove Element - Easy

 Given an integer array of nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val. Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:     Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. Return k Example: Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2,_,_] Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 0 <= nums.length <= 100 0 <= nums[i] <= 50 0 <= val <= 100 Solution: var removeElement = function(nums, val) {     let index = 0;      ...

88. Merge Sorted Array - Easy

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. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead, be stored inside the array nums1. To accommodate this, nums1 has the 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 the length of n. Example 1: Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Explanation: The arrays we are merging are [1,2,3] and [2,5,6] The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. Constraints: nums1.length === m + n nums2.length == n 0 <= m, n <= 200 1 <= m + n <= 200 -10**9 <= nums1[i], nums2[j] <= 10**9 My approach: Two pointer We can start wi...