Skip to content

Commit

Permalink
Merge pull request #9 from rajat19/question-crawler-leetcode
Browse files Browse the repository at this point in the history
add crawling leetcode question
  • Loading branch information
rajat19 committed Feb 10, 2024
2 parents 8f7dd44 + 1303ec6 commit 120be35
Show file tree
Hide file tree
Showing 6 changed files with 253 additions and 10 deletions.
1 change: 1 addition & 0 deletions _data/topics.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- hash-table
- heap
- linked-list
- math
- matrix
- queue
- recursion
Expand Down
18 changes: 18 additions & 0 deletions _includes/code/palindromic-substrings/solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution {
int count = 0;
public int countSubstrings(String s) {
if (s == null || s.length() == 0) return 0;
for (int i = 0; i < s.length(); i++) { // i is the mid point
extendPalindrome(s, i, i); // odd length;
extendPalindrome(s, i, i + 1); // even length
}
return count;

}

private void extendPalindrome(String s, int left, int right) {
while (left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
count++; left--; right++;
}
}
}
23 changes: 23 additions & 0 deletions _includes/code/partition-array-for-maximum-sum/solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
public int maxSumAfterPartitioning(int[] arr, int k) {
int[] dp = new int[arr.length];
Arrays.fill(dp, -1);
return maxSum(arr, k, dp, arr.length, 0);
}

private int maxSum(int[] arr, int k, int[] dp, int n, int start) {
if (start >= n) {
return 0;
}
if (dp[start] != -1) {
return dp[start];
}
int max = 0, ans = 0;
int end = Math.min(n, start + k);
for(int i = start; i < end; i++) {
max = Math.max(max, arr[i]);
ans = Math.max(ans, max*(i-start+1) + maxSum(arr, k, dp, n, i+1));
}
return dp[start] = ans;
}
}
41 changes: 31 additions & 10 deletions posts/_hard/basic-calculator.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,48 @@
layout: post
author: Rajat Srivastava
title: Basic Calculator
topics: recursion stack string
topics: math string stack recursion
langs: java cpp py
tc: O(n)
sc: O(n)
leetid: 224
companies:
---

Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

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()`.
---

## Test Cases

**Example 1:**
**Example 1:**
```
Input: s = "1 + 1"
Output: 2
```

**Example 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 * 10<sup>5</sup>`

* `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.

62 changes: 62 additions & 0 deletions posts/_hard/partition-array-for-maximum-sum.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
---
layout: post
author: Rajat Srivastava
title: Partition Array for Maximum Sum
topics: array dynamic-programming
langs: java
tc: O(nk)
sc: O(n)
leetid: 1043
---

Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`.
After partitioning, each subarray has their values changed to become the maximum value of that subarray.

Return the _largest sum of the given array after partitioning_. Test cases are generated so that the answer fits in a **_32-bit integer_**.

---

## Test Cases

**Example 1:**
```
Input: arr = [1,15,7,9,2,5,10], k = 3
Output: 84
Explanation: arr becomes [15,15,15,9,10,10,10]
```

**Example 2:**
```
Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
Output: 83
```

**Example 2:**
```
Input: arr = [1], k = 1
Output: 1
```

---

## How to Solve

At every index, we need to decide whether to move the element at the index to a new partition or use the existing partition

For the first test case, `arr = [1,15,7,9,2,5,10], k = 3`
```mermaid
graph TD
0 --> 1
0 --> 2
0 --> 3
1 --> 2
1 --> 3
1 --> 4
2 --> 3
2 --> 4
2 --> 5
```

From above graph, we can see that we are reusing some of the pre-calculated values. We should proceed with dynamic programming for this

At every index, check for all elements upto `index + k` and find max sum that can be made by multipying the max element in sub-array
118 changes: 118 additions & 0 deletions scripts/leetcode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import requests
import os
import re
from html import unescape


