Compare commits

...

3 Commits

7 changed files with 221 additions and 1 deletions

View File

@ -41,7 +41,7 @@ const $ch = cheerio.load(q.content);
$ch("pre").wrapInner("<code></code>");
const td = new Turndown({});
const mdBody = td.turndown($ch("body").html());
const mdBody = td.turndown($ch("body").html()) + `\n\n${link}`;
await $`mkdir -p ${solutionDir}`;
await $`touch ${solutionFilePath}`;

View File

@ -0,0 +1,61 @@
# Time: O(N)
# Space: O(N)
class Solution:
def trap(self, heights: List[int]) -> int:
if len(heights) < 2: return 0
# For every ith height, we need to calculate the max height
# on left and max on right of it
max_lefts, max_rights = [0] * len(heights), [0] * len(heights)
maxl = 0
for i in range(len(heights)):
max_lefts[i] = maxl
maxl = max(maxl, heights[i])
maxr = 0
for j in range(len(heights) - 1, -1, -1):
max_rights[j] = maxr
maxr = max(maxr, heights[j])
print(max_lefts)
print(max_rights)
# For every ith height, we can now compute the water output it can hold
# by doing the following:
#
# min(max_height_to_left, max_height_to_right) - height_of_bar
#
# If we ignore height_of_bar for a moment, the amount of water that can be
# held would be constrained by the least heights out of left/right.
#
# 3
# 2 |
# | |
# | 0 |
#
# In the above case, would be min(2, 3) == 2. But, if we fill the space up with a bar
# then:
#
# 3
# 2 |
# | 1 |
# | | |
#
# We can't put 2 water units. We need to subtract the height of the bar from the prev
# min() which will give us 1.
#
# NOTE: We need to do this for every ith height in the array.
output = 0
for i, h in enumerate(heights):
value = min(max_lefts[i], max_rights[i]) - heights[i]
# It's possible that ith height is very large, causing
# the expression above to give us -ve value. In this case
# we just ignore it (i.e, 0 output for this ith height)
if value > 0:
output += value
return output

View File

@ -0,0 +1,48 @@
# Time: O(N)
# Space: O(N)
class Solution:
def trap(self, heights: List[int]) -> int:
# Two pointer approach
left, right = 0, len(heights) - 1
# Since while scanning the array, at a given index i, we
# only need to consider the minimum of max_left_heights and
# max_right_heights, we just need to keep moving from both
# ends and keep track of the maximum height seen so far. We
# can then compare these two heights and decide from which
# side to move next.
max_left = max_right = 0
output = 0
while left <= right:
# By the formula from the DP approach:
#
# min(max_left, max_right) - heights[i]
#
# If max_left <= max_right, formula becomes:
#
# max_left - heights[i]
#
if max_left <= max_right:
# Shorter form to avoid -ve values
output += max(max_left - heights[left], 0)
max_left = max(max_left, heights[left])
left += 1
# By the formula from the DP approach:
#
# min(max_left, max_right) - heights[i]
#
# If max_left > max_right, formula becomes:
#
# max_right - heights[i]
#
else:
output += max(max_right - heights[right], 0)
max_right = max(max_right, heights[right])
right -= 1
return output

View File

@ -0,0 +1,25 @@
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
You want to maximize 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 1:**
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.
**Example 2:**
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
**Constraints:**
* `1 <= prices.length <= 105`
* `0 <= prices[i] <= 104`

View File

@ -0,0 +1,20 @@
# Time: O(N)
# Space: O(1)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) < 1: return 0
i, j = 0, 1
max_profit = 0
while i <= j < len(prices):
max_profit = max(prices[j] - prices[i], max_profit)
# Buy low, sell high — so we need to keep moving i (like
# a buy pointer) if jth price is smaller than what ith is.
if prices[j] < prices[i]:
i = j
else:
j += 1
return max_profit

View File

@ -0,0 +1,29 @@
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL.
There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Implement the `Solution` class:
* `Solution()` Initializes the object of the system.
* `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`.
* `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object.
**Example 1:**
Input: url = "https://leetcode.com/problems/design-tinyurl"
Output: "https://leetcode.com/problems/design-tinyurl"
Explanation:
Solution obj = new Solution();
string tiny = obj.encode(url); // returns the encoded tiny url.
string ans = obj.decode(tiny); // returns the original url after deconding it.
**Constraints:**
* `1 <= url.length <= 104`
* `url` is guranteed to be a valid URL.
https://leetcode.com/problems/encode-and-decode-tinyurl

View File

@ -0,0 +1,37 @@
# NOTE: This one is an open-ended question, and relevant to system design. Refer
# the notes.
import string
import random
class Codec:
store = {}
base = 'https://tiny.url/'
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
tiny = None
while True:
tiny = ''.join(random.choices(string.ascii_letters + string.digits, k = 5))
if tiny not in self.store:
break
self.store[tiny] = longUrl
return f'{self.base}{tiny}'
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
_, tiny = shortUrl.split(self.base)
return self.store[tiny]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))