Skip to content

Commit

Permalink
add more solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
franklingu authored and franklingu-stripe committed Jan 2, 2023
1 parent 3bfddf4 commit 7ad7e5c
Show file tree
Hide file tree
Showing 60 changed files with 3,114 additions and 20 deletions.
60 changes: 59 additions & 1 deletion README.md

Large diffs are not rendered by default.

35 changes: 16 additions & 19 deletions download_solutions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
'python3': 'py',
'java': 'java',
'sql': 'sql',
'mysql': 'sql',
'shell': 'sh',
}
lang_name_mapping = {
'cpp': 'C++',
'py': 'Python',
'java': 'Java',
'sql': 'SQL',
'mysql': 'SQL',
'sh': 'Shell',
}
comment_mapping = {
Expand All @@ -31,6 +33,7 @@
'python3': ['"""', '"""'],
'java': ['/*', '*/'],
'sql': ['/*', '*/'],
'mysql': ['/*', '*/'],
'shell': [": '", "'"],
}
diff_mapping = {
Expand All @@ -47,7 +50,6 @@ class ParseReadmeState(Enum):

cookie = ''


def get_question_meta(session):
res = session.get('https://leetcode.com/api/problems/all/')
total = res.json()['stat_status_pairs']
Expand All @@ -70,16 +72,15 @@ def get_question(session, question_meta):

def get_solution(session, question_meta):
res = session.post('https://leetcode.com/graphql', json={
"operationName": "Submissions",
"query": "\n query submissionList($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!, $lang: Int, $status: Int) {\n questionSubmissionList(\n offset: $offset\n limit: $limit\n lastKey: $lastKey\n questionSlug: $questionSlug\n lang: $lang\n status: $status\n ) {\n lastKey\n hasNext\n submissions {\n id\n title\n titleSlug\n status\n statusDisplay\n lang\n langName\n runtime\n timestamp\n url\n isPending\n memory\n hasNotes\n }\n }\n}\n ",
"variables": {
"questionSlug": question_meta['stat']['question__title_slug'],
"offset": 0,
"limit": 20,
"lastKey": None,
"questionSlug": question_meta['stat']['question__title_slug']
},
"query": "query Submissions($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!) {\n submissionList(offset: $offset, limit: $limit, lastKey: $lastKey, questionSlug: $questionSlug) {\n lastKey\n hasNext\n submissions {\n id\n statusDisplay\n lang\n runtime\n timestamp\n url\n isPending\n memory\n __typename\n }\n __typename\n }\n}\n"
}
})
submissions = res.json()['data']['submissionList']['submissions']
submissions = res.json()['data']['questionSubmissionList']['submissions']
selected = None
lang = None
for submission in submissions:
Expand All @@ -89,20 +90,16 @@ def get_solution(session, question_meta):
selected = submission
break
if selected is None:
print('no AC solution found: ', question_meta['stat']['question__title'])
return None
res = session.get('https://leetcode.com{}'.format(selected['url']))
code_line = ''
for line in res.text.split('\n'):
if 'submissionCode:' in line:
code_line = line
break
match = re.search("submissionCode: '(.+)'", code_line)
if match is None:
print('cannot find solution: ', question_meta['stat']['question__title'])
return None, None
code_line = match.group(1)
code_line = code_line.encode('utf-8').decode('unicode-escape')
return code_line, lang
res = session.post('https://leetcode.com/graphql', json={
"query": "\n query submissionDetails($submissionId: Int!) {\n submissionDetails(submissionId: $submissionId) {\n runtime\n runtimeDisplay\n runtimePercentile\n runtimeDistribution\n memory\n memoryDisplay\n memoryPercentile\n memoryDistribution\n code\n timestamp\n statusCode\n user {\n username\n profile {\n realName\n userAvatar\n }\n }\n lang {\n name\n verboseName\n }\n question {\n questionId\n }\n notes\n topicTags {\n tagId\n slug\n name\n }\n runtimeError\n compileError\n lastTestcase\n }\n}\n ",
"variables": {
"submissionId": selected['id'],
},
})
submission_details = res.json()['data']['submissionDetails']
return submission_details['code'], lang


def get_solution_dir(question_meta):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
Table: ActorDirector
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| actor_id | int |
| director_id | int |
| timestamp | int |
+-------------+---------+
timestamp is the primary key column for this table.
 
Write a SQL query for a report that provides the pairs (actor_id, director_id) where the actor has cooperated with the director at least three times.
Return the result table in any order.
The query result format is in the following example.
 
Example 1:
Input:
ActorDirector table:
+-------------+-------------+-------------+
| actor_id | director_id | timestamp |
+-------------+-------------+-------------+
| 1 | 1 | 0 |
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 2 | 3 |
| 1 | 2 | 4 |
| 2 | 1 | 5 |
| 2 | 1 | 6 |
+-------------+-------------+-------------+
Output:
+-------------+-------------+
| actor_id | director_id |
+-------------+-------------+
| 1 | 1 |
+-------------+-------------+
Explanation: The only pair is (1, 1) where they cooperated exactly 3 times.
*/


# Write your MySQL query statement below
select actor_id, director_id from ActorDirector group by actor_id, director_id having count(1) >= 3
58 changes: 58 additions & 0 deletions questions/add-to-array-form-of-integer/Solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""
The array-form of an integer num is an array representing its digits in left to right order.
For example, for num = 1321, the array form is [1,3,2,1].
Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.
 