class Leetcode:
def __init__(self, question, time_complexity, space_complexity, languages):
self.question = question
self.time_complexity = time_complexity
self.space_complexity = space_complexity
self.languages = languages
self.url = "https://leetcode.com/graphql"
self.question_query = """
query questionData($titleSlug: String!) {
question(titleSlug: $titleSlug) {
questionId
title
titleSlug
content
difficulty
exampleTestcases
categoryTitle
topicTags {
name
slug
translatedName
}
hints
challengeQuestion {
id
date
incompleteChallengeCount
streakCount
type
}
}
}
"""
self.variable = {"titleSlug": self.question}
self.question_data = None
self.post_data_format = """---
layout: post
author: Rajat Srivastava
title: {title}
topics: {topics}
langs: {languages}
tc: {tc}
sc: {sc}
leetid: {leetcode_id}
companies:
---
{content}
"""

def retrieve_question_data(self):
response = requests.post(self.url, json={'query': self.question_query, 'variables': self.variable})
self.question_data = response.json()['data']['question']

def create_post_data(self):
html_content = unescape(self.question_data['content'])
markdown_content = re.sub(r'\n\n', r'\n', html_content)
markdown_content = re.sub(r'<p>(.*?)</p>', r'\1\n', markdown_content)
markdown_content = re.sub(r'<code>(.*?)</code>', r'`\1`', markdown_content)
markdown_content = re.sub(r'<strong>(.*?)</strong>', r'**\1**', markdown_content)
markdown_content = re.sub(r'<strong class="example">(.*?)</strong>', r'**\1**', markdown_content)
markdown_content = re.sub(r'<em>(.*?)</em>', r'*\1*', markdown_content)
markdown_content = re.sub(r'<pre>(.*?)</pre>', lambda match: f'```{match.group(1)}```',
markdown_content, flags=re.DOTALL)
markdown_content = re.sub(r'<ul>(.*?)</ul>', r'\1', markdown_content)
markdown_content = re.sub(r'<ul>', r'', markdown_content)
markdown_content = re.sub(r'</ul>', r'', markdown_content)
markdown_content = re.sub(r'<li>(.*?)</li>', r'\n* \1', markdown_content)
markdown_content = re.sub(r'&nbsp;', r' ', markdown_content)
markdown_content = re.sub(r'\*\*Input:\*\*', r'Input:', markdown_content)
markdown_content = re.sub(r'\*\*Output:\*\*', r'Output:', markdown_content)
markdown_content = re.sub(r'\*\*Explanation:\*\*', r'Explanation:', markdown_content)
markdown_content = re.sub(r'(\*\*Example 1:\*\*)', r'---\n## Test Cases\n\1', markdown_content)
markdown_content = re.sub(r'\n(\n+)', r'\n', markdown_content)
markdown_content = re.sub(r' ', r' ', markdown_content)

return self.format_content(markdown_content)

def format_content(self, content):
topics = ' '.join([tag['slug'] for tag in self.question_data['topicTags']])
return self.post_data_format.format(
title=self.question_data['title'],
topics=topics,
leetcode_id=self.question_data['questionId'],
tc=self.time_complexity,
sc=self.space_complexity,
languages=self.languages if self.languages != '' else 'java',
content=content
)

def create_file(self, content, ext='md'):
difficulty_path = '_{}'.format(self.question_data['difficulty'].lower())
file_name = os.path.join('..', 'posts', difficulty_path, self.question + '.' + ext)
# print(file_name, content)
os.makedirs(os.path.dirname(file_name), exist_ok=True)
with open(file_name, 'w') as text_file:
text_file.write(content)

def generate_question(self):
self.retrieve_question_data()
post_data = self.create_post_data()
self.create_file(post_data, 'md')
# self.create_file(self.format_content(self.question_data['content']), 'html')
print('Successfully created post for ', self.question)


if __name__ == '__main__':
ques = input('Question title: ')
tc = input('Time complexity: ')
sc = input('Space complexity: ')
languages = input('Available languages (default java): ')
leetcode = Leetcode(ques, tc, sc, languages)
leetcode.generate_question()

0 comments on commit 120be35

Please sign in to comment.