From 1303ec6b23ebe22b45f20ee5ea6088f7e29d27e4 Mon Sep 17 00:00:00 2001 From: evilj0ker Date: Sat, 10 Feb 2024 17:53:32 +0530 Subject: [PATCH] add crawling leetcode question --- _data/topics.yml | 1 + .../code/palindromic-substrings/solution.java | 18 +++ .../solution.java | 23 ++++ posts/_hard/basic-calculator.md | 41 ++++-- .../_hard/partition-array-for-maximum-sum.md | 62 +++++++++ scripts/leetcode.py | 118 ++++++++++++++++++ 6 files changed, 253 insertions(+), 10 deletions(-) create mode 100644 _includes/code/palindromic-substrings/solution.java create mode 100644 _includes/code/partition-array-for-maximum-sum/solution.java create mode 100644 posts/_hard/partition-array-for-maximum-sum.md create mode 100644 scripts/leetcode.py diff --git a/_data/topics.yml b/_data/topics.yml index 5070c11..3328a47 100644 --- a/_data/topics.yml +++ b/_data/topics.yml @@ -12,6 +12,7 @@ - hash-table - heap - linked-list +- math - matrix - queue - recursion diff --git a/_includes/code/palindromic-substrings/solution.java b/_includes/code/palindromic-substrings/solution.java new file mode 100644 index 0000000..283889b --- /dev/null +++ b/_includes/code/palindromic-substrings/solution.java @@ -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++; + } + } +} \ No newline at end of file diff --git a/_includes/code/partition-array-for-maximum-sum/solution.java b/_includes/code/partition-array-for-maximum-sum/solution.java new file mode 100644 index 0000000..757ffc8 --- /dev/null +++ b/_includes/code/partition-array-for-maximum-sum/solution.java @@ -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; + } +} \ No newline at end of file diff --git a/posts/_hard/basic-calculator.md b/posts/_hard/basic-calculator.md index babbb4f..947b536 100644 --- a/posts/_hard/basic-calculator.md +++ b/posts/_hard/basic-calculator.md @@ -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 -``` \ No newline at end of file +``` + +**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. + + \ No newline at end of file diff --git a/posts/_hard/partition-array-for-maximum-sum.md b/posts/_hard/partition-array-for-maximum-sum.md new file mode 100644 index 0000000..f566caa --- /dev/null +++ b/posts/_hard/partition-array-for-maximum-sum.md @@ -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 \ No newline at end of file diff --git a/scripts/leetcode.py b/scripts/leetcode.py new file mode 100644 index 0000000..b0c741d --- /dev/null +++ b/scripts/leetcode.py @@ -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'

(.*?)

', r'\1\n', markdown_content) + markdown_content = re.sub(r'(.*?)', r'`\1`', markdown_content) + markdown_content = re.sub(r'(.*?)', r'**\1**', markdown_content) + markdown_content = re.sub(r'(.*?)', r'**\1**', markdown_content) + markdown_content = re.sub(r'(.*?)', r'*\1*', markdown_content) + markdown_content = re.sub(r'
(.*?)
', lambda match: f'```{match.group(1)}```', + markdown_content, flags=re.DOTALL) + markdown_content = re.sub(r'', r'\1', markdown_content) + markdown_content = re.sub(r'', r'', markdown_content) + markdown_content = re.sub(r'
  • (.*?)
  • ', r'\n* \1', markdown_content) + markdown_content = re.sub(r' ', 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()