Example 1:
Input: num = [1,2,0,0], k = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234
Example 2:
Input: num = [2,7,4], k = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455
Example 3:
Input: num = [2,1,5], k = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021
 
Constraints:
1 <= num.length <= 104
0 <= num[i] <= 9
num does not contain any leading zeros except for the zero itself.
1 <= k <= 104
"""


class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
def int_to_arr(val):
ret = []
while val > 0:
val, c = divmod(val, 10)
ret.append(c)
return ret[::-1]

def add_arrs(arr1, arr2):
ret = []
carry = 0
for a, b in itertools.zip_longest(reversed(arr1), reversed(arr2), fillvalue=0):
carry, c = divmod(a + b + carry, 10)
ret.append(c)
if carry != 0:
ret.append(carry)
return ret[::-1]

return add_arrs(num, int_to_arr(k))
60 changes: 60 additions & 0 deletions questions/arithmetic-slices-ii-subsequence/Solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""
Given an integer array nums, return the number of all the arithmetic subsequences of nums.
A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.
For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.
A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].
The test cases are generated so that the answer fits in 32-bit integer.
 
Example 1:
Input: nums = [2,4,6,8,10]
Output: 7
Explanation: All arithmetic subsequence slices are:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]
Example 2:
Input: nums = [7,7,7,7,7]
Output: 16
Explanation: Any subsequence of this array is arithmetic.
 
Constraints:
1  <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
"""


class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
# use defaultdict(int) to easily get the difference in arithmetic subsequences ending with ```j```
dp = [defaultdict(int) for _ in range(len(nums))]
res = 0
for i in range(len(nums)):
for j in range(i):

# We are looking for the number of elements before j in the arithmetic subsequence that has nums[j]-nums[i] as difference.
dif = nums[j]-nums[i]

# Simply add it to the result.
res += dp[j][dif]

# Increase the number of elements in arithmetic subsequence at i with this dif.
dp[i][dif] += dp[j][dif]+1
return res
50 changes: 50 additions & 0 deletions questions/article-views-i/Solution.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Table: Views
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| article_id | int |
| author_id | int |
| viewer_id | int |
| view_date | date |
+---------------+---------+
There is no primary key for this table, it may have duplicate rows.
Each row of this table indicates that some viewer viewed an article (written by some author) on some date.
Note that equal author_id and viewer_id indicate the same person.
 
Write an SQL query to find all the authors that viewed at least one of their own articles.
Return the result table sorted by id in ascending order.
The query result format is in the following example.
 
Example 1:
Input:
Views table:
+------------+-----------+-----------+------------+
| article_id | author_id | viewer_id | view_date |
+------------+-----------+-----------+------------+
| 1 | 3 | 5 | 2019-08-01 |
| 1 | 3 | 6 | 2019-08-02 |
| 2 | 7 | 7 | 2019-08-01 |
| 2 | 7 | 6 | 2019-08-02 |
| 4 | 7 | 1 | 2019-07-22 |
| 3 | 4 | 4 | 2019-07-21 |
| 3 | 4 | 4 | 2019-07-21 |
+------------+-----------+-----------+------------+
Output:
+------+
| id |
+------+
| 4 |
| 7 |
+------+
*/


# Write your MySQL query statement below
select distinct(author_id) as id from Views where author_id = viewer_id order by author_id asc;
90 changes: 90 additions & 0 deletions questions/basic-calculator/Solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
 
Example 1:
Input: s = "1 + 1"
Output: 2
Example 2:
Input: s = " 2-1 + 2 "
Output: 3
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
 
Constraints:
1 <= s.length <= 3 * 105
s consists of digits, '+', '-', '(', ')', and ' '.
s represents a valid expression.
'+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
'-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
There will be no two consecutive operators in the input.
Every number and running calculation will fit in a signed 32-bit integer.
"""


class Solution:
def calculate(self, s: str) -> int:

### num is the current number we are constructing

### sign is the '+' or '-' before the current number we are constructing/holding
### Note that we initialize sign with 1 to represent '+'

### The last element in the stack will be the number we are updating during the
### process, so put a 0 in it.
num, sign, stack = 0, 1, [0]

for c in s:

### Constructing the number.
if c.isdigit():
num = num*10 + int(c)

### Skip the space
elif c==' ':
continue

### When we see '+', we need to multiply the current number we are holding with the
### sign before this number, and update the last element in the stack.
### We also need to reset num to 0 and sign to 1
elif c == '+':
stack[-1] += num * sign
sign = 1
num = 0

### Doing the same thing as '+', but reset sign to -1
elif c == '-':
stack[-1] += num * sign
sign = -1
num = 0

### We add sign to stack which represent the sign of this ()
### We also add a 0 so we can keep update while evaluating the expression inside this ()
### Reset num and sign again
elif c == '(':
stack.extend([sign,0])
sign = 1
num = 0

### pop the last element and combine it with the current num and sign we are holding (the last element inside this '()' ).
### pop the last element again which is the sign for this '()' and muitiply them together.
### add everything we get inside this '()' to the last element in the stack.
elif c == ')':
lastNum = (stack.pop() + num*sign) * stack.pop()
stack[-1] += lastNum
sign = 1
num = 0

### stack should only contain one element representing everything except the last number if the expression ended with a number, so add the current num we are holding to the result.
return stack[-1]+num*sign
Loading

0 comments on commit 7ad7e5c

Please sign in to comment.