diff --git a/best-time-to-buy-and-sell-stock/sounmind.ts b/best-time-to-buy-and-sell-stock/sounmind.ts new file mode 100644 index 000000000..75519cd40 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/sounmind.ts @@ -0,0 +1,18 @@ +function maxProfit(prices: number[]): number { + let minPrice = Number.MAX_SAFE_INTEGER; + let maxProfit = 0; + + for (let i = 0; i < prices.length; i++) { + if (prices[i] < minPrice) { + minPrice = prices[i]; + } + + const potentialProfit = prices[i] - minPrice; + + if (maxProfit < potentialProfit) { + maxProfit = potentialProfit; + } + } + + return maxProfit; +} diff --git a/contains-duplicate/sounmind.ts b/contains-duplicate/sounmind.ts new file mode 100644 index 000000000..b97ce7292 --- /dev/null +++ b/contains-duplicate/sounmind.ts @@ -0,0 +1,3 @@ +function containsDuplicate(nums: number[]): boolean { + return nums.length !== new Set(nums).size; +} diff --git a/two-sum/sounmind.ts b/two-sum/sounmind.ts new file mode 100644 index 000000000..bb847291a --- /dev/null +++ b/two-sum/sounmind.ts @@ -0,0 +1,24 @@ +function twoSum(nums: number[], target: number): number[] { + // Pair each element with its index + const numsWithIndex = nums.map((value, index) => ({ value, index })); + + // Sort the array based on the values + numsWithIndex.sort((a, b) => a.value - b.value); + + let left = 0; + let right = numsWithIndex.length - 1; + + while (left < right) { + const sum = numsWithIndex[left].value + numsWithIndex[right].value; + + if (sum === target) { + return [numsWithIndex[left].index, numsWithIndex[right].index]; + } else if (sum < target) { + left++; + } else { + right--; + } + } + + return []; // In case there is no solution +} diff --git a/valid-anagram/sounmind.ts b/valid-anagram/sounmind.ts new file mode 100644 index 000000000..3302b4de1 --- /dev/null +++ b/valid-anagram/sounmind.ts @@ -0,0 +1,25 @@ +function isAnagram(s: string, t: string): boolean { + if (s.length !== t.length) { + return false; + } + + const frequencyMap = {}; + + for (const letter of s) { + if (frequencyMap[letter]) { + frequencyMap[letter] += 1; + } else { + frequencyMap[letter] = 1; + } + } + + for (const letter of t) { + if (frequencyMap[letter]) { + frequencyMap[letter] -= 1; + } else { + return false; + } + } + + return true; +} diff --git a/valid-palindrome/sounmind.ts b/valid-palindrome/sounmind.ts new file mode 100644 index 000000000..e3509c0bf --- /dev/null +++ b/valid-palindrome/sounmind.ts @@ -0,0 +1,16 @@ +function isPalindrome(s: string): boolean { + const filteredString = s.replace(/[^a-zA-Z0-9]/g, "").toUpperCase(); + + let [left, right] = [0, filteredString.length - 1]; + + while (left <= right) { + if (filteredString[left] !== filteredString[right]) { + return false; + } + + left += 1; + right -= 1; + } + + return true; +}