diff --git a/leetcode/populate-notes.mjs b/leetcode/populate-notes.mjs new file mode 100644 index 0000000..ca7b929 --- /dev/null +++ b/leetcode/populate-notes.mjs @@ -0,0 +1,277 @@ +#!/usr/bin/env node + +/** + * Populate DSA note files with problem descriptions and code stubs + * from LeetCode's GraphQL API. + * + * Usage: + * node populate-notes.mjs # populate all missing + * node populate-notes.mjs --force # overwrite existing content + * node populate-notes.mjs --dry-run # show what would change + */ + +import { + readFileSync, + writeFileSync, + existsSync, + mkdirSync, +} from "node:fs"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +const args = process.argv.slice(2); +const force = args.includes("--force"); +const dryRun = args.includes("--dry-run"); + +const roadmap = JSON.parse( + readFileSync(join(__dirname, "out/roadmap.json"), "utf8") +); +const dsaDir = join(__dirname, "../org/study_deck_02/dsa"); +const cacheDir = join(__dirname, ".cache/leetcode"); +mkdirSync(cacheDir, { recursive: true }); + +const API = "https://leetcode.com/graphql"; +const DELAY_MS = 300; + +const topicSlug = (name) => + name + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/(^-|-$)/g, ""); + +function sleep(ms) { + return new Promise((r) => setTimeout(r, ms)); +} + +async function fetchProblem(titleSlug) { + const cachePath = join(cacheDir, `${titleSlug}.json`); + if (existsSync(cachePath)) { + return JSON.parse(readFileSync(cachePath, "utf8")); + } + + const res = await fetch(API, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + query: `query { + question(titleSlug: "${titleSlug}") { + title + content + difficulty + codeSnippets { lang langSlug code } + } + }`, + }), + }); + + if (!res.ok) { + console.error(` HTTP ${res.status} for ${titleSlug}`); + return null; + } + + const data = await res.json(); + const q = data?.data?.question; + if (!q) { + console.error(` No data for ${titleSlug}`); + return null; + } + + writeFileSync(cachePath, JSON.stringify(q, null, 2), "utf8"); + return q; +} + +function htmlToOrg(html) { + if (!html) return ""; + + let text = html; + + // Preserve code blocks + const codeBlocks = []; + text = text.replace( + /
([\s\S]*?)<\/pre>/g,
+    (_, code) => {
+      const cleaned = code
+        .replace(/<[^>]+>/g, "")
+        .replace(/</g, "<")
+        .replace(/>/g, ">")
+        .replace(/&/g, "&")
+        .replace(/ /g, " ")
+        .replace(/"/g, '"')
+        .trim();
+      codeBlocks.push(cleaned);
+      return `__CODE_BLOCK_${codeBlocks.length - 1}__`;
+    }
+  );
+
+  // Inline code
+  text = text.replace(/([\s\S]*?)<\/code>/g, "~$1~");
+
+  // Bold
+  text = text.replace(/]*>([\s\S]*?)<\/strong>/g, "*$1*");
+
+  // Italic
+  text = text.replace(/([\s\S]*?)<\/em>/g, "/$1/");
+
+  // Line breaks and paragraphs
+  text = text.replace(//g, "\n");
+  text = text.replace(/<\/p>/g, "\n");
+  text = text.replace(/]*>/g, "");
+
+  // Lists
+  text = text.replace(/]*>/g, "- ");
+  text = text.replace(/<\/li>/g, "\n");
+  text = text.replace(/<\/?[ou]l[^>]*>/g, "");
+
+  // Sup/sub
+  text = text.replace(/([\s\S]*?)<\/sup>/g, "^{$1}");
+  text = text.replace(/([\s\S]*?)<\/sub>/g, "_{$1}");
+
+  // Example blocks — flatten to plain text
+  text = text.replace(
+    /
([\s\S]*?)<\/div>/g, + (_, inner) => inner.replace(/<[^>]+>/g, "").trim() + "\n" + ); + + // Strip remaining HTML tags + text = text.replace(/<[^>]+>/g, ""); + + // Decode HTML entities + text = text.replace(/</g, "<"); + text = text.replace(/>/g, ">"); + text = text.replace(/&/g, "&"); + text = text.replace(/ /g, " "); + text = text.replace(/"/g, '"'); + text = text.replace(/'/g, "'"); + + // Collapse whitespace but preserve intentional newlines + text = text.replace(/[ \t]+/g, " "); + text = text.replace(/\n\s*\n\s*\n+/g, "\n\n"); + text = text.trim(); + + // Restore code blocks + for (let i = 0; i < codeBlocks.length; i++) { + text = text.replace( + `__CODE_BLOCK_${i}__`, + `\n#+begin_src\n${codeBlocks[i]}\n#+end_src\n` + ); + } + + return text; +} + +function buildNoteContent(num, name, diff, description, stubs, relPath) { + const py = stubs.find((s) => s.langSlug === "python3"); + const cpp = stubs.find((s) => s.langSlug === "cpp"); + + let out = `#+PROPERTY: STUDY_DECK_02 +* TODO ${num}. ${name} :${diff}: +:PROPERTIES: +:NEETCODE: [[file:${relPath}][${num}. ${name}]] +:END: +`; + + if (description) { + out += `\n${description}\n`; + } + + out += ` +** TODO Approach +Write your approach here. + +** TODO Python +#+begin_src python +${py ? py.code.trim() : ""} +#+end_src + +** TODO C++ +#+begin_src cpp +${cpp ? cpp.code.trim() : ""} +#+end_src +`; + + return out; +} + +// ── Main ──────────────────────────────────────────────────────────────── + +async function main() { + const allProblems = []; + for (const [topic, problems] of Object.entries(roadmap.problemsByTopic)) { + for (const p of problems) { + if (p.neetcode150) { + allProblems.push({ ...p, topicSlug: topicSlug(topic) }); + } + } + } + + console.log(`Processing ${allProblems.length} NeetCode 150 problems...`); + if (dryRun) console.log("(dry run — no files written)\n"); + + let populated = 0; + let skipped = 0; + let errors = 0; + + for (let i = 0; i < allProblems.length; i++) { + const p = allProblems[i]; + const titleSlug = p.link.replace(/\/$/, ""); + const filePath = join(dsaDir, p.topicSlug, `${p.code}.org`); + + process.stdout.write(`[${i + 1}/${allProblems.length}] ${p.code}...`); + + if (!existsSync(filePath)) { + console.log(" SKIP (no note file)"); + skipped++; + continue; + } + + const existing = readFileSync(filePath, "utf8"); + const hasDescription = existing.includes("** TODO Approach\nWrite your approach here.") === false || + existing.split("\n").filter(l => l.trim() && !l.startsWith("#") && !l.startsWith(":") && !l.startsWith("*") && !l.startsWith("**") && !l.startsWith("-") && !l.startsWith("Write your approach")).length > 10; + + if (!force && hasDescription && !existing.includes("Write your approach here.")) { + console.log(" SKIP (already populated)"); + skipped++; + continue; + } + + const question = await fetchProblem(titleSlug); + if (!question) { + console.log(" ERROR"); + errors++; + await sleep(DELAY_MS); + continue; + } + + const description = htmlToOrg(question.content); + const stubs = question.codeSnippets || []; + const num = p.code.split("-")[0]; + const relPath = `../../roadmap.org::*${num}. ${p.name}`; + + const content = buildNoteContent( + num, + p.name, + p.difficulty.toLowerCase(), + description, + stubs, + relPath + ); + + if (!dryRun) { + writeFileSync(filePath, content, "utf8"); + } + + console.log(` OK (${description.length} chars)`); + populated++; + + await sleep(DELAY_MS); + } + + console.log(`\nDone: ${populated} populated, ${skipped} skipped, ${errors} errors`); +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0005-longest-palindromic-substring.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0005-longest-palindromic-substring.org index 3292e95..4ed1984 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0005-longest-palindromic-substring.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0005-longest-palindromic-substring.org @@ -1,18 +1,51 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0005. Longest Palindromic Substring :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0005. Longest Palindromic Substring][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0005. Longest Palindromic Substring][0005. Longest Palindromic Substring]] :END: +Given a string ~s~, return /the longest/ /palindromic/ /substring/ in ~s~. + +*Example 1:* + + +#+begin_src +Input: s = "babad" +Output: "bab" +Explanation: "aba" is also a valid answer. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "cbbd" +Output: "bb" +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 1000~ + + - ~s~ consist of only digits and English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def longestPalindrome(self, s: str) -> str: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + string longestPalindrome(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0070-climbing-stairs.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0070-climbing-stairs.org index 1d1917e..6783783 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0070-climbing-stairs.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0070-climbing-stairs.org @@ -1,18 +1,57 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0070. Climbing Stairs :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0070. Climbing Stairs][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0070. Climbing Stairs][0070. Climbing Stairs]] :END: +You are climbing a staircase. It takes ~n~ steps to reach the top. + +Each time you can either climb ~1~ or ~2~ steps. In how many distinct ways can you climb to the top? + +*Example 1:* + + +#+begin_src +Input: n = 2 +Output: 2 +Explanation: There are two ways to climb to the top. +1. 1 step + 1 step +2. 2 steps +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 3 +Output: 3 +Explanation: There are three ways to climb to the top. +1. 1 step + 1 step + 1 step +2. 1 step + 2 steps +3. 2 steps + 1 step +#+end_src + + +*Constraints:* + + - ~1 <= n <= 45~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def climbStairs(self, n: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int climbStairs(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0091-decode-ways.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0091-decode-ways.org index 2dda1f0..8ab0788 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0091-decode-ways.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0091-decode-ways.org @@ -1,18 +1,88 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0091. Decode Ways :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0091. Decode Ways][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0091. Decode Ways][0091. Decode Ways]] :END: +You have intercepted a secret message encoded as a string of numbers. The message is *decoded* via the following mapping: + +~"1" -> 'A' + +"2" -> 'B' + +... + +"25" -> 'Y' + +"26" -> 'Z'~ + +However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes (~"2"~ and ~"5"~ vs ~"25"~). + +For example, ~"11106"~ can be decoded into: + + - ~"AAJF"~ with the grouping ~(1, 1, 10, 6)~ + + - ~"KJF"~ with the grouping ~(11, 10, 6)~ + + - The grouping ~(1, 11, 06)~ is invalid because ~"06"~ is not a valid code (only ~"6"~ is valid). + +Note: there may be strings that are impossible to decode. + +Given a string s containing only digits, return the *number of ways* to *decode* it. If the entire string cannot be decoded in any valid way, return ~0~. + +The test cases are generated so that the answer fits in a *32-bit* integer. + +*Example 1:* + +*Input:* s = "12" + +*Output:* 2 + +*Explanation:* + +"12" could be decoded as "AB" (1 2) or "L" (12). + +*Example 2:* + +*Input:* s = "226" + +*Output:* 3 + +*Explanation:* + +"226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). + +*Example 3:* + +*Input:* s = "06" + +*Output:* 0 + +*Explanation:* + +"06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). In this case, the string is not a valid encoding, so return 0. + +*Constraints:* + + - ~1 <= s.length <= 100~ + + - ~s~ contains only digits and may contain leading zero(s). + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def numDecodings(self, s: str) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int numDecodings(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0139-word-break.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0139-word-break.org index 786f4dc..d6787ef 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0139-word-break.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0139-word-break.org @@ -1,18 +1,70 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0139. Word Break :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0139. Word Break][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0139. Word Break][0139. Word Break]] :END: +Given a string ~s~ and a dictionary of strings ~wordDict~, return ~true~ if ~s~ can be segmented into a space-separated sequence of one or more dictionary words. + +*Note* that the same word in the dictionary may be reused multiple times in the segmentation. + +*Example 1:* + + +#+begin_src +Input: s = "leetcode", wordDict = ["leet","code"] +Output: true +Explanation: Return true because "leetcode" can be segmented as "leet code". +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "applepenapple", wordDict = ["apple","pen"] +Output: true +Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". +Note that you are allowed to reuse a dictionary word. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] +Output: false +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 300~ + + - ~1 <= wordDict.length <= 1000~ + + - ~1 <= wordDict[i].length <= 20~ + + - ~s~ and ~wordDict[i]~ consist of only lowercase English letters. + + - All the strings of ~wordDict~ are *unique*. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0152-maximum-product-subarray.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0152-maximum-product-subarray.org index 9d3128d..577d566 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0152-maximum-product-subarray.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0152-maximum-product-subarray.org @@ -1,18 +1,58 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0152. Maximum Product Subarray :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0152. Maximum Product Subarray][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0152. Maximum Product Subarray][0152. Maximum Product Subarray]] :END: +Given an integer array ~nums~, find a subarray that has the largest product, and return /the product/. + +The test cases are generated so that the answer will fit in a *32-bit* integer. + +*Note* that the product of an array with a single element is the value of that element. + +*Example 1:* + + +#+begin_src +Input: nums = [2,3,-2,4] +Output: 6 +Explanation: [2,3] has the largest product 6. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [-2,0,-1] +Output: 0 +Explanation: The result cannot be 2, because [-2,-1] is not a subarray. +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 2 * 10^{4}~ + + - ~-10 <= nums[i] <= 10~ + + - The product of any subarray of ~nums~ is *guaranteed* to fit in a *32-bit* integer. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxProduct(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int maxProduct(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0198-house-robber.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0198-house-robber.org index f11c256..36d4f72 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0198-house-robber.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0198-house-robber.org @@ -1,18 +1,56 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0198. House Robber :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0198. House Robber][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0198. House Robber][0198. House Robber]] :END: +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. + +Given an integer array ~nums~ representing the amount of money of each house, return /the maximum amount of money you can rob tonight without alerting the police/. + +*Example 1:* + + +#+begin_src +Input: nums = [1,2,3,1] +Output: 4 +Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). +Total amount you can rob = 1 + 3 = 4. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [2,7,9,3,1] +Output: 12 +Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). +Total amount you can rob = 2 + 9 + 1 = 12. +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 100~ + + - ~0 <= nums[i] <= 400~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def rob(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int rob(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0213-house-robber-ii.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0213-house-robber-ii.org index bfc03f3..30da2a1 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0213-house-robber-ii.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0213-house-robber-ii.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0213. House Robber II :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0213. House Robber II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0213. House Robber II][0213. House Robber II]] :END: +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are *arranged in a circle.* That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. + +Given an integer array ~nums~ representing the amount of money of each house, return /the maximum amount of money you can rob tonight *without alerting the police*/. + +*Example 1:* + + +#+begin_src +Input: nums = [2,3,2] +Output: 3 +Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [1,2,3,1] +Output: 4 +Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). +Total amount you can rob = 1 + 3 = 4. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [1,2,3] +Output: 3 +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 100~ + + - ~0 <= nums[i] <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def rob(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int rob(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0300-longest-increasing-subsequence.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0300-longest-increasing-subsequence.org index 504e3cf..16c7577 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0300-longest-increasing-subsequence.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0300-longest-increasing-subsequence.org @@ -1,18 +1,62 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0300. Longest Increasing Subsequence :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0300. Longest Increasing Subsequence][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0300. Longest Increasing Subsequence][0300. Longest Increasing Subsequence]] :END: +Given an integer array ~nums~, return /the length of the longest *strictly increasing *//*subsequence*/. + +*Example 1:* + + +#+begin_src +Input: nums = [10,9,2,5,3,7,101,18] +Output: 4 +Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [0,1,0,3,2,3] +Output: 4 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [7,7,7,7,7,7,7] +Output: 1 +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 2500~ + + - ~-10^{4} <= nums[i] <= 10^{4}~ + +Follow up: Can you come up with an algorithm that runs in ~O(n log(n))~ time complexity? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int lengthOfLIS(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0322-coin-change.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0322-coin-change.org index ebac9e1..e96dd34 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0322-coin-change.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0322-coin-change.org @@ -1,18 +1,66 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0322. Coin Change :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0322. Coin Change][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0322. Coin Change][0322. Coin Change]] :END: +You are given an integer array ~coins~ representing coins of different denominations and an integer ~amount~ representing a total amount of money. + +Return /the fewest number of coins that you need to make up that amount/. If that amount of money cannot be made up by any combination of the coins, return ~-1~. + +You may assume that you have an infinite number of each kind of coin. + +*Example 1:* + + +#+begin_src +Input: coins = [1,2,5], amount = 11 +Output: 3 +Explanation: 11 = 5 + 5 + 1 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: coins = [2], amount = 3 +Output: -1 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: coins = [1], amount = 0 +Output: 0 +#+end_src + + +*Constraints:* + + - ~1 <= coins.length <= 12~ + + - ~1 <= coins[i] <= 2^{31} - 1~ + + - ~0 <= amount <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int coinChange(vector& coins, int amount) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0416-partition-equal-subset-sum.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0416-partition-equal-subset-sum.org index 4ee1c83..bcc5c1b 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0416-partition-equal-subset-sum.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0416-partition-equal-subset-sum.org @@ -1,18 +1,52 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0416. Partition Equal Subset Sum :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0416. Partition Equal Subset Sum][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0416. Partition Equal Subset Sum][0416. Partition Equal Subset Sum]] :END: +Given an integer array ~nums~, return ~true~ /if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or /~false~/ otherwise/. + +*Example 1:* + + +#+begin_src +Input: nums = [1,5,11,5] +Output: true +Explanation: The array can be partitioned as [1, 5, 5] and [11]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [1,2,3,5] +Output: false +Explanation: The array cannot be partitioned into equal sum subsets. +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 200~ + + - ~1 <= nums[i] <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def canPartition(self, nums: List[int]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool canPartition(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0647-palindromic-substrings.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0647-palindromic-substrings.org index 9b0f229..7b96f0f 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0647-palindromic-substrings.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0647-palindromic-substrings.org @@ -1,18 +1,56 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0647. Palindromic Substrings :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0647. Palindromic Substrings][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0647. Palindromic Substrings][0647. Palindromic Substrings]] :END: +Given a string ~s~, return /the number of *palindromic substrings* in it/. + +A string is a *palindrome* when it reads the same backward as forward. + +A *substring* is a contiguous sequence of characters within the string. + +*Example 1:* + + +#+begin_src +Input: s = "abc" +Output: 3 +Explanation: Three palindromic strings: "a", "b", "c". +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "aaa" +Output: 6 +Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 1000~ + + - ~s~ consists of lowercase English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def countSubstrings(self, s: str) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int countSubstrings(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0656-coin-path.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0656-coin-path.org index 5b57ecb..3b17eb9 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0656-coin-path.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0656-coin-path.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0656. Coin Path :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0656. Coin Path][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0656. Coin Path][0656. Coin Path]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/1-d-dynamic-programming/0746-min-cost-climbing-stairs.org b/org/study_deck_02/dsa/1-d-dynamic-programming/0746-min-cost-climbing-stairs.org index 0f6b23a..fdb2e33 100644 --- a/org/study_deck_02/dsa/1-d-dynamic-programming/0746-min-cost-climbing-stairs.org +++ b/org/study_deck_02/dsa/1-d-dynamic-programming/0746-min-cost-climbing-stairs.org @@ -1,18 +1,65 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0746. Min Cost Climbing Stairs :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0746. Min Cost Climbing Stairs][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0746. Min Cost Climbing Stairs][0746. Min Cost Climbing Stairs]] :END: +You are given an integer array ~cost~ where ~cost[i]~ is the cost of ~i^{th}~ step on a staircase. Once you pay the cost, you can either climb one or two steps. + +You can either start from the step with index ~0~, or the step with index ~1~. + +Return /the minimum cost to reach the top of the floor/. + +*Example 1:* + + +#+begin_src +Input: cost = [10,15,20] +Output: 15 +Explanation: You will start at index 1. +- Pay 15 and climb two steps to reach the top. +The total cost is 15. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: cost = [1,100,1,1,1,100,1,1,100,1] +Output: 6 +Explanation: You will start at index 0. +- Pay 1 and climb two steps to reach index 2. +- Pay 1 and climb two steps to reach index 4. +- Pay 1 and climb two steps to reach index 6. +- Pay 1 and climb one step to reach index 7. +- Pay 1 and climb two steps to reach index 9. +- Pay 1 and climb one step to reach the top. +The total cost is 6. +#+end_src + + +*Constraints:* + + - ~2 <= cost.length <= 1000~ + + - ~0 <= cost[i] <= 999~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0010-regular-expression-matching.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0010-regular-expression-matching.org index 68ad122..ddfecd7 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0010-regular-expression-matching.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0010-regular-expression-matching.org @@ -1,18 +1,74 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0010. Regular Expression Matching :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0010. Regular Expression Matching][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0010. Regular Expression Matching][0010. Regular Expression Matching]] :END: +Given an input string ~s~ and a pattern ~p~, implement regular expression matching with support for ~'.'~ and ~'*'~ where: + + - ~'.'~ Matches any single character.​​​​ + + - ~'*'~ Matches zero or more of the preceding element. + +Return a boolean indicating whether the matching covers the entire input string (not partial). + +*Example 1:* + + +#+begin_src +Input: s = "aa", p = "a" +Output: false +Explanation: "a" does not match the entire string "aa". +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "aa", p = "a*" +Output: true +Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". +#+end_src + + +*Example 3:* + + +#+begin_src +Input: s = "ab", p = ".*" +Output: true +Explanation: ".*" means "zero or more (*) of any character (.)". +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 20~ + + - ~1 <= p.length <= 20~ + + - ~s~ contains only lowercase English letters. + + - ~p~ contains only lowercase English letters, ~'.'~, and ~'*'~. + + - It is guaranteed for each appearance of the character ~'*'~, there will be a previous valid character to match. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isMatch(self, s: str, p: str) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isMatch(string s, string p) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0062-unique-paths.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0062-unique-paths.org index f6a79d2..b17824d 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0062-unique-paths.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0062-unique-paths.org @@ -1,18 +1,56 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0062. Unique Paths :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0062. Unique Paths][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0062. Unique Paths][0062. Unique Paths]] :END: +There is a robot on an ~m x n~ grid. The robot is initially located at the *top-left corner* (i.e., ~grid[0][0]~). The robot tries to move to the *bottom-right corner* (i.e., ~grid[m - 1][n - 1]~). The robot can only move either down or right at any point in time. + +Given the two integers ~m~ and ~n~, return /the number of possible unique paths that the robot can take to reach the bottom-right corner/. + +The test cases are generated so that the answer will be less than or equal to ~2 * 10^{9}~. + +*Example 1:* + + +#+begin_src +Input: m = 3, n = 7 +Output: 28 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: m = 3, n = 2 +Output: 3 +Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: +1. Right -> Down -> Down +2. Down -> Down -> Right +3. Down -> Right -> Down +#+end_src + + +*Constraints:* + + - ~1 <= m, n <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def uniquePaths(self, m: int, n: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int uniquePaths(int m, int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0072-edit-distance.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0072-edit-distance.org index 513584a..fb747c4 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0072-edit-distance.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0072-edit-distance.org @@ -1,18 +1,68 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0072. Edit Distance :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0072. Edit Distance][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0072. Edit Distance][0072. Edit Distance]] :END: +Given two strings ~word1~ and ~word2~, return /the minimum number of operations required to convert ~word1~ to ~word2~/. + +You have the following three operations permitted on a word: + + - Insert a character + + - Delete a character + + - Replace a character + +*Example 1:* + + +#+begin_src +Input: word1 = "horse", word2 = "ros" +Output: 3 +Explanation: +horse -> rorse (replace 'h' with 'r') +rorse -> rose (remove 'r') +rose -> ros (remove 'e') +#+end_src + + +*Example 2:* + + +#+begin_src +Input: word1 = "intention", word2 = "execution" +Output: 5 +Explanation: +intention -> inention (remove 't') +inention -> enention (replace 'i' with 'e') +enention -> exention (replace 'n' with 'x') +exention -> exection (replace 'n' with 'c') +exection -> execution (insert 'u') +#+end_src + + +*Constraints:* + + - ~0 <= word1.length, word2.length <= 500~ + + - ~word1~ and ~word2~ consist of lowercase English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def minDistance(self, word1: str, word2: str) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int minDistance(string word1, string word2) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0097-interleaving-string.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0097-interleaving-string.org index a64efb6..c7e2cd1 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0097-interleaving-string.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0097-interleaving-string.org @@ -1,18 +1,80 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0097. Interleaving String :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0097. Interleaving String][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0097. Interleaving String][0097. Interleaving String]] :END: +Given strings ~s1~, ~s2~, and ~s3~, find whether ~s3~ is formed by an *interleaving* of ~s1~ and ~s2~. + +An *interleaving* of two strings ~s~ and ~t~ is a configuration where ~s~ and ~t~ are divided into ~n~ and ~m~ substrings respectively, such that: + + - ~s = s_{1} + s_{2} + ... + s_{n}~ + + - ~t = t_{1} + t_{2} + ... + t_{m}~ + + - ~|n - m| <= 1~ + + - The *interleaving* is ~s_{1} + t_{1} + s_{2} + t_{2} + s_{3} + t_{3} + ...~ or ~t_{1} + s_{1} + t_{2} + s_{2} + t_{3} + s_{3} + ...~ + +*Note:* ~a + b~ is the concatenation of strings ~a~ and ~b~. + +*Example 1:* + + +#+begin_src +Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" +Output: true +Explanation: One way to obtain s3 is: +Split s1 into s1 = "aa" + "bc" + "c", and s2 into s2 = "dbbc" + "a". +Interleaving the two splits, we get "aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac". +Since s3 can be obtained by interleaving s1 and s2, we return true. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" +Output: false +Explanation: Notice how it is impossible to interleave s2 with any other string to obtain s3. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: s1 = "", s2 = "", s3 = "" +Output: true +#+end_src + + +*Constraints:* + + - ~0 <= s1.length, s2.length <= 100~ + + - ~0 <= s3.length <= 200~ + + - ~s1~, ~s2~, and ~s3~ consist of lowercase English letters. + +*Follow up:* Could you solve it using only ~O(s2.length)~ additional memory space? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0115-distinct-subsequences.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0115-distinct-subsequences.org index a4b4149..29f3713 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0115-distinct-subsequences.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0115-distinct-subsequences.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0115. Distinct Subsequences :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0115. Distinct Subsequences][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0115. Distinct Subsequences][0115. Distinct Subsequences]] :END: +Given two strings s and t, return the number of distinct subsequences of s which equals t. + +The test cases are generated so that the answer fits on a 32-bit signed integer. + +*Example 1:* + + +#+begin_src +Input: s = "rabbbit", t = "rabbit" +Output: 3 +Explanation: +As shown below, there are 3 ways you can generate "rabbit" from s. +rabbbit +rabbbit +rabbbit +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "babgbag", t = "bag" +Output: 5 +Explanation: +As shown below, there are 5 ways you can generate "bag" from s. +babgbag +babgbag +babgbag +babgbag +babgbag +#+end_src + + +*Constraints:* + + - ~1 <= s.length, t.length <= 1000~ + + - ~s~ and ~t~ consist of English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def numDistinct(self, s: str, t: str) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int numDistinct(string s, string t) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0309-best-time-to-buy-and-sell-stock-with-cooldown.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0309-best-time-to-buy-and-sell-stock-with-cooldown.org index a1b8b0b..427cf55 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0309-best-time-to-buy-and-sell-stock-with-cooldown.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0309-best-time-to-buy-and-sell-stock-with-cooldown.org @@ -1,18 +1,57 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0309. Best Time to Buy And Sell Stock With Cooldown :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0309. Best Time to Buy And Sell Stock With Cooldown][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0309. Best Time to Buy And Sell Stock With Cooldown][0309. Best Time to Buy And Sell Stock With Cooldown]] :END: +You are given an array ~prices~ where ~prices[i]~ is the price of a given stock on the ~i^{th}~ day. + +Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: + + - After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). + +*Note:* You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). + +*Example 1:* + + +#+begin_src +Input: prices = [1,2,3,0,2] +Output: 3 +Explanation: transactions = [buy, sell, cooldown, buy, sell] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: prices = [1] +Output: 0 +#+end_src + + +*Constraints:* + + - ~1 <= prices.length <= 5000~ + + - ~0 <= prices[i] <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxProfit(self, prices: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int maxProfit(vector& prices) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0312-burst-balloons.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0312-burst-balloons.org index 1b3b77b..e60ae42 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0312-burst-balloons.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0312-burst-balloons.org @@ -1,18 +1,59 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0312. Burst Balloons :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0312. Burst Balloons][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0312. Burst Balloons][0312. Burst Balloons]] :END: +You are given ~n~ balloons, indexed from ~0~ to ~n - 1~. Each balloon is painted with a number on it represented by an array ~nums~. You are asked to burst all the balloons. + +If you burst the ~i^{th}~ balloon, you will get ~nums[i - 1] * nums[i] * nums[i + 1]~ coins. If ~i - 1~ or ~i + 1~ goes out of bounds of the array, then treat it as if there is a balloon with a ~1~ painted on it. + +Return /the maximum coins you can collect by bursting the balloons wisely/. + +*Example 1:* + + +#+begin_src +Input: nums = [3,1,5,8] +Output: 167 +Explanation: +nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] +coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [1,5] +Output: 10 +#+end_src + + +*Constraints:* + + - ~n == nums.length~ + + - ~1 <= n <= 300~ + + - ~0 <= nums[i] <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxCoins(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int maxCoins(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0329-longest-increasing-path-in-a-matrix.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0329-longest-increasing-path-in-a-matrix.org index cd54223..414f8c6 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0329-longest-increasing-path-in-a-matrix.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0329-longest-increasing-path-in-a-matrix.org @@ -1,18 +1,67 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0329. Longest Increasing Path In a Matrix :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0329. Longest Increasing Path In a Matrix][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0329. Longest Increasing Path In a Matrix][0329. Longest Increasing Path In a Matrix]] :END: +Given an ~m x n~ integers ~matrix~, return /the length of the longest increasing path in /~matrix~. + +From each cell, you can either move in four directions: left, right, up, or down. You *may not* move *diagonally* or move *outside the boundary* (i.e., wrap-around is not allowed). + +*Example 1:* + + +#+begin_src +Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] +Output: 4 +Explanation: The longest increasing path is [1, 2, 6, 9]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: matrix = [[3,4,5],[3,2,6],[2,2,1]] +Output: 4 +Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: matrix = [[1]] +Output: 1 +#+end_src + + +*Constraints:* + + - ~m == matrix.length~ + + - ~n == matrix[i].length~ + + - ~1 <= m, n <= 200~ + + - ~0 <= matrix[i][j] <= 2^{31} - 1~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def longestIncreasingPath(self, matrix: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int longestIncreasingPath(vector>& matrix) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0494-target-sum.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0494-target-sum.org index 6ea8493..b4324b6 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0494-target-sum.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0494-target-sum.org @@ -1,18 +1,66 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0494. Target Sum :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0494. Target Sum][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0494. Target Sum][0494. Target Sum]] :END: +You are given an integer array ~nums~ and an integer ~target~. + +You want to build an *expression* out of nums by adding one of the symbols ~'+'~ and ~'-'~ before each integer in nums and then concatenate all the integers. + + - For example, if ~nums = [2, 1]~, you can add a ~'+'~ before ~2~ and a ~'-'~ before ~1~ and concatenate them to build the expression ~"+2-1"~. + +Return the number of different *expressions* that you can build, which evaluates to ~target~. + +*Example 1:* + + +#+begin_src +Input: nums = [1,1,1,1,1], target = 3 +Output: 5 +Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3. +-1 + 1 + 1 + 1 + 1 = 3 ++1 - 1 + 1 + 1 + 1 = 3 ++1 + 1 - 1 + 1 + 1 = 3 ++1 + 1 + 1 - 1 + 1 = 3 ++1 + 1 + 1 + 1 - 1 = 3 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [1], target = 1 +Output: 1 +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 20~ + + - ~0 <= nums[i] <= 1000~ + + - ~0 <= sum(nums[i]) <= 1000~ + + - ~-1000 <= target <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/0518-coin-change-ii.org b/org/study_deck_02/dsa/2-d-dynamic-programming/0518-coin-change-ii.org index a1590ac..8a21757 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/0518-coin-change-ii.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/0518-coin-change-ii.org @@ -1,18 +1,75 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0518. Coin Change II :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0518. Coin Change II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0518. Coin Change II][0518. Coin Change II]] :END: +You are given an integer array ~coins~ representing coins of different denominations and an integer ~amount~ representing a total amount of money. + +Return /the number of combinations that make up that amount/. If that amount of money cannot be made up by any combination of the coins, return ~0~. + +You may assume that you have an infinite number of each kind of coin. + +The answer is *guaranteed* to fit into a signed *32-bit* integer. + +*Example 1:* + + +#+begin_src +Input: amount = 5, coins = [1,2,5] +Output: 4 +Explanation: there are four ways to make up the amount: +5=5 +5=2+2+1 +5=2+1+1+1 +5=1+1+1+1+1 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: amount = 3, coins = [2] +Output: 0 +Explanation: the amount of 3 cannot be made up just with coins of 2. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: amount = 10, coins = [10] +Output: 1 +#+end_src + + +*Constraints:* + + - ~1 <= coins.length <= 300~ + + - ~1 <= coins[i] <= 5000~ + + - All the values of ~coins~ are *unique*. + + - ~0 <= amount <= 5000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def change(self, amount: int, coins: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int change(int amount, vector& coins) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/1143-longest-common-subsequence.org b/org/study_deck_02/dsa/2-d-dynamic-programming/1143-longest-common-subsequence.org index eb795cd..b4fb9c6 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/1143-longest-common-subsequence.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/1143-longest-common-subsequence.org @@ -1,18 +1,68 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1143. Longest Common Subsequence :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1143. Longest Common Subsequence][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1143. Longest Common Subsequence][1143. Longest Common Subsequence]] :END: +Given two strings ~text1~ and ~text2~, return /the length of their longest *common subsequence*. /If there is no *common subsequence*, return ~0~. + +A *subsequence* of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + + - For example, ~"ace"~ is a subsequence of ~"abcde"~. + +A *common subsequence* of two strings is a subsequence that is common to both strings. + +*Example 1:* + + +#+begin_src +Input: text1 = "abcde", text2 = "ace" +Output: 3 +Explanation: The longest common subsequence is "ace" and its length is 3. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: text1 = "abc", text2 = "abc" +Output: 3 +Explanation: The longest common subsequence is "abc" and its length is 3. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: text1 = "abc", text2 = "def" +Output: 0 +Explanation: There is no such common subsequence, so the result is 0. +#+end_src + + +*Constraints:* + + - ~1 <= text1.length, text2.length <= 1000~ + + - ~text1~ and ~text2~ consist of only lowercase English characters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/1220-count-vowels-permutation.org b/org/study_deck_02/dsa/2-d-dynamic-programming/1220-count-vowels-permutation.org index 09c784e..6d90370 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/1220-count-vowels-permutation.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/1220-count-vowels-permutation.org @@ -1,18 +1,73 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1220. Count Vowels Permutation :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1220. Count Vowels Permutation][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1220. Count Vowels Permutation][1220. Count Vowels Permutation]] :END: +Given an integer ~n~, your task is to count how many strings of length ~n~ can be formed under the following rules: + + - Each character is a lower case vowel (~'a'~, ~'e'~, ~'i'~, ~'o'~, ~'u'~) + + - Each vowel ~'a'~ may only be followed by an ~'e'~. + + - Each vowel ~'e'~ may only be followed by an ~'a'~ or an ~'i'~. + + - Each vowel ~'i'~ *may not* be followed by another ~'i'~. + + - Each vowel ~'o'~ may only be followed by an ~'i'~ or a ~'u'~. + + - Each vowel ~'u'~ may only be followed by an ~'a'~. + +Since the answer may be too large, return it modulo ~10^9 + 7~. + +*Example 1:* + + +#+begin_src +Input: n = 1 +Output: 5 +Explanation: All possible strings are: "a", "e", "i" , "o" and "u". +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 2 +Output: 10 +Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua". +#+end_src + + +*Example 3: * + + +#+begin_src +Input: n = 5 +Output: 68 +#+end_src + + +*Constraints:* + + - ~1 <= n <= 2 * 10^4~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def countVowelPermutation(self, n: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int countVowelPermutation(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/2-d-dynamic-programming/1911-maximum-alternating-subsequence-sum.org b/org/study_deck_02/dsa/2-d-dynamic-programming/1911-maximum-alternating-subsequence-sum.org index 0336926..8f6ccb6 100644 --- a/org/study_deck_02/dsa/2-d-dynamic-programming/1911-maximum-alternating-subsequence-sum.org +++ b/org/study_deck_02/dsa/2-d-dynamic-programming/1911-maximum-alternating-subsequence-sum.org @@ -1,18 +1,68 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1911. Maximum Alternating Subsequence Sum :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1911. Maximum Alternating Subsequence Sum][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1911. Maximum Alternating Subsequence Sum][1911. Maximum Alternating Subsequence Sum]] :END: +The *alternating sum* of a *0-indexed* array is defined as the *sum* of the elements at *even* indices *minus* the *sum* of the elements at *odd* indices. + + - For example, the alternating sum of ~[4,2,5,3]~ is ~(4 + 5) - (2 + 3) = 4~. + +Given an array ~nums~, return /the *maximum alternating sum* of any subsequence of /~nums~/ (after *reindexing* the elements of the subsequence)/. + +A *subsequence* of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, ~[2,7,4]~ is a subsequence of ~[4,2,3,7,2,1,4]~ (the underlined elements), while ~[2,4,2]~ is not. + +*Example 1:* + + +#+begin_src +Input: nums = [4,2,5,3] +Output: 7 +Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [5,6,7,8] +Output: 8 +Explanation: It is optimal to choose the subsequence [8] with alternating sum 8. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [6,2,1,2,4,5] +Output: 10 +Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10. +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 10^{5}~ + + - ~1 <= nums[i] <= 10^{5}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxAlternatingSum(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + long long maxAlternatingSum(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/advanced-graphs/0269-alien-dictionary.org b/org/study_deck_02/dsa/advanced-graphs/0269-alien-dictionary.org index 12a0376..ef3b8a8 100644 --- a/org/study_deck_02/dsa/advanced-graphs/0269-alien-dictionary.org +++ b/org/study_deck_02/dsa/advanced-graphs/0269-alien-dictionary.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0269. Alien Dictionary :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0269. Alien Dictionary][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0269. Alien Dictionary][0269. Alien Dictionary]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/advanced-graphs/0332-reconstruct-itinerary.org b/org/study_deck_02/dsa/advanced-graphs/0332-reconstruct-itinerary.org index e0b8aa1..b4697c3 100644 --- a/org/study_deck_02/dsa/advanced-graphs/0332-reconstruct-itinerary.org +++ b/org/study_deck_02/dsa/advanced-graphs/0332-reconstruct-itinerary.org @@ -1,18 +1,65 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0332. Reconstruct Itinerary :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0332. Reconstruct Itinerary][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0332. Reconstruct Itinerary][0332. Reconstruct Itinerary]] :END: +You are given a list of airline ~tickets~ where ~tickets[i] = [from_{i}, to_{i}]~ represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. + +All of the tickets belong to a man who departs from ~"JFK"~, thus, the itinerary must begin with ~"JFK"~. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. + + - For example, the itinerary ~["JFK", "LGA"]~ has a smaller lexical order than ~["JFK", "LGB"]~. + +You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. + +*Example 1:* + + +#+begin_src +Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] +Output: ["JFK","MUC","LHR","SFO","SJC"] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] +Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] +Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order. +#+end_src + + +*Constraints:* + + - ~1 <= tickets.length <= 300~ + + - ~tickets[i].length == 2~ + + - ~from_{i}.length == 3~ + + - ~to_{i}.length == 3~ + + - ~from_{i}~ and ~to_{i}~ consist of uppercase English letters. + + - ~from_{i} != to_{i}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findItinerary(self, tickets: List[List[str]]) -> List[str]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector findItinerary(vector>& tickets) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/advanced-graphs/0743-network-delay-time.org b/org/study_deck_02/dsa/advanced-graphs/0743-network-delay-time.org index 0d0ed90..a3bb3e4 100644 --- a/org/study_deck_02/dsa/advanced-graphs/0743-network-delay-time.org +++ b/org/study_deck_02/dsa/advanced-graphs/0743-network-delay-time.org @@ -1,18 +1,71 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0743. Network Delay Time :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0743. Network Delay Time][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0743. Network Delay Time][0743. Network Delay Time]] :END: +You are given a network of ~n~ nodes, labeled from ~1~ to ~n~. You are also given ~times~, a list of travel times as directed edges ~times[i] = (u_{i}, v_{i}, w_{i})~, where ~u_{i}~ is the source node, ~v_{i}~ is the target node, and ~w_{i}~ is the time it takes for a signal to travel from source to target. + +We will send a signal from a given node ~k~. Return /the *minimum* time it takes for all the/ ~n~ /nodes to receive the signal/. If it is impossible for all the ~n~ nodes to receive the signal, return ~-1~. + +*Example 1:* + + +#+begin_src +Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 +Output: 2 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: times = [[1,2,1]], n = 2, k = 1 +Output: 1 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: times = [[1,2,1]], n = 2, k = 2 +Output: -1 +#+end_src + + +*Constraints:* + + - ~1 <= k <= n <= 100~ + + - ~1 <= times.length <= 6000~ + + - ~times[i].length == 3~ + + - ~1 <= u_{i}, v_{i} <= n~ + + - ~u_{i} != v_{i}~ + + - ~0 <= w_{i} <= 100~ + + - All the pairs ~(u_{i}, v_{i})~ are *unique*. (i.e., no multiple edges.) + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int networkDelayTime(vector>& times, int n, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/advanced-graphs/0778-swim-in-rising-water.org b/org/study_deck_02/dsa/advanced-graphs/0778-swim-in-rising-water.org index 70911e6..5c99a13 100644 --- a/org/study_deck_02/dsa/advanced-graphs/0778-swim-in-rising-water.org +++ b/org/study_deck_02/dsa/advanced-graphs/0778-swim-in-rising-water.org @@ -1,18 +1,69 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0778. Swim In Rising Water :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0778. Swim In Rising Water][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0778. Swim In Rising Water][0778. Swim In Rising Water]] :END: +You are given an ~n x n~ integer matrix ~grid~ where each value ~grid[i][j]~ represents the elevation at that point ~(i, j)~. + +It starts raining, and water gradually rises over time. At time ~t~, the water level is ~t~, meaning *any* cell with elevation less than equal to ~t~ is submerged or reachable. + +You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most ~t~. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. + +Return /the minimum time until you can reach the bottom right square /~(n - 1, n - 1)~/ if you start at the top left square /~(0, 0)~. + +*Example 1:* + + +#+begin_src +Input: grid = [[0,2],[1,3]] +Output: 3 +Explanation: +At time 0, you are in grid location (0, 0). +You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. +You cannot reach point (1, 1) until time 3. +When the depth of water is 3, we can swim anywhere inside the grid. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] +Output: 16 +Explanation: The final route is shown. +We need to wait until time 16 so that (0, 0) and (4, 4) are connected. +#+end_src + + +*Constraints:* + + - ~n == grid.length~ + + - ~n == grid[i].length~ + + - ~1 <= n <= 50~ + + - ~0 <= grid[i][j] < n^{2}~ + + - Each value ~grid[i][j]~ is *unique*. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def swimInWater(self, grid: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int swimInWater(vector>& grid) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/advanced-graphs/0787-cheapest-flights-within-k-stops.org b/org/study_deck_02/dsa/advanced-graphs/0787-cheapest-flights-within-k-stops.org index 14ac418..96c71b4 100644 --- a/org/study_deck_02/dsa/advanced-graphs/0787-cheapest-flights-within-k-stops.org +++ b/org/study_deck_02/dsa/advanced-graphs/0787-cheapest-flights-within-k-stops.org @@ -1,18 +1,85 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0787. Cheapest Flights Within K Stops :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0787. Cheapest Flights Within K Stops][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0787. Cheapest Flights Within K Stops][0787. Cheapest Flights Within K Stops]] :END: +There are ~n~ cities connected by some number of flights. You are given an array ~flights~ where ~flights[i] = [from_{i}, to_{i}, price_{i}]~ indicates that there is a flight from city ~from_{i}~ to city ~to_{i}~ with cost ~price_{i}~. + +You are also given three integers ~src~, ~dst~, and ~k~, return /*the cheapest price* from /~src~/ to /~dst~/ with at most /~k~/ stops. /If there is no such route, return/ /~-1~. + +*Example 1:* + + +#+begin_src +Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 +Output: 700 +Explanation: +The graph is shown above. +The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. +Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 +Output: 200 +Explanation: +The graph is shown above. +The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 +Output: 500 +Explanation: +The graph is shown above. +The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. +#+end_src + + +*Constraints:* + + - ~2 <= n <= 100~ + + - ~0 <= flights.length <= (n * (n - 1) / 2)~ + + - ~flights[i].length == 3~ + + - ~0 <= from_{i}, to_{i} < n~ + + - ~from_{i} != to_{i}~ + + - ~1 <= price_{i} <= 10^{4}~ + + - There will not be any multiple flights between two cities. + + - ~0 <= src, dst, k < n~ + + - ~src != dst~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/advanced-graphs/1584-min-cost-to-connect-all-points.org b/org/study_deck_02/dsa/advanced-graphs/1584-min-cost-to-connect-all-points.org index febe742..ea1181c 100644 --- a/org/study_deck_02/dsa/advanced-graphs/1584-min-cost-to-connect-all-points.org +++ b/org/study_deck_02/dsa/advanced-graphs/1584-min-cost-to-connect-all-points.org @@ -1,18 +1,60 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1584. Min Cost to Connect All Points :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1584. Min Cost to Connect All Points][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1584. Min Cost to Connect All Points][1584. Min Cost to Connect All Points]] :END: +You are given an array ~points~ representing integer coordinates of some points on a 2D-plane, where ~points[i] = [x_{i}, y_{i}]~. + +The cost of connecting two points ~[x_{i}, y_{i}]~ and ~[x_{j}, y_{j}]~ is the *manhattan distance* between them: ~|x_{i} - x_{j}| + |y_{i} - y_{j}|~, where ~|val|~ denotes the absolute value of ~val~. + +Return /the minimum cost to make all points connected./ All points are connected if there is *exactly one* simple path between any two points. + +*Example 1:* + + +#+begin_src +Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] +Output: 20 +Explanation: + +We can connect the points as shown above to get the minimum cost of 20. +Notice that there is a unique path between every pair of points. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: points = [[3,12],[-2,5],[-4,1]] +Output: 18 +#+end_src + + +*Constraints:* + + - ~1 <= points.length <= 1000~ + + - ~-10^{6} <= x_{i}, y_{i} <= 10^{6}~ + + - All pairs ~(x_{i}, y_{i})~ are distinct. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def minCostConnectPoints(self, points: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int minCostConnectPoints(vector>& points) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/advanced-graphs/2493-divide-nodes-into-the-maximum-number-of-groups.org b/org/study_deck_02/dsa/advanced-graphs/2493-divide-nodes-into-the-maximum-number-of-groups.org index ac9bdca..8b0f4d7 100644 --- a/org/study_deck_02/dsa/advanced-graphs/2493-divide-nodes-into-the-maximum-number-of-groups.org +++ b/org/study_deck_02/dsa/advanced-graphs/2493-divide-nodes-into-the-maximum-number-of-groups.org @@ -1,18 +1,77 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2493. Divide Nodes Into the Maximum Number of Groups :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2493. Divide Nodes Into the Maximum Number of Groups][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2493. Divide Nodes Into the Maximum Number of Groups][2493. Divide Nodes Into the Maximum Number of Groups]] :END: +You are given a positive integer ~n~ representing the number of nodes in an *undirected* graph. The nodes are labeled from ~1~ to ~n~. + +You are also given a 2D integer array ~edges~, where ~edges[i] = [a_{i, }b_{i}]~ indicates that there is a *bidirectional* edge between nodes ~a_{i}~ and ~b_{i}~. *Notice* that the given graph may be disconnected. + +Divide the nodes of the graph into ~m~ groups (*1-indexed*) such that: + + - Each node in the graph belongs to exactly one group. + + - For every pair of nodes in the graph that are connected by an edge ~[a_{i, }b_{i}]~, if ~a_{i}~ belongs to the group with index ~x~, and ~b_{i}~ belongs to the group with index ~y~, then ~|y - x| = 1~. + +Return /the maximum number of groups (i.e., maximum /~m~/) into which you can divide the nodes/. Return ~-1~ /if it is impossible to group the nodes with the given conditions/. + +*Example 1:* + + +#+begin_src +Input: n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]] +Output: 4 +Explanation: As shown in the image we: +- Add node 5 to the first group. +- Add node 1 to the second group. +- Add nodes 2 and 4 to the third group. +- Add nodes 3 and 6 to the fourth group. +We can see that every edge is satisfied. +It can be shown that that if we create a fifth group and move any node from the third or fourth group to it, at least on of the edges will not be satisfied. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 3, edges = [[1,2],[2,3],[3,1]] +Output: -1 +Explanation: If we add node 1 to the first group, node 2 to the second group, and node 3 to the third group to satisfy the first two edges, we can see that the third edge will not be satisfied. +It can be shown that no grouping is possible. +#+end_src + + +*Constraints:* + + - ~1 <= n <= 500~ + + - ~1 <= edges.length <= 10^{4}~ + + - ~edges[i].length == 2~ + + - ~1 <= a_{i}, b_{i} <= n~ + + - ~a_{i} != b_{i}~ + + - There is at most one edge between any pair of vertices. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def magnificentSets(self, n: int, edges: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int magnificentSets(int n, vector>& edges) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/advanced-graphs/2812-find-the-safest-path-in-a-grid.org b/org/study_deck_02/dsa/advanced-graphs/2812-find-the-safest-path-in-a-grid.org index bd682d3..bfea644 100644 --- a/org/study_deck_02/dsa/advanced-graphs/2812-find-the-safest-path-in-a-grid.org +++ b/org/study_deck_02/dsa/advanced-graphs/2812-find-the-safest-path-in-a-grid.org @@ -1,18 +1,85 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2812. Find the Safest Path in a Grid :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2812. Find the Safest Path in a Grid][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2812. Find the Safest Path in a Grid][2812. Find the Safest Path in a Grid]] :END: +You are given a *0-indexed* 2D matrix ~grid~ of size ~n x n~, where ~(r, c)~ represents: + + - A cell containing a thief if ~grid[r][c] = 1~ + + - An empty cell if ~grid[r][c] = 0~ + +You are initially positioned at cell ~(0, 0)~. In one move, you can move to any adjacent cell in the grid, including cells containing thieves. + +The *safeness factor* of a path on the grid is defined as the *minimum* manhattan distance from any cell in the path to any thief in the grid. + +Return /the *maximum safeness factor* of all paths leading to cell /~(n - 1, n - 1)~/./ + +An *adjacent* cell of cell ~(r, c)~, is one of the cells ~(r, c + 1)~, ~(r, c - 1)~, ~(r + 1, c)~ and ~(r - 1, c)~ if it exists. + +The *Manhattan distance* between two cells ~(a, b)~ and ~(x, y)~ is equal to ~|a - x| + |b - y|~, where ~|val|~ denotes the absolute value of val. + +*Example 1:* + + +#+begin_src +Input: grid = [[1,0,0],[0,0,0],[0,0,1]] +Output: 0 +Explanation: All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1). +#+end_src + + +*Example 2:* + + +#+begin_src +Input: grid = [[0,0,1],[0,0,0],[0,0,0]] +Output: 2 +Explanation: The path depicted in the picture above has a safeness factor of 2 since: +- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2. +It can be shown that there are no other paths with a higher safeness factor. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]] +Output: 2 +Explanation: The path depicted in the picture above has a safeness factor of 2 since: +- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2. +- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2. +It can be shown that there are no other paths with a higher safeness factor. +#+end_src + + +*Constraints:* + + - ~1 <= grid.length == n <= 400~ + + - ~grid[i].length == n~ + + - ~grid[i][j]~ is either ~0~ or ~1~. + + - There is at least one thief in the ~grid~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maximumSafenessFactor(self, grid: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int maximumSafenessFactor(vector>& grid) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/0001-two-sum.org b/org/study_deck_02/dsa/arrays-hashing/0001-two-sum.org index d42d185..6381dd9 100644 --- a/org/study_deck_02/dsa/arrays-hashing/0001-two-sum.org +++ b/org/study_deck_02/dsa/arrays-hashing/0001-two-sum.org @@ -1,18 +1,70 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0001. Two Sum :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0001. Two Sum][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0001. Two Sum][0001. Two Sum]] :END: +Given an array of integers ~nums~ and an integer ~target~, return /indices of the two numbers such that they add up to ~target~/. + +You may assume that each input would have */exactly/ one solution*, and you may not use the /same/ element twice. + +You can return the answer in any order. + +*Example 1:* + + +#+begin_src +Input: nums = [2,7,11,15], target = 9 +Output: [0,1] +Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [3,2,4], target = 6 +Output: [1,2] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [3,3], target = 6 +Output: [0,1] +#+end_src + + +*Constraints:* + + - ~2 <= nums.length <= 10^{4}~ + + - ~-10^{9} <= nums[i] <= 10^{9}~ + + - ~-10^{9} <= target <= 10^{9}~ + + - *Only one valid answer exists.* + +*Follow-up: *Can you come up with an algorithm that is less than ~O(n^{2})~ time complexity? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector twoSum(vector& nums, int target) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/0036-valid-sudoku.org b/org/study_deck_02/dsa/arrays-hashing/0036-valid-sudoku.org index 8efda1a..f8f83c1 100644 --- a/org/study_deck_02/dsa/arrays-hashing/0036-valid-sudoku.org +++ b/org/study_deck_02/dsa/arrays-hashing/0036-valid-sudoku.org @@ -1,18 +1,83 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0036. Valid Sudoku :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0036. Valid Sudoku][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0036. Valid Sudoku][0036. Valid Sudoku]] :END: +Determine if a ~9 x 9~ Sudoku board is valid. Only the filled cells need to be validated *according to the following rules*: + + - Each row must contain the digits ~1-9~ without repetition. + + - Each column must contain the digits ~1-9~ without repetition. + + - Each of the nine ~3 x 3~ sub-boxes of the grid must contain the digits ~1-9~ without repetition. + +*Note:* + + - A Sudoku board (partially filled) could be valid but is not necessarily solvable. + + - Only the filled cells need to be validated according to the mentioned rules. + +*Example 1:* + + +#+begin_src +Input: board = +[["5","3",".",".","7",".",".",".","."] +,["6",".",".","1","9","5",".",".","."] +,[".","9","8",".",".",".",".","6","."] +,["8",".",".",".","6",".",".",".","3"] +,["4",".",".","8",".","3",".",".","1"] +,["7",".",".",".","2",".",".",".","6"] +,[".","6",".",".",".",".","2","8","."] +,[".",".",".","4","1","9",".",".","5"] +,[".",".",".",".","8",".",".","7","9"]] +Output: true +#+end_src + + +*Example 2:* + + +#+begin_src +Input: board = +[["8","3",".",".","7",".",".",".","."] +,["6",".",".","1","9","5",".",".","."] +,[".","9","8",".",".",".",".","6","."] +,["8",".",".",".","6",".",".",".","3"] +,["4",".",".","8",".","3",".",".","1"] +,["7",".",".",".","2",".",".",".","6"] +,[".","6",".",".",".",".","2","8","."] +,[".",".",".","4","1","9",".",".","5"] +,[".",".",".",".","8",".",".","7","9"]] +Output: false +Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. +#+end_src + + +*Constraints:* + + - ~board.length == 9~ + + - ~board[i].length == 9~ + + - ~board[i][j]~ is a digit ~1-9~ or ~'.'~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isValidSudoku(vector>& board) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/0049-group-anagrams.org b/org/study_deck_02/dsa/arrays-hashing/0049-group-anagrams.org index ad3c24d..dbcbeb3 100644 --- a/org/study_deck_02/dsa/arrays-hashing/0049-group-anagrams.org +++ b/org/study_deck_02/dsa/arrays-hashing/0049-group-anagrams.org @@ -1,18 +1,60 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0049. Group Anagrams :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0049. Group Anagrams][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0049. Group Anagrams][0049. Group Anagrams]] :END: +Given an array of strings ~strs~, group the anagrams together. You can return the answer in *any order*. + +*Example 1:* + +*Input:* strs = ["eat","tea","tan","ate","nat","bat"] + +*Output:* [["bat"],["nat","tan"],["ate","eat","tea"]] + +*Explanation:* + + - There is no string in strs that can be rearranged to form ~"bat"~. + + - The strings ~"nat"~ and ~"tan"~ are anagrams as they can be rearranged to form each other. + + - The strings ~"ate"~, ~"eat"~, and ~"tea"~ are anagrams as they can be rearranged to form each other. + +*Example 2:* + +*Input:* strs = [""] + +*Output:* [[""]] + +*Example 3:* + +*Input:* strs = ["a"] + +*Output:* [["a"]] + +*Constraints:* + + - ~1 <= strs.length <= 10^{4}~ + + - ~0 <= strs[i].length <= 100~ + + - ~strs[i]~ consists of lowercase English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> groupAnagrams(vector& strs) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/0128-longest-consecutive-sequence.org b/org/study_deck_02/dsa/arrays-hashing/0128-longest-consecutive-sequence.org index 968a05b..79d7a61 100644 --- a/org/study_deck_02/dsa/arrays-hashing/0128-longest-consecutive-sequence.org +++ b/org/study_deck_02/dsa/arrays-hashing/0128-longest-consecutive-sequence.org @@ -1,18 +1,62 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0128. Longest Consecutive Sequence :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0128. Longest Consecutive Sequence][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0128. Longest Consecutive Sequence][0128. Longest Consecutive Sequence]] :END: +Given an unsorted array of integers ~nums~, return /the length of the longest consecutive elements sequence./ + +You must write an algorithm that runs in ~O(n)~ time. + +*Example 1:* + + +#+begin_src +Input: nums = [100,4,200,1,3,2] +Output: 4 +Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [0,3,7,2,5,8,4,6,0,1] +Output: 9 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [1,0,1,2] +Output: 3 +#+end_src + + +*Constraints:* + + - ~0 <= nums.length <= 10^{5}~ + + - ~-10^{9} <= nums[i] <= 10^{9}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int longestConsecutive(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/0217-contains-duplicate.org b/org/study_deck_02/dsa/arrays-hashing/0217-contains-duplicate.org index b33cea0..8d5701b 100644 --- a/org/study_deck_02/dsa/arrays-hashing/0217-contains-duplicate.org +++ b/org/study_deck_02/dsa/arrays-hashing/0217-contains-duplicate.org @@ -1,18 +1,58 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0217. Contains Duplicate :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0217. Contains Duplicate][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0217. Contains Duplicate][0217. Contains Duplicate]] :END: +Given an integer array ~nums~, return ~true~ if any value appears *at least twice* in the array, and return ~false~ if every element is distinct. + +*Example 1:* + +*Input:* nums = [1,2,3,1] + +*Output:* true + +*Explanation:* + +The element 1 occurs at the indices 0 and 3. + +*Example 2:* + +*Input:* nums = [1,2,3,4] + +*Output:* false + +*Explanation:* + +All elements are distinct. + +*Example 3:* + +*Input:* nums = [1,1,1,3,3,4,3,2,4,2] + +*Output:* true + +*Constraints:* + + - ~1 <= nums.length <= 10^{5}~ + + - ~-10^{9} <= nums[i] <= 10^{9}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool containsDuplicate(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/0238-product-of-array-except-self.org b/org/study_deck_02/dsa/arrays-hashing/0238-product-of-array-except-self.org index d0eca5a..a5caef2 100644 --- a/org/study_deck_02/dsa/arrays-hashing/0238-product-of-array-except-self.org +++ b/org/study_deck_02/dsa/arrays-hashing/0238-product-of-array-except-self.org @@ -1,18 +1,56 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0238. Product of Array Except Self :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0238. Product of Array Except Self][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0238. Product of Array Except Self][0238. Product of Array Except Self]] :END: +Given an integer array ~nums~, return /an array/ ~answer~ /such that/ ~answer[i]~ /is equal to the product of all the elements of/ ~nums~ /except/ ~nums[i]~. + +The product of any prefix or suffix of ~nums~ is *guaranteed* to fit in a *32-bit* integer. + +You must write an algorithm that runs in ~O(n)~ time and without using the division operation. + +*Example 1:* + + +#+begin_src +Input: nums = [1,2,3,4] +Output: [24,12,8,6] +#+end_src +*Example 2:* + + +#+begin_src +Input: nums = [-1,1,0,-3,3] +Output: [0,0,9,0,0] +#+end_src + + +*Constraints:* + + - ~2 <= nums.length <= 10^{5}~ + + - ~-30 <= nums[i] <= 30~ + + - The input is generated such that ~answer[i]~ is *guaranteed* to fit in a *32-bit* integer. + +*Follow up:* Can you solve the problem in ~O(1)~ extra space complexity? (The output array *does not* count as extra space for space complexity analysis.) + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector productExceptSelf(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/0242-valid-anagram.org b/org/study_deck_02/dsa/arrays-hashing/0242-valid-anagram.org index dc1d9bb..a3c9ec9 100644 --- a/org/study_deck_02/dsa/arrays-hashing/0242-valid-anagram.org +++ b/org/study_deck_02/dsa/arrays-hashing/0242-valid-anagram.org @@ -1,18 +1,46 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0242. Valid Anagram :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0242. Valid Anagram][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0242. Valid Anagram][0242. Valid Anagram]] :END: +Given two strings ~s~ and ~t~, return ~true~ if ~t~ is an anagram of ~s~, and ~false~ otherwise. + +*Example 1:* + +*Input:* s = "anagram", t = "nagaram" + +*Output:* true + +*Example 2:* + +*Input:* s = "rat", t = "car" + +*Output:* false + +*Constraints:* + + - ~1 <= s.length, t.length <= 5 * 10^{4}~ + + - ~s~ and ~t~ consist of lowercase English letters. + +*Follow up:* What if the inputs contain Unicode characters? How would you adapt your solution to such a case? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isAnagram(self, s: str, t: str) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isAnagram(string s, string t) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/0271-encode-and-decode-strings.org b/org/study_deck_02/dsa/arrays-hashing/0271-encode-and-decode-strings.org index eb2ca70..6204152 100644 --- a/org/study_deck_02/dsa/arrays-hashing/0271-encode-and-decode-strings.org +++ b/org/study_deck_02/dsa/arrays-hashing/0271-encode-and-decode-strings.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0271. Encode and Decode Strings :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0271. Encode and Decode Strings][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0271. Encode and Decode Strings][0271. Encode and Decode Strings]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/arrays-hashing/0347-top-k-frequent-elements.org b/org/study_deck_02/dsa/arrays-hashing/0347-top-k-frequent-elements.org index e074396..63a5772 100644 --- a/org/study_deck_02/dsa/arrays-hashing/0347-top-k-frequent-elements.org +++ b/org/study_deck_02/dsa/arrays-hashing/0347-top-k-frequent-elements.org @@ -1,18 +1,56 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0347. Top K Frequent Elements :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0347. Top K Frequent Elements][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0347. Top K Frequent Elements][0347. Top K Frequent Elements]] :END: +Given an integer array ~nums~ and an integer ~k~, return /the/ ~k~ /most frequent elements/. You may return the answer in *any order*. + +*Example 1:* + +*Input:* nums = [1,1,1,2,2,3], k = 2 + +*Output:* [1,2] + +*Example 2:* + +*Input:* nums = [1], k = 1 + +*Output:* [1] + +*Example 3:* + +*Input:* nums = [1,2,1,2,1,2,3,1,3,2], k = 2 + +*Output:* [1,2] + +*Constraints:* + + - ~1 <= nums.length <= 10^{5}~ + + - ~-10^{4} <= nums[i] <= 10^{4}~ + + - ~k~ is in the range ~[1, the number of unique elements in the array]~. + + - It is *guaranteed* that the answer is *unique*. + +*Follow up:* Your algorithm's time complexity must be better than ~O(n log n)~, where n is the array's size. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/1408-string-matching-in-an-array.org b/org/study_deck_02/dsa/arrays-hashing/1408-string-matching-in-an-array.org index 1ba3077..d076b6c 100644 --- a/org/study_deck_02/dsa/arrays-hashing/1408-string-matching-in-an-array.org +++ b/org/study_deck_02/dsa/arrays-hashing/1408-string-matching-in-an-array.org @@ -1,18 +1,67 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1408. String Matching in an Array :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1408. String Matching in an Array][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1408. String Matching in an Array][1408. String Matching in an Array]] :END: +Given an array of string ~words~, return all strings in/ /~words~/ /that are a substring of another word. You can return the answer in *any order*. + +*Example 1:* + + +#+begin_src +Input: words = ["mass","as","hero","superhero"] +Output: ["as","hero"] +Explanation: "as" is substring of "mass" and "hero" is substring of "superhero". +["hero","as"] is also a valid answer. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: words = ["leetcode","et","code"] +Output: ["et","code"] +Explanation: "et", "code" are substring of "leetcode". +#+end_src + + +*Example 3:* + + +#+begin_src +Input: words = ["blue","green","bu"] +Output: [] +Explanation: No string of words is substring of another string. +#+end_src + + +*Constraints:* + + - ~1 <= words.length <= 100~ + + - ~1 <= words[i].length <= 30~ + + - ~words[i]~ contains only lowercase English letters. + + - All the strings of ~words~ are *unique*. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def stringMatching(self, words: List[str]) -> List[str]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector stringMatching(vector& words) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.org b/org/study_deck_02/dsa/arrays-hashing/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.org index 452c2c2..292d48f 100644 --- a/org/study_deck_02/dsa/arrays-hashing/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.org +++ b/org/study_deck_02/dsa/arrays-hashing/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.org @@ -1,18 +1,62 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1769. Minimum Number of Operations to Move All Balls to Each Box :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1769. Minimum Number of Operations to Move All Balls to Each Box][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1769. Minimum Number of Operations to Move All Balls to Each Box][1769. Minimum Number of Operations to Move All Balls to Each Box]] :END: +You have ~n~ boxes. You are given a binary string ~boxes~ of length ~n~, where ~boxes[i]~ is ~'0'~ if the ~i^{th}~ box is *empty*, and ~'1'~ if it contains *one* ball. + +In one operation, you can move *one* ball from a box to an adjacent box. Box ~i~ is adjacent to box ~j~ if ~abs(i - j) == 1~. Note that after doing so, there may be more than one ball in some boxes. + +Return an array ~answer~ of size ~n~, where ~answer[i]~ is the *minimum* number of operations needed to move all the balls to the ~i^{th}~ box. + +Each ~answer[i]~ is calculated considering the *initial* state of the boxes. + +*Example 1:* + + +#+begin_src +Input: boxes = "110" +Output: [1,1,3] +Explanation: The answer for each box is as follows: +1) First box: you will have to move one ball from the second box to the first box in one operation. +2) Second box: you will have to move one ball from the first box to the second box in one operation. +3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: boxes = "001011" +Output: [11,8,5,4,3,4] +#+end_src + + +*Constraints:* + + - ~n == boxes.length~ + + - ~1 <= n <= 2000~ + + - ~boxes[i]~ is either ~'0'~ or ~'1'~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def minOperations(self, boxes: str) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector minOperations(string boxes) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/arrays-hashing/2678-number-of-senior-citizens.org b/org/study_deck_02/dsa/arrays-hashing/2678-number-of-senior-citizens.org index 94ccddc..6367e5a 100644 --- a/org/study_deck_02/dsa/arrays-hashing/2678-number-of-senior-citizens.org +++ b/org/study_deck_02/dsa/arrays-hashing/2678-number-of-senior-citizens.org @@ -1,18 +1,68 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2678. Number of Senior Citizens :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2678. Number of Senior Citizens][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2678. Number of Senior Citizens][2678. Number of Senior Citizens]] :END: +You are given a *0-indexed* array of strings ~details~. Each element of ~details~ provides information about a given passenger compressed into a string of length ~15~. The system is such that: + + - The first ten characters consist of the phone number of passengers. + + - The next character denotes the gender of the person. + + - The following two characters are used to indicate the age of the person. + + - The last two characters determine the seat allotted to that person. + +Return /the number of passengers who are *strictly **more than 60 years old*./ + +*Example 1:* + + +#+begin_src +Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"] +Output: 2 +Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: details = ["1313579440F2036","2921522980M5644"] +Output: 0 +Explanation: None of the passengers are older than 60. +#+end_src + + +*Constraints:* + + - ~1 <= details.length <= 100~ + + - ~details[i].length == 15~ + + - ~details[i] consists of digits from '0' to '9'.~ + + - ~details[i][10] is either 'M' or 'F' or 'O'.~ + + - The phone numbers and seat numbers of the passengers are distinct. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def countSeniors(self, details: List[str]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int countSeniors(vector& details) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0017-letter-combinations-of-a-phone-number.org b/org/study_deck_02/dsa/backtracking/0017-letter-combinations-of-a-phone-number.org index c3993c1..a3adf22 100644 --- a/org/study_deck_02/dsa/backtracking/0017-letter-combinations-of-a-phone-number.org +++ b/org/study_deck_02/dsa/backtracking/0017-letter-combinations-of-a-phone-number.org @@ -1,18 +1,52 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0017. Letter Combinations of a Phone Number :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0017. Letter Combinations of a Phone Number][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0017. Letter Combinations of a Phone Number][0017. Letter Combinations of a Phone Number]] :END: +Given a string containing digits from ~2-9~ inclusive, return all possible letter combinations that the number could represent. Return the answer in *any order*. + +A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. + +*Example 1:* + + +#+begin_src +Input: digits = "23" +Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: digits = "2" +Output: ["a","b","c"] +#+end_src + + +*Constraints:* + + - ~1 <= digits.length <= 4~ + + - ~digits[i]~ is a digit in the range ~['2', '9']~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def letterCombinations(self, digits: str) -> List[str]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector letterCombinations(string digits) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0022-generate-parentheses.org b/org/study_deck_02/dsa/backtracking/0022-generate-parentheses.org index 6549cd2..2e97c0a 100644 --- a/org/study_deck_02/dsa/backtracking/0022-generate-parentheses.org +++ b/org/study_deck_02/dsa/backtracking/0022-generate-parentheses.org @@ -1,18 +1,46 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0022. Generate Parentheses :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0022. Generate Parentheses][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0022. Generate Parentheses][0022. Generate Parentheses]] :END: +Given ~n~ pairs of parentheses, write a function to /generate all combinations of well-formed parentheses/. + +*Example 1:* + + +#+begin_src +Input: n = 3 +Output: ["((()))","(()())","(())()","()(())","()()()"] +#+end_src +*Example 2:* + + +#+begin_src +Input: n = 1 +Output: ["()"] +#+end_src + + +*Constraints:* + + - ~1 <= n <= 8~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def generateParenthesis(self, n: int) -> List[str]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector generateParenthesis(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0039-combination-sum.org b/org/study_deck_02/dsa/backtracking/0039-combination-sum.org index 2fdab01..489eaa6 100644 --- a/org/study_deck_02/dsa/backtracking/0039-combination-sum.org +++ b/org/study_deck_02/dsa/backtracking/0039-combination-sum.org @@ -1,18 +1,71 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0039. Combination Sum :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0039. Combination Sum][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0039. Combination Sum][0039. Combination Sum]] :END: +Given an array of *distinct* integers ~candidates~ and a target integer ~target~, return /a list of all *unique combinations* of /~candidates~/ where the chosen numbers sum to /~target~/./ You may return the combinations in *any order*. + +The *same* number may be chosen from ~candidates~ an *unlimited number of times*. Two combinations are unique if the frequency of at least one of the chosen numbers is different. + +The test cases are generated such that the number of unique combinations that sum up to ~target~ is less than ~150~ combinations for the given input. + +*Example 1:* + + +#+begin_src +Input: candidates = [2,3,6,7], target = 7 +Output: [[2,2,3],[7]] +Explanation: +2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. +7 is a candidate, and 7 = 7. +These are the only two combinations. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: candidates = [2,3,5], target = 8 +Output: [[2,2,2,2],[2,3,3],[3,5]] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: candidates = [2], target = 1 +Output: [] +#+end_src + + +*Constraints:* + + - ~1 <= candidates.length <= 30~ + + - ~2 <= candidates[i] <= 40~ + + - All elements of ~candidates~ are *distinct*. + + - ~1 <= target <= 40~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> combinationSum(vector& candidates, int target) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0040-combination-sum-ii.org b/org/study_deck_02/dsa/backtracking/0040-combination-sum-ii.org index 18dd4c1..06d9b62 100644 --- a/org/study_deck_02/dsa/backtracking/0040-combination-sum-ii.org +++ b/org/study_deck_02/dsa/backtracking/0040-combination-sum-ii.org @@ -1,18 +1,66 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0040. Combination Sum II :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0040. Combination Sum II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0040. Combination Sum II][0040. Combination Sum II]] :END: +Given a collection of candidate numbers (~candidates~) and a target number (~target~), find all unique combinations in ~candidates~ where the candidate numbers sum to ~target~. + +Each number in ~candidates~ may only be used *once* in the combination. + +*Note:* The solution set must not contain duplicate combinations. + +*Example 1:* + + +#+begin_src +Input: candidates = [10,1,2,7,6,1,5], target = 8 +Output: +[ +[1,1,6], +[1,2,5], +[1,7], +[2,6] +] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: candidates = [2,5,2,1,2], target = 5 +Output: +[ +[1,2,2], +[5] +] +#+end_src + + +*Constraints:* + + - ~1 <= candidates.length <= 100~ + + - ~1 <= candidates[i] <= 50~ + + - ~1 <= target <= 30~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> combinationSum2(vector& candidates, int target) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0046-permutations.org b/org/study_deck_02/dsa/backtracking/0046-permutations.org index 8eb09dc..59910d5 100644 --- a/org/study_deck_02/dsa/backtracking/0046-permutations.org +++ b/org/study_deck_02/dsa/backtracking/0046-permutations.org @@ -1,18 +1,57 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0046. Permutations :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0046. Permutations][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0046. Permutations][0046. Permutations]] :END: +Given an array ~nums~ of distinct integers, return all the possible permutations. You can return the answer in *any order*. + +*Example 1:* + + +#+begin_src +Input: nums = [1,2,3] +Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] +#+end_src +*Example 2:* + + +#+begin_src +Input: nums = [0,1] +Output: [[0,1],[1,0]] +#+end_src +*Example 3:* + + +#+begin_src +Input: nums = [1] +Output: [[1]] +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 6~ + + - ~-10 <= nums[i] <= 10~ + + - All the integers of ~nums~ are *unique*. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> permute(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0051-n-queens.org b/org/study_deck_02/dsa/backtracking/0051-n-queens.org index dc02d78..db147ce 100644 --- a/org/study_deck_02/dsa/backtracking/0051-n-queens.org +++ b/org/study_deck_02/dsa/backtracking/0051-n-queens.org @@ -1,18 +1,53 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0051. N Queens :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0051. N Queens][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0051. N Queens][0051. N Queens]] :END: +The *n-queens* puzzle is the problem of placing ~n~ queens on an ~n x n~ chessboard such that no two queens attack each other. + +Given an integer ~n~, return /all distinct solutions to the *n-queens puzzle*/. You may return the answer in *any order*. + +Each solution contains a distinct board configuration of the n-queens' placement, where ~'Q'~ and ~'.'~ both indicate a queen and an empty space, respectively. + +*Example 1:* + + +#+begin_src +Input: n = 4 +Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] +Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 1 +Output: [["Q"]] +#+end_src + + +*Constraints:* + + - ~1 <= n <= 9~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def solveNQueens(self, n: int) -> List[List[str]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> solveNQueens(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0052-n-queens-ii.org b/org/study_deck_02/dsa/backtracking/0052-n-queens-ii.org index 6ad4f80..c83d452 100644 --- a/org/study_deck_02/dsa/backtracking/0052-n-queens-ii.org +++ b/org/study_deck_02/dsa/backtracking/0052-n-queens-ii.org @@ -1,18 +1,51 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0052. N Queens II :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0052. N Queens II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0052. N Queens II][0052. N Queens II]] :END: +The *n-queens* puzzle is the problem of placing ~n~ queens on an ~n x n~ chessboard such that no two queens attack each other. + +Given an integer ~n~, return /the number of distinct solutions to the *n-queens puzzle*/. + +*Example 1:* + + +#+begin_src +Input: n = 4 +Output: 2 +Explanation: There are two distinct solutions to the 4-queens puzzle as shown. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 1 +Output: 1 +#+end_src + + +*Constraints:* + + - ~1 <= n <= 9~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def totalNQueens(self, n: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int totalNQueens(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0077-combinations.org b/org/study_deck_02/dsa/backtracking/0077-combinations.org index e40d067..cefab37 100644 --- a/org/study_deck_02/dsa/backtracking/0077-combinations.org +++ b/org/study_deck_02/dsa/backtracking/0077-combinations.org @@ -1,18 +1,55 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0077. Combinations :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0077. Combinations][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0077. Combinations][0077. Combinations]] :END: +Given two integers ~n~ and ~k~, return /all possible combinations of/ ~k~ /numbers chosen from the range/ ~[1, n]~. + +You may return the answer in *any order*. + +*Example 1:* + + +#+begin_src +Input: n = 4, k = 2 +Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] +Explanation: There are 4 choose 2 = 6 total combinations. +Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 1, k = 1 +Output: [[1]] +Explanation: There is 1 choose 1 = 1 total combination. +#+end_src + + +*Constraints:* + + - ~1 <= n <= 20~ + + - ~1 <= k <= n~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def combine(self, n: int, k: int) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> combine(int n, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0078-subsets.org b/org/study_deck_02/dsa/backtracking/0078-subsets.org index 3ad8352..88b6eda 100644 --- a/org/study_deck_02/dsa/backtracking/0078-subsets.org +++ b/org/study_deck_02/dsa/backtracking/0078-subsets.org @@ -1,18 +1,54 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0078. Subsets :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0078. Subsets][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0078. Subsets][0078. Subsets]] :END: +Given an integer array ~nums~ of *unique* elements, return /all possible/ /subsets/ /(the power set)/. + +The solution set *must not* contain duplicate subsets. Return the solution in *any order*. + +*Example 1:* + + +#+begin_src +Input: nums = [1,2,3] +Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [0] +Output: [[],[0]] +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 10~ + + - ~-10 <= nums[i] <= 10~ + + - All the numbers of ~nums~ are *unique*. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> subsets(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0079-word-search.org b/org/study_deck_02/dsa/backtracking/0079-word-search.org index 4d23bcf..dda43ce 100644 --- a/org/study_deck_02/dsa/backtracking/0079-word-search.org +++ b/org/study_deck_02/dsa/backtracking/0079-word-search.org @@ -1,18 +1,69 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0079. Word Search :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0079. Word Search][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0079. Word Search][0079. Word Search]] :END: +Given an ~m x n~ grid of characters ~board~ and a string ~word~, return ~true~ /if/ ~word~ /exists in the grid/. + +The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. + +*Example 1:* + + +#+begin_src +Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" +Output: true +#+end_src + + +*Example 2:* + + +#+begin_src +Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" +Output: true +#+end_src + + +*Example 3:* + + +#+begin_src +Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" +Output: false +#+end_src + + +*Constraints:* + + - ~m == board.length~ + + - ~n = board[i].length~ + + - ~1 <= m, n <= 6~ + + - ~1 <= word.length <= 15~ + + - ~board~ and ~word~ consists of only lowercase and uppercase English letters. + +*Follow up:* Could you use search pruning to make your solution faster with a larger ~board~? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool exist(vector>& board, string word) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0090-subsets-ii.org b/org/study_deck_02/dsa/backtracking/0090-subsets-ii.org index 8e9a239..0b0281e 100644 --- a/org/study_deck_02/dsa/backtracking/0090-subsets-ii.org +++ b/org/study_deck_02/dsa/backtracking/0090-subsets-ii.org @@ -1,18 +1,50 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0090. Subsets II :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0090. Subsets II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0090. Subsets II][0090. Subsets II]] :END: +Given an integer array ~nums~ that may contain duplicates, return /all possible/ /subsets// (the power set)/. + +The solution set *must not* contain duplicate subsets. Return the solution in *any order*. + +*Example 1:* + + +#+begin_src +Input: nums = [1,2,2] +Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] +#+end_src +*Example 2:* + + +#+begin_src +Input: nums = [0] +Output: [[],[0]] +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 10~ + + - ~-10 <= nums[i] <= 10~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0131-palindrome-partitioning.org b/org/study_deck_02/dsa/backtracking/0131-palindrome-partitioning.org index 5f63334..3595c3c 100644 --- a/org/study_deck_02/dsa/backtracking/0131-palindrome-partitioning.org +++ b/org/study_deck_02/dsa/backtracking/0131-palindrome-partitioning.org @@ -1,18 +1,48 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0131. Palindrome Partitioning :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0131. Palindrome Partitioning][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0131. Palindrome Partitioning][0131. Palindrome Partitioning]] :END: +Given a string ~s~, partition ~s~ such that every substring of the partition is a *palindrome*. Return /all possible palindrome partitioning of /~s~. + +*Example 1:* + + +#+begin_src +Input: s = "aab" +Output: [["a","a","b"],["aa","b"]] +#+end_src +*Example 2:* + + +#+begin_src +Input: s = "a" +Output: [["a"]] +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 16~ + + - ~s~ contains only lowercase English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def partition(self, s: str) -> List[List[str]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> partition(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/backtracking/0351-android-unlock-patterns.org b/org/study_deck_02/dsa/backtracking/0351-android-unlock-patterns.org index 16d0dab..2e2bbb7 100644 --- a/org/study_deck_02/dsa/backtracking/0351-android-unlock-patterns.org +++ b/org/study_deck_02/dsa/backtracking/0351-android-unlock-patterns.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0351. Android Unlock Patterns :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0351. Android Unlock Patterns][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0351. Android Unlock Patterns][0351. Android Unlock Patterns]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/backtracking/1079-letter-tile-possibilities.org b/org/study_deck_02/dsa/backtracking/1079-letter-tile-possibilities.org index 02fad78..ec0f000 100644 --- a/org/study_deck_02/dsa/backtracking/1079-letter-tile-possibilities.org +++ b/org/study_deck_02/dsa/backtracking/1079-letter-tile-possibilities.org @@ -1,18 +1,62 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1079. Letter Tile Possibilities :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1079. Letter Tile Possibilities][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1079. Letter Tile Possibilities][1079. Letter Tile Possibilities]] :END: +You have ~n~ ~tiles~, where each tile has one letter ~tiles[i]~ printed on it. + +Return /the number of possible non-empty sequences of letters/ you can make using the letters printed on those ~tiles~. + +*Example 1:* + + +#+begin_src +Input: tiles = "AAB" +Output: 8 +Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". +#+end_src + + +*Example 2:* + + +#+begin_src +Input: tiles = "AAABBC" +Output: 188 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: tiles = "V" +Output: 1 +#+end_src + + +*Constraints:* + + - ~1 <= tiles.length <= 7~ + + - ~tiles~ consists of uppercase English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def numTilePossibilities(self, tiles: str) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int numTilePossibilities(string tiles) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/binary-search/0004-median-of-two-sorted-arrays.org b/org/study_deck_02/dsa/binary-search/0004-median-of-two-sorted-arrays.org index 3fba694..bc41904 100644 --- a/org/study_deck_02/dsa/binary-search/0004-median-of-two-sorted-arrays.org +++ b/org/study_deck_02/dsa/binary-search/0004-median-of-two-sorted-arrays.org @@ -1,18 +1,62 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0004. Median of Two Sorted Arrays :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0004. Median of Two Sorted Arrays][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0004. Median of Two Sorted Arrays][0004. Median of Two Sorted Arrays]] :END: +Given two sorted arrays ~nums1~ and ~nums2~ of size ~m~ and ~n~ respectively, return *the median* of the two sorted arrays. + +The overall run time complexity should be ~O(log (m+n))~. + +*Example 1:* + + +#+begin_src +Input: nums1 = [1,3], nums2 = [2] +Output: 2.00000 +Explanation: merged array = [1,2,3] and median is 2. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums1 = [1,2], nums2 = [3,4] +Output: 2.50000 +Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. +#+end_src + + +*Constraints:* + + - ~nums1.length == m~ + + - ~nums2.length == n~ + + - ~0 <= m <= 1000~ + + - ~0 <= n <= 1000~ + + - ~1 <= m + n <= 2000~ + + - ~-10^{6} <= nums1[i], nums2[i] <= 10^{6}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/binary-search/0033-search-in-rotated-sorted-array.org b/org/study_deck_02/dsa/binary-search/0033-search-in-rotated-sorted-array.org index 2bf3607..07ac07f 100644 --- a/org/study_deck_02/dsa/binary-search/0033-search-in-rotated-sorted-array.org +++ b/org/study_deck_02/dsa/binary-search/0033-search-in-rotated-sorted-array.org @@ -1,18 +1,67 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0033. Search In Rotated Sorted Array :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0033. Search In Rotated Sorted Array][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0033. Search In Rotated Sorted Array][0033. Search In Rotated Sorted Array]] :END: +There is an integer array ~nums~ sorted in ascending order (with *distinct* values). + +Prior to being passed to your function, ~nums~ is *possibly left rotated* at an unknown index ~k~ (~1 <= k < nums.length~) such that the resulting array is ~[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]~ (*0-indexed*). For example, ~[0,1,2,4,5,6,7]~ might be left rotated by ~3~ indices and become ~[4,5,6,7,0,1,2]~. + +Given the array ~nums~ *after* the possible rotation and an integer ~target~, return /the index of /~target~/ if it is in /~nums~/, or /~-1~/ if it is not in /~nums~. + +You must write an algorithm with ~O(log n)~ runtime complexity. + +*Example 1:* + + +#+begin_src +Input: nums = [4,5,6,7,0,1,2], target = 0 +Output: 4 +#+end_src +*Example 2:* + + +#+begin_src +Input: nums = [4,5,6,7,0,1,2], target = 3 +Output: -1 +#+end_src +*Example 3:* + + +#+begin_src +Input: nums = [1], target = 0 +Output: -1 +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 5000~ + + - ~-10^{4} <= nums[i] <= 10^{4}~ + + - All values of ~nums~ are *unique*. + + - ~nums~ is an ascending array that is possibly rotated. + + - ~-10^{4} <= target <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def search(self, nums: List[int], target: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int search(vector& nums, int target) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/binary-search/0074-search-a-2d-matrix.org b/org/study_deck_02/dsa/binary-search/0074-search-a-2d-matrix.org index 10906b1..356b285 100644 --- a/org/study_deck_02/dsa/binary-search/0074-search-a-2d-matrix.org +++ b/org/study_deck_02/dsa/binary-search/0074-search-a-2d-matrix.org @@ -1,18 +1,62 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0074. Search a 2D Matrix :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0074. Search a 2D Matrix][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0074. Search a 2D Matrix][0074. Search a 2D Matrix]] :END: +You are given an ~m x n~ integer matrix ~matrix~ with the following two properties: + + - Each row is sorted in non-decreasing order. + + - The first integer of each row is greater than the last integer of the previous row. + +Given an integer ~target~, return ~true~ /if/ ~target~ /is in/ ~matrix~ /or/ ~false~ /otherwise/. + +You must write a solution in ~O(log(m * n))~ time complexity. + +*Example 1:* + + +#+begin_src +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 +Output: true +#+end_src + + +*Example 2:* + + +#+begin_src +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 +Output: false +#+end_src + + +*Constraints:* + + - ~m == matrix.length~ + + - ~n == matrix[i].length~ + + - ~1 <= m, n <= 100~ + + - ~-10^{4} <= matrix[i][j], target <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/binary-search/0153-find-minimum-in-rotated-sorted-array.org b/org/study_deck_02/dsa/binary-search/0153-find-minimum-in-rotated-sorted-array.org index 17b3606..d7fcc3d 100644 --- a/org/study_deck_02/dsa/binary-search/0153-find-minimum-in-rotated-sorted-array.org +++ b/org/study_deck_02/dsa/binary-search/0153-find-minimum-in-rotated-sorted-array.org @@ -1,18 +1,78 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0153. Find Minimum In Rotated Sorted Array :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0153. Find Minimum In Rotated Sorted Array][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0153. Find Minimum In Rotated Sorted Array][0153. Find Minimum In Rotated Sorted Array]] :END: +Suppose an array of length ~n~ sorted in ascending order is *rotated* between ~1~ and ~n~ times. For example, the array ~nums = [0,1,2,4,5,6,7]~ might become: + + - ~[4,5,6,7,0,1,2]~ if it was rotated ~4~ times. + + - ~[0,1,2,4,5,6,7]~ if it was rotated ~7~ times. + +Notice that *rotating* an array ~[a[0], a[1], a[2], ..., a[n-1]]~ 1 time results in the array ~[a[n-1], a[0], a[1], a[2], ..., a[n-2]]~. + +Given the sorted rotated array ~nums~ of *unique* elements, return /the minimum element of this array/. + +You must write an algorithm that runs in ~O(log n) time~. + +*Example 1:* + + +#+begin_src +Input: nums = [3,4,5,1,2] +Output: 1 +Explanation: The original array was [1,2,3,4,5] rotated 3 times. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [4,5,6,7,0,1,2] +Output: 0 +Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [11,13,15,17] +Output: 11 +Explanation: The original array was [11,13,15,17] and it was rotated 4 times. +#+end_src + + +*Constraints:* + + - ~n == nums.length~ + + - ~1 <= n <= 5000~ + + - ~-5000 <= nums[i] <= 5000~ + + - All the integers of ~nums~ are *unique*. + + - ~nums~ is sorted and rotated between ~1~ and ~n~ times. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findMin(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int findMin(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/binary-search/0704-binary-search.org b/org/study_deck_02/dsa/binary-search/0704-binary-search.org index 3cf60a1..262bf84 100644 --- a/org/study_deck_02/dsa/binary-search/0704-binary-search.org +++ b/org/study_deck_02/dsa/binary-search/0704-binary-search.org @@ -1,18 +1,58 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0704. Binary Search :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0704. Binary Search][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0704. Binary Search][0704. Binary Search]] :END: +Given an array of integers ~nums~ which is sorted in ascending order, and an integer ~target~, write a function to search ~target~ in ~nums~. If ~target~ exists, then return its index. Otherwise, return ~-1~. + +You must write an algorithm with ~O(log n)~ runtime complexity. + +*Example 1:* + + +#+begin_src +Input: nums = [-1,0,3,5,9,12], target = 9 +Output: 4 +Explanation: 9 exists in nums and its index is 4 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [-1,0,3,5,9,12], target = 2 +Output: -1 +Explanation: 2 does not exist in nums so return -1 +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 10^{4}~ + + - ~-10^{4} < nums[i], target < 10^{4}~ + + - All the integers in ~nums~ are *unique*. + + - ~nums~ is sorted in ascending order. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def search(self, nums: List[int], target: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int search(vector& nums, int target) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/binary-search/0719-find-k-th-smallest-pair-distance.org b/org/study_deck_02/dsa/binary-search/0719-find-k-th-smallest-pair-distance.org index 49e7424..c8416b2 100644 --- a/org/study_deck_02/dsa/binary-search/0719-find-k-th-smallest-pair-distance.org +++ b/org/study_deck_02/dsa/binary-search/0719-find-k-th-smallest-pair-distance.org @@ -1,18 +1,70 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0719. Find K-th Smallest Pair Distance :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0719. Find K-th Smallest Pair Distance][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0719. Find K-th Smallest Pair Distance][0719. Find K-th Smallest Pair Distance]] :END: +The *distance of a pair* of integers ~a~ and ~b~ is defined as the absolute difference between ~a~ and ~b~. + +Given an integer array ~nums~ and an integer ~k~, return /the/ ~k^{th}~ /smallest *distance among all the pairs*/ ~nums[i]~ /and/ ~nums[j]~ /where/ ~0 <= i < j < nums.length~. + +*Example 1:* + + +#+begin_src +Input: nums = [1,3,1], k = 1 +Output: 0 +Explanation: Here are all the pairs: +(1,3) -> 2 +(1,1) -> 0 +(3,1) -> 2 +Then the 1st smallest distance pair is (1,1), and its distance is 0. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [1,1,1], k = 2 +Output: 0 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [1,6,1], k = 3 +Output: 5 +#+end_src + + +*Constraints:* + + - ~n == nums.length~ + + - ~2 <= n <= 10^{4}~ + + - ~0 <= nums[i] <= 10^{6}~ + + - ~1 <= k <= n * (n - 1) / 2~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def smallestDistancePair(self, nums: List[int], k: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int smallestDistancePair(vector& nums, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/binary-search/0875-koko-eating-bananas.org b/org/study_deck_02/dsa/binary-search/0875-koko-eating-bananas.org index e635565..1333e2c 100644 --- a/org/study_deck_02/dsa/binary-search/0875-koko-eating-bananas.org +++ b/org/study_deck_02/dsa/binary-search/0875-koko-eating-bananas.org @@ -1,18 +1,67 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0875. Koko Eating Bananas :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0875. Koko Eating Bananas][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0875. Koko Eating Bananas][0875. Koko Eating Bananas]] :END: +Koko loves to eat bananas. There are ~n~ piles of bananas, the ~i^{th}~ pile has ~piles[i]~ bananas. The guards have gone and will come back in ~h~ hours. + +Koko can decide her bananas-per-hour eating speed of ~k~. Each hour, she chooses some pile of bananas and eats ~k~ bananas from that pile. If the pile has less than ~k~ bananas, she eats all of them instead and will not eat any more bananas during this hour. + +Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. + +Return /the minimum integer/ ~k~ /such that she can eat all the bananas within/ ~h~ /hours/. + +*Example 1:* + + +#+begin_src +Input: piles = [3,6,7,11], h = 8 +Output: 4 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: piles = [30,11,23,4,20], h = 5 +Output: 30 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: piles = [30,11,23,4,20], h = 6 +Output: 23 +#+end_src + + +*Constraints:* + + - ~1 <= piles.length <= 10^{4}~ + + - ~piles.length <= h <= 10^{9}~ + + - ~1 <= piles[i] <= 10^{9}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def minEatingSpeed(self, piles: List[int], h: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int minEatingSpeed(vector& piles, int h) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/binary-search/0981-time-based-key-value-store.org b/org/study_deck_02/dsa/binary-search/0981-time-based-key-value-store.org index f5da752..ca0b00f 100644 --- a/org/study_deck_02/dsa/binary-search/0981-time-based-key-value-store.org +++ b/org/study_deck_02/dsa/binary-search/0981-time-based-key-value-store.org @@ -1,18 +1,96 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0981. Time Based Key Value Store :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0981. Time Based Key Value Store][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0981. Time Based Key Value Store][0981. Time Based Key Value Store]] :END: +Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. + +Implement the ~TimeMap~ class: + + - ~TimeMap()~ Initializes the object of the data structure. + + - ~void set(String key, String value, int timestamp)~ Stores the key ~key~ with the value ~value~ at the given time ~timestamp~. + + - ~String get(String key, int timestamp)~ Returns a value such that ~set~ was called previously, with ~timestamp_prev <= timestamp~. If there are multiple such values, it returns the value associated with the largest ~timestamp_prev~. If there are no values, it returns ~""~. + +*Example 1:* + + +#+begin_src +Input +["TimeMap", "set", "get", "get", "set", "get", "get"] +[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]] +Output +[null, null, "bar", "bar", null, "bar2", "bar2"] + +Explanation +TimeMap timeMap = new TimeMap(); +timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1. +timeMap.get("foo", 1); // return "bar" +timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar". +timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4. +timeMap.get("foo", 4); // return "bar2" +timeMap.get("foo", 5); // return "bar2" +#+end_src + + +*Constraints:* + + - ~1 <= key.length, value.length <= 100~ + + - ~key~ and ~value~ consist of lowercase English letters and digits. + + - ~1 <= timestamp <= 10^{7}~ + + - All the timestamps ~timestamp~ of ~set~ are strictly increasing. + + - At most ~2 * 10^{5}~ calls will be made to ~set~ and ~get~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class TimeMap: + def __init__(self): + + + def set(self, key: str, value: str, timestamp: int) -> None: + + + def get(self, key: str, timestamp: int) -> str: + + + +# Your TimeMap object will be instantiated and called as such: +# obj = TimeMap() +# obj.set(key,value,timestamp) +# param_2 = obj.get(key,timestamp) #+end_src ** TODO C++ #+begin_src cpp +class TimeMap { +public: + TimeMap() { + + } + + void set(string key, string value, int timestamp) { + + } + + string get(string key, int timestamp) { + + } +}; +/** + * Your TimeMap object will be instantiated and called as such: + * TimeMap* obj = new TimeMap(); + * obj->set(key,value,timestamp); + * string param_2 = obj->get(key,timestamp); + */ #+end_src diff --git a/org/study_deck_02/dsa/binary-search/2300-successful-pairs-of-spells-and-potions.org b/org/study_deck_02/dsa/binary-search/2300-successful-pairs-of-spells-and-potions.org index b592896..f65f529 100644 --- a/org/study_deck_02/dsa/binary-search/2300-successful-pairs-of-spells-and-potions.org +++ b/org/study_deck_02/dsa/binary-search/2300-successful-pairs-of-spells-and-potions.org @@ -1,18 +1,70 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2300. Successful Pairs of Spells and Potions :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2300. Successful Pairs of Spells and Potions][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2300. Successful Pairs of Spells and Potions][2300. Successful Pairs of Spells and Potions]] :END: +You are given two positive integer arrays ~spells~ and ~potions~, of length ~n~ and ~m~ respectively, where ~spells[i]~ represents the strength of the ~i^{th}~ spell and ~potions[j]~ represents the strength of the ~j^{th}~ potion. + +You are also given an integer ~success~. A spell and potion pair is considered *successful* if the *product* of their strengths is *at least* ~success~. + +Return /an integer array /~pairs~/ of length /~n~/ where /~pairs[i]~/ is the number of *potions* that will form a successful pair with the /~i^{th}~/ spell./ + +*Example 1:* + + +#+begin_src +Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7 +Output: [4,0,3] +Explanation: +- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful. +- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful. +- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful. +Thus, [4,0,3] is returned. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: spells = [3,1,2], potions = [8,5,8], success = 16 +Output: [2,0,2] +Explanation: +- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful. +- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. +- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. +Thus, [2,0,2] is returned. +#+end_src + + +*Constraints:* + + - ~n == spells.length~ + + - ~m == potions.length~ + + - ~1 <= n, m <= 10^{5}~ + + - ~1 <= spells[i], potions[i] <= 10^{5}~ + + - ~1 <= success <= 10^{10}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector successfulPairs(vector& spells, vector& potions, long long success) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/0007-reverse-integer.org b/org/study_deck_02/dsa/bit-manipulation/0007-reverse-integer.org index 8738725..f4a9174 100644 --- a/org/study_deck_02/dsa/bit-manipulation/0007-reverse-integer.org +++ b/org/study_deck_02/dsa/bit-manipulation/0007-reverse-integer.org @@ -1,18 +1,59 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0007. Reverse Integer :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0007. Reverse Integer][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0007. Reverse Integer][0007. Reverse Integer]] :END: +Given a signed 32-bit integer ~x~, return ~x~/ with its digits reversed/. If reversing ~x~ causes the value to go outside the signed 32-bit integer range ~[-2^{31}, 2^{31} - 1]~, then return ~0~. + +*Assume the environment does not allow you to store 64-bit integers (signed or unsigned).* + +*Example 1:* + + +#+begin_src +Input: x = 123 +Output: 321 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: x = -123 +Output: -321 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: x = 120 +Output: 21 +#+end_src + + +*Constraints:* + + - ~-2^{31} <= x <= 2^{31} - 1~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def reverse(self, x: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int reverse(int x) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/0136-single-number.org b/org/study_deck_02/dsa/bit-manipulation/0136-single-number.org index 564e493..17410f8 100644 --- a/org/study_deck_02/dsa/bit-manipulation/0136-single-number.org +++ b/org/study_deck_02/dsa/bit-manipulation/0136-single-number.org @@ -1,18 +1,54 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0136. Single Number :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0136. Single Number][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0136. Single Number][0136. Single Number]] :END: +Given a *non-empty* array of integers ~nums~, every element appears /twice/ except for one. Find that single one. + +You must implement a solution with a linear runtime complexity and use only constant extra space. + +*Example 1:* + +*Input:* nums = [2,2,1] + +*Output:* 1 + +*Example 2:* + +*Input:* nums = [4,1,2,1,2] + +*Output:* 4 + +*Example 3:* + +*Input:* nums = [1] + +*Output:* 1 + +*Constraints:* + + - ~1 <= nums.length <= 3 * 10^{4}~ + + - ~-3 * 10^{4} <= nums[i] <= 3 * 10^{4}~ + + - Each element in the array appears twice except for one element which appears only once. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def singleNumber(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int singleNumber(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/0190-reverse-bits.org b/org/study_deck_02/dsa/bit-manipulation/0190-reverse-bits.org index d822219..290a802 100644 --- a/org/study_deck_02/dsa/bit-manipulation/0190-reverse-bits.org +++ b/org/study_deck_02/dsa/bit-manipulation/0190-reverse-bits.org @@ -1,18 +1,68 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0190. Reverse Bits :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0190. Reverse Bits][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0190. Reverse Bits][0190. Reverse Bits]] :END: +Reverse bits of a given 32 bits signed integer. + +*Example 1:* + +*Input:* n = 43261596 + +*Output:* 964176192 + +*Explanation:* + + Integer + Binary + + 43261596 + 00000010100101000001111010011100 + + 964176192 + 00111001011110000010100101000000 + +*Example 2:* + +*Input:* n = 2147483644 + +*Output:* 1073741822 + +*Explanation:* + + Integer + Binary + + 2147483644 + 01111111111111111111111111111100 + + 1073741822 + 00111111111111111111111111111110 + +*Constraints:* + + - ~0 <= n <= 2^{31} - 2~ + + - ~n~ is even. + +*Follow up:* If this function is called many times, how would you optimize it? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def reverseBits(self, n: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int reverseBits(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/0191-number-of-1-bits.org b/org/study_deck_02/dsa/bit-manipulation/0191-number-of-1-bits.org index beef005..23760ae 100644 --- a/org/study_deck_02/dsa/bit-manipulation/0191-number-of-1-bits.org +++ b/org/study_deck_02/dsa/bit-manipulation/0191-number-of-1-bits.org @@ -1,18 +1,62 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0191. Number of 1 Bits :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0191. Number of 1 Bits][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0191. Number of 1 Bits][0191. Number of 1 Bits]] :END: +Given a positive integer ~n~, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight). + +*Example 1:* + +*Input:* n = 11 + +*Output:* 3 + +*Explanation:* + +The input binary string *1011* has a total of three set bits. + +*Example 2:* + +*Input:* n = 128 + +*Output:* 1 + +*Explanation:* + +The input binary string *10000000* has a total of one set bit. + +*Example 3:* + +*Input:* n = 2147483645 + +*Output:* 30 + +*Explanation:* + +The input binary string *1111111111111111111111111111101* has a total of thirty set bits. + +*Constraints:* + + - ~1 <= n <= 2^{31} - 1~ + +*Follow up:* If this function is called many times, how would you optimize it? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def hammingWeight(self, n: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int hammingWeight(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/0231-power-of-two.org b/org/study_deck_02/dsa/bit-manipulation/0231-power-of-two.org index 72deb1e..edc6241 100644 --- a/org/study_deck_02/dsa/bit-manipulation/0231-power-of-two.org +++ b/org/study_deck_02/dsa/bit-manipulation/0231-power-of-two.org @@ -1,18 +1,63 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0231. Power of Two :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0231. Power of Two][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0231. Power of Two][0231. Power of Two]] :END: +Given an integer ~n~, return /~true~ if it is a power of two. Otherwise, return ~false~/. + +An integer ~n~ is a power of two, if there exists an integer ~x~ such that ~n == 2^{x}~. + +*Example 1:* + + +#+begin_src +Input: n = 1 +Output: true +Explanation: 20 = 1 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 16 +Output: true +Explanation: 24 = 16 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: n = 3 +Output: false +#+end_src + + +*Constraints:* + + - ~-2^{31} <= n <= 2^{31} - 1~ + +*Follow up:* Could you solve it without loops/recursion? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isPowerOfTwo(self, n: int) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isPowerOfTwo(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/0260-single-number-iii.org b/org/study_deck_02/dsa/bit-manipulation/0260-single-number-iii.org index 7dd49fe..92271d5 100644 --- a/org/study_deck_02/dsa/bit-manipulation/0260-single-number-iii.org +++ b/org/study_deck_02/dsa/bit-manipulation/0260-single-number-iii.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0260. Single Number III :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0260. Single Number III][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0260. Single Number III][0260. Single Number III]] :END: +Given an integer array ~nums~, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in *any order*. + +You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. + +*Example 1:* + + +#+begin_src +Input: nums = [1,2,1,3,2,5] +Output: [3,5] +Explanation: [5, 3] is also a valid answer. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [-1,0] +Output: [-1,0] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [0,1] +Output: [1,0] +#+end_src + + +*Constraints:* + + - ~2 <= nums.length <= 3 * 10^{4}~ + + - ~-2^{31} <= nums[i] <= 2^{31} - 1~ + + - Each integer in ~nums~ will appear twice, only two integers will appear once. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector singleNumber(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/0268-missing-number.org b/org/study_deck_02/dsa/bit-manipulation/0268-missing-number.org index 2b38a96..73b4d57 100644 --- a/org/study_deck_02/dsa/bit-manipulation/0268-missing-number.org +++ b/org/study_deck_02/dsa/bit-manipulation/0268-missing-number.org @@ -1,18 +1,68 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0268. Missing Number :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0268. Missing Number][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0268. Missing Number][0268. Missing Number]] :END: +Given an array ~nums~ containing ~n~ distinct numbers in the range ~[0, n]~, return /the only number in the range that is missing from the array./ + +*Example 1:* + +*Input:* nums = [3,0,1] + +*Output:* 2 + +*Explanation:* + +~n = 3~ since there are 3 numbers, so all numbers are in the range ~[0,3]~. 2 is the missing number in the range since it does not appear in ~nums~. + +*Example 2:* + +*Input:* nums = [0,1] + +*Output:* 2 + +*Explanation:* + +~n = 2~ since there are 2 numbers, so all numbers are in the range ~[0,2]~. 2 is the missing number in the range since it does not appear in ~nums~. + +*Example 3:* + +*Input:* nums = [9,6,4,2,3,5,7,0,1] + +*Output:* 8 + +*Explanation:* + +~n = 9~ since there are 9 numbers, so all numbers are in the range ~[0,9]~. 8 is the missing number in the range since it does not appear in ~nums~. + +*Constraints:* + + - ~n == nums.length~ + + - ~1 <= n <= 10^{4}~ + + - ~0 <= nums[i] <= n~ + + - All the numbers of ~nums~ are *unique*. + +*Follow up:* Could you implement a solution using only ~O(1)~ extra space complexity and ~O(n)~ runtime complexity? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def missingNumber(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int missingNumber(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/0338-counting-bits.org b/org/study_deck_02/dsa/bit-manipulation/0338-counting-bits.org index ab18be9..f4bc629 100644 --- a/org/study_deck_02/dsa/bit-manipulation/0338-counting-bits.org +++ b/org/study_deck_02/dsa/bit-manipulation/0338-counting-bits.org @@ -1,18 +1,65 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0338. Counting Bits :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0338. Counting Bits][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0338. Counting Bits][0338. Counting Bits]] :END: +Given an integer ~n~, return /an array /~ans~/ of length /~n + 1~/ such that for each /~i~/ /(~0 <= i <= n~)/, /~ans[i]~/ is the *number of */~1~/*'s* in the binary representation of /~i~. + +*Example 1:* + + +#+begin_src +Input: n = 2 +Output: [0,1,1] +Explanation: +0 --> 0 +1 --> 1 +2 --> 10 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 5 +Output: [0,1,1,2,1,2] +Explanation: +0 --> 0 +1 --> 1 +2 --> 10 +3 --> 11 +4 --> 100 +5 --> 101 +#+end_src + + +*Constraints:* + + - ~0 <= n <= 10^{5}~ + +*Follow up:* + + - It is very easy to come up with a solution with a runtime of ~O(n log n)~. Can you do it in linear time ~O(n)~ and possibly in a single pass? + + - Can you do it without using any built-in function (i.e., like ~__builtin_popcount~ in C++)? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def countBits(self, n: int) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector countBits(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/0371-sum-of-two-integers.org b/org/study_deck_02/dsa/bit-manipulation/0371-sum-of-two-integers.org index a4ce843..4658956 100644 --- a/org/study_deck_02/dsa/bit-manipulation/0371-sum-of-two-integers.org +++ b/org/study_deck_02/dsa/bit-manipulation/0371-sum-of-two-integers.org @@ -1,18 +1,46 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0371. Sum of Two Integers :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0371. Sum of Two Integers][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0371. Sum of Two Integers][0371. Sum of Two Integers]] :END: +Given two integers ~a~ and ~b~, return /the sum of the two integers without using the operators/ ~+~ /and/ ~-~. + +*Example 1:* + + +#+begin_src +Input: a = 1, b = 2 +Output: 3 +#+end_src +*Example 2:* + + +#+begin_src +Input: a = 2, b = 3 +Output: 5 +#+end_src + + +*Constraints:* + + - ~-1000 <= a, b <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def getSum(self, a: int, b: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int getSum(int a, int b) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/bit-manipulation/2220-minimum-bit-flips-to-convert-number.org b/org/study_deck_02/dsa/bit-manipulation/2220-minimum-bit-flips-to-convert-number.org index 3ebdffe..01699f4 100644 --- a/org/study_deck_02/dsa/bit-manipulation/2220-minimum-bit-flips-to-convert-number.org +++ b/org/study_deck_02/dsa/bit-manipulation/2220-minimum-bit-flips-to-convert-number.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2220. Minimum Bit Flips to Convert Number :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2220. Minimum Bit Flips to Convert Number][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2220. Minimum Bit Flips to Convert Number][2220. Minimum Bit Flips to Convert Number]] :END: +A *bit flip* of a number ~x~ is choosing a bit in the binary representation of ~x~ and *flipping* it from either ~0~ to ~1~ or ~1~ to ~0~. + + - For example, for ~x = 7~, the binary representation is ~111~ and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get ~110~, flip the second bit from the right to get ~101~, flip the fifth bit from the right (a leading zero) to get ~10111~, etc. + +Given two integers ~start~ and ~goal~, return/ the *minimum* number of *bit flips* to convert /~start~/ to /~goal~. + +*Example 1:* + + +#+begin_src +Input: start = 10, goal = 7 +Output: 3 +Explanation: The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps: +- Flip the first bit from the right: 1010 -> 1011. +- Flip the third bit from the right: 1011 -> 1111. +- Flip the fourth bit from the right: 1111 -> 0111. +It can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: start = 3, goal = 4 +Output: 3 +Explanation: The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps: +- Flip the first bit from the right: 011 -> 010. +- Flip the second bit from the right: 010 -> 000. +- Flip the third bit from the right: 000 -> 100. +It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3. +#+end_src + + +*Constraints:* + + - ~0 <= start, goal <= 10^{9}~ + +*Note:* This question is the same as 461: Hamming Distance. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def minBitFlips(self, start: int, goal: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int minBitFlips(int start, int goal) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0127-word-ladder.org b/org/study_deck_02/dsa/graphs/0127-word-ladder.org index 0b6ffbf..0db5b3e 100644 --- a/org/study_deck_02/dsa/graphs/0127-word-ladder.org +++ b/org/study_deck_02/dsa/graphs/0127-word-ladder.org @@ -1,18 +1,70 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0127. Word Ladder :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0127. Word Ladder][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0127. Word Ladder][0127. Word Ladder]] :END: +A *transformation sequence* from word ~beginWord~ to word ~endWord~ using a dictionary ~wordList~ is a sequence of words ~beginWord -> s_{1} -> s_{2} -> ... -> s_{k}~ such that: + + - Every adjacent pair of words differs by a single letter. + + - Every ~s_{i}~ for ~1 <= i <= k~ is in ~wordList~. Note that ~beginWord~ does not need to be in ~wordList~. + + - ~s_{k} == endWord~ + +Given two words, ~beginWord~ and ~endWord~, and a dictionary ~wordList~, return /the *number of words* in the *shortest transformation sequence* from/ ~beginWord~ /to/ ~endWord~/, or /~0~/ if no such sequence exists./ + +*Example 1:* + + +#+begin_src +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] +Output: 5 +Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] +Output: 0 +Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. +#+end_src + + +*Constraints:* + + - ~1 <= beginWord.length <= 10~ + + - ~endWord.length == beginWord.length~ + + - ~1 <= wordList.length <= 5000~ + + - ~wordList[i].length == beginWord.length~ + + - ~beginWord~, ~endWord~, and ~wordList[i]~ consist of lowercase English letters. + + - ~beginWord != endWord~ + + - All the words in ~wordList~ are *unique*. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0130-surrounded-regions.org b/org/study_deck_02/dsa/graphs/0130-surrounded-regions.org index ce77530..bb50c58 100644 --- a/org/study_deck_02/dsa/graphs/0130-surrounded-regions.org +++ b/org/study_deck_02/dsa/graphs/0130-surrounded-regions.org @@ -1,18 +1,63 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0130. Surrounded Regions :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0130. Surrounded Regions][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0130. Surrounded Regions][0130. Surrounded Regions]] :END: +You are given an ~m x n~ matrix ~board~ containing *letters* ~'X'~ and ~'O'~, *capture regions* that are *surrounded*: + + - *Connect*: A cell is connected to adjacent cells horizontally or vertically. + + - *Region*: To form a region *connect every* ~'O'~ cell. + + - *Surround*: A region is surrounded if none of the ~'O'~ cells in that region are on the edge of the board. Such regions are *completely enclosed *by ~'X'~ cells. + +To capture a *surrounded region*, replace all ~'O'~s with ~'X'~s *in-place* within the original board. You do not need to return anything. + +*Example 1:* + +*Input:* board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] + +*Output:* [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] + +*Explanation:* + +In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded. + +*Example 2:* + +*Input:* board = [["X"]] + +*Output:* [["X"]] + +*Constraints:* + + - ~m == board.length~ + + - ~n == board[i].length~ + + - ~1 <= m, n <= 200~ + + - ~board[i][j]~ is ~'X'~ or ~'O'~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def solve(self, board: List[List[str]]) -> None: + """ + Do not return anything, modify board in-place instead. + """ #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + void solve(vector>& board) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0133-clone-graph.org b/org/study_deck_02/dsa/graphs/0133-clone-graph.org index 9f577e7..c1177b4 100644 --- a/org/study_deck_02/dsa/graphs/0133-clone-graph.org +++ b/org/study_deck_02/dsa/graphs/0133-clone-graph.org @@ -1,18 +1,123 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0133. Clone Graph :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0133. Clone Graph][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0133. Clone Graph][0133. Clone Graph]] :END: +Given a reference of a node in a *connected* undirected graph. + +Return a *deep copy* (clone) of the graph. + +Each node in the graph contains a value (~int~) and a list (~List[Node]~) of its neighbors. + + +#+begin_src +class Node { + public int val; + public List neighbors; +} +#+end_src + + +*Test case format:* + +For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with ~val == 1~, the second node with ~val == 2~, and so on. The graph is represented in the test case using an adjacency list. + +An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. + +The given node will always be the first node with ~val = 1~. You must return the *copy of the given node* as a reference to the cloned graph. + +*Example 1:* + + +#+begin_src +Input: adjList = [[2,4],[1,3],[2,4],[1,3]] +Output: [[2,4],[1,3],[2,4],[1,3]] +Explanation: There are 4 nodes in the graph. +1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). +2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). +3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). +4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). +#+end_src + + +*Example 2:* + + +#+begin_src +Input: adjList = [[]] +Output: [[]] +Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: adjList = [] +Output: [] +Explanation: This an empty graph, it does not have any nodes. +#+end_src + + +*Constraints:* + + - The number of nodes in the graph is in the range ~[0, 100]~. + + - ~1 <= Node.val <= 100~ + + - ~Node.val~ is unique for each node. + + - There are no repeated edges and no self-loops in the graph. + + - The Graph is connected and all nodes can be visited starting from the given node. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +""" +# Definition for a Node. +class Node: + def __init__(self, val = 0, neighbors = None): + self.val = val + self.neighbors = neighbors if neighbors is not None else [] +""" +from typing import Optional +class Solution: + def cloneGraph(self, node: Optional['Node']) -> Optional['Node']: #+end_src ** TODO C++ #+begin_src cpp +/* +// Definition for a Node. +class Node { +public: + int val; + vector neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; +*/ +class Solution { +public: + Node* cloneGraph(Node* node) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0200-number-of-islands.org b/org/study_deck_02/dsa/graphs/0200-number-of-islands.org index 14aaa1e..49df303 100644 --- a/org/study_deck_02/dsa/graphs/0200-number-of-islands.org +++ b/org/study_deck_02/dsa/graphs/0200-number-of-islands.org @@ -1,18 +1,66 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0200. Number of Islands :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0200. Number of Islands][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0200. Number of Islands][0200. Number of Islands]] :END: +Given an ~m x n~ 2D binary grid ~grid~ which represents a map of ~'1'~s (land) and ~'0'~s (water), return /the number of islands/. + +An *island* is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. + +*Example 1:* + + +#+begin_src +Input: grid = [ + ["1","1","1","1","0"], + ["1","1","0","1","0"], + ["1","1","0","0","0"], + ["0","0","0","0","0"] +] +Output: 1 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: grid = [ + ["1","1","0","0","0"], + ["1","1","0","0","0"], + ["0","0","1","0","0"], + ["0","0","0","1","1"] +] +Output: 3 +#+end_src + + +*Constraints:* + + - ~m == grid.length~ + + - ~n == grid[i].length~ + + - ~1 <= m, n <= 300~ + + - ~grid[i][j]~ is ~'0'~ or ~'1'~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int numIslands(vector>& grid) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0207-course-schedule.org b/org/study_deck_02/dsa/graphs/0207-course-schedule.org index 9356d3e..bd88a87 100644 --- a/org/study_deck_02/dsa/graphs/0207-course-schedule.org +++ b/org/study_deck_02/dsa/graphs/0207-course-schedule.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0207. Course Schedule :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0207. Course Schedule][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0207. Course Schedule][0207. Course Schedule]] :END: +There are a total of ~numCourses~ courses you have to take, labeled from ~0~ to ~numCourses - 1~. You are given an array ~prerequisites~ where ~prerequisites[i] = [a_{i}, b_{i}]~ indicates that you *must* take course ~b_{i}~ first if you want to take course ~a_{i}~. + + - For example, the pair ~[0, 1]~, indicates that to take course ~0~ you have to first take course ~1~. + +Return ~true~ if you can finish all courses. Otherwise, return ~false~. + +*Example 1:* + + +#+begin_src +Input: numCourses = 2, prerequisites = [[1,0]] +Output: true +Explanation: There are a total of 2 courses to take. +To take course 1 you should have finished course 0. So it is possible. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: numCourses = 2, prerequisites = [[1,0],[0,1]] +Output: false +Explanation: There are a total of 2 courses to take. +To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. +#+end_src + + +*Constraints:* + + - ~1 <= numCourses <= 2000~ + + - ~0 <= prerequisites.length <= 5000~ + + - ~prerequisites[i].length == 2~ + + - ~0 <= a_{i}, b_{i} < numCourses~ + + - All the pairs prerequisites[i] are *unique*. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool canFinish(int numCourses, vector>& prerequisites) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0210-course-schedule-ii.org b/org/study_deck_02/dsa/graphs/0210-course-schedule-ii.org index c495595..6049aae 100644 --- a/org/study_deck_02/dsa/graphs/0210-course-schedule-ii.org +++ b/org/study_deck_02/dsa/graphs/0210-course-schedule-ii.org @@ -1,18 +1,74 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0210. Course Schedule II :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0210. Course Schedule II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0210. Course Schedule II][0210. Course Schedule II]] :END: +There are a total of ~numCourses~ courses you have to take, labeled from ~0~ to ~numCourses - 1~. You are given an array ~prerequisites~ where ~prerequisites[i] = [a_{i}, b_{i}]~ indicates that you *must* take course ~b_{i}~ first if you want to take course ~a_{i}~. + + - For example, the pair ~[0, 1]~, indicates that to take course ~0~ you have to first take course ~1~. + +Return /the ordering of courses you should take to finish all courses/. If there are many valid answers, return *any* of them. If it is impossible to finish all courses, return *an empty array*. + +*Example 1:* + + +#+begin_src +Input: numCourses = 2, prerequisites = [[1,0]] +Output: [0,1] +Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] +Output: [0,2,1,3] +Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. +So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: numCourses = 1, prerequisites = [] +Output: [0] +#+end_src + + +*Constraints:* + + - ~1 <= numCourses <= 2000~ + + - ~0 <= prerequisites.length <= numCourses * (numCourses - 1)~ + + - ~prerequisites[i].length == 2~ + + - ~0 <= a_{i}, b_{i} < numCourses~ + + - ~a_{i} != b_{i}~ + + - All the pairs ~[a_{i}, b_{i}]~ are *distinct*. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector findOrder(int numCourses, vector>& prerequisites) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0261-graph-valid-tree.org b/org/study_deck_02/dsa/graphs/0261-graph-valid-tree.org index e1da8cd..cb1b800 100644 --- a/org/study_deck_02/dsa/graphs/0261-graph-valid-tree.org +++ b/org/study_deck_02/dsa/graphs/0261-graph-valid-tree.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0261. Graph Valid Tree :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0261. Graph Valid Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0261. Graph Valid Tree][0261. Graph Valid Tree]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/graphs/0286-walls-and-gates.org b/org/study_deck_02/dsa/graphs/0286-walls-and-gates.org index 8811740..38ea24b 100644 --- a/org/study_deck_02/dsa/graphs/0286-walls-and-gates.org +++ b/org/study_deck_02/dsa/graphs/0286-walls-and-gates.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0286. Walls And Gates :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0286. Walls And Gates][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0286. Walls And Gates][0286. Walls And Gates]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/graphs/0323-number-of-connected-components-in-an-undirected-graph.org b/org/study_deck_02/dsa/graphs/0323-number-of-connected-components-in-an-undirected-graph.org index 0d92703..0e28168 100644 --- a/org/study_deck_02/dsa/graphs/0323-number-of-connected-components-in-an-undirected-graph.org +++ b/org/study_deck_02/dsa/graphs/0323-number-of-connected-components-in-an-undirected-graph.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0323. Number of Connected Components In An Undirected Graph :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0323. Number of Connected Components In An Undirected Graph][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0323. Number of Connected Components In An Undirected Graph][0323. Number of Connected Components In An Undirected Graph]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/graphs/0417-pacific-atlantic-water-flow.org b/org/study_deck_02/dsa/graphs/0417-pacific-atlantic-water-flow.org index 7528e17..b06fcc1 100644 --- a/org/study_deck_02/dsa/graphs/0417-pacific-atlantic-water-flow.org +++ b/org/study_deck_02/dsa/graphs/0417-pacific-atlantic-water-flow.org @@ -1,18 +1,77 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0417. Pacific Atlantic Water Flow :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0417. Pacific Atlantic Water Flow][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0417. Pacific Atlantic Water Flow][0417. Pacific Atlantic Water Flow]] :END: +There is an ~m x n~ rectangular island that borders both the *Pacific Ocean* and *Atlantic Ocean*. The *Pacific Ocean* touches the island's left and top edges, and the *Atlantic Ocean* touches the island's right and bottom edges. + +The island is partitioned into a grid of square cells. You are given an ~m x n~ integer matrix ~heights~ where ~heights[r][c]~ represents the *height above sea level* of the cell at coordinate ~(r, c)~. + +The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is *less than or equal to* the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. + +Return /a *2D list* of grid coordinates /~result~/ where /~result[i] = [r_{i}, c_{i}]~/ denotes that rain water can flow from cell /~(r_{i}, c_{i})~/ to *both* the Pacific and Atlantic oceans/. + +*Example 1:* + + +#+begin_src +Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] +Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] +Explanation: The following cells can flow to the Pacific and Atlantic oceans, as shown below: +[0,4]: [0,4] -> Pacific Ocean + [0,4] -> Atlantic Ocean +[1,3]: [1,3] -> [0,3] -> Pacific Ocean + [1,3] -> [1,4] -> Atlantic Ocean +[1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean + [1,4] -> Atlantic Ocean +[2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean + [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean +[3,0]: [3,0] -> Pacific Ocean + [3,0] -> [4,0] -> Atlantic Ocean +[3,1]: [3,1] -> [3,0] -> Pacific Ocean + [3,1] -> [4,1] -> Atlantic Ocean +[4,0]: [4,0] -> Pacific Ocean + [4,0] -> Atlantic Ocean +Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: heights = [[1]] +Output: [[0,0]] +Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans. +#+end_src + + +*Constraints:* + + - ~m == heights.length~ + + - ~n == heights[r].length~ + + - ~1 <= m, n <= 200~ + + - ~0 <= heights[r][c] <= 10^{5}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> pacificAtlantic(vector>& heights) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0684-redundant-connection.org b/org/study_deck_02/dsa/graphs/0684-redundant-connection.org index b6f8d35..a12623b 100644 --- a/org/study_deck_02/dsa/graphs/0684-redundant-connection.org +++ b/org/study_deck_02/dsa/graphs/0684-redundant-connection.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0684. Redundant Connection :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0684. Redundant Connection][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0684. Redundant Connection][0684. Redundant Connection]] :END: +In this problem, a tree is an *undirected graph* that is connected and has no cycles. + +You are given a graph that started as a tree with ~n~ nodes labeled from ~1~ to ~n~, with one additional edge added. The added edge has two *different* vertices chosen from ~1~ to ~n~, and was not an edge that already existed. The graph is represented as an array ~edges~ of length ~n~ where ~edges[i] = [a_{i}, b_{i}]~ indicates that there is an edge between nodes ~a_{i}~ and ~b_{i}~ in the graph. + +Return /an edge that can be removed so that the resulting graph is a tree of /~n~/ nodes/. If there are multiple answers, return the answer that occurs last in the input. + +*Example 1:* + + +#+begin_src +Input: edges = [[1,2],[1,3],[2,3]] +Output: [2,3] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]] +Output: [1,4] +#+end_src + + +*Constraints:* + + - ~n == edges.length~ + + - ~3 <= n <= 1000~ + + - ~edges[i].length == 2~ + + - ~1 <= a_{i} < b_{i} <= edges.length~ + + - ~a_{i} != b_{i}~ + + - There are no repeated edges. + + - The given graph is connected. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector findRedundantConnection(vector>& edges) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0695-max-area-of-island.org b/org/study_deck_02/dsa/graphs/0695-max-area-of-island.org index 8916ee4..1f3d6b0 100644 --- a/org/study_deck_02/dsa/graphs/0695-max-area-of-island.org +++ b/org/study_deck_02/dsa/graphs/0695-max-area-of-island.org @@ -1,18 +1,59 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0695. Max Area of Island :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0695. Max Area of Island][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0695. Max Area of Island][0695. Max Area of Island]] :END: +You are given an ~m x n~ binary matrix ~grid~. An island is a group of ~1~'s (representing land) connected *4-directionally* (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. + +The *area* of an island is the number of cells with a value ~1~ in the island. + +Return /the maximum *area* of an island in /~grid~. If there is no island, return ~0~. + +*Example 1:* + + +#+begin_src +Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]] +Output: 6 +Explanation: The answer is not 11, because the island must be connected 4-directionally. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: grid = [[0,0,0,0,0,0,0,0]] +Output: 0 +#+end_src + + +*Constraints:* + + - ~m == grid.length~ + + - ~n == grid[i].length~ + + - ~1 <= m, n <= 50~ + + - ~grid[i][j]~ is either ~0~ or ~1~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int maxAreaOfIsland(vector>& grid) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0802-find-eventual-safe-states.org b/org/study_deck_02/dsa/graphs/0802-find-eventual-safe-states.org index 88efb0a..f7cb1c9 100644 --- a/org/study_deck_02/dsa/graphs/0802-find-eventual-safe-states.org +++ b/org/study_deck_02/dsa/graphs/0802-find-eventual-safe-states.org @@ -1,18 +1,69 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0802. Find Eventual Safe States :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0802. Find Eventual Safe States][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0802. Find Eventual Safe States][0802. Find Eventual Safe States]] :END: +There is a directed graph of ~n~ nodes with each node labeled from ~0~ to ~n - 1~. The graph is represented by a *0-indexed* 2D integer array ~graph~ where ~graph[i]~ is an integer array of nodes adjacent to node ~i~, meaning there is an edge from node ~i~ to each node in ~graph[i]~. + +A node is a *terminal node* if there are no outgoing edges. A node is a *safe node* if every possible path starting from that node leads to a *terminal node* (or another safe node). + +Return /an array containing all the *safe nodes* of the graph/. The answer should be sorted in *ascending* order. + +*Example 1:* + + +#+begin_src +Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] +Output: [2,4,5,6] +Explanation: The given graph is shown above. +Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them. +Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]] +Output: [4] +Explanation: +Only node 4 is a terminal node, and every path starting at node 4 leads to node 4. +#+end_src + + +*Constraints:* + + - ~n == graph.length~ + + - ~1 <= n <= 10^{4}~ + + - ~0 <= graph[i].length <= n~ + + - ~0 <= graph[i][j] <= n - 1~ + + - ~graph[i]~ is sorted in a strictly increasing order. + + - The graph may contain self-loops. + + - The number of edges in the graph will be in the range ~[1, 4 * 10^{4}]~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector eventualSafeNodes(vector>& graph) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/0994-rotting-oranges.org b/org/study_deck_02/dsa/graphs/0994-rotting-oranges.org index 0523fb4..931feda 100644 --- a/org/study_deck_02/dsa/graphs/0994-rotting-oranges.org +++ b/org/study_deck_02/dsa/graphs/0994-rotting-oranges.org @@ -1,18 +1,75 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0994. Rotting Oranges :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0994. Rotting Oranges][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0994. Rotting Oranges][0994. Rotting Oranges]] :END: +You are given an ~m x n~ ~grid~ where each cell can have one of three values: + + - ~0~ representing an empty cell, + + - ~1~ representing a fresh orange, or + + - ~2~ representing a rotten orange. + +Every minute, any fresh orange that is *4-directionally adjacent* to a rotten orange becomes rotten. + +Return /the minimum number of minutes that must elapse until no cell has a fresh orange/. If /this is impossible, return/ ~-1~. + +*Example 1:* + + +#+begin_src +Input: grid = [[2,1,1],[1,1,0],[0,1,1]] +Output: 4 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: grid = [[2,1,1],[0,1,1],[1,0,1]] +Output: -1 +Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: grid = [[0,2]] +Output: 0 +Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. +#+end_src + + +*Constraints:* + + - ~m == grid.length~ + + - ~n == grid[i].length~ + + - ~1 <= m, n <= 10~ + + - ~grid[i][j]~ is ~0~, ~1~, or ~2~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def orangesRotting(self, grid: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int orangesRotting(vector>& grid) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/1905-count-sub-islands.org b/org/study_deck_02/dsa/graphs/1905-count-sub-islands.org index fa323cf..4b556e3 100644 --- a/org/study_deck_02/dsa/graphs/1905-count-sub-islands.org +++ b/org/study_deck_02/dsa/graphs/1905-count-sub-islands.org @@ -1,18 +1,62 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1905. Count Sub Islands :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1905. Count Sub Islands][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1905. Count Sub Islands][1905. Count Sub Islands]] :END: +You are given two ~m x n~ binary matrices ~grid1~ and ~grid2~ containing only ~0~'s (representing water) and ~1~'s (representing land). An *island* is a group of ~1~'s connected *4-directionally* (horizontal or vertical). Any cells outside of the grid are considered water cells. + +An island in ~grid2~ is considered a *sub-island *if there is an island in ~grid1~ that contains *all* the cells that make up *this* island in ~grid2~. + +Return the /*number* of islands in /~grid2~ /that are considered *sub-islands*/. + +*Example 1:* + + +#+begin_src +Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]] +Output: 3 +Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. +The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]] +Output: 2 +Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. +The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands. +#+end_src + + +*Constraints:* + + - ~m == grid1.length == grid2.length~ + + - ~n == grid1[i].length == grid2[i].length~ + + - ~1 <= m, n <= 500~ + + - ~grid1[i][j]~ and ~grid2[i][j]~ are either ~0~ or ~1~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int countSubIslands(vector>& grid1, vector>& grid2) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/2092-find-all-people-with-secret.org b/org/study_deck_02/dsa/graphs/2092-find-all-people-with-secret.org index b63db3f..92f323d 100644 --- a/org/study_deck_02/dsa/graphs/2092-find-all-people-with-secret.org +++ b/org/study_deck_02/dsa/graphs/2092-find-all-people-with-secret.org @@ -1,18 +1,92 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2092. Find All People With Secret :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2092. Find All People With Secret][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2092. Find All People With Secret][2092. Find All People With Secret]] :END: +You are given an integer ~n~ indicating there are ~n~ people numbered from ~0~ to ~n - 1~. You are also given a *0-indexed* 2D integer array ~meetings~ where ~meetings[i] = [x_{i}, y_{i}, time_{i}]~ indicates that person ~x_{i}~ and person ~y_{i}~ have a meeting at ~time_{i}~. A person may attend *multiple meetings* at the same time. Finally, you are given an integer ~firstPerson~. + +Person ~0~ has a *secret* and initially shares the secret with a person ~firstPerson~ at time ~0~. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person ~x_{i}~ has the secret at ~time_{i}~, then they will share the secret with person ~y_{i}~, and vice versa. + +The secrets are shared *instantaneously*. That is, a person may receive the secret and share it with people in other meetings within the same time frame. + +Return /a list of all the people that have the secret after all the meetings have taken place. /You may return the answer in *any order*. + +*Example 1:* + + +#+begin_src +Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1 +Output: [0,1,2,3,5] +Explanation: +At time 0, person 0 shares the secret with person 1. +At time 5, person 1 shares the secret with person 2. +At time 8, person 2 shares the secret with person 3. +At time 10, person 1 shares the secret with person 5.​​​​ +Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3 +Output: [0,1,3] +Explanation: +At time 0, person 0 shares the secret with person 3. +At time 2, neither person 1 nor person 2 know the secret. +At time 3, person 3 shares the secret with person 0 and person 1. +Thus, people 0, 1, and 3 know the secret after all the meetings. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1 +Output: [0,1,2,3,4] +Explanation: +At time 0, person 0 shares the secret with person 1. +At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3. +Note that person 2 can share the secret at the same time as receiving it. +At time 2, person 3 shares the secret with person 4. +Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings. +#+end_src + + +*Constraints:* + + - ~2 <= n <= 10^{5}~ + + - ~1 <= meetings.length <= 10^{5}~ + + - ~meetings[i].length == 3~ + + - ~0 <= x_{i}, y_{i }<= n - 1~ + + - ~x_{i} != y_{i}~ + + - ~1 <= time_{i} <= 10^{5}~ + + - ~1 <= firstPerson <= n - 1~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector findAllPeople(int n, vector>& meetings, int firstPerson) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/2658-maximum-number-of-fish-in-a-grid.org b/org/study_deck_02/dsa/graphs/2658-maximum-number-of-fish-in-a-grid.org index bebf82b..0a8dd57 100644 --- a/org/study_deck_02/dsa/graphs/2658-maximum-number-of-fish-in-a-grid.org +++ b/org/study_deck_02/dsa/graphs/2658-maximum-number-of-fish-in-a-grid.org @@ -1,18 +1,70 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2658. Maximum Number of Fish in a Grid :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2658. Maximum Number of Fish in a Grid][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2658. Maximum Number of Fish in a Grid][2658. Maximum Number of Fish in a Grid]] :END: +You are given a *0-indexed* 2D matrix ~grid~ of size ~m x n~, where ~(r, c)~ represents: + + - A *land* cell if ~grid[r][c] = 0~, or + + - A *water* cell containing ~grid[r][c]~ fish, if ~grid[r][c] > 0~. + +A fisher can start at any *water* cell ~(r, c)~ and can do the following operations any number of times: + + - Catch all the fish at cell ~(r, c)~, or + + - Move to any adjacent *water* cell. + +Return /the *maximum* number of fish the fisher can catch if he chooses his starting cell optimally, or /~0~ if no water cell exists. + +An *adjacent* cell of the cell ~(r, c)~, is one of the cells ~(r, c + 1)~, ~(r, c - 1)~, ~(r + 1, c)~ or ~(r - 1, c)~ if it exists. + +*Example 1:* + + +#+begin_src +Input: grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]] +Output: 7 +Explanation: The fisher can start at cell (1,3) and collect 3 fish, then move to cell (2,3) and collect 4 fish. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] +Output: 1 +Explanation: The fisher can start at cells (0,0) or (3,3) and collect a single fish. +#+end_src + + +*Constraints:* + + - ~m == grid.length~ + + - ~n == grid[i].length~ + + - ~1 <= m, n <= 10~ + + - ~0 <= grid[i][j] <= 10~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findMaxFish(self, grid: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int findMaxFish(vector>& grid) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/graphs/2924-find-champion-ii.org b/org/study_deck_02/dsa/graphs/2924-find-champion-ii.org index 11c5565..24582b2 100644 --- a/org/study_deck_02/dsa/graphs/2924-find-champion-ii.org +++ b/org/study_deck_02/dsa/graphs/2924-find-champion-ii.org @@ -1,18 +1,78 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2924. Find Champion II :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2924. Find Champion II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2924. Find Champion II][2924. Find Champion II]] :END: +There are ~n~ teams numbered from ~0~ to ~n - 1~ in a tournament; each team is also a node in a *DAG*. + +You are given the integer ~n~ and a *0-indexed* 2D integer array ~edges~ of length ~m~ representing the *DAG*, where ~edges[i] = [u_{i}, v_{i}]~ indicates that there is a directed edge from team ~u_{i}~ to team ~v_{i}~ in the graph. + +A directed edge from ~a~ to ~b~ in the graph means that team ~a~ is *stronger* than team ~b~ and team ~b~ is *weaker* than team ~a~. + +Team ~a~ will be the *champion* of the tournament if there is no team ~b~ that is *stronger* than team ~a~. + +Return /the team that will be the *champion* of the tournament if there is a *unique* champion, otherwise, return /~-1~/./ + +*Notes* + + - A *cycle* is a series of nodes ~a_{1}, a_{2}, ..., a_{n}, a_{n+1}~ such that node ~a_{1}~ is the same node as node ~a_{n+1}~, the nodes ~a_{1}, a_{2}, ..., a_{n}~ are distinct, and there is a directed edge from the node ~a_{i}~ to node ~a_{i+1}~ for every ~i~ in the range ~[1, n]~. + + - A *DAG* is a directed graph that does not have any *cycle*. + +*Example 1:* + + +#+begin_src +Input: n = 3, edges = [[0,1],[1,2]] +Output: 0 +Explanation: Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 4, edges = [[0,2],[1,3],[1,2]] +Output: -1 +Explanation: Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -1. +#+end_src + + +*Constraints:* + + - ~1 <= n <= 100~ + + - ~m == edges.length~ + + - ~0 <= m <= n * (n - 1) / 2~ + + - ~edges[i].length == 2~ + + - ~0 <= edge[i][j] <= n - 1~ + + - ~edges[i][0] != edges[i][1]~ + + - The input is generated such that if team ~a~ is stronger than team ~b~, team ~b~ is not stronger than team ~a~. + + - The input is generated such that if team ~a~ is stronger than team ~b~ and team ~b~ is stronger than team ~c~, then team ~a~ is stronger than team ~c~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findChampion(self, n: int, edges: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int findChampion(int n, vector>& edges) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/0045-jump-game-ii.org b/org/study_deck_02/dsa/greedy/0045-jump-game-ii.org index 57713ed..4db29be 100644 --- a/org/study_deck_02/dsa/greedy/0045-jump-game-ii.org +++ b/org/study_deck_02/dsa/greedy/0045-jump-game-ii.org @@ -1,18 +1,61 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0045. Jump Game II :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0045. Jump Game II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0045. Jump Game II][0045. Jump Game II]] :END: +You are given a *0-indexed* array of integers ~nums~ of length ~n~. You are initially positioned at index 0. + +Each element ~nums[i]~ represents the maximum length of a forward jump from index ~i~. In other words, if you are at index ~i~, you can jump to any index ~(i + j)~ where: + + - ~0 <= j <= nums[i]~ and + + - ~i + j < n~ + +Return /the minimum number of jumps to reach index /~n - 1~. The test cases are generated such that you can reach index ~n - 1~. + +*Example 1:* + + +#+begin_src +Input: nums = [2,3,1,1,4] +Output: 2 +Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [2,3,0,1,4] +Output: 2 +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 10^{4}~ + + - ~0 <= nums[i] <= 1000~ + + - It's guaranteed that you can reach ~nums[n - 1]~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def jump(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int jump(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/0053-maximum-subarray.org b/org/study_deck_02/dsa/greedy/0053-maximum-subarray.org index 19e508e..dc7ec6a 100644 --- a/org/study_deck_02/dsa/greedy/0053-maximum-subarray.org +++ b/org/study_deck_02/dsa/greedy/0053-maximum-subarray.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0053. Maximum Subarray :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0053. Maximum Subarray][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0053. Maximum Subarray][0053. Maximum Subarray]] :END: +Given an integer array ~nums~, find the subarray with the largest sum, and return /its sum/. + +*Example 1:* + + +#+begin_src +Input: nums = [-2,1,-3,4,-1,2,1,-5,4] +Output: 6 +Explanation: The subarray [4,-1,2,1] has the largest sum 6. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [1] +Output: 1 +Explanation: The subarray [1] has the largest sum 1. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [5,4,-1,7,8] +Output: 23 +Explanation: The subarray [5,4,-1,7,8] has the largest sum 23. +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 10^{5}~ + + - ~-10^{4} <= nums[i] <= 10^{4}~ + +*Follow up:* If you have figured out the ~O(n)~ solution, try coding another solution using the *divide and conquer* approach, which is more subtle. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxSubArray(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int maxSubArray(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/0055-jump-game.org b/org/study_deck_02/dsa/greedy/0055-jump-game.org index 2181b9c..ef449cc 100644 --- a/org/study_deck_02/dsa/greedy/0055-jump-game.org +++ b/org/study_deck_02/dsa/greedy/0055-jump-game.org @@ -1,18 +1,54 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0055. Jump Game :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0055. Jump Game][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0055. Jump Game][0055. Jump Game]] :END: +You are given an integer array ~nums~. You are initially positioned at the array's *first index*, and each element in the array represents your maximum jump length at that position. + +Return ~true~/ if you can reach the last index, or /~false~/ otherwise/. + +*Example 1:* + + +#+begin_src +Input: nums = [2,3,1,1,4] +Output: true +Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [3,2,1,0,4] +Output: false +Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 10^{4}~ + + - ~0 <= nums[i] <= 10^{5}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def canJump(self, nums: List[int]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool canJump(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/0134-gas-station.org b/org/study_deck_02/dsa/greedy/0134-gas-station.org index d072480..8bb53cd 100644 --- a/org/study_deck_02/dsa/greedy/0134-gas-station.org +++ b/org/study_deck_02/dsa/greedy/0134-gas-station.org @@ -1,18 +1,73 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0134. Gas Station :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0134. Gas Station][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0134. Gas Station][0134. Gas Station]] :END: +There are ~n~ gas stations along a circular route, where the amount of gas at the ~i^{th}~ station is ~gas[i]~. + +You have a car with an unlimited gas tank and it costs ~cost[i]~ of gas to travel from the ~i^{th}~ station to its next ~(i + 1)^{th}~ station. You begin the journey with an empty tank at one of the gas stations. + +Given two integer arrays ~gas~ and ~cost~, return /the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return/ ~-1~. If there exists a solution, it is *guaranteed* to be *unique*. + +*Example 1:* + + +#+begin_src +Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] +Output: 3 +Explanation: +Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 +Travel to station 4. Your tank = 4 - 1 + 5 = 8 +Travel to station 0. Your tank = 8 - 2 + 1 = 7 +Travel to station 1. Your tank = 7 - 3 + 2 = 6 +Travel to station 2. Your tank = 6 - 4 + 3 = 5 +Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. +Therefore, return 3 as the starting index. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: gas = [2,3,4], cost = [3,4,3] +Output: -1 +Explanation: +You can't start at station 0 or 1, as there is not enough gas to travel to the next station. +Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 +Travel to station 0. Your tank = 4 - 3 + 2 = 3 +Travel to station 1. Your tank = 3 - 3 + 3 = 3 +You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. +Therefore, you can't travel around the circuit once no matter where you start. +#+end_src + + +*Constraints:* + + - ~n == gas.length == cost.length~ + + - ~1 <= n <= 10^{5}~ + + - ~0 <= gas[i], cost[i] <= 10^{4}~ + + - The input is generated such that the answer is unique. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int canCompleteCircuit(vector& gas, vector& cost) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/0678-valid-parenthesis-string.org b/org/study_deck_02/dsa/greedy/0678-valid-parenthesis-string.org index 7ce6ad7..614d63b 100644 --- a/org/study_deck_02/dsa/greedy/0678-valid-parenthesis-string.org +++ b/org/study_deck_02/dsa/greedy/0678-valid-parenthesis-string.org @@ -1,18 +1,65 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0678. Valid Parenthesis String :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0678. Valid Parenthesis String][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0678. Valid Parenthesis String][0678. Valid Parenthesis String]] :END: +Given a string ~s~ containing only three types of characters: ~'('~, ~')'~ and ~'*'~, return ~true~ /if/ ~s~ /is *valid*/. + +The following rules define a *valid* string: + + - Any left parenthesis ~'('~ must have a corresponding right parenthesis ~')'~. + + - Any right parenthesis ~')'~ must have a corresponding left parenthesis ~'('~. + + - Left parenthesis ~'('~ must go before the corresponding right parenthesis ~')'~. + + - ~'*'~ could be treated as a single right parenthesis ~')'~ or a single left parenthesis ~'('~ or an empty string ~""~. + +*Example 1:* + + +#+begin_src +Input: s = "()" +Output: true +#+end_src +*Example 2:* + + +#+begin_src +Input: s = "(*)" +Output: true +#+end_src +*Example 3:* + + +#+begin_src +Input: s = "(*))" +Output: true +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 100~ + + - ~s[i]~ is ~'('~, ~')'~ or ~'*'~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def checkValidString(self, s: str) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool checkValidString(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/0763-partition-labels.org b/org/study_deck_02/dsa/greedy/0763-partition-labels.org index 79eef0e..53af6ba 100644 --- a/org/study_deck_02/dsa/greedy/0763-partition-labels.org +++ b/org/study_deck_02/dsa/greedy/0763-partition-labels.org @@ -1,18 +1,58 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0763. Partition Labels :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0763. Partition Labels][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0763. Partition Labels][0763. Partition Labels]] :END: +You are given a string ~s~. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string ~"ababcc"~ can be partitioned into ~["abab", "cc"]~, but partitions such as ~["aba", "bcc"]~ or ~["ab", "ab", "cc"]~ are invalid. + +Note that the partition is done so that after concatenating all the parts in order, the resultant string should be ~s~. + +Return /a list of integers representing the size of these parts/. + +*Example 1:* + + +#+begin_src +Input: s = "ababcbacadefegdehijhklij" +Output: [9,7,8] +Explanation: +The partition is "ababcbaca", "defegde", "hijhklij". +This is a partition so that each letter appears in at most one part. +A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "eccbbbbdec" +Output: [10] +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 500~ + + - ~s~ consists of lowercase English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def partitionLabels(self, s: str) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector partitionLabels(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/0846-hand-of-straights.org b/org/study_deck_02/dsa/greedy/0846-hand-of-straights.org index cba8660..0dbd79b 100644 --- a/org/study_deck_02/dsa/greedy/0846-hand-of-straights.org +++ b/org/study_deck_02/dsa/greedy/0846-hand-of-straights.org @@ -1,18 +1,58 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0846. Hand of Straights :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0846. Hand of Straights][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0846. Hand of Straights][0846. Hand of Straights]] :END: +Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size ~groupSize~, and consists of ~groupSize~ consecutive cards. + +Given an integer array ~hand~ where ~hand[i]~ is the value written on the ~i^{th}~ card and an integer ~groupSize~, return ~true~ if she can rearrange the cards, or ~false~ otherwise. + +*Example 1:* + + +#+begin_src +Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 +Output: true +Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: hand = [1,2,3,4,5], groupSize = 4 +Output: false +Explanation: Alice's hand can not be rearranged into groups of 4. +#+end_src + + +*Constraints:* + + - ~1 <= hand.length <= 10^{4}~ + + - ~0 <= hand[i] <= 10^{9}~ + + - ~1 <= groupSize <= hand.length~ + +*Note:* This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isNStraightHand(vector& hand, int groupSize) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/0945-minimum-increment-to-make-array-unique.org b/org/study_deck_02/dsa/greedy/0945-minimum-increment-to-make-array-unique.org index e946a50..daa6ae4 100644 --- a/org/study_deck_02/dsa/greedy/0945-minimum-increment-to-make-array-unique.org +++ b/org/study_deck_02/dsa/greedy/0945-minimum-increment-to-make-array-unique.org @@ -1,18 +1,57 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0945. Minimum Increment to Make Array Unique :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0945. Minimum Increment to Make Array Unique][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0945. Minimum Increment to Make Array Unique][0945. Minimum Increment to Make Array Unique]] :END: +You are given an integer array ~nums~. In one move, you can pick an index ~i~ where ~0 <= i < nums.length~ and increment ~nums[i]~ by ~1~. + +Return /the minimum number of moves to make every value in /~nums~/ *unique*/. + +The test cases are generated so that the answer fits in a 32-bit integer. + +*Example 1:* + + +#+begin_src +Input: nums = [1,2,2] +Output: 1 +Explanation: After 1 move, the array could be [1, 2, 3]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [3,2,1,2,1,7] +Output: 6 +Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. +It can be shown that it is impossible for the array to have all unique values with 5 or less moves. +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 10^{5}~ + + - ~0 <= nums[i] <= 10^{5}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def minIncrementForUnique(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int minIncrementForUnique(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/0978-longest-turbulent-subarray.org b/org/study_deck_02/dsa/greedy/0978-longest-turbulent-subarray.org index 3fd6c91..4a4dfb5 100644 --- a/org/study_deck_02/dsa/greedy/0978-longest-turbulent-subarray.org +++ b/org/study_deck_02/dsa/greedy/0978-longest-turbulent-subarray.org @@ -1,18 +1,76 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0978. Longest Turbulent Subarray :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0978. Longest Turbulent Subarray][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0978. Longest Turbulent Subarray][0978. Longest Turbulent Subarray]] :END: +Given an integer array ~arr~, return /the length of a maximum size turbulent subarray of/ ~arr~. + +A subarray is *turbulent* if the comparison sign flips between each adjacent pair of elements in the subarray. + +More formally, a subarray ~[arr[i], arr[i + 1], ..., arr[j]]~ of ~arr~ is said to be turbulent if and only if: + + - For ~i <= k < j~: + + - ~arr[k] > arr[k + 1]~ when ~k~ is odd, and + + - ~arr[k] < arr[k + 1]~ when ~k~ is even. + + - Or, for ~i <= k < j~: + + - ~arr[k] > arr[k + 1]~ when ~k~ is even, and + + - ~arr[k] < arr[k + 1]~ when ~k~ is odd. + +*Example 1:* + + +#+begin_src +Input: arr = [9,4,2,10,7,8,8,1,9] +Output: 5 +Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: arr = [4,8,12,16] +Output: 2 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: arr = [100] +Output: 1 +#+end_src + + +*Constraints:* + + - ~1 <= arr.length <= 4 * 10^{4}~ + + - ~0 <= arr[i] <= 10^{9}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxTurbulenceSize(self, arr: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int maxTurbulenceSize(vector& arr) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/1871-jump-game-vii.org b/org/study_deck_02/dsa/greedy/1871-jump-game-vii.org index 849cebb..5d5cda2 100644 --- a/org/study_deck_02/dsa/greedy/1871-jump-game-vii.org +++ b/org/study_deck_02/dsa/greedy/1871-jump-game-vii.org @@ -1,18 +1,63 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1871. Jump Game VII :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1871. Jump Game VII][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1871. Jump Game VII][1871. Jump Game VII]] :END: +You are given a *0-indexed* binary string ~s~ and two integers ~minJump~ and ~maxJump~. In the beginning, you are standing at index ~0~, which is equal to ~'0'~. You can move from index ~i~ to index ~j~ if the following conditions are fulfilled: + + - ~i + minJump <= j <= min(i + maxJump, s.length - 1)~, and + + - ~s[j] == '0'~. + +Return ~true~ if you can reach index ~s.length - 1~ in ~s~/, or /~false~/ otherwise./ + +*Example 1:* + + +#+begin_src +Input: s = "011010", minJump = 2, maxJump = 3 +Output: true +Explanation: +In the first step, move from index 0 to index 3. +In the second step, move from index 3 to index 5. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "01101110", minJump = 2, maxJump = 3 +Output: false +#+end_src + + +*Constraints:* + + - ~2 <= s.length <= 10^{5}~ + + - ~s[i]~ is either ~'0'~ or ~'1'~. + + - ~s[0] == '0'~ + + - ~1 <= minJump <= maxJump < s.length~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def canReach(self, s: str, minJump: int, maxJump: int) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool canReach(string s, int minJump, int maxJump) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/greedy/1899-merge-triplets-to-form-target-triplet.org b/org/study_deck_02/dsa/greedy/1899-merge-triplets-to-form-target-triplet.org index f664e65..0fadf2f 100644 --- a/org/study_deck_02/dsa/greedy/1899-merge-triplets-to-form-target-triplet.org +++ b/org/study_deck_02/dsa/greedy/1899-merge-triplets-to-form-target-triplet.org @@ -1,18 +1,77 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1899. Merge Triplets to Form Target Triplet :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1899. Merge Triplets to Form Target Triplet][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1899. Merge Triplets to Form Target Triplet][1899. Merge Triplets to Form Target Triplet]] :END: +A *triplet* is an array of three integers. You are given a 2D integer array ~triplets~, where ~triplets[i] = [a_{i}, b_{i}, c_{i}]~ describes the ~i^{th}~ *triplet*. You are also given an integer array ~target = [x, y, z]~ that describes the *triplet* you want to obtain. + +To obtain ~target~, you may apply the following operation on ~triplets~ *any number* of times (possibly *zero*): + + - Choose two indices (*0-indexed*) ~i~ and ~j~ (~i != j~) and *update* ~triplets[j]~ to become ~[max(a_{i}, a_{j}), max(b_{i}, b_{j}), max(c_{i}, c_{j})]~. + + - For example, if ~triplets[i] = [2, 5, 3]~ and ~triplets[j] = [1, 7, 5]~, ~triplets[j]~ will be updated to ~[max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]~. + +Return ~true~ /if it is possible to obtain the /~target~/ *triplet* /~[x, y, z]~/ as an* element* of /~triplets~/, or /~false~/ otherwise/. + +*Example 1:* + + +#+begin_src +Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] +Output: true +Explanation: Perform the following operations: +- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]] +The target triplet [2,7,5] is now an element of triplets. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5] +Output: false +Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] +Output: true +Explanation: Perform the following operations: +- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. +- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]]. +The target triplet [5,5,5] is now an element of triplets. +#+end_src + + +*Constraints:* + + - ~1 <= triplets.length <= 10^{5}~ + + - ~triplets[i].length == target.length == 3~ + + - ~1 <= a_{i}, b_{i}, c_{i}, x, y, z <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool mergeTriplets(vector>& triplets, vector& target) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/heap-priority-queue/0215-kth-largest-element-in-an-array.org b/org/study_deck_02/dsa/heap-priority-queue/0215-kth-largest-element-in-an-array.org index 8e306b5..8cc427f 100644 --- a/org/study_deck_02/dsa/heap-priority-queue/0215-kth-largest-element-in-an-array.org +++ b/org/study_deck_02/dsa/heap-priority-queue/0215-kth-largest-element-in-an-array.org @@ -1,18 +1,52 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0215. Kth Largest Element In An Array :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0215. Kth Largest Element In An Array][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0215. Kth Largest Element In An Array][0215. Kth Largest Element In An Array]] :END: +Given an integer array ~nums~ and an integer ~k~, return /the/ ~k^{th}~ /largest element in the array/. + +Note that it is the ~k^{th}~ largest element in the sorted order, not the ~k^{th}~ distinct element. + +Can you solve it without sorting? + +*Example 1:* + + +#+begin_src +Input: nums = [3,2,1,5,6,4], k = 2 +Output: 5 +#+end_src +*Example 2:* + + +#+begin_src +Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 +Output: 4 +#+end_src + + +*Constraints:* + + - ~1 <= k <= nums.length <= 10^{5}~ + + - ~-10^{4} <= nums[i] <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int findKthLargest(vector& nums, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/heap-priority-queue/0295-find-median-from-data-stream.org b/org/study_deck_02/dsa/heap-priority-queue/0295-find-median-from-data-stream.org index b21c48f..ea1836f 100644 --- a/org/study_deck_02/dsa/heap-priority-queue/0295-find-median-from-data-stream.org +++ b/org/study_deck_02/dsa/heap-priority-queue/0295-find-median-from-data-stream.org @@ -1,18 +1,101 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0295. Find Median From Data Stream :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0295. Find Median From Data Stream][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0295. Find Median From Data Stream][0295. Find Median From Data Stream]] :END: +The *median* is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. + + - For example, for ~arr = [2,3,4]~, the median is ~3~. + + - For example, for ~arr = [2,3]~, the median is ~(2 + 3) / 2 = 2.5~. + +Implement the MedianFinder class: + + - ~MedianFinder()~ initializes the ~MedianFinder~ object. + + - ~void addNum(int num)~ adds the integer ~num~ from the data stream to the data structure. + + - ~double findMedian()~ returns the median of all elements so far. Answers within ~10^{-5}~ of the actual answer will be accepted. + +*Example 1:* + + +#+begin_src +Input +["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] +[[], [1], [2], [], [3], []] +Output +[null, null, null, 1.5, null, 2.0] + +Explanation +MedianFinder medianFinder = new MedianFinder(); +medianFinder.addNum(1); // arr = [1] +medianFinder.addNum(2); // arr = [1, 2] +medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) +medianFinder.addNum(3); // arr[1, 2, 3] +medianFinder.findMedian(); // return 2.0 +#+end_src + + +*Constraints:* + + - ~-10^{5} <= num <= 10^{5}~ + + - There will be at least one element in the data structure before calling ~findMedian~. + + - At most ~5 * 10^{4}~ calls will be made to ~addNum~ and ~findMedian~. + +*Follow up:* + + - If all integer numbers from the stream are in the range ~[0, 100]~, how would you optimize your solution? + + - If ~99%~ of all integer numbers from the stream are in the range ~[0, 100]~, how would you optimize your solution? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class MedianFinder: + def __init__(self): + + + def addNum(self, num: int) -> None: + + + def findMedian(self) -> float: + + + +# Your MedianFinder object will be instantiated and called as such: +# obj = MedianFinder() +# obj.addNum(num) +# param_2 = obj.findMedian() #+end_src ** TODO C++ #+begin_src cpp +class MedianFinder { +public: + MedianFinder() { + + } + + void addNum(int num) { + + } + + double findMedian() { + + } +}; +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder* obj = new MedianFinder(); + * obj->addNum(num); + * double param_2 = obj->findMedian(); + */ #+end_src diff --git a/org/study_deck_02/dsa/heap-priority-queue/0355-design-twitter.org b/org/study_deck_02/dsa/heap-priority-queue/0355-design-twitter.org index 98c8e9a..054ca96 100644 --- a/org/study_deck_02/dsa/heap-priority-queue/0355-design-twitter.org +++ b/org/study_deck_02/dsa/heap-priority-queue/0355-design-twitter.org @@ -1,18 +1,119 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0355. Design Twitter :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0355. Design Twitter][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0355. Design Twitter][0355. Design Twitter]] :END: +Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the ~10~ most recent tweets in the user's news feed. + +Implement the ~Twitter~ class: + + - ~Twitter()~ Initializes your twitter object. + + - ~void postTweet(int userId, int tweetId)~ Composes a new tweet with ID ~tweetId~ by the user ~userId~. Each call to this function will be made with a unique ~tweetId~. + + - ~List getNewsFeed(int userId)~ Retrieves the ~10~ most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be *ordered from most recent to least recent*. + + - ~void follow(int followerId, int followeeId)~ The user with ID ~followerId~ started following the user with ID ~followeeId~. + + - ~void unfollow(int followerId, int followeeId)~ The user with ID ~followerId~ started unfollowing the user with ID ~followeeId~. + +*Example 1:* + + +#+begin_src +Input +["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] +[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] +Output +[null, null, [5], null, null, [6, 5], null, [5]] + +Explanation +Twitter twitter = new Twitter(); +twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] +twitter.follow(1, 2); // User 1 follows user 2. +twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. +twitter.unfollow(1, 2); // User 1 unfollows user 2. +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2. +#+end_src + + +*Constraints:* + + - ~1 <= userId, followerId, followeeId <= 500~ + + - ~0 <= tweetId <= 10^{4}~ + + - All the tweets have *unique* IDs. + + - At most ~3 * 10^{4}~ calls will be made to ~postTweet~, ~getNewsFeed~, ~follow~, and ~unfollow~. + + - A user cannot follow himself. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class Twitter: + def __init__(self): + + + def postTweet(self, userId: int, tweetId: int) -> None: + + + def getNewsFeed(self, userId: int) -> List[int]: + + + def follow(self, followerId: int, followeeId: int) -> None: + + + def unfollow(self, followerId: int, followeeId: int) -> None: + + + +# Your Twitter object will be instantiated and called as such: +# obj = Twitter() +# obj.postTweet(userId,tweetId) +# param_2 = obj.getNewsFeed(userId) +# obj.follow(followerId,followeeId) +# obj.unfollow(followerId,followeeId) #+end_src ** TODO C++ #+begin_src cpp +class Twitter { +public: + Twitter() { + + } + + void postTweet(int userId, int tweetId) { + + } + + vector getNewsFeed(int userId) { + + } + + void follow(int followerId, int followeeId) { + + } + + void unfollow(int followerId, int followeeId) { + + } +}; +/** + * Your Twitter object will be instantiated and called as such: + * Twitter* obj = new Twitter(); + * obj->postTweet(userId,tweetId); + * vector param_2 = obj->getNewsFeed(userId); + * obj->follow(followerId,followeeId); + * obj->unfollow(followerId,followeeId); + */ #+end_src diff --git a/org/study_deck_02/dsa/heap-priority-queue/0621-task-scheduler.org b/org/study_deck_02/dsa/heap-priority-queue/0621-task-scheduler.org index 39229a7..1110bcb 100644 --- a/org/study_deck_02/dsa/heap-priority-queue/0621-task-scheduler.org +++ b/org/study_deck_02/dsa/heap-priority-queue/0621-task-scheduler.org @@ -1,18 +1,66 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0621. Task Scheduler :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0621. Task Scheduler][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0621. Task Scheduler][0621. Task Scheduler]] :END: +You are given an array of CPU ~tasks~, each labeled with a letter from A to Z, and a number ~n~. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there's a constraint: there has to be a gap of *at least* ~n~ intervals between two tasks with the same label. + +Return the *minimum* number of CPU intervals required to complete all tasks. + +*Example 1:* + +*Input:* tasks = ["A","A","A","B","B","B"], n = 2 + +*Output:* 8 + +*Explanation:* A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B. + +After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3^{rd} interval, neither A nor B can be done, so you idle. By the 4^{th} interval, you can do A again as 2 intervals have passed. + +*Example 2:* + +*Input:* tasks = ["A","C","A","B","D","B"], n = 1 + +*Output:* 6 + +*Explanation:* A possible sequence is: A -> B -> C -> D -> A -> B. + +With a cooling interval of 1, you can repeat a task after just one other task. + +*Example 3:* + +*Input:* tasks = ["A","A","A", "B","B","B"], n = 3 + +*Output:* 10 + +*Explanation:* A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B. + +There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks. + +*Constraints:* + + - ~1 <= tasks.length <= 10^{4}~ + + - ~tasks[i]~ is an uppercase English letter. + + - ~0 <= n <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def leastInterval(self, tasks: List[str], n: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int leastInterval(vector& tasks, int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/heap-priority-queue/0703-kth-largest-element-in-a-stream.org b/org/study_deck_02/dsa/heap-priority-queue/0703-kth-largest-element-in-a-stream.org index 2ab1984..00bc438 100644 --- a/org/study_deck_02/dsa/heap-priority-queue/0703-kth-largest-element-in-a-stream.org +++ b/org/study_deck_02/dsa/heap-priority-queue/0703-kth-largest-element-in-a-stream.org @@ -1,18 +1,112 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0703. Kth Largest Element In a Stream :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0703. Kth Largest Element In a Stream][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0703. Kth Largest Element In a Stream][0703. Kth Largest Element In a Stream]] :END: +You are part of a university admissions office and need to keep track of the ~kth~ highest test score from applicants in real-time. This helps to determine cut-off marks for interviews and admissions dynamically as new applicants submit their scores. + +You are tasked to implement a class which, for a given integer ~k~, maintains a stream of test scores and continuously returns the ~k~th highest test score *after* a new score has been submitted. More specifically, we are looking for the ~k~th highest score in the sorted list of all scores. + +Implement the ~KthLargest~ class: + + - ~KthLargest(int k, int[] nums)~ Initializes the object with the integer ~k~ and the stream of test scores ~nums~. + + - ~int add(int val)~ Adds a new test score ~val~ to the stream and returns the element representing the ~k^{th}~ largest element in the pool of test scores so far. + +*Example 1:* + +*Input:* + +["KthLargest", "add", "add", "add", "add", "add"] + +[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] + +*Output:* [null, 4, 5, 5, 8, 8] + +*Explanation:* + +KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); + +kthLargest.add(3); // return 4 + +kthLargest.add(5); // return 5 + +kthLargest.add(10); // return 5 + +kthLargest.add(9); // return 8 + +kthLargest.add(4); // return 8 + +*Example 2:* + +*Input:* + +["KthLargest", "add", "add", "add", "add"] + +[[4, [7, 7, 7, 7, 8, 3]], [2], [10], [9], [9]] + +*Output:* [null, 7, 7, 7, 8] + +*Explanation:* + +KthLargest kthLargest = new KthLargest(4, [7, 7, 7, 7, 8, 3]); + +kthLargest.add(2); // return 7 + +kthLargest.add(10); // return 7 + +kthLargest.add(9); // return 7 + +kthLargest.add(9); // return 8 + +*Constraints:* + + - ~0 <= nums.length <= 10^{4}~ + + - ~1 <= k <= nums.length + 1~ + + - ~-10^{4} <= nums[i] <= 10^{4}~ + + - ~-10^{4} <= val <= 10^{4}~ + + - At most ~10^{4}~ calls will be made to ~add~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class KthLargest: + def __init__(self, k: int, nums: List[int]): + + + def add(self, val: int) -> int: + + + +# Your KthLargest object will be instantiated and called as such: +# obj = KthLargest(k, nums) +# param_1 = obj.add(val) #+end_src ** TODO C++ #+begin_src cpp +class KthLargest { +public: + KthLargest(int k, vector& nums) { + + } + + int add(int val) { + + } +}; +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest* obj = new KthLargest(k, nums); + * int param_1 = obj->add(val); + */ #+end_src diff --git a/org/study_deck_02/dsa/heap-priority-queue/0973-k-closest-points-to-origin.org b/org/study_deck_02/dsa/heap-priority-queue/0973-k-closest-points-to-origin.org index 0971014..514ac58 100644 --- a/org/study_deck_02/dsa/heap-priority-queue/0973-k-closest-points-to-origin.org +++ b/org/study_deck_02/dsa/heap-priority-queue/0973-k-closest-points-to-origin.org @@ -1,18 +1,60 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0973. K Closest Points to Origin :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0973. K Closest Points to Origin][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0973. K Closest Points to Origin][0973. K Closest Points to Origin]] :END: +Given an array of ~points~ where ~points[i] = [x_{i}, y_{i}]~ represents a point on the *X-Y* plane and an integer ~k~, return the ~k~ closest points to the origin ~(0, 0)~. + +The distance between two points on the *X-Y* plane is the Euclidean distance (i.e., ~√(x_{1} - x_{2})^{2} + (y_{1} - y_{2})^{2}~). + +You may return the answer in *any order*. The answer is *guaranteed* to be *unique* (except for the order that it is in). + +*Example 1:* + + +#+begin_src +Input: points = [[1,3],[-2,2]], k = 1 +Output: [[-2,2]] +Explanation: +The distance between (1, 3) and the origin is sqrt(10). +The distance between (-2, 2) and the origin is sqrt(8). +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: points = [[3,3],[5,-1],[-2,4]], k = 2 +Output: [[3,3],[-2,4]] +Explanation: The answer [[-2,4],[3,3]] would also be accepted. +#+end_src + + +*Constraints:* + + - ~1 <= k <= points.length <= 10^{4}~ + + - ~-10^{4} <= x_{i}, y_{i} <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> kClosest(vector>& points, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/heap-priority-queue/1046-last-stone-weight.org b/org/study_deck_02/dsa/heap-priority-queue/1046-last-stone-weight.org index 165bc5d..63d3f3a 100644 --- a/org/study_deck_02/dsa/heap-priority-queue/1046-last-stone-weight.org +++ b/org/study_deck_02/dsa/heap-priority-queue/1046-last-stone-weight.org @@ -1,18 +1,65 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1046. Last Stone Weight :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1046. Last Stone Weight][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1046. Last Stone Weight][1046. Last Stone Weight]] :END: +You are given an array of integers ~stones~ where ~stones[i]~ is the weight of the ~i^{th}~ stone. + +We are playing a game with the stones. On each turn, we choose the *heaviest two stones* and smash them together. Suppose the heaviest two stones have weights ~x~ and ~y~ with ~x <= y~. The result of this smash is: + + - If ~x == y~, both stones are destroyed, and + + - If ~x != y~, the stone of weight ~x~ is destroyed, and the stone of weight ~y~ has new weight ~y - x~. + +At the end of the game, there is *at most one* stone left. + +Return /the weight of the last remaining stone/. If there are no stones left, return ~0~. + +*Example 1:* + + +#+begin_src +Input: stones = [2,7,4,1,8,1] +Output: 1 +Explanation: +We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, +we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, +we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, +we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: stones = [1] +Output: 1 +#+end_src + + +*Constraints:* + + - ~1 <= stones.length <= 30~ + + - ~1 <= stones[i] <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def lastStoneWeight(self, stones: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int lastStoneWeight(vector& stones) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/intervals/0056-merge-intervals.org b/org/study_deck_02/dsa/intervals/0056-merge-intervals.org index 033c54b..5804f58 100644 --- a/org/study_deck_02/dsa/intervals/0056-merge-intervals.org +++ b/org/study_deck_02/dsa/intervals/0056-merge-intervals.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0056. Merge Intervals :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0056. Merge Intervals][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0056. Merge Intervals][0056. Merge Intervals]] :END: +Given an array of ~intervals~ where ~intervals[i] = [start_{i}, end_{i}]~, merge all overlapping intervals, and return /an array of the non-overlapping intervals that cover all the intervals in the input/. + +*Example 1:* + + +#+begin_src +Input: intervals = [[1,3],[2,6],[8,10],[15,18]] +Output: [[1,6],[8,10],[15,18]] +Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: intervals = [[1,4],[4,5]] +Output: [[1,5]] +Explanation: Intervals [1,4] and [4,5] are considered overlapping. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: intervals = [[4,7],[1,4]] +Output: [[1,7]] +Explanation: Intervals [1,4] and [4,7] are considered overlapping. +#+end_src + + +*Constraints:* + + - ~1 <= intervals.length <= 10^{4}~ + + - ~intervals[i].length == 2~ + + - ~0 <= start_{i} <= end_{i} <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> merge(vector>& intervals) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/intervals/0057-insert-interval.org b/org/study_deck_02/dsa/intervals/0057-insert-interval.org index 3d55959..15a2752 100644 --- a/org/study_deck_02/dsa/intervals/0057-insert-interval.org +++ b/org/study_deck_02/dsa/intervals/0057-insert-interval.org @@ -1,18 +1,65 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0057. Insert Interval :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0057. Insert Interval][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0057. Insert Interval][0057. Insert Interval]] :END: +You are given an array of non-overlapping intervals ~intervals~ where ~intervals[i] = [start_{i}, end_{i}]~ represent the start and the end of the ~i^{th}~ interval and ~intervals~ is sorted in ascending order by ~start_{i}~. You are also given an interval ~newInterval = [start, end]~ that represents the start and end of another interval. + +Insert ~newInterval~ into ~intervals~ such that ~intervals~ is still sorted in ascending order by ~start_{i}~ and ~intervals~ still does not have any overlapping intervals (merge overlapping intervals if necessary). + +Return ~intervals~/ after the insertion/. + +*Note* that you don't need to modify ~intervals~ in-place. You can make a new array and return it. + +*Example 1:* + + +#+begin_src +Input: intervals = [[1,3],[6,9]], newInterval = [2,5] +Output: [[1,5],[6,9]] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] +Output: [[1,2],[3,10],[12,16]] +Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. +#+end_src + + +*Constraints:* + + - ~0 <= intervals.length <= 10^{4}~ + + - ~intervals[i].length == 2~ + + - ~0 <= start_{i} <= end_{i} <= 10^{5}~ + + - ~intervals~ is sorted by ~start_{i}~ in *ascending* order. + + - ~newInterval.length == 2~ + + - ~0 <= start <= end <= 10^{5}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/intervals/0252-meeting-rooms.org b/org/study_deck_02/dsa/intervals/0252-meeting-rooms.org index 9a320df..8cc1df6 100644 --- a/org/study_deck_02/dsa/intervals/0252-meeting-rooms.org +++ b/org/study_deck_02/dsa/intervals/0252-meeting-rooms.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0252. Meeting Rooms :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0252. Meeting Rooms][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0252. Meeting Rooms][0252. Meeting Rooms]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/intervals/0253-meeting-rooms-ii.org b/org/study_deck_02/dsa/intervals/0253-meeting-rooms-ii.org index c0de56c..ab9fd77 100644 --- a/org/study_deck_02/dsa/intervals/0253-meeting-rooms-ii.org +++ b/org/study_deck_02/dsa/intervals/0253-meeting-rooms-ii.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0253. Meeting Rooms II :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0253. Meeting Rooms II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0253. Meeting Rooms II][0253. Meeting Rooms II]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/intervals/0435-non-overlapping-intervals.org b/org/study_deck_02/dsa/intervals/0435-non-overlapping-intervals.org index 955e45b..aaa4eb6 100644 --- a/org/study_deck_02/dsa/intervals/0435-non-overlapping-intervals.org +++ b/org/study_deck_02/dsa/intervals/0435-non-overlapping-intervals.org @@ -1,18 +1,66 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0435. Non Overlapping Intervals :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0435. Non Overlapping Intervals][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0435. Non Overlapping Intervals][0435. Non Overlapping Intervals]] :END: +Given an array of intervals ~intervals~ where ~intervals[i] = [start_{i}, end_{i}]~, return /the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping/. + +*Note* that intervals which only touch at a point are *non-overlapping*. For example, ~[1, 2]~ and ~[2, 3]~ are non-overlapping. + +*Example 1:* + + +#+begin_src +Input: intervals = [[1,2],[2,3],[3,4],[1,3]] +Output: 1 +Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: intervals = [[1,2],[1,2],[1,2]] +Output: 2 +Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: intervals = [[1,2],[2,3]] +Output: 0 +Explanation: You don't need to remove any of the intervals since they're already non-overlapping. +#+end_src + + +*Constraints:* + + - ~1 <= intervals.length <= 10^{5}~ + + - ~intervals[i].length == 2~ + + - ~-5 * 10^{4} <= start_{i} < end_{i} <= 5 * 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/intervals/0986-interval-list-intersections.org b/org/study_deck_02/dsa/intervals/0986-interval-list-intersections.org index 8851f53..d650452 100644 --- a/org/study_deck_02/dsa/intervals/0986-interval-list-intersections.org +++ b/org/study_deck_02/dsa/intervals/0986-interval-list-intersections.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0986. Interval List Intersections :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0986. Interval List Intersections][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0986. Interval List Intersections][0986. Interval List Intersections]] :END: +You are given two lists of closed intervals, ~firstList~ and ~secondList~, where ~firstList[i] = [start_{i}, end_{i}]~ and ~secondList[j] = [start_{j}, end_{j}]~. Each list of intervals is pairwise *disjoint* and in *sorted order*. + +Return /the intersection of these two interval lists/. + +A *closed interval* ~[a, b]~ (with ~a <= b~) denotes the set of real numbers ~x~ with ~a <= x <= b~. + +The *intersection* of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of ~[1, 3]~ and ~[2, 4]~ is ~[2, 3]~. + +*Example 1:* + + +#+begin_src +Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]] +Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: firstList = [[1,3],[5,9]], secondList = [] +Output: [] +#+end_src + + +*Constraints:* + + - ~0 <= firstList.length, secondList.length <= 1000~ + + - ~firstList.length + secondList.length >= 1~ + + - ~0 <= start_{i} < end_{i} <= 10^{9}~ + + - ~end_{i} < start_{i+1}~ + + - ~0 <= start_{j} < end_{j} <= 10^{9} ~ + + - ~end_{j} < start_{j+1}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> intervalIntersection(vector>& firstList, vector>& secondList) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/intervals/1851-minimum-interval-to-include-each-query.org b/org/study_deck_02/dsa/intervals/1851-minimum-interval-to-include-each-query.org index 1bb7ec3..90bf751 100644 --- a/org/study_deck_02/dsa/intervals/1851-minimum-interval-to-include-each-query.org +++ b/org/study_deck_02/dsa/intervals/1851-minimum-interval-to-include-each-query.org @@ -1,18 +1,70 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1851. Minimum Interval to Include Each Query :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1851. Minimum Interval to Include Each Query][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1851. Minimum Interval to Include Each Query][1851. Minimum Interval to Include Each Query]] :END: +You are given a 2D integer array ~intervals~, where ~intervals[i] = [left_{i}, right_{i}]~ describes the ~i^{th}~ interval starting at ~left_{i}~ and ending at ~right_{i}~ *(inclusive)*. The *size* of an interval is defined as the number of integers it contains, or more formally ~right_{i} - left_{i} + 1~. + +You are also given an integer array ~queries~. The answer to the ~j^{th}~ query is the *size of the smallest interval* ~i~ such that ~left_{i} <= queries[j] <= right_{i}~. If no such interval exists, the answer is ~-1~. + +Return /an array containing the answers to the queries/. + +*Example 1:* + + +#+begin_src +Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5] +Output: [3,3,1,4] +Explanation: The queries are processed as follows: +- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. +- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. +- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. +- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22] +Output: [2,-1,4,6] +Explanation: The queries are processed as follows: +- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. +- Query = 19: None of the intervals contain 19. The answer is -1. +- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. +- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. +#+end_src + + +*Constraints:* + + - ~1 <= intervals.length <= 10^{5}~ + + - ~1 <= queries.length <= 10^{5}~ + + - ~intervals[i].length == 2~ + + - ~1 <= left_{i} <= right_{i} <= 10^{7}~ + + - ~1 <= queries[j] <= 10^{7}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector minInterval(vector>& intervals, vector& queries) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0002-add-two-numbers.org b/org/study_deck_02/dsa/linked-list/0002-add-two-numbers.org index 4bea470..310bcf9 100644 --- a/org/study_deck_02/dsa/linked-list/0002-add-two-numbers.org +++ b/org/study_deck_02/dsa/linked-list/0002-add-two-numbers.org @@ -1,18 +1,79 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0002. Add Two Numbers :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0002. Add Two Numbers][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0002. Add Two Numbers][0002. Add Two Numbers]] :END: +You are given two *non-empty* linked lists representing two non-negative integers. The digits are stored in *reverse order*, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +*Example 1:* + + +#+begin_src +Input: l1 = [2,4,3], l2 = [5,6,4] +Output: [7,0,8] +Explanation: 342 + 465 = 807. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: l1 = [0], l2 = [0] +Output: [0] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] +Output: [8,9,9,9,0,0,0,1] +#+end_src + + +*Constraints:* + + - The number of nodes in each linked list is in the range ~[1, 100]~. + + - ~0 <= Node.val <= 9~ + + - It is guaranteed that the list represents a number that does not have leading zeros. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0019-remove-nth-node-from-end-of-list.org b/org/study_deck_02/dsa/linked-list/0019-remove-nth-node-from-end-of-list.org index 3b79d14..aac68eb 100644 --- a/org/study_deck_02/dsa/linked-list/0019-remove-nth-node-from-end-of-list.org +++ b/org/study_deck_02/dsa/linked-list/0019-remove-nth-node-from-end-of-list.org @@ -1,18 +1,80 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0019. Remove Nth Node From End of List :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0019. Remove Nth Node From End of List][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0019. Remove Nth Node From End of List][0019. Remove Nth Node From End of List]] :END: +Given the ~head~ of a linked list, remove the ~n^{th}~ node from the end of the list and return its head. + +*Example 1:* + + +#+begin_src +Input: head = [1,2,3,4,5], n = 2 +Output: [1,2,3,5] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: head = [1], n = 1 +Output: [] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: head = [1,2], n = 1 +Output: [1] +#+end_src + + +*Constraints:* + + - The number of nodes in the list is ~sz~. + + - ~1 <= sz <= 30~ + + - ~0 <= Node.val <= 100~ + + - ~1 <= n <= sz~ + +*Follow up:* Could you do this in one pass? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0021-merge-two-sorted-lists.org b/org/study_deck_02/dsa/linked-list/0021-merge-two-sorted-lists.org index ed0868b..a67d8ac 100644 --- a/org/study_deck_02/dsa/linked-list/0021-merge-two-sorted-lists.org +++ b/org/study_deck_02/dsa/linked-list/0021-merge-two-sorted-lists.org @@ -1,18 +1,80 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0021. Merge Two Sorted Lists :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0021. Merge Two Sorted Lists][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0021. Merge Two Sorted Lists][0021. Merge Two Sorted Lists]] :END: +You are given the heads of two sorted linked lists ~list1~ and ~list2~. + +Merge the two lists into one *sorted* list. The list should be made by splicing together the nodes of the first two lists. + +Return /the head of the merged linked list/. + +*Example 1:* + + +#+begin_src +Input: list1 = [1,2,4], list2 = [1,3,4] +Output: [1,1,2,3,4,4] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: list1 = [], list2 = [] +Output: [] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: list1 = [], list2 = [0] +Output: [0] +#+end_src + + +*Constraints:* + + - The number of nodes in both lists is in the range ~[0, 50]~. + + - ~-100 <= Node.val <= 100~ + + - Both ~list1~ and ~list2~ are sorted in *non-decreasing* order. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0023-merge-k-sorted-lists.org b/org/study_deck_02/dsa/linked-list/0023-merge-k-sorted-lists.org index 993939b..0fe160a 100644 --- a/org/study_deck_02/dsa/linked-list/0023-merge-k-sorted-lists.org +++ b/org/study_deck_02/dsa/linked-list/0023-merge-k-sorted-lists.org @@ -1,18 +1,92 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0023. Merge K Sorted Lists :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0023. Merge K Sorted Lists][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0023. Merge K Sorted Lists][0023. Merge K Sorted Lists]] :END: +You are given an array of ~k~ linked-lists ~lists~, each linked-list is sorted in ascending order. + +/Merge all the linked-lists into one sorted linked-list and return it./ + +*Example 1:* + + +#+begin_src +Input: lists = [[1,4,5],[1,3,4],[2,6]] +Output: [1,1,2,3,4,4,5,6] +Explanation: The linked-lists are: +[ + 1->4->5, + 1->3->4, + 2->6 +] +merging them into one sorted linked list: +1->1->2->3->4->4->5->6 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: lists = [] +Output: [] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: lists = [[]] +Output: [] +#+end_src + + +*Constraints:* + + - ~k == lists.length~ + + - ~0 <= k <= 10^{4}~ + + - ~0 <= lists[i].length <= 500~ + + - ~-10^{4} <= lists[i][j] <= 10^{4}~ + + - ~lists[i]~ is sorted in *ascending order*. + + - The sum of ~lists[i].length~ will not exceed ~10^{4}~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0025-reverse-nodes-in-k-group.org b/org/study_deck_02/dsa/linked-list/0025-reverse-nodes-in-k-group.org index 6fca712..354330e 100644 --- a/org/study_deck_02/dsa/linked-list/0025-reverse-nodes-in-k-group.org +++ b/org/study_deck_02/dsa/linked-list/0025-reverse-nodes-in-k-group.org @@ -1,18 +1,73 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0025. Reverse Nodes In K Group :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0025. Reverse Nodes In K Group][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0025. Reverse Nodes In K Group][0025. Reverse Nodes In K Group]] :END: +Given the ~head~ of a linked list, reverse the nodes of the list ~k~ at a time, and return /the modified list/. + +~k~ is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of ~k~ then left-out nodes, in the end, should remain as it is. + +You may not alter the values in the list's nodes, only nodes themselves may be changed. + +*Example 1:* + + +#+begin_src +Input: head = [1,2,3,4,5], k = 2 +Output: [2,1,4,3,5] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: head = [1,2,3,4,5], k = 3 +Output: [3,2,1,4,5] +#+end_src + + +*Constraints:* + + - The number of nodes in the list is ~n~. + + - ~1 <= k <= n <= 5000~ + + - ~0 <= Node.val <= 1000~ + +*Follow-up:* Can you solve the problem in ~O(1)~ extra memory space? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0138-copy-list-with-random-pointer.org b/org/study_deck_02/dsa/linked-list/0138-copy-list-with-random-pointer.org index 1690707..d9ff203 100644 --- a/org/study_deck_02/dsa/linked-list/0138-copy-list-with-random-pointer.org +++ b/org/study_deck_02/dsa/linked-list/0138-copy-list-with-random-pointer.org @@ -1,18 +1,102 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0138. Copy List With Random Pointer :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0138. Copy List With Random Pointer][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0138. Copy List With Random Pointer][0138. Copy List With Random Pointer]] :END: +A linked list of length ~n~ is given such that each node contains an additional random pointer, which could point to any node in the list, or ~null~. + +Construct a *deep copy* of the list. The deep copy should consist of exactly ~n~ *brand new* nodes, where each new node has its value set to the value of its corresponding original node. Both the ~next~ and ~random~ pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. *None of the pointers in the new list should point to nodes in the original list*. + +For example, if there are two nodes ~X~ and ~Y~ in the original list, where ~X.random --> Y~, then for the corresponding two nodes ~x~ and ~y~ in the copied list, ~x.random --> y~. + +Return /the head of the copied linked list/. + +The linked list is represented in the input/output as a list of ~n~ nodes. Each node is represented as a pair of ~[val, random_index]~ where: + + - ~val~: an integer representing ~Node.val~ + + - ~random_index~: the index of the node (range from ~0~ to ~n-1~) that the ~random~ pointer points to, or ~null~ if it does not point to any node. + +Your code will *only* be given the ~head~ of the original linked list. + +*Example 1:* + + +#+begin_src +Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] +Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: head = [[1,1],[2,1]] +Output: [[1,1],[2,1]] +#+end_src + + +*Example 3:* + +** + + +#+begin_src +Input: head = [[3,null],[3,0],[3,null]] +Output: [[3,null],[3,0],[3,null]] +#+end_src + + +*Constraints:* + + - ~0 <= n <= 1000~ + + - ~-10^{4} <= Node.val <= 10^{4}~ + + - ~Node.random~ is ~null~ or is pointing to some node in the linked list. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" +class Solution: + def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': #+end_src ** TODO C++ #+begin_src cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ +class Solution { +public: + Node* copyRandomList(Node* head) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0141-linked-list-cycle.org b/org/study_deck_02/dsa/linked-list/0141-linked-list-cycle.org index 02dd047..a4a980e 100644 --- a/org/study_deck_02/dsa/linked-list/0141-linked-list-cycle.org +++ b/org/study_deck_02/dsa/linked-list/0141-linked-list-cycle.org @@ -1,18 +1,84 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0141. Linked List Cycle :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0141. Linked List Cycle][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0141. Linked List Cycle][0141. Linked List Cycle]] :END: +Given ~head~, the head of a linked list, determine if the linked list has a cycle in it. + +There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the ~next~ pointer. Internally, ~pos~ is used to denote the index of the node that tail's ~next~ pointer is connected to. *Note that ~pos~ is not passed as a parameter*. + +Return ~true~/ if there is a cycle in the linked list/. Otherwise, return ~false~. + +*Example 1:* + + +#+begin_src +Input: head = [3,2,0,-4], pos = 1 +Output: true +Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). +#+end_src + + +*Example 2:* + + +#+begin_src +Input: head = [1,2], pos = 0 +Output: true +Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: head = [1], pos = -1 +Output: false +Explanation: There is no cycle in the linked list. +#+end_src + + +*Constraints:* + + - The number of the nodes in the list is in the range ~[0, 10^{4}]~. + + - ~-10^{5} <= Node.val <= 10^{5}~ + + - ~pos~ is ~-1~ or a *valid index* in the linked-list. + +*Follow up:* Can you solve it using ~O(1)~ (i.e. constant) memory? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None +class Solution: + def hasCycle(self, head: Optional[ListNode]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0143-reorder-list.org b/org/study_deck_02/dsa/linked-list/0143-reorder-list.org index 4771d42..19d1f80 100644 --- a/org/study_deck_02/dsa/linked-list/0143-reorder-list.org +++ b/org/study_deck_02/dsa/linked-list/0143-reorder-list.org @@ -1,18 +1,84 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0143. Reorder List :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0143. Reorder List][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0143. Reorder List][0143. Reorder List]] :END: +You are given the head of a singly linked-list. The list can be represented as: + + +#+begin_src +L0 → L1 → … → Ln - 1 → Ln +#+end_src + + +/Reorder the list to be on the following form:/ + + +#+begin_src +L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … +#+end_src + + +You may not modify the values in the list's nodes. Only nodes themselves may be changed. + +*Example 1:* + + +#+begin_src +Input: head = [1,2,3,4] +Output: [1,4,2,3] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: head = [1,2,3,4,5] +Output: [1,5,2,4,3] +#+end_src + + +*Constraints:* + + - The number of nodes in the list is in the range ~[1, 5 * 10^{4}]~. + + - ~1 <= Node.val <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reorderList(self, head: Optional[ListNode]) -> None: + """ + Do not return anything, modify head in-place instead. + """ #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + void reorderList(ListNode* head) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0146-lru-cache.org b/org/study_deck_02/dsa/linked-list/0146-lru-cache.org index 0cd2b81..b2138b3 100644 --- a/org/study_deck_02/dsa/linked-list/0146-lru-cache.org +++ b/org/study_deck_02/dsa/linked-list/0146-lru-cache.org @@ -1,18 +1,99 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0146. LRU Cache :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0146. LRU Cache][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0146. LRU Cache][0146. LRU Cache]] :END: +Design a data structure that follows the constraints of a *Least Recently Used (LRU) cache*. + +Implement the ~LRUCache~ class: + + - ~LRUCache(int capacity)~ Initialize the LRU cache with *positive* size ~capacity~. + + - ~int get(int key)~ Return the value of the ~key~ if the key exists, otherwise return ~-1~. + + - ~void put(int key, int value)~ Update the value of the ~key~ if the ~key~ exists. Otherwise, add the ~key-value~ pair to the cache. If the number of keys exceeds the ~capacity~ from this operation, *evict* the least recently used key. + +The functions ~get~ and ~put~ must each run in ~O(1)~ average time complexity. + +*Example 1:* + + +#+begin_src +Input +["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] +[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] +Output +[null, null, null, 1, null, -1, null, -1, 3, 4] + +Explanation +LRUCache lRUCache = new LRUCache(2); +lRUCache.put(1, 1); // cache is {1=1} +lRUCache.put(2, 2); // cache is {1=1, 2=2} +lRUCache.get(1); // return 1 +lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} +lRUCache.get(2); // returns -1 (not found) +lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} +lRUCache.get(1); // return -1 (not found) +lRUCache.get(3); // return 3 +lRUCache.get(4); // return 4 +#+end_src + + +*Constraints:* + + - ~1 <= capacity <= 3000~ + + - ~0 <= key <= 10^{4}~ + + - ~0 <= value <= 10^{5}~ + + - At most ~2 * 10^{5}~ calls will be made to ~get~ and ~put~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class LRUCache: + def __init__(self, capacity: int): + + + def get(self, key: int) -> int: + + + def put(self, key: int, value: int) -> None: + + + +# Your LRUCache object will be instantiated and called as such: +# obj = LRUCache(capacity) +# param_1 = obj.get(key) +# obj.put(key,value) #+end_src ** TODO C++ #+begin_src cpp +class LRUCache { +public: + LRUCache(int capacity) { + + } + + int get(int key) { + + } + + void put(int key, int value) { + + } +}; +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache* obj = new LRUCache(capacity); + * int param_1 = obj->get(key); + * obj->put(key,value); + */ #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0206-reverse-linked-list.org b/org/study_deck_02/dsa/linked-list/0206-reverse-linked-list.org index b9f7caa..c1299a9 100644 --- a/org/study_deck_02/dsa/linked-list/0206-reverse-linked-list.org +++ b/org/study_deck_02/dsa/linked-list/0206-reverse-linked-list.org @@ -1,18 +1,76 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0206. Reverse Linked List :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0206. Reverse Linked List][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0206. Reverse Linked List][0206. Reverse Linked List]] :END: +Given the ~head~ of a singly linked list, reverse the list, and return /the reversed list/. + +*Example 1:* + + +#+begin_src +Input: head = [1,2,3,4,5] +Output: [5,4,3,2,1] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: head = [1,2] +Output: [2,1] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: head = [] +Output: [] +#+end_src + + +*Constraints:* + + - The number of nodes in the list is the range ~[0, 5000]~. + + - ~-5000 <= Node.val <= 5000~ + +*Follow up:* A linked list can be reversed either iteratively or recursively. Could you implement both? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0287-find-the-duplicate-number.org b/org/study_deck_02/dsa/linked-list/0287-find-the-duplicate-number.org index 8f1ae99..b868143 100644 --- a/org/study_deck_02/dsa/linked-list/0287-find-the-duplicate-number.org +++ b/org/study_deck_02/dsa/linked-list/0287-find-the-duplicate-number.org @@ -1,18 +1,73 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0287. Find The Duplicate Number :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0287. Find The Duplicate Number][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0287. Find The Duplicate Number][0287. Find The Duplicate Number]] :END: +Given an array of integers ~nums~ containing ~n + 1~ integers where each integer is in the range ~[1, n]~ inclusive. + +There is only *one repeated number* in ~nums~, return /this repeated number/. + +You must solve the problem *without* modifying the array ~nums~ and using only constant extra space. + +*Example 1:* + + +#+begin_src +Input: nums = [1,3,4,2,2] +Output: 2 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [3,1,3,4,2] +Output: 3 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [3,3,3,3,3] +Output: 3 +#+end_src + + +*Constraints:* + + - ~1 <= n <= 10^{5}~ + + - ~nums.length == n + 1~ + + - ~1 <= nums[i] <= n~ + + - All the integers in ~nums~ appear only *once* except for *precisely one integer* which appears *two or more* times. + +Follow up: + + - How can we prove that at least one duplicate number must exist in ~nums~? + + - Can you solve the problem in linear runtime complexity? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findDuplicate(self, nums: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int findDuplicate(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/0725-split-linked-list-in-parts.org b/org/study_deck_02/dsa/linked-list/0725-split-linked-list-in-parts.org index 4adab14..0ad3882 100644 --- a/org/study_deck_02/dsa/linked-list/0725-split-linked-list-in-parts.org +++ b/org/study_deck_02/dsa/linked-list/0725-split-linked-list-in-parts.org @@ -1,18 +1,78 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0725. Split Linked List in Parts :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0725. Split Linked List in Parts][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0725. Split Linked List in Parts][0725. Split Linked List in Parts]] :END: +Given the ~head~ of a singly linked list and an integer ~k~, split the linked list into ~k~ consecutive linked list parts. + +The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. + +The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. + +Return /an array of the /~k~/ parts/. + +*Example 1:* + + +#+begin_src +Input: head = [1,2,3], k = 5 +Output: [[1],[2],[3],[],[]] +Explanation: +The first element output[0] has output[0].val = 1, output[0].next = null. +The last element output[4] is null, but its string representation as a ListNode is []. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3 +Output: [[1,2,3,4],[5,6,7],[8,9,10]] +Explanation: +The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. +#+end_src + + +*Constraints:* + + - The number of nodes in the list is in the range ~[0, 1000]~. + + - ~0 <= Node.val <= 1000~ + + - ~1 <= k <= 50~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + vector splitListToParts(ListNode* head, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/1472-design-browser-history.org b/org/study_deck_02/dsa/linked-list/1472-design-browser-history.org index 81e5618..2b58f60 100644 --- a/org/study_deck_02/dsa/linked-list/1472-design-browser-history.org +++ b/org/study_deck_02/dsa/linked-list/1472-design-browser-history.org @@ -1,18 +1,111 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1472. Design Browser History :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1472. Design Browser History][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1472. Design Browser History][1472. Design Browser History]] :END: +You have a *browser* of one tab where you start on the ~homepage~ and you can visit another ~url~, get back in the history number of ~steps~ or move forward in the history number of ~steps~. + +Implement the ~BrowserHistory~ class: + + - ~BrowserHistory(string homepage)~ Initializes the object with the ~homepage~ of the browser. + + - ~void visit(string url)~ Visits ~url~ from the current page. It clears up all the forward history. + + - ~string back(int steps)~ Move ~steps~ back in history. If you can only return ~x~ steps in the history and ~steps > x~, you will return only ~x~ steps. Return the current ~url~ after moving back in history *at most* ~steps~. + + - ~string forward(int steps)~ Move ~steps~ forward in history. If you can only forward ~x~ steps in the history and ~steps > x~, you will forward only ~x~ steps. Return the current ~url~ after forwarding in history *at most* ~steps~. + +*Example:* + + +#+begin_src +Input: +["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"] +[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]] +Output: +[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"] + +Explanation: +BrowserHistory browserHistory = new BrowserHistory("leetcode.com"); +browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com" +browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com" +browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com" +browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com" +browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com" +browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com" +browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com" +browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps. +browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com" +browserHistory.back(7); // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com" +#+end_src + + +*Constraints:* + + - ~1 <= homepage.length <= 20~ + + - ~1 <= url.length <= 20~ + + - ~1 <= steps <= 100~ + + - ~homepage~ and ~url~ consist of '.' or lower case English letters. + + - At most ~5000~ calls will be made to ~visit~, ~back~, and ~forward~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class BrowserHistory: + def __init__(self, homepage: str): + + + def visit(self, url: str) -> None: + + + def back(self, steps: int) -> str: + + + def forward(self, steps: int) -> str: + + + +# Your BrowserHistory object will be instantiated and called as such: +# obj = BrowserHistory(homepage) +# obj.visit(url) +# param_2 = obj.back(steps) +# param_3 = obj.forward(steps) #+end_src ** TODO C++ #+begin_src cpp +class BrowserHistory { +public: + BrowserHistory(string homepage) { + + } + + void visit(string url) { + + } + + string back(int steps) { + + } + + string forward(int steps) { + + } +}; +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory* obj = new BrowserHistory(homepage); + * obj->visit(url); + * string param_2 = obj->back(steps); + * string param_3 = obj->forward(steps); + */ #+end_src diff --git a/org/study_deck_02/dsa/linked-list/1721-swapping-nodes-in-a-linked-list.org b/org/study_deck_02/dsa/linked-list/1721-swapping-nodes-in-a-linked-list.org index ad06ca4..88b7f9a 100644 --- a/org/study_deck_02/dsa/linked-list/1721-swapping-nodes-in-a-linked-list.org +++ b/org/study_deck_02/dsa/linked-list/1721-swapping-nodes-in-a-linked-list.org @@ -1,18 +1,69 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1721. Swapping Nodes in a Linked List :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1721. Swapping Nodes in a Linked List][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1721. Swapping Nodes in a Linked List][1721. Swapping Nodes in a Linked List]] :END: +You are given the ~head~ of a linked list, and an integer ~k~. + +Return /the head of the linked list after *swapping* the values of the /~k^{th}~ /node from the beginning and the /~k^{th}~ /node from the end (the list is *1-indexed*)./ + +*Example 1:* + + +#+begin_src +Input: head = [1,2,3,4,5], k = 2 +Output: [1,4,3,2,5] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 +Output: [7,9,6,6,8,7,3,0,9,5] +#+end_src + + +*Constraints:* + + - The number of nodes in the list is ~n~. + + - ~1 <= k <= n <= 10^{5}~ + + - ~0 <= Node.val <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapNodes(ListNode* head, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/linked-list/2487-remove-nodes-from-linked-list.org b/org/study_deck_02/dsa/linked-list/2487-remove-nodes-from-linked-list.org index 317d845..d001c84 100644 --- a/org/study_deck_02/dsa/linked-list/2487-remove-nodes-from-linked-list.org +++ b/org/study_deck_02/dsa/linked-list/2487-remove-nodes-from-linked-list.org @@ -1,18 +1,74 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2487. Remove Nodes From Linked List :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2487. Remove Nodes From Linked List][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2487. Remove Nodes From Linked List][2487. Remove Nodes From Linked List]] :END: +You are given the ~head~ of a linked list. + +Remove every node which has a node with a greater value anywhere to the right side of it. + +Return /the /~head~/ of the modified linked list./ + +*Example 1:* + + +#+begin_src +Input: head = [5,2,13,3,8] +Output: [13,8] +Explanation: The nodes that should be removed are 5, 2 and 3. +- Node 13 is to the right of node 5. +- Node 13 is to the right of node 2. +- Node 8 is to the right of node 3. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: head = [1,1,1,1] +Output: [1,1,1,1] +Explanation: Every node has value 1, so no nodes are removed. +#+end_src + + +*Constraints:* + + - The number of the nodes in the given list is in the range ~[1, 10^{5}]~. + + - ~1 <= Node.val <= 10^{5}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNodes(ListNode* head) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/0009-palindrome-number.org b/org/study_deck_02/dsa/math-geometry/0009-palindrome-number.org index ca4447c..32aebcb 100644 --- a/org/study_deck_02/dsa/math-geometry/0009-palindrome-number.org +++ b/org/study_deck_02/dsa/math-geometry/0009-palindrome-number.org @@ -1,18 +1,62 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0009. Palindrome Number :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0009. Palindrome Number][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0009. Palindrome Number][0009. Palindrome Number]] :END: +Given an integer ~x~, return ~true~/ if /~x~/ is a //*palindrome*//, and /~false~/ otherwise/. + +*Example 1:* + + +#+begin_src +Input: x = 121 +Output: true +Explanation: 121 reads as 121 from left to right and from right to left. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: x = -121 +Output: false +Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: x = 10 +Output: false +Explanation: Reads 01 from right to left. Therefore it is not a palindrome. +#+end_src + + +*Constraints:* + + - ~-2^{31} <= x <= 2^{31} - 1~ + +*Follow up:* Could you solve it without converting the integer to a string? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isPalindrome(self, x: int) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isPalindrome(int x) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/0012-integer-to-roman.org b/org/study_deck_02/dsa/math-geometry/0012-integer-to-roman.org index 7e188b9..eb7836a 100644 --- a/org/study_deck_02/dsa/math-geometry/0012-integer-to-roman.org +++ b/org/study_deck_02/dsa/math-geometry/0012-integer-to-roman.org @@ -1,18 +1,114 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0012. Integer to Roman :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0012. Integer to Roman][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0012. Integer to Roman][0012. Integer to Roman]] :END: +Seven different symbols represent Roman numerals with the following values: + + Symbol + Value + + I + 1 + + V + 5 + + X + 10 + + L + 50 + + C + 100 + + D + 500 + + M + 1000 + +Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules: + + - If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral. + + - If the value starts with 4 or 9 use the *subtractive form* representing one symbol subtracted from the following symbol, for example, 4 is 1 (~I~) less than 5 (~V~): ~IV~ and 9 is 1 (~I~) less than 10 (~X~): ~IX~. Only the following subtractive forms are used: 4 (~IV~), 9 (~IX~), 40 (~XL~), 90 (~XC~), 400 (~CD~) and 900 (~CM~). + + - Only powers of 10 (~I~, ~X~, ~C~, ~M~) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (~V~), 50 (~L~), or 500 (~D~) multiple times. If you need to append a symbol 4 times use the *subtractive form*. + +Given an integer, convert it to a Roman numeral. + +*Example 1:* + +*Input:* num = 3749 + +*Output:* "MMMDCCXLIX" + +*Explanation:* + + +#+begin_src +3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) + 700 = DCC as 500 (D) + 100 (C) + 100 (C) + 40 = XL as 10 (X) less of 50 (L) + 9 = IX as 1 (I) less of 10 (X) +Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places +#+end_src + + +*Example 2:* + +*Input:* num = 58 + +*Output:* "LVIII" + +*Explanation:* + + +#+begin_src +50 = L + 8 = VIII +#+end_src + + +*Example 3:* + +*Input:* num = 1994 + +*Output:* "MCMXCIV" + +*Explanation:* + + +#+begin_src +1000 = M + 900 = CM + 90 = XC + 4 = IV +#+end_src + + +*Constraints:* + + - ~1 <= num <= 3999~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def intToRoman(self, num: int) -> str: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + string intToRoman(int num) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/0043-multiply-strings.org b/org/study_deck_02/dsa/math-geometry/0043-multiply-strings.org index efd5275..6282d96 100644 --- a/org/study_deck_02/dsa/math-geometry/0043-multiply-strings.org +++ b/org/study_deck_02/dsa/math-geometry/0043-multiply-strings.org @@ -1,18 +1,52 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0043. Multiply Strings :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0043. Multiply Strings][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0043. Multiply Strings][0043. Multiply Strings]] :END: +Given two non-negative integers ~num1~ and ~num2~ represented as strings, return the product of ~num1~ and ~num2~, also represented as a string. + +*Note:* You must not use any built-in BigInteger library or convert the inputs to integer directly. + +*Example 1:* + + +#+begin_src +Input: num1 = "2", num2 = "3" +Output: "6" +#+end_src +*Example 2:* + + +#+begin_src +Input: num1 = "123", num2 = "456" +Output: "56088" +#+end_src + + +*Constraints:* + + - ~1 <= num1.length, num2.length <= 200~ + + - ~num1~ and ~num2~ consist of digits only. + + - Both ~num1~ and ~num2~ do not contain any leading zero, except the number ~0~ itself. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def multiply(self, num1: str, num2: str) -> str: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + string multiply(string num1, string num2) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/0048-rotate-image.org b/org/study_deck_02/dsa/math-geometry/0048-rotate-image.org index f7d4086..bbc9845 100644 --- a/org/study_deck_02/dsa/math-geometry/0048-rotate-image.org +++ b/org/study_deck_02/dsa/math-geometry/0048-rotate-image.org @@ -1,18 +1,57 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0048. Rotate Image :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0048. Rotate Image][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0048. Rotate Image][0048. Rotate Image]] :END: +You are given an ~n x n~ 2D ~matrix~ representing an image, rotate the image by *90* degrees (clockwise). + +You have to rotate the image *in-place*, which means you have to modify the input 2D matrix directly. *DO NOT* allocate another 2D matrix and do the rotation. + +*Example 1:* + + +#+begin_src +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [[7,4,1],[8,5,2],[9,6,3]] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] +Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] +#+end_src + + +*Constraints:* + + - ~n == matrix.length == matrix[i].length~ + + - ~1 <= n <= 20~ + + - ~-1000 <= matrix[i][j] <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + void rotate(vector>& matrix) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/0054-spiral-matrix.org b/org/study_deck_02/dsa/math-geometry/0054-spiral-matrix.org index c8446a3..d651768 100644 --- a/org/study_deck_02/dsa/math-geometry/0054-spiral-matrix.org +++ b/org/study_deck_02/dsa/math-geometry/0054-spiral-matrix.org @@ -1,18 +1,54 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0054. Spiral Matrix :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0054. Spiral Matrix][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0054. Spiral Matrix][0054. Spiral Matrix]] :END: +Given an ~m x n~ ~matrix~, return /all elements of the/ ~matrix~ /in spiral order/. + +*Example 1:* + + +#+begin_src +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [1,2,3,6,9,8,7,4,5] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] +Output: [1,2,3,4,8,12,11,10,9,5,6,7] +#+end_src + + +*Constraints:* + + - ~m == matrix.length~ + + - ~n == matrix[i].length~ + + - ~1 <= m, n <= 10~ + + - ~-100 <= matrix[i][j] <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector spiralOrder(vector>& matrix) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/0066-plus-one.org b/org/study_deck_02/dsa/math-geometry/0066-plus-one.org index 051b8cc..adc88a2 100644 --- a/org/study_deck_02/dsa/math-geometry/0066-plus-one.org +++ b/org/study_deck_02/dsa/math-geometry/0066-plus-one.org @@ -1,18 +1,72 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0066. Plus One :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0066. Plus One][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0066. Plus One][0066. Plus One]] :END: +You are given a *large integer* represented as an integer array ~digits~, where each ~digits[i]~ is the ~i^{th}~ digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading ~0~'s. + +Increment the large integer by one and return /the resulting array of digits/. + +*Example 1:* + + +#+begin_src +Input: digits = [1,2,3] +Output: [1,2,4] +Explanation: The array represents the integer 123. +Incrementing by one gives 123 + 1 = 124. +Thus, the result should be [1,2,4]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: digits = [4,3,2,1] +Output: [4,3,2,2] +Explanation: The array represents the integer 4321. +Incrementing by one gives 4321 + 1 = 4322. +Thus, the result should be [4,3,2,2]. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: digits = [9] +Output: [1,0] +Explanation: The array represents the integer 9. +Incrementing by one gives 9 + 1 = 10. +Thus, the result should be [1,0]. +#+end_src + + +*Constraints:* + + - ~1 <= digits.length <= 100~ + + - ~0 <= digits[i] <= 9~ + + - ~digits~ does not contain any leading ~0~'s. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def plusOne(self, digits: List[int]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector plusOne(vector& digits) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/0073-set-matrix-zeroes.org b/org/study_deck_02/dsa/math-geometry/0073-set-matrix-zeroes.org index 0547447..45d5e44 100644 --- a/org/study_deck_02/dsa/math-geometry/0073-set-matrix-zeroes.org +++ b/org/study_deck_02/dsa/math-geometry/0073-set-matrix-zeroes.org @@ -1,18 +1,67 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0073. Set Matrix Zeroes :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0073. Set Matrix Zeroes][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0073. Set Matrix Zeroes][0073. Set Matrix Zeroes]] :END: +Given an ~m x n~ integer matrix ~matrix~, if an element is ~0~, set its entire row and column to ~0~'s. + +You must do it in place. + +*Example 1:* + + +#+begin_src +Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] +Output: [[1,0,1],[0,0,0],[1,0,1]] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] +Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]] +#+end_src + + +*Constraints:* + + - ~m == matrix.length~ + + - ~n == matrix[0].length~ + + - ~1 <= m, n <= 200~ + + - ~-2^{31} <= matrix[i][j] <= 2^{31} - 1~ + +*Follow up:* + + - A straightforward solution using ~O(mn)~ space is probably a bad idea. + + - A simple improvement uses ~O(m + n)~ space, but still not the best solution. + + - Could you devise a constant space solution? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + void setZeroes(vector>& matrix) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/0202-happy-number.org b/org/study_deck_02/dsa/math-geometry/0202-happy-number.org index a1f3dd9..1704d38 100644 --- a/org/study_deck_02/dsa/math-geometry/0202-happy-number.org +++ b/org/study_deck_02/dsa/math-geometry/0202-happy-number.org @@ -1,18 +1,63 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0202. Happy Number :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0202. Happy Number][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0202. Happy Number][0202. Happy Number]] :END: +Write an algorithm to determine if a number ~n~ is happy. + +A *happy number* is a number defined by the following process: + + - Starting with any positive integer, replace the number by the sum of the squares of its digits. + + - Repeat the process until the number equals 1 (where it will stay), or it *loops endlessly in a cycle* which does not include 1. + + - Those numbers for which this process *ends in 1* are happy. + +Return ~true~ /if/ ~n~ /is a happy number, and/ ~false~ /if not/. + +*Example 1:* + + +#+begin_src +Input: n = 19 +Output: true +Explanation: +12 + 92 = 82 +82 + 22 = 68 +62 + 82 = 100 +12 + 02 + 02 = 1 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 2 +Output: false +#+end_src + + +*Constraints:* + + - ~1 <= n <= 2^{31} - 1~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isHappy(self, n: int) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isHappy(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/0296-best-meeting-point.org b/org/study_deck_02/dsa/math-geometry/0296-best-meeting-point.org index 3e59258..037d80f 100644 --- a/org/study_deck_02/dsa/math-geometry/0296-best-meeting-point.org +++ b/org/study_deck_02/dsa/math-geometry/0296-best-meeting-point.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0296. Best Meeting Point :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0296. Best Meeting Point][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0296. Best Meeting Point][0296. Best Meeting Point]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/math-geometry/0840-magic-squares-in-grid.org b/org/study_deck_02/dsa/math-geometry/0840-magic-squares-in-grid.org index 516b2fd..056acdc 100644 --- a/org/study_deck_02/dsa/math-geometry/0840-magic-squares-in-grid.org +++ b/org/study_deck_02/dsa/math-geometry/0840-magic-squares-in-grid.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0840. Magic Squares In Grid :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0840. Magic Squares In Grid][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0840. Magic Squares In Grid][0840. Magic Squares In Grid]] :END: +A ~3 x 3~ *magic square* is a ~3 x 3~ grid filled with distinct numbers *from *1* to *9 such that each row, column, and both diagonals all have the same sum. + +Given a ~row x col~ ~grid~ of integers, how many ~3 x 3~ magic square subgrids are there? + +Note: while a magic square can only contain numbers from 1 to 9, ~grid~ may contain numbers up to 15. + +*Example 1:* + + +#+begin_src +Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]] +Output: 1 +Explanation: +The following subgrid is a 3 x 3 magic square: + +while this one is not: + +In total, there is only one magic square inside the given grid. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: grid = [[8]] +Output: 0 +#+end_src + + +*Constraints:* + + - ~row == grid.length~ + + - ~col == grid[i].length~ + + - ~1 <= row, col <= 10~ + + - ~0 <= grid[i][j] <= 15~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def numMagicSquaresInside(self, grid: List[List[int]]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int numMagicSquaresInside(vector>& grid) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/1780-check-if-number-is-a-sum-of-powers-of-three.org b/org/study_deck_02/dsa/math-geometry/1780-check-if-number-is-a-sum-of-powers-of-three.org index 3cbdc86..dfc1aa0 100644 --- a/org/study_deck_02/dsa/math-geometry/1780-check-if-number-is-a-sum-of-powers-of-three.org +++ b/org/study_deck_02/dsa/math-geometry/1780-check-if-number-is-a-sum-of-powers-of-three.org @@ -1,18 +1,61 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1780. Check if Number is a Sum of Powers of Three :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1780. Check if Number is a Sum of Powers of Three][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1780. Check if Number is a Sum of Powers of Three][1780. Check if Number is a Sum of Powers of Three]] :END: +Given an integer ~n~, return ~true~ /if it is possible to represent /~n~/ as the sum of distinct powers of three./ Otherwise, return ~false~. + +An integer ~y~ is a power of three if there exists an integer ~x~ such that ~y == 3^{x}~. + +*Example 1:* + + +#+begin_src +Input: n = 12 +Output: true +Explanation: 12 = 31 + 32 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 91 +Output: true +Explanation: 91 = 30 + 32 + 34 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: n = 21 +Output: false +#+end_src + + +*Constraints:* + + - ~1 <= n <= 10^{7}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def checkPowersOfThree(self, n: int) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool checkPowersOfThree(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/2013-detect-squares.org b/org/study_deck_02/dsa/math-geometry/2013-detect-squares.org index 3a6554b..46bab68 100644 --- a/org/study_deck_02/dsa/math-geometry/2013-detect-squares.org +++ b/org/study_deck_02/dsa/math-geometry/2013-detect-squares.org @@ -1,18 +1,102 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2013. Detect Squares :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2013. Detect Squares][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2013. Detect Squares][2013. Detect Squares]] :END: +You are given a stream of points on the X-Y plane. Design an algorithm that: + + - *Adds* new points from the stream into a data structure. *Duplicate* points are allowed and should be treated as different points. + + - Given a query point, *counts* the number of ways to choose three points from the data structure such that the three points and the query point form an *axis-aligned square* with *positive area*. + +An *axis-aligned square* is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. + +Implement the ~DetectSquares~ class: + + - ~DetectSquares()~ Initializes the object with an empty data structure. + + - ~void add(int[] point)~ Adds a new point ~point = [x, y]~ to the data structure. + + - ~int count(int[] point)~ Counts the number of ways to form *axis-aligned squares* with point ~point = [x, y]~ as described above. + +*Example 1:* + + +#+begin_src +Input +["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] +[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] +Output +[null, null, null, null, 1, 0, null, 2] + +Explanation +DetectSquares detectSquares = new DetectSquares(); +detectSquares.add([3, 10]); +detectSquares.add([11, 2]); +detectSquares.add([3, 2]); +detectSquares.count([11, 10]); // return 1. You can choose: + // - The first, second, and third points +detectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure. +detectSquares.add([11, 2]); // Adding duplicate points is allowed. +detectSquares.count([11, 10]); // return 2. You can choose: + // - The first, second, and third points + // - The first, third, and fourth points +#+end_src + + +*Constraints:* + + - ~point.length == 2~ + + - ~0 <= x, y <= 1000~ + + - At most ~3000~ calls *in total* will be made to ~add~ and ~count~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class DetectSquares: + def __init__(self): + + + def add(self, point: List[int]) -> None: + + + def count(self, point: List[int]) -> int: + + + +# Your DetectSquares object will be instantiated and called as such: +# obj = DetectSquares() +# obj.add(point) +# param_2 = obj.count(point) #+end_src ** TODO C++ #+begin_src cpp +class DetectSquares { +public: + DetectSquares() { + + } + + void add(vector point) { + + } + + int count(vector point) { + + } +}; +/** + * Your DetectSquares object will be instantiated and called as such: + * DetectSquares* obj = new DetectSquares(); + * obj->add(point); + * int param_2 = obj->count(point); + */ #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/2326-spiral-matrix-iv.org b/org/study_deck_02/dsa/math-geometry/2326-spiral-matrix-iv.org index ac0314a..cfcaf84 100644 --- a/org/study_deck_02/dsa/math-geometry/2326-spiral-matrix-iv.org +++ b/org/study_deck_02/dsa/math-geometry/2326-spiral-matrix-iv.org @@ -1,18 +1,79 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2326. Spiral Matrix IV :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2326. Spiral Matrix IV][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2326. Spiral Matrix IV][2326. Spiral Matrix IV]] :END: +You are given two integers ~m~ and ~n~, which represent the dimensions of a matrix. + +You are also given the ~head~ of a linked list of integers. + +Generate an ~m x n~ matrix that contains the integers in the linked list presented in *spiral* order *(clockwise)*, starting from the *top-left* of the matrix. If there are remaining empty spaces, fill them with ~-1~. + +Return /the generated matrix/. + +*Example 1:* + + +#+begin_src +Input: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0] +Output: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]] +Explanation: The diagram above shows how the values are printed in the matrix. +Note that the remaining spaces in the matrix are filled with -1. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: m = 1, n = 4, head = [0,1,2] +Output: [[0,1,2,-1]] +Explanation: The diagram above shows how the values are printed from left to right in the matrix. +The last space in the matrix is set to -1. +#+end_src + + +*Constraints:* + + - ~1 <= m, n <= 10^{5}~ + + - ~1 <= m * n <= 10^{5}~ + + - The number of nodes in the list is in the range ~[1, m * n]~. + + - ~0 <= Node.val <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + vector> spiralMatrix(int m, int n, ListNode* head) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/math-geometry/2698-find-the-punishment-number-of-an-integer.org b/org/study_deck_02/dsa/math-geometry/2698-find-the-punishment-number-of-an-integer.org index c72e5b5..6ab8d54 100644 --- a/org/study_deck_02/dsa/math-geometry/2698-find-the-punishment-number-of-an-integer.org +++ b/org/study_deck_02/dsa/math-geometry/2698-find-the-punishment-number-of-an-integer.org @@ -1,18 +1,65 @@ #+PROPERTY: STUDY_DECK_02 * TODO 2698. Find the Punishment Number of an Integer :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*2698. Find the Punishment Number of an Integer][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*2698. Find the Punishment Number of an Integer][2698. Find the Punishment Number of an Integer]] :END: +Given a positive integer ~n~, return /the *punishment number*/ of ~n~. + +The *punishment number* of ~n~ is defined as the sum of the squares of all integers ~i~ such that: + + - ~1 <= i <= n~ + + - The decimal representation of ~i * i~ can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals ~i~. + +*Example 1:* + + +#+begin_src +Input: n = 10 +Output: 182 +Explanation: There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement: +- 1 since 1 * 1 = 1 +- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9. +- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10. +Hence, the punishment number of 10 is 1 + 81 + 100 = 182 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 37 +Output: 1478 +Explanation: There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement: +- 1 since 1 * 1 = 1. +- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. +- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. +- 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. +Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478 +#+end_src + + +*Constraints:* + + - ~1 <= n <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def punishmentNumber(self, n: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int punishmentNumber(int n) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/sliding-window/0003-longest-substring-without-repeating-characters.org b/org/study_deck_02/dsa/sliding-window/0003-longest-substring-without-repeating-characters.org index 3a96441..6a72d1b 100644 --- a/org/study_deck_02/dsa/sliding-window/0003-longest-substring-without-repeating-characters.org +++ b/org/study_deck_02/dsa/sliding-window/0003-longest-substring-without-repeating-characters.org @@ -1,18 +1,63 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0003. Longest Substring Without Repeating Characters :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0003. Longest Substring Without Repeating Characters][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0003. Longest Substring Without Repeating Characters][0003. Longest Substring Without Repeating Characters]] :END: +Given a string ~s~, find the length of the *longest* *substring* without duplicate characters. + +*Example 1:* + + +#+begin_src +Input: s = "abcabcbb" +Output: 3 +Explanation: The answer is "abc", with the length of 3. Note that "bca" and "cab" are also correct answers. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "bbbbb" +Output: 1 +Explanation: The answer is "b", with the length of 1. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: s = "pwwkew" +Output: 3 +Explanation: The answer is "wke", with the length of 3. +Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. +#+end_src + + +*Constraints:* + + - ~0 <= s.length <= 5 * 10^{4}~ + + - ~s~ consists of English letters, digits, symbols and spaces. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int lengthOfLongestSubstring(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/sliding-window/0076-minimum-window-substring.org b/org/study_deck_02/dsa/sliding-window/0076-minimum-window-substring.org index 50824cd..7ee6631 100644 --- a/org/study_deck_02/dsa/sliding-window/0076-minimum-window-substring.org +++ b/org/study_deck_02/dsa/sliding-window/0076-minimum-window-substring.org @@ -1,18 +1,71 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0076. Minimum Window Substring :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0076. Minimum Window Substring][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0076. Minimum Window Substring][0076. Minimum Window Substring]] :END: +Given two strings ~s~ and ~t~ of lengths ~m~ and ~n~ respectively, return /the *minimum window*/ */substring/*/ of /~s~/ such that every character in /~t~/ (*including duplicates*) is included in the window/. If there is no such substring, return /the empty string /~""~. + +The testcases will be generated such that the answer is *unique*. + +*Example 1:* + + +#+begin_src +Input: s = "ADOBECODEBANC", t = "ABC" +Output: "BANC" +Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "a", t = "a" +Output: "a" +Explanation: The entire string s is the minimum window. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: s = "a", t = "aa" +Output: "" +Explanation: Both 'a's from t must be included in the window. +Since the largest window of s only has one 'a', return empty string. +#+end_src + + +*Constraints:* + + - ~m == s.length~ + + - ~n == t.length~ + + - ~1 <= m, n <= 10^{5}~ + + - ~s~ and ~t~ consist of uppercase and lowercase English letters. + +*Follow up:* Could you find an algorithm that runs in ~O(m + n)~ time? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def minWindow(self, s: str, t: str) -> str: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + string minWindow(string s, string t) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/sliding-window/0121-best-time-to-buy-and-sell-stock.org b/org/study_deck_02/dsa/sliding-window/0121-best-time-to-buy-and-sell-stock.org index 8fd3d48..52ed86f 100644 --- a/org/study_deck_02/dsa/sliding-window/0121-best-time-to-buy-and-sell-stock.org +++ b/org/study_deck_02/dsa/sliding-window/0121-best-time-to-buy-and-sell-stock.org @@ -1,18 +1,57 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0121. Best Time to Buy And Sell Stock :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0121. Best Time to Buy And Sell Stock][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0121. Best Time to Buy And Sell Stock][0121. Best Time to Buy And Sell Stock]] :END: +You are given an array ~prices~ where ~prices[i]~ is the price of a given stock on the ~i^{th}~ 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:* + + +#+begin_src +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. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: prices = [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transactions are done and the max profit = 0. +#+end_src + + +*Constraints:* + + - ~1 <= prices.length <= 10^{5}~ + + - ~0 <= prices[i] <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxProfit(self, prices: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int maxProfit(vector& prices) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/sliding-window/0239-sliding-window-maximum.org b/org/study_deck_02/dsa/sliding-window/0239-sliding-window-maximum.org index 99b9d73..94a2e94 100644 --- a/org/study_deck_02/dsa/sliding-window/0239-sliding-window-maximum.org +++ b/org/study_deck_02/dsa/sliding-window/0239-sliding-window-maximum.org @@ -1,18 +1,63 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0239. Sliding Window Maximum :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0239. Sliding Window Maximum][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0239. Sliding Window Maximum][0239. Sliding Window Maximum]] :END: +You are given an array of integers ~nums~, there is a sliding window of size ~k~ which is moving from the very left of the array to the very right. You can only see the ~k~ numbers in the window. Each time the sliding window moves right by one position. + +Return /the max sliding window/. + +*Example 1:* + + +#+begin_src +Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 +Output: [3,3,5,5,6,7] +Explanation: +Window position Max +--------------- ----- +[1 3 -1] -3 5 3 6 7 3 + 1 [3 -1 -3] 5 3 6 7 3 + 1 3 [-1 -3 5] 3 6 7 5 + 1 3 -1 [-3 5 3] 6 7 5 + 1 3 -1 -3 [5 3 6] 7 6 + 1 3 -1 -3 5 [3 6 7] 7 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [1], k = 1 +Output: [1] +#+end_src + + +*Constraints:* + + - ~1 <= nums.length <= 10^{5}~ + + - ~-10^{4} <= nums[i] <= 10^{4}~ + + - ~1 <= k <= nums.length~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/sliding-window/0424-longest-repeating-character-replacement.org b/org/study_deck_02/dsa/sliding-window/0424-longest-repeating-character-replacement.org index 2ec9a70..0c76e10 100644 --- a/org/study_deck_02/dsa/sliding-window/0424-longest-repeating-character-replacement.org +++ b/org/study_deck_02/dsa/sliding-window/0424-longest-repeating-character-replacement.org @@ -1,18 +1,58 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0424. Longest Repeating Character Replacement :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0424. Longest Repeating Character Replacement][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0424. Longest Repeating Character Replacement][0424. Longest Repeating Character Replacement]] :END: +You are given a string ~s~ and an integer ~k~. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most ~k~ times. + +Return /the length of the longest substring containing the same letter you can get after performing the above operations/. + +*Example 1:* + + +#+begin_src +Input: s = "ABAB", k = 2 +Output: 4 +Explanation: Replace the two 'A's with two 'B's or vice versa. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "AABABBA", k = 1 +Output: 4 +Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". +The substring "BBBB" has the longest repeating letters, which is 4. +There may exists other ways to achieve this answer too. +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 10^{5}~ + + - ~s~ consists of only uppercase English letters. + + - ~0 <= k <= s.length~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def characterReplacement(self, s: str, k: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int characterReplacement(string s, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/sliding-window/0567-permutation-in-string.org b/org/study_deck_02/dsa/sliding-window/0567-permutation-in-string.org index 951eb39..27b3e9b 100644 --- a/org/study_deck_02/dsa/sliding-window/0567-permutation-in-string.org +++ b/org/study_deck_02/dsa/sliding-window/0567-permutation-in-string.org @@ -1,18 +1,53 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0567. Permutation In String :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0567. Permutation In String][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0567. Permutation In String][0567. Permutation In String]] :END: +Given two strings ~s1~ and ~s2~, return ~true~ if ~s2~ contains a permutation of ~s1~, or ~false~ otherwise. + +In other words, return ~true~ if one of ~s1~'s permutations is the substring of ~s2~. + +*Example 1:* + + +#+begin_src +Input: s1 = "ab", s2 = "eidbaooo" +Output: true +Explanation: s2 contains one permutation of s1 ("ba"). +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s1 = "ab", s2 = "eidboaoo" +Output: false +#+end_src + + +*Constraints:* + + - ~1 <= s1.length, s2.length <= 10^{4}~ + + - ~s1~ and ~s2~ consist of lowercase English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def checkInclusion(self, s1: str, s2: str) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool checkInclusion(string s1, string s2) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/sliding-window/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.org b/org/study_deck_02/dsa/sliding-window/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.org index b5e768e..daa1302 100644 --- a/org/study_deck_02/dsa/sliding-window/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.org +++ b/org/study_deck_02/dsa/sliding-window/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.org @@ -1,18 +1,72 @@ #+PROPERTY: STUDY_DECK_02 * TODO 3306. Count of Substrings Containing Every Vowel and K Consonants II :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*3306. Count of Substrings Containing Every Vowel and K Consonants II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*3306. Count of Substrings Containing Every Vowel and K Consonants II][3306. Count of Substrings Containing Every Vowel and K Consonants II]] :END: +You are given a string ~word~ and a *non-negative* integer ~k~. + +Return the total number of substrings of ~word~ that contain every vowel (~'a'~, ~'e'~, ~'i'~, ~'o'~, and ~'u'~) *at least* once and *exactly* ~k~ consonants. + +*Example 1:* + +*Input:* word = "aeioqq", k = 1 + +*Output:* 0 + +*Explanation:* + +There is no substring with every vowel. + +*Example 2:* + +*Input:* word = "aeiou", k = 0 + +*Output:* 1 + +*Explanation:* + +The only substring with every vowel and zero consonants is ~word[0..4]~, which is ~"aeiou"~. + +*Example 3:* + +*Input:* word = "ieaouqqieaouqq", k = 1 + +*Output:* 3 + +*Explanation:* + +The substrings with every vowel and one consonant are: + + - ~word[0..5]~, which is ~"ieaouq"~. + + - ~word[6..11]~, which is ~"qieaou"~. + + - ~word[7..12]~, which is ~"ieaouq"~. + +*Constraints:* + + - ~5 <= word.length <= 2 * 10^{5}~ + + - ~word~ consists only of lowercase English letters. + + - ~0 <= k <= word.length - 5~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def countOfSubstrings(self, word: str, k: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + long long countOfSubstrings(string word, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/stack/0020-valid-parentheses.org b/org/study_deck_02/dsa/stack/0020-valid-parentheses.org index d61c6f1..c958929 100644 --- a/org/study_deck_02/dsa/stack/0020-valid-parentheses.org +++ b/org/study_deck_02/dsa/stack/0020-valid-parentheses.org @@ -1,18 +1,70 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0020. Valid Parentheses :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0020. Valid Parentheses][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0020. Valid Parentheses][0020. Valid Parentheses]] :END: +Given a string ~s~ containing just the characters ~'('~, ~')'~, ~'{'~, ~'}'~, ~'['~ and ~']'~, determine if the input string is valid. + +An input string is valid if: + + - Open brackets must be closed by the same type of brackets. + + - Open brackets must be closed in the correct order. + + - Every close bracket has a corresponding open bracket of the same type. + +*Example 1:* + +*Input:* s = "()" + +*Output:* true + +*Example 2:* + +*Input:* s = "()[]{}" + +*Output:* true + +*Example 3:* + +*Input:* s = "(]" + +*Output:* false + +*Example 4:* + +*Input:* s = "([])" + +*Output:* true + +*Example 5:* + +*Input:* s = "([)]" + +*Output:* false + +*Constraints:* + + - ~1 <= s.length <= 10^{4}~ + + - ~s~ consists of parentheses only ~'()[]{}'~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isValid(self, s: str) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isValid(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/stack/0084-largest-rectangle-in-histogram.org b/org/study_deck_02/dsa/stack/0084-largest-rectangle-in-histogram.org index 3dc0d6d..386c51b 100644 --- a/org/study_deck_02/dsa/stack/0084-largest-rectangle-in-histogram.org +++ b/org/study_deck_02/dsa/stack/0084-largest-rectangle-in-histogram.org @@ -1,18 +1,52 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0084. Largest Rectangle In Histogram :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0084. Largest Rectangle In Histogram][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0084. Largest Rectangle In Histogram][0084. Largest Rectangle In Histogram]] :END: +Given an array of integers ~heights~ representing the histogram's bar height where the width of each bar is ~1~, return /the area of the largest rectangle in the histogram/. + +*Example 1:* + + +#+begin_src +Input: heights = [2,1,5,6,2,3] +Output: 10 +Explanation: The above is a histogram where width of each bar is 1. +The largest rectangle is shown in the red area, which has an area = 10 units. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: heights = [2,4] +Output: 4 +#+end_src + + +*Constraints:* + + - ~1 <= heights.length <= 10^{5}~ + + - ~0 <= heights[i] <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int largestRectangleArea(vector& heights) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/stack/0150-evaluate-reverse-polish-notation.org b/org/study_deck_02/dsa/stack/0150-evaluate-reverse-polish-notation.org index e769faf..c86b5e8 100644 --- a/org/study_deck_02/dsa/stack/0150-evaluate-reverse-polish-notation.org +++ b/org/study_deck_02/dsa/stack/0150-evaluate-reverse-polish-notation.org @@ -1,18 +1,84 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0150. Evaluate Reverse Polish Notation :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0150. Evaluate Reverse Polish Notation][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0150. Evaluate Reverse Polish Notation][0150. Evaluate Reverse Polish Notation]] :END: +You are given an array of strings ~tokens~ that represents an arithmetic expression in a Reverse Polish Notation. + +Evaluate the expression. Return /an integer that represents the value of the expression/. + +*Note* that: + + - The valid operators are ~'+'~, ~'-'~, ~'*'~, and ~'/'~. + + - Each operand may be an integer or another expression. + + - The division between two integers always *truncates toward zero*. + + - There will not be any division by zero. + + - The input represents a valid arithmetic expression in a reverse polish notation. + + - The answer and all the intermediate calculations can be represented in a *32-bit* integer. + +*Example 1:* + + +#+begin_src +Input: tokens = ["2","1","+","3","*"] +Output: 9 +Explanation: ((2 + 1) * 3) = 9 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: tokens = ["4","13","5","/","+"] +Output: 6 +Explanation: (4 + (13 / 5)) = 6 +#+end_src + + +*Example 3:* + + +#+begin_src +Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] +Output: 22 +Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 += ((10 * (6 / (12 * -11))) + 17) + 5 += ((10 * (6 / -132)) + 17) + 5 += ((10 * 0) + 17) + 5 += (0 + 17) + 5 += 17 + 5 += 22 +#+end_src + + +*Constraints:* + + - ~1 <= tokens.length <= 10^{4}~ + + - ~tokens[i]~ is either an operator: ~"+"~, ~"-"~, ~"*"~, or ~"/"~, or an integer in the range ~[-200, 200]~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def evalRPN(self, tokens: List[str]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int evalRPN(vector& tokens) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/stack/0155-min-stack.org b/org/study_deck_02/dsa/stack/0155-min-stack.org index d20b916..85beb9f 100644 --- a/org/study_deck_02/dsa/stack/0155-min-stack.org +++ b/org/study_deck_02/dsa/stack/0155-min-stack.org @@ -1,18 +1,118 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0155. Min Stack :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0155. Min Stack][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0155. Min Stack][0155. Min Stack]] :END: +Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. + +Implement the ~MinStack~ class: + + - ~MinStack()~ initializes the stack object. + + - ~void push(int val)~ pushes the element ~val~ onto the stack. + + - ~void pop()~ removes the element on the top of the stack. + + - ~int top()~ gets the top element of the stack. + + - ~int getMin()~ retrieves the minimum element in the stack. + +You must implement a solution with ~O(1)~ time complexity for each function. + +*Example 1:* + + +#+begin_src +Input +["MinStack","push","push","push","getMin","pop","top","getMin"] +[[],[-2],[0],[-3],[],[],[],[]] + +Output +[null,null,null,null,-3,null,0,-2] + +Explanation +MinStack minStack = new MinStack(); +minStack.push(-2); +minStack.push(0); +minStack.push(-3); +minStack.getMin(); // return -3 +minStack.pop(); +minStack.top(); // return 0 +minStack.getMin(); // return -2 +#+end_src + + +*Constraints:* + + - ~-2^{31} <= val <= 2^{31} - 1~ + + - Methods ~pop~, ~top~ and ~getMin~ operations will always be called on *non-empty* stacks. + + - At most ~3 * 10^{4}~ calls will be made to ~push~, ~pop~, ~top~, and ~getMin~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class MinStack: + def __init__(self): + + + def push(self, val: int) -> None: + + + def pop(self) -> None: + + + def top(self) -> int: + + + def getMin(self) -> int: + + + +# Your MinStack object will be instantiated and called as such: +# obj = MinStack() +# obj.push(val) +# obj.pop() +# param_3 = obj.top() +# param_4 = obj.getMin() #+end_src ** TODO C++ #+begin_src cpp +class MinStack { +public: + MinStack() { + + } + + void push(int val) { + + } + + void pop() { + + } + + int top() { + + } + + int getMin() { + + } +}; +/** + * Your MinStack object will be instantiated and called as such: + * MinStack* obj = new MinStack(); + * obj->push(val); + * obj->pop(); + * int param_3 = obj->top(); + * int param_4 = obj->getMin(); + */ #+end_src diff --git a/org/study_deck_02/dsa/stack/0682-baseball-game.org b/org/study_deck_02/dsa/stack/0682-baseball-game.org index 09769cb..0312020 100644 --- a/org/study_deck_02/dsa/stack/0682-baseball-game.org +++ b/org/study_deck_02/dsa/stack/0682-baseball-game.org @@ -1,18 +1,106 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0682. Baseball Game :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0682. Baseball Game][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0682. Baseball Game][0682. Baseball Game]] :END: +You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. + +You are given a list of strings ~operations~, where ~operations[i]~ is the ~i^{th}~ operation you must apply to the record and is one of the following: + + - An integer ~x~. + + - Record a new score of ~x~. + + - ~'+'~. + + - Record a new score that is the sum of the previous two scores. + + - ~'D'~. + + - Record a new score that is the double of the previous score. + + - ~'C'~. + + - Invalidate the previous score, removing it from the record. + +Return /the sum of all the scores on the record after applying all the operations/. + +The test cases are generated such that the answer and all intermediate calculations fit in a *32-bit* integer and that all operations are valid. + +*Example 1:* + + +#+begin_src +Input: ops = ["5","2","C","D","+"] +Output: 30 +Explanation: +"5" - Add 5 to the record, record is now [5]. +"2" - Add 2 to the record, record is now [5, 2]. +"C" - Invalidate and remove the previous score, record is now [5]. +"D" - Add 2 * 5 = 10 to the record, record is now [5, 10]. +"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15]. +The total sum is 5 + 10 + 15 = 30. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: ops = ["5","-2","4","C","D","9","+","+"] +Output: 27 +Explanation: +"5" - Add 5 to the record, record is now [5]. +"-2" - Add -2 to the record, record is now [5, -2]. +"4" - Add 4 to the record, record is now [5, -2, 4]. +"C" - Invalidate and remove the previous score, record is now [5, -2]. +"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4]. +"9" - Add 9 to the record, record is now [5, -2, -4, 9]. +"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5]. +"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14]. +The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: ops = ["1","C"] +Output: 0 +Explanation: +"1" - Add 1 to the record, record is now [1]. +"C" - Invalidate and remove the previous score, record is now []. +Since the record is empty, the total sum is 0. +#+end_src + + +*Constraints:* + + - ~1 <= operations.length <= 1000~ + + - ~operations[i]~ is ~"C"~, ~"D"~, ~"+"~, or a string representing an integer in the range ~[-3 * 10^{4}, 3 * 10^{4}]~. + + - For operation ~"+"~, there will always be at least two previous scores on the record. + + - For operations ~"C"~ and ~"D"~, there will always be at least one previous score on the record. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def calPoints(self, operations: List[str]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int calPoints(vector& operations) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/stack/0726-number-of-atoms.org b/org/study_deck_02/dsa/stack/0726-number-of-atoms.org index 199c505..5f6f7a1 100644 --- a/org/study_deck_02/dsa/stack/0726-number-of-atoms.org +++ b/org/study_deck_02/dsa/stack/0726-number-of-atoms.org @@ -1,18 +1,82 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0726. Number of Atoms :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0726. Number of Atoms][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0726. Number of Atoms][0726. Number of Atoms]] :END: +Given a string ~formula~ representing a chemical formula, return /the count of each atom/. + +The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name. + +One or more digits representing that element's count may follow if the count is greater than ~1~. If the count is ~1~, no digits will follow. + + - For example, ~"H2O"~ and ~"H2O2"~ are possible, but ~"H1O2"~ is impossible. + +Two formulas are concatenated together to produce another formula. + + - For example, ~"H2O2He3Mg4"~ is also a formula. + +A formula placed in parentheses, and a count (optionally added) is also a formula. + + - For example, ~"(H2O2)"~ and ~"(H2O2)3"~ are formulas. + +Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than ~1~), followed by the second name (in sorted order), followed by its count (if that count is more than ~1~), and so on. + +The test cases are generated so that all the values in the output fit in a *32-bit* integer. + +*Example 1:* + + +#+begin_src +Input: formula = "H2O" +Output: "H2O" +Explanation: The count of elements are {'H': 2, 'O': 1}. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: formula = "Mg(OH)2" +Output: "H2MgO2" +Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: formula = "K4(ON(SO3)2)2" +Output: "K4N2O14S4" +Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}. +#+end_src + + +*Constraints:* + + - ~1 <= formula.length <= 1000~ + + - ~formula~ consists of English letters, digits, ~'('~, and ~')'~. + + - ~formula~ is always valid. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def countOfAtoms(self, formula: str) -> str: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + string countOfAtoms(string formula) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/stack/0739-daily-temperatures.org b/org/study_deck_02/dsa/stack/0739-daily-temperatures.org index 0b897c6..ad12887 100644 --- a/org/study_deck_02/dsa/stack/0739-daily-temperatures.org +++ b/org/study_deck_02/dsa/stack/0739-daily-temperatures.org @@ -1,18 +1,55 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0739. Daily Temperatures :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0739. Daily Temperatures][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0739. Daily Temperatures][0739. Daily Temperatures]] :END: +Given an array of integers ~temperatures~ represents the daily temperatures, return /an array/ ~answer~ /such that/ ~answer[i]~ /is the number of days you have to wait after the/ ~i^{th}~ /day to get a warmer temperature/. If there is no future day for which this is possible, keep ~answer[i] == 0~ instead. + +*Example 1:* + + +#+begin_src +Input: temperatures = [73,74,75,71,69,72,76,73] +Output: [1,1,4,2,1,1,0,0] +#+end_src +*Example 2:* + + +#+begin_src +Input: temperatures = [30,40,50,60] +Output: [1,1,1,0] +#+end_src +*Example 3:* + + +#+begin_src +Input: temperatures = [30,60,90] +Output: [1,1,0] +#+end_src + + +*Constraints:* + + - ~1 <= temperatures.length <= 10^{5}~ + + - ~30 <= temperatures[i] <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/stack/0853-car-fleet.org b/org/study_deck_02/dsa/stack/0853-car-fleet.org index 0fae44e..f64f7d4 100644 --- a/org/study_deck_02/dsa/stack/0853-car-fleet.org +++ b/org/study_deck_02/dsa/stack/0853-car-fleet.org @@ -1,18 +1,86 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0853. Car Fleet :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0853. Car Fleet][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0853. Car Fleet][0853. Car Fleet]] :END: +There are ~n~ cars at given miles away from the starting mile 0, traveling to reach the mile ~target~. + +You are given two integer arrays ~position~ and ~speed~, both of length ~n~, where ~position[i]~ is the starting mile of the ~i^{th}~ car and ~speed[i]~ is the speed of the ~i^{th}~ car in miles per hour. + +A car cannot pass another car, but it can catch up and then travel next to it at the speed of the slower car. + +A *car fleet* is a single car or a group of cars driving next to each other. The speed of the car fleet is the *minimum* speed of any car in the fleet. + +If a car catches up to a car fleet at the mile ~target~, it will still be considered as part of the car fleet. + +Return the number of car fleets that will arrive at the destination. + +*Example 1:* + +*Input:* target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] + +*Output:* 3 + +*Explanation:* + + - The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The fleet forms at ~target~. + + - The car starting at 0 (speed 1) does not catch up to any other car, so it is a fleet by itself. + + - The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches ~target~. + +*Example 2:* + +*Input:* target = 10, position = [3], speed = [3] + +*Output:* 1 + +*Explanation:* + +There is only one car, hence there is only one fleet. + +*Example 3:* + +*Input:* target = 100, position = [0,2,4], speed = [4,2,1] + +*Output:* 1 + +*Explanation:* + + - The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The car starting at 4 (speed 1) travels to 5. + + - Then, the fleet at 4 (speed 2) and the car at position 5 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches ~target~. + +*Constraints:* + + - ~n == position.length == speed.length~ + + - ~1 <= n <= 10^{5}~ + + - ~0 < target <= 10^{6}~ + + - ~0 <= position[i] < target~ + + - All the values of ~position~ are *unique*. + + - ~0 < speed[i] <= 10^{6}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int carFleet(int target, vector& position, vector& speed) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/stack/0901-online-stock-span.org b/org/study_deck_02/dsa/stack/0901-online-stock-span.org index 7ad3503..e0cefb1 100644 --- a/org/study_deck_02/dsa/stack/0901-online-stock-span.org +++ b/org/study_deck_02/dsa/stack/0901-online-stock-span.org @@ -1,18 +1,86 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0901. Online Stock Span :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0901. Online Stock Span][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0901. Online Stock Span][0901. Online Stock Span]] :END: +Design an algorithm that collects daily price quotes for some stock and returns *the span* of that stock's price for the current day. + +The *span* of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. + + - For example, if the prices of the stock in the last four days is ~[7,2,1,2]~ and the price of the stock today is ~2~, then the span of today is ~4~ because starting from today, the price of the stock was less than or equal ~2~ for ~4~ consecutive days. + + - Also, if the prices of the stock in the last four days is ~[7,34,1,2]~ and the price of the stock today is ~8~, then the span of today is ~3~ because starting from today, the price of the stock was less than or equal ~8~ for ~3~ consecutive days. + +Implement the ~StockSpanner~ class: + + - ~StockSpanner()~ Initializes the object of the class. + + - ~int next(int price)~ Returns the *span* of the stock's price given that today's price is ~price~. + +*Example 1:* + + +#+begin_src +Input +["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] +[[], [100], [80], [60], [70], [60], [75], [85]] +Output +[null, 1, 1, 1, 2, 1, 4, 6] + +Explanation +StockSpanner stockSpanner = new StockSpanner(); +stockSpanner.next(100); // return 1 +stockSpanner.next(80); // return 1 +stockSpanner.next(60); // return 1 +stockSpanner.next(70); // return 2 +stockSpanner.next(60); // return 1 +stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. +stockSpanner.next(85); // return 6 +#+end_src + + +*Constraints:* + + - ~1 <= price <= 10^{5}~ + + - At most ~10^{4}~ calls will be made to ~next~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class StockSpanner: + def __init__(self): + + + def next(self, price: int) -> int: + + + +# Your StockSpanner object will be instantiated and called as such: +# obj = StockSpanner() +# param_1 = obj.next(price) #+end_src ** TODO C++ #+begin_src cpp +class StockSpanner { +public: + StockSpanner() { + + } + + int next(int price) { + + } +}; +/** + * Your StockSpanner object will be instantiated and called as such: + * StockSpanner* obj = new StockSpanner(); + * int param_1 = obj->next(price); + */ #+end_src diff --git a/org/study_deck_02/dsa/stack/1544-make-the-string-great.org b/org/study_deck_02/dsa/stack/1544-make-the-string-great.org index 4453d2c..789b0ec 100644 --- a/org/study_deck_02/dsa/stack/1544-make-the-string-great.org +++ b/org/study_deck_02/dsa/stack/1544-make-the-string-great.org @@ -1,18 +1,75 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1544. Make The String Great :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1544. Make The String Great][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1544. Make The String Great][1544. Make The String Great]] :END: +Given a string ~s~ of lower and upper case English letters. + +A good string is a string which doesn't have *two adjacent characters* ~s[i]~ and ~s[i + 1]~ where: + + - ~0 <= i <= s.length - 2~ + + - ~s[i]~ is a lower-case letter and ~s[i + 1]~ is the same letter but in upper-case or *vice-versa*. + +To make the string good, you can choose *two adjacent* characters that make the string bad and remove them. You can keep doing this until the string becomes good. + +Return /the string/ after making it good. The answer is guaranteed to be unique under the given constraints. + +*Notice* that an empty string is also good. + +*Example 1:* + + +#+begin_src +Input: s = "leEeetcode" +Output: "leetcode" +Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode". +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "abBAcC" +Output: "" +Explanation: We have many possible scenarios, and all lead to the same answer. For example: +"abBAcC" --> "aAcC" --> "cC" --> "" +"abBAcC" --> "abBA" --> "aA" --> "" +#+end_src + + +*Example 3:* + + +#+begin_src +Input: s = "s" +Output: "s" +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 100~ + + - ~s~ contains only lower and upper case English letters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def makeGood(self, s: str) -> str: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + string makeGood(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0098-validate-binary-search-tree.org b/org/study_deck_02/dsa/trees/0098-validate-binary-search-tree.org index 6bfd876..d651edd 100644 --- a/org/study_deck_02/dsa/trees/0098-validate-binary-search-tree.org +++ b/org/study_deck_02/dsa/trees/0098-validate-binary-search-tree.org @@ -1,18 +1,76 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0098. Validate Binary Search Tree :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0098. Validate Binary Search Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0098. Validate Binary Search Tree][0098. Validate Binary Search Tree]] :END: +Given the ~root~ of a binary tree, /determine if it is a valid binary search tree (BST)/. + +A *valid BST* is defined as follows: + + - The left subtree of a node contains only nodes with keys *strictly less than* the node's key. + + - The right subtree of a node contains only nodes with keys *strictly greater than* the node's key. + + - Both the left and right subtrees must also be binary search trees. + +*Example 1:* + + +#+begin_src +Input: root = [2,1,3] +Output: true +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [5,1,4,null,null,3,6] +Output: false +Explanation: The root node's value is 5 but its right child's value is 4. +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[1, 10^{4}]~. + + - ~-2^{31} <= Node.val <= 2^{31} - 1~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isValidBST(TreeNode* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0100-same-tree.org b/org/study_deck_02/dsa/trees/0100-same-tree.org index 177d958..88ed164 100644 --- a/org/study_deck_02/dsa/trees/0100-same-tree.org +++ b/org/study_deck_02/dsa/trees/0100-same-tree.org @@ -1,18 +1,78 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0100. Same Tree :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0100. Same Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0100. Same Tree][0100. Same Tree]] :END: +Given the roots of two binary trees ~p~ and ~q~, write a function to check if they are the same or not. + +Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. + +*Example 1:* + + +#+begin_src +Input: p = [1,2,3], q = [1,2,3] +Output: true +#+end_src + + +*Example 2:* + + +#+begin_src +Input: p = [1,2], q = [1,null,2] +Output: false +#+end_src + + +*Example 3:* + + +#+begin_src +Input: p = [1,2,1], q = [1,1,2] +Output: false +#+end_src + + +*Constraints:* + + - The number of nodes in both trees is in the range ~[0, 100]~. + + - ~-10^{4} <= Node.val <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0102-binary-tree-level-order-traversal.org b/org/study_deck_02/dsa/trees/0102-binary-tree-level-order-traversal.org index c561aa2..010b249 100644 --- a/org/study_deck_02/dsa/trees/0102-binary-tree-level-order-traversal.org +++ b/org/study_deck_02/dsa/trees/0102-binary-tree-level-order-traversal.org @@ -1,18 +1,76 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0102. Binary Tree Level Order Traversal :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0102. Binary Tree Level Order Traversal][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0102. Binary Tree Level Order Traversal][0102. Binary Tree Level Order Traversal]] :END: +Given the ~root~ of a binary tree, return /the level order traversal of its nodes' values/. (i.e., from left to right, level by level). + +*Example 1:* + + +#+begin_src +Input: root = [3,9,20,null,null,15,7] +Output: [[3],[9,20],[15,7]] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [1] +Output: [[1]] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: root = [] +Output: [] +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[0, 2000]~. + + - ~-1000 <= Node.val <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0104-maximum-depth-of-binary-tree.org b/org/study_deck_02/dsa/trees/0104-maximum-depth-of-binary-tree.org index dc93f91..8a774ca 100644 --- a/org/study_deck_02/dsa/trees/0104-maximum-depth-of-binary-tree.org +++ b/org/study_deck_02/dsa/trees/0104-maximum-depth-of-binary-tree.org @@ -1,18 +1,69 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0104. Maximum Depth of Binary Tree :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0104. Maximum Depth of Binary Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0104. Maximum Depth of Binary Tree][0104. Maximum Depth of Binary Tree]] :END: +Given the ~root~ of a binary tree, return /its maximum depth/. + +A binary tree's *maximum depth* is the number of nodes along the longest path from the root node down to the farthest leaf node. + +*Example 1:* + + +#+begin_src +Input: root = [3,9,20,null,null,15,7] +Output: 3 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [1,null,2] +Output: 2 +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[0, 10^{4}]~. + + - ~-100 <= Node.val <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxDepth(TreeNode* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0105-construct-binary-tree-from-preorder-and-inorder-traversal.org b/org/study_deck_02/dsa/trees/0105-construct-binary-tree-from-preorder-and-inorder-traversal.org index d7bc646..0728d3f 100644 --- a/org/study_deck_02/dsa/trees/0105-construct-binary-tree-from-preorder-and-inorder-traversal.org +++ b/org/study_deck_02/dsa/trees/0105-construct-binary-tree-from-preorder-and-inorder-traversal.org @@ -1,18 +1,77 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0105. Construct Binary Tree From Preorder And Inorder Traversal :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0105. Construct Binary Tree From Preorder And Inorder Traversal][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0105. Construct Binary Tree From Preorder And Inorder Traversal][0105. Construct Binary Tree From Preorder And Inorder Traversal]] :END: +Given two integer arrays ~preorder~ and ~inorder~ where ~preorder~ is the preorder traversal of a binary tree and ~inorder~ is the inorder traversal of the same tree, construct and return /the binary tree/. + +*Example 1:* + + +#+begin_src +Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] +Output: [3,9,20,null,null,15,7] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: preorder = [-1], inorder = [-1] +Output: [-1] +#+end_src + + +*Constraints:* + + - ~1 <= preorder.length <= 3000~ + + - ~inorder.length == preorder.length~ + + - ~-3000 <= preorder[i], inorder[i] <= 3000~ + + - ~preorder~ and ~inorder~ consist of *unique* values. + + - Each value of ~inorder~ also appears in ~preorder~. + + - ~preorder~ is *guaranteed* to be the preorder traversal of the tree. + + - ~inorder~ is *guaranteed* to be the inorder traversal of the tree. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* buildTree(vector& preorder, vector& inorder) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0110-balanced-binary-tree.org b/org/study_deck_02/dsa/trees/0110-balanced-binary-tree.org index 33684e1..dc7c91b 100644 --- a/org/study_deck_02/dsa/trees/0110-balanced-binary-tree.org +++ b/org/study_deck_02/dsa/trees/0110-balanced-binary-tree.org @@ -1,18 +1,76 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0110. Balanced Binary Tree :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0110. Balanced Binary Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0110. Balanced Binary Tree][0110. Balanced Binary Tree]] :END: +Given a binary tree, determine if it is *height-balanced*. + +*Example 1:* + + +#+begin_src +Input: root = [3,9,20,null,null,15,7] +Output: true +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [1,2,2,3,3,null,null,4,4] +Output: false +#+end_src + + +*Example 3:* + + +#+begin_src +Input: root = [] +Output: true +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[0, 5000]~. + + - ~-10^{4} <= Node.val <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isBalanced(self, root: Optional[TreeNode]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isBalanced(TreeNode* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0124-binary-tree-maximum-path-sum.org b/org/study_deck_02/dsa/trees/0124-binary-tree-maximum-path-sum.org index cd03ab4..7885395 100644 --- a/org/study_deck_02/dsa/trees/0124-binary-tree-maximum-path-sum.org +++ b/org/study_deck_02/dsa/trees/0124-binary-tree-maximum-path-sum.org @@ -1,18 +1,73 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0124. Binary Tree Maximum Path Sum :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0124. Binary Tree Maximum Path Sum][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0124. Binary Tree Maximum Path Sum][0124. Binary Tree Maximum Path Sum]] :END: +A *path* in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence *at most once*. Note that the path does not need to pass through the root. + +The *path sum* of a path is the sum of the node's values in the path. + +Given the ~root~ of a binary tree, return /the maximum *path sum* of any *non-empty* path/. + +*Example 1:* + + +#+begin_src +Input: root = [1,2,3] +Output: 6 +Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [-10,9,20,null,null,15,7] +Output: 42 +Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[1, 3 * 10^{4}]~. + + - ~-1000 <= Node.val <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxPathSum(self, root: Optional[TreeNode]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxPathSum(TreeNode* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0199-binary-tree-right-side-view.org b/org/study_deck_02/dsa/trees/0199-binary-tree-right-side-view.org index 9808743..a20aa13 100644 --- a/org/study_deck_02/dsa/trees/0199-binary-tree-right-side-view.org +++ b/org/study_deck_02/dsa/trees/0199-binary-tree-right-side-view.org @@ -1,18 +1,77 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0199. Binary Tree Right Side View :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0199. Binary Tree Right Side View][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0199. Binary Tree Right Side View][0199. Binary Tree Right Side View]] :END: +Given the ~root~ of a binary tree, imagine yourself standing on the *right side* of it, return /the values of the nodes you can see ordered from top to bottom/. + +*Example 1:* + +*Input:* root = [1,2,3,null,5,null,4] + +*Output:* [1,3,4] + +*Explanation:* + +*Example 2:* + +*Input:* root = [1,2,3,4,null,null,null,5] + +*Output:* [1,3,4,5] + +*Explanation:* + +*Example 3:* + +*Input:* root = [1,null,3] + +*Output:* [1,3] + +*Example 4:* + +*Input:* root = [] + +*Output:* [] + +*Constraints:* + + - The number of nodes in the tree is in the range ~[0, 100]~. + + - ~-100 <= Node.val <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector rightSideView(TreeNode* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0226-invert-binary-tree.org b/org/study_deck_02/dsa/trees/0226-invert-binary-tree.org index 98e745f..60a0f2d 100644 --- a/org/study_deck_02/dsa/trees/0226-invert-binary-tree.org +++ b/org/study_deck_02/dsa/trees/0226-invert-binary-tree.org @@ -1,18 +1,76 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0226. Invert Binary Tree :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0226. Invert Binary Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0226. Invert Binary Tree][0226. Invert Binary Tree]] :END: +Given the ~root~ of a binary tree, invert the tree, and return /its root/. + +*Example 1:* + + +#+begin_src +Input: root = [4,2,7,1,3,6,9] +Output: [4,7,2,9,6,3,1] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [2,1,3] +Output: [2,3,1] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: root = [] +Output: [] +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[0, 100]~. + + - ~-100 <= Node.val <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0230-kth-smallest-element-in-a-bst.org b/org/study_deck_02/dsa/trees/0230-kth-smallest-element-in-a-bst.org index 2b2b8db..7d4b4bf 100644 --- a/org/study_deck_02/dsa/trees/0230-kth-smallest-element-in-a-bst.org +++ b/org/study_deck_02/dsa/trees/0230-kth-smallest-element-in-a-bst.org @@ -1,18 +1,71 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0230. Kth Smallest Element In a Bst :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0230. Kth Smallest Element In a Bst][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0230. Kth Smallest Element In a Bst][0230. Kth Smallest Element In a Bst]] :END: +Given the ~root~ of a binary search tree, and an integer ~k~, return /the/ ~k^{th}~ /smallest value (*1-indexed*) of all the values of the nodes in the tree/. + +*Example 1:* + + +#+begin_src +Input: root = [3,1,4,null,2], k = 1 +Output: 1 +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [5,3,6,2,4,null,null,1], k = 3 +Output: 3 +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is ~n~. + + - ~1 <= k <= n <= 10^{4}~ + + - ~0 <= Node.val <= 10^{4}~ + +*Follow up:* If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0235-lowest-common-ancestor-of-a-binary-search-tree.org b/org/study_deck_02/dsa/trees/0235-lowest-common-ancestor-of-a-binary-search-tree.org index 176e0b4..59226c6 100644 --- a/org/study_deck_02/dsa/trees/0235-lowest-common-ancestor-of-a-binary-search-tree.org +++ b/org/study_deck_02/dsa/trees/0235-lowest-common-ancestor-of-a-binary-search-tree.org @@ -1,18 +1,86 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0235. Lowest Common Ancestor of a Binary Search Tree :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0235. Lowest Common Ancestor of a Binary Search Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0235. Lowest Common Ancestor of a Binary Search Tree][0235. Lowest Common Ancestor of a Binary Search Tree]] :END: +Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. + +According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes ~p~ and ~q~ as the lowest node in ~T~ that has both ~p~ and ~q~ as descendants (where we allow *a node to be a descendant of itself*).” + +*Example 1:* + + +#+begin_src +Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 +Output: 6 +Explanation: The LCA of nodes 2 and 8 is 6. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 +Output: 2 +Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: root = [2,1], p = 2, q = 1 +Output: 2 +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[2, 10^{5}]~. + + - ~-10^{9} <= Node.val <= 10^{9}~ + + - All ~Node.val~ are *unique*. + + - ~p != q~ + + - ~p~ and ~q~ will exist in the BST. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': #+end_src ** TODO C++ #+begin_src cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0297-serialize-and-deserialize-binary-tree.org b/org/study_deck_02/dsa/trees/0297-serialize-and-deserialize-binary-tree.org index 4edd280..74a1151 100644 --- a/org/study_deck_02/dsa/trees/0297-serialize-and-deserialize-binary-tree.org +++ b/org/study_deck_02/dsa/trees/0297-serialize-and-deserialize-binary-tree.org @@ -1,18 +1,101 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0297. Serialize And Deserialize Binary Tree :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0297. Serialize And Deserialize Binary Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0297. Serialize And Deserialize Binary Tree][0297. Serialize And Deserialize Binary Tree]] :END: +Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. + +Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. + +*Clarification:* The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. + +*Example 1:* + + +#+begin_src +Input: root = [1,2,3,null,null,4,5] +Output: [1,2,3,null,null,4,5] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [] +Output: [] +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[0, 10^{4}]~. + + - ~-1000 <= Node.val <= 1000~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None +class Codec: + + def serialize(self, root): + """Encodes a tree to a single string. + + :type root: TreeNode + :rtype: str + """ + + + def deserialize(self, data): + """Decodes your encoded data to tree. + + :type data: str + :rtype: TreeNode + """ + + +# Your Codec object will be instantiated and called as such: +# ser = Codec() +# deser = Codec() +# ans = deser.deserialize(ser.serialize(root)) #+end_src ** TODO C++ #+begin_src cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { +public: + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec ser, deser; +// TreeNode* ans = deser.deserialize(ser.serialize(root)); #+end_src diff --git a/org/study_deck_02/dsa/trees/0543-diameter-of-binary-tree.org b/org/study_deck_02/dsa/trees/0543-diameter-of-binary-tree.org index 2c84022..83bf1ba 100644 --- a/org/study_deck_02/dsa/trees/0543-diameter-of-binary-tree.org +++ b/org/study_deck_02/dsa/trees/0543-diameter-of-binary-tree.org @@ -1,18 +1,72 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0543. Diameter of Binary Tree :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0543. Diameter of Binary Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0543. Diameter of Binary Tree][0543. Diameter of Binary Tree]] :END: +Given the ~root~ of a binary tree, return /the length of the *diameter* of the tree/. + +The *diameter* of a binary tree is the *length* of the longest path between any two nodes in a tree. This path may or may not pass through the ~root~. + +The *length* of a path between two nodes is represented by the number of edges between them. + +*Example 1:* + + +#+begin_src +Input: root = [1,2,3,4,5] +Output: 3 +Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [1,2] +Output: 1 +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[1, 10^{4}]~. + + - ~-100 <= Node.val <= 100~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int diameterOfBinaryTree(TreeNode* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0572-subtree-of-another-tree.org b/org/study_deck_02/dsa/trees/0572-subtree-of-another-tree.org index 533de1e..8619a0b 100644 --- a/org/study_deck_02/dsa/trees/0572-subtree-of-another-tree.org +++ b/org/study_deck_02/dsa/trees/0572-subtree-of-another-tree.org @@ -1,18 +1,73 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0572. Subtree of Another Tree :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0572. Subtree of Another Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0572. Subtree of Another Tree][0572. Subtree of Another Tree]] :END: +Given the roots of two binary trees ~root~ and ~subRoot~, return ~true~ if there is a subtree of ~root~ with the same structure and node values of~ subRoot~ and ~false~ otherwise. + +A subtree of a binary tree ~tree~ is a tree that consists of a node in ~tree~ and all of this node's descendants. The tree ~tree~ could also be considered as a subtree of itself. + +*Example 1:* + + +#+begin_src +Input: root = [3,4,5,1,2], subRoot = [4,1,2] +Output: true +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] +Output: false +#+end_src + + +*Constraints:* + + - The number of nodes in the ~root~ tree is in the range ~[1, 2000]~. + + - The number of nodes in the ~subRoot~ tree is in the range ~[1, 1000]~. + + - ~-10^{4} <= root.val <= 10^{4}~ + + - ~-10^{4} <= subRoot.val <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSubtree(TreeNode* root, TreeNode* subRoot) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/0590-n-ary-tree-postorder-traversal.org b/org/study_deck_02/dsa/trees/0590-n-ary-tree-postorder-traversal.org index 9db02a5..231ff90 100644 --- a/org/study_deck_02/dsa/trees/0590-n-ary-tree-postorder-traversal.org +++ b/org/study_deck_02/dsa/trees/0590-n-ary-tree-postorder-traversal.org @@ -1,18 +1,84 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0590. N-ary Tree Postorder Traversal :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0590. N-ary Tree Postorder Traversal][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0590. N-ary Tree Postorder Traversal][0590. N-ary Tree Postorder Traversal]] :END: +Given the ~root~ of an n-ary tree, return /the postorder traversal of its nodes' values/. + +Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) + +*Example 1:* + + +#+begin_src +Input: root = [1,null,3,2,4,null,5,6] +Output: [5,6,3,2,4,1] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] +Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1] +#+end_src + + +*Constraints:* + + - The number of nodes in the tree is in the range ~[0, 10^{4}]~. + + - ~0 <= Node.val <= 10^{4}~ + + - The height of the n-ary tree is less than or equal to ~1000~. + +*Follow up:* Recursive solution is trivial, could you do it iteratively? + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +""" +# Definition for a Node. +class Node: + def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None): + self.val = val + self.children = children +""" +class Solution: + def postorder(self, root: 'Node') -> List[int]: #+end_src ** TODO C++ #+begin_src cpp +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + vector postorder(Node* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/1028-recover-a-tree-from-preorder-traversal.org b/org/study_deck_02/dsa/trees/1028-recover-a-tree-from-preorder-traversal.org index 03bc116..198b706 100644 --- a/org/study_deck_02/dsa/trees/1028-recover-a-tree-from-preorder-traversal.org +++ b/org/study_deck_02/dsa/trees/1028-recover-a-tree-from-preorder-traversal.org @@ -1,18 +1,82 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1028. Recover a Tree From Preorder Traversal :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1028. Recover a Tree From Preorder Traversal][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1028. Recover a Tree From Preorder Traversal][1028. Recover a Tree From Preorder Traversal]] :END: +We run a preorder depth-first search (DFS) on the ~root~ of a binary tree. + +At each node in this traversal, we output ~D~ dashes (where ~D~ is the depth of this node), then we output the value of this node. If the depth of a node is ~D~, the depth of its immediate child is ~D + 1~. The depth of the ~root~ node is ~0~. + +If a node has only one child, that child is guaranteed to be *the left child*. + +Given the output ~traversal~ of this traversal, recover the tree and return /its/ ~root~. + +*Example 1:* + + +#+begin_src +Input: traversal = "1-2--3--4-5--6--7" +Output: [1,2,5,3,4,6,7] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: traversal = "1-2--3---4-5--6---7" +Output: [1,2,5,3,null,6,null,4,null,7] +#+end_src + + +*Example 3:* + + +#+begin_src +Input: traversal = "1-401--349---90--88" +Output: [1,401,null,349,88,90] +#+end_src + + +*Constraints:* + + - The number of nodes in the original tree is in the range ~[1, 1000]~. + + - ~1 <= Node.val <= 10^{9}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* recoverFromPreorder(string traversal) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/1376-time-needed-to-inform-all-employees.org b/org/study_deck_02/dsa/trees/1376-time-needed-to-inform-all-employees.org index 7ebbc46..1d70806 100644 --- a/org/study_deck_02/dsa/trees/1376-time-needed-to-inform-all-employees.org +++ b/org/study_deck_02/dsa/trees/1376-time-needed-to-inform-all-employees.org @@ -1,18 +1,75 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1376. Time Needed to Inform All Employees :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1376. Time Needed to Inform All Employees][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1376. Time Needed to Inform All Employees][1376. Time Needed to Inform All Employees]] :END: +A company has ~n~ employees with a unique ID for each employee from ~0~ to ~n - 1~. The head of the company is the one with ~headID~. + +Each employee has one direct manager given in the ~manager~ array where ~manager[i]~ is the direct manager of the ~i-th~ employee, ~manager[headID] = -1~. Also, it is guaranteed that the subordination relationships have a tree structure. + +The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news. + +The ~i-th~ employee needs ~informTime[i]~ minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news). + +Return /the number of minutes/ needed to inform all the employees about the urgent news. + +*Example 1:* + + +#+begin_src +Input: n = 1, headID = 0, manager = [-1], informTime = [0] +Output: 0 +Explanation: The head of the company is the only employee in the company. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0] +Output: 1 +Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. +The tree structure of the employees in the company is shown. +#+end_src + + +*Constraints:* + + - ~1 <= n <= 10^{5}~ + + - ~0 <= headID < n~ + + - ~manager.length == n~ + + - ~0 <= manager[i] < n~ + + - ~manager[headID] == -1~ + + - ~informTime.length == n~ + + - ~0 <= informTime[i] <= 1000~ + + - ~informTime[i] == 0~ if employee ~i~ has no subordinates. + + - It is *guaranteed* that all the employees can be informed. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int numOfMinutes(int n, int headID, vector& manager, vector& informTime) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/trees/1448-count-good-nodes-in-binary-tree.org b/org/study_deck_02/dsa/trees/1448-count-good-nodes-in-binary-tree.org index e3d2cae..f01dbb3 100644 --- a/org/study_deck_02/dsa/trees/1448-count-good-nodes-in-binary-tree.org +++ b/org/study_deck_02/dsa/trees/1448-count-good-nodes-in-binary-tree.org @@ -1,18 +1,89 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1448. Count Good Nodes In Binary Tree :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1448. Count Good Nodes In Binary Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1448. Count Good Nodes In Binary Tree][1448. Count Good Nodes In Binary Tree]] :END: +Given a binary tree ~root~, a node /X/ in the tree is named *good* if in the path from root to /X/ there are no nodes with a value /greater than/ X. + +Return the number of *good* nodes in the binary tree. + +*Example 1:* + +** + + +#+begin_src +Input: root = [3,1,4,3,null,1,5] +Output: 4 +Explanation: Nodes in blue are good. +Root Node (3) is always a good node. +Node 4 -> (3,4) is the maximum value in the path starting from the root. +Node 5 -> (3,4,5) is the maximum value in the path +Node 3 -> (3,1,3) is the maximum value in the path. +#+end_src + + +*Example 2:* + +** + + +#+begin_src +Input: root = [3,3,null,4,2] +Output: 3 +Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: root = [1] +Output: 1 +Explanation: Root is considered as good. +#+end_src + + +*Constraints:* + + - The number of nodes in the binary tree is in the range ~[1, 10^5]~. + + - Each node's value is between ~[-10^4, 10^4]~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def goodNodes(self, root: TreeNode) -> int: #+end_src ** TODO C++ #+begin_src cpp - +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int goodNodes(TreeNode* root) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/tries/0208-implement-trie-prefix-tree.org b/org/study_deck_02/dsa/tries/0208-implement-trie-prefix-tree.org index 4c6b850..d595f59 100644 --- a/org/study_deck_02/dsa/tries/0208-implement-trie-prefix-tree.org +++ b/org/study_deck_02/dsa/tries/0208-implement-trie-prefix-tree.org @@ -1,18 +1,103 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0208. Implement Trie Prefix Tree :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0208. Implement Trie Prefix Tree][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0208. Implement Trie Prefix Tree][0208. Implement Trie Prefix Tree]] :END: +A *trie* (pronounced as "try") or *prefix tree* is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. + +Implement the Trie class: + + - ~Trie()~ Initializes the trie object. + + - ~void insert(String word)~ Inserts the string ~word~ into the trie. + + - ~boolean search(String word)~ Returns ~true~ if the string ~word~ is in the trie (i.e., was inserted before), and ~false~ otherwise. + + - ~boolean startsWith(String prefix)~ Returns ~true~ if there is a previously inserted string ~word~ that has the prefix ~prefix~, and ~false~ otherwise. + +*Example 1:* + + +#+begin_src +Input +["Trie", "insert", "search", "search", "startsWith", "insert", "search"] +[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] +Output +[null, null, true, false, true, null, true] + +Explanation +Trie trie = new Trie(); +trie.insert("apple"); +trie.search("apple"); // return True +trie.search("app"); // return False +trie.startsWith("app"); // return True +trie.insert("app"); +trie.search("app"); // return True +#+end_src + + +*Constraints:* + + - ~1 <= word.length, prefix.length <= 2000~ + + - ~word~ and ~prefix~ consist only of lowercase English letters. + + - At most ~3 * 10^{4}~ calls *in total* will be made to ~insert~, ~search~, and ~startsWith~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class Trie: + def __init__(self): + + + def insert(self, word: str) -> None: + + + def search(self, word: str) -> bool: + + + def startsWith(self, prefix: str) -> bool: + + + +# Your Trie object will be instantiated and called as such: +# obj = Trie() +# obj.insert(word) +# param_2 = obj.search(word) +# param_3 = obj.startsWith(prefix) #+end_src ** TODO C++ #+begin_src cpp +class Trie { +public: + Trie() { + + } + + void insert(string word) { + + } + + bool search(string word) { + + } + + bool startsWith(string prefix) { + + } +}; +/** + * Your Trie object will be instantiated and called as such: + * Trie* obj = new Trie(); + * obj->insert(word); + * bool param_2 = obj->search(word); + * bool param_3 = obj->startsWith(prefix); + */ #+end_src diff --git a/org/study_deck_02/dsa/tries/0211-design-add-and-search-words-data-structure.org b/org/study_deck_02/dsa/tries/0211-design-add-and-search-words-data-structure.org index 8de21b7..4ea4831 100644 --- a/org/study_deck_02/dsa/tries/0211-design-add-and-search-words-data-structure.org +++ b/org/study_deck_02/dsa/tries/0211-design-add-and-search-words-data-structure.org @@ -1,18 +1,97 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0211. Design Add And Search Words Data Structure :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0211. Design Add And Search Words Data Structure][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0211. Design Add And Search Words Data Structure][0211. Design Add And Search Words Data Structure]] :END: +Design a data structure that supports adding new words and finding if a string matches any previously added string. + +Implement the ~WordDictionary~ class: + + - ~WordDictionary()~ Initializes the object. + + - ~void addWord(word)~ Adds ~word~ to the data structure, it can be matched later. + + - ~bool search(word)~ Returns ~true~ if there is any string in the data structure that matches ~word~ or ~false~ otherwise. ~word~ may contain dots ~'.'~ where dots can be matched with any letter. + +*Example:* + + +#+begin_src +Input +["WordDictionary","addWord","addWord","addWord","search","search","search","search"] +[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] +Output +[null,null,null,null,false,true,true,true] + +Explanation +WordDictionary wordDictionary = new WordDictionary(); +wordDictionary.addWord("bad"); +wordDictionary.addWord("dad"); +wordDictionary.addWord("mad"); +wordDictionary.search("pad"); // return False +wordDictionary.search("bad"); // return True +wordDictionary.search(".ad"); // return True +wordDictionary.search("b.."); // return True +#+end_src + + +*Constraints:* + + - ~1 <= word.length <= 25~ + + - ~word~ in ~addWord~ consists of lowercase English letters. + + - ~word~ in ~search~ consist of ~'.'~ or lowercase English letters. + + - There will be at most ~2~ dots in ~word~ for ~search~ queries. + + - At most ~10^{4}~ calls will be made to ~addWord~ and ~search~. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python +class WordDictionary: + def __init__(self): + + + def addWord(self, word: str) -> None: + + + def search(self, word: str) -> bool: + + + +# Your WordDictionary object will be instantiated and called as such: +# obj = WordDictionary() +# obj.addWord(word) +# param_2 = obj.search(word) #+end_src ** TODO C++ #+begin_src cpp +class WordDictionary { +public: + WordDictionary() { + + } + + void addWord(string word) { + + } + + bool search(string word) { + + } +}; +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary* obj = new WordDictionary(); + * obj->addWord(word); + * bool param_2 = obj->search(word); + */ #+end_src diff --git a/org/study_deck_02/dsa/tries/0212-word-search-ii.org b/org/study_deck_02/dsa/tries/0212-word-search-ii.org index 0884fa2..0c7c51d 100644 --- a/org/study_deck_02/dsa/tries/0212-word-search-ii.org +++ b/org/study_deck_02/dsa/tries/0212-word-search-ii.org @@ -1,18 +1,64 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0212. Word Search II :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0212. Word Search II][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0212. Word Search II][0212. Word Search II]] :END: +Given an ~m x n~ ~board~ of characters and a list of strings ~words~, return /all words on the board/. + +Each word must be constructed from letters of sequentially adjacent cells, where *adjacent cells* are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. + +*Example 1:* + + +#+begin_src +Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] +Output: ["eat","oath"] +#+end_src + + +*Example 2:* + + +#+begin_src +Input: board = [["a","b"],["c","d"]], words = ["abcb"] +Output: [] +#+end_src + + +*Constraints:* + + - ~m == board.length~ + + - ~n == board[i].length~ + + - ~1 <= m, n <= 12~ + + - ~board[i][j]~ is a lowercase English letter. + + - ~1 <= words.length <= 3 * 10^{4}~ + + - ~1 <= words[i].length <= 10~ + + - ~words[i]~ consists of lowercase English letters. + + - All the strings of ~words~ are unique. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector findWords(vector>& board, vector& words) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/tries/1166-design-file-system.org b/org/study_deck_02/dsa/tries/1166-design-file-system.org index c840eb3..0dc8425 100644 --- a/org/study_deck_02/dsa/tries/1166-design-file-system.org +++ b/org/study_deck_02/dsa/tries/1166-design-file-system.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 1166. Design File System :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*1166. Design File System][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*1166. Design File System][1166. Design File System]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/two-pointers/0011-container-with-most-water.org b/org/study_deck_02/dsa/two-pointers/0011-container-with-most-water.org index 4f9c7c8..41ea597 100644 --- a/org/study_deck_02/dsa/two-pointers/0011-container-with-most-water.org +++ b/org/study_deck_02/dsa/two-pointers/0011-container-with-most-water.org @@ -1,18 +1,59 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0011. Container With Most Water :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0011. Container With Most Water][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0011. Container With Most Water][0011. Container With Most Water]] :END: +You are given an integer array ~height~ of length ~n~. There are ~n~ vertical lines drawn such that the two endpoints of the ~i^{th}~ line are ~(i, 0)~ and ~(i, height[i])~. + +Find two lines that together with the x-axis form a container, such that the container contains the most water. + +Return /the maximum amount of water a container can store/. + +*Notice* that you may not slant the container. + +*Example 1:* + + +#+begin_src +Input: height = [1,8,6,2,5,4,8,3,7] +Output: 49 +Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: height = [1,1] +Output: 1 +#+end_src + + +*Constraints:* + + - ~n == height.length~ + + - ~2 <= n <= 10^{5}~ + + - ~0 <= height[i] <= 10^{4}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def maxArea(self, height: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int maxArea(vector& height) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/two-pointers/0015-3sum.org b/org/study_deck_02/dsa/two-pointers/0015-3sum.org index 396c342..1e65a37 100644 --- a/org/study_deck_02/dsa/two-pointers/0015-3sum.org +++ b/org/study_deck_02/dsa/two-pointers/0015-3sum.org @@ -1,18 +1,69 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0015. 3Sum :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0015. 3Sum][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0015. 3Sum][0015. 3Sum]] :END: +Given an integer array nums, return all the triplets ~[nums[i], nums[j], nums[k]]~ such that ~i != j~, ~i != k~, and ~j != k~, and ~nums[i] + nums[j] + nums[k] == 0~. + +Notice that the solution set must not contain duplicate triplets. + +*Example 1:* + + +#+begin_src +Input: nums = [-1,0,1,2,-1,-4] +Output: [[-1,-1,2],[-1,0,1]] +Explanation: +nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. +nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. +nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. +The distinct triplets are [-1,0,1] and [-1,-1,2]. +Notice that the order of the output and the order of the triplets does not matter. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: nums = [0,1,1] +Output: [] +Explanation: The only possible triplet does not sum up to 0. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: nums = [0,0,0] +Output: [[0,0,0]] +Explanation: The only possible triplet sums up to 0. +#+end_src + + +*Constraints:* + + - ~3 <= nums.length <= 3000~ + + - ~-10^{5} <= nums[i] <= 10^{5}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def threeSum(self, nums: list[int]) -> list[list[int]]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector> threeSum(vector& nums) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/two-pointers/0042-trapping-rain-water.org b/org/study_deck_02/dsa/two-pointers/0042-trapping-rain-water.org index c2402ce..d6d0efa 100644 --- a/org/study_deck_02/dsa/two-pointers/0042-trapping-rain-water.org +++ b/org/study_deck_02/dsa/two-pointers/0042-trapping-rain-water.org @@ -1,18 +1,53 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0042. Trapping Rain Water :hard: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0042. Trapping Rain Water][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0042. Trapping Rain Water][0042. Trapping Rain Water]] :END: +Given ~n~ non-negative integers representing an elevation map where the width of each bar is ~1~, compute how much water it can trap after raining. + +*Example 1:* + + +#+begin_src +Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] +Output: 6 +Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: height = [4,2,0,3,2,5] +Output: 9 +#+end_src + + +*Constraints:* + + - ~n == height.length~ + + - ~1 <= n <= 2 * 10^{4}~ + + - ~0 <= height[i] <= 10^{5}~ + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def trap(self, height: List[int]) -> int: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + int trap(vector& height) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/two-pointers/0125-valid-palindrome.org b/org/study_deck_02/dsa/two-pointers/0125-valid-palindrome.org index 5bfe141..671e5d8 100644 --- a/org/study_deck_02/dsa/two-pointers/0125-valid-palindrome.org +++ b/org/study_deck_02/dsa/two-pointers/0125-valid-palindrome.org @@ -1,18 +1,65 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0125. Valid Palindrome :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0125. Valid Palindrome][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0125. Valid Palindrome][0125. Valid Palindrome]] :END: +A phrase is a *palindrome* if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. + +Given a string ~s~, return ~true~/ if it is a *palindrome*, or /~false~/ otherwise/. + +*Example 1:* + + +#+begin_src +Input: s = "A man, a plan, a canal: Panama" +Output: true +Explanation: "amanaplanacanalpanama" is a palindrome. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: s = "race a car" +Output: false +Explanation: "raceacar" is not a palindrome. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: s = " " +Output: true +Explanation: s is an empty string "" after removing non-alphanumeric characters. +Since an empty string reads the same forward and backward, it is a palindrome. +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 2 * 10^{5}~ + + - ~s~ consists only of printable ASCII characters. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def isPalindrome(self, s: str) -> bool: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + bool isPalindrome(string s) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/two-pointers/0167-two-sum-ii-input-array-is-sorted.org b/org/study_deck_02/dsa/two-pointers/0167-two-sum-ii-input-array-is-sorted.org index 7f1dca8..c56f33e 100644 --- a/org/study_deck_02/dsa/two-pointers/0167-two-sum-ii-input-array-is-sorted.org +++ b/org/study_deck_02/dsa/two-pointers/0167-two-sum-ii-input-array-is-sorted.org @@ -1,18 +1,74 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0167. Two Sum II Input Array Is Sorted :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0167. Two Sum II Input Array Is Sorted][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0167. Two Sum II Input Array Is Sorted][0167. Two Sum II Input Array Is Sorted]] :END: +Given a *1-indexed* array of integers ~numbers~ that is already */sorted in non-decreasing order/*, find two numbers such that they add up to a specific ~target~ number. Let these two numbers be ~numbers[index_{1}]~ and ~numbers[index_{2}]~ where ~1 <= index_{1} < index_{2} <= numbers.length~. + +Return/ the indices of the two numbers /~index_{1}~/ and /~index_{2}~/, *each incremented by one,* as an integer array /~[index_{1}, index_{2}]~/ of length 2./ + +The tests are generated such that there is *exactly one solution*. You *may not* use the same element twice. + +Your solution must use only constant extra space. + +*Example 1:* + + +#+begin_src +Input: numbers = [2,7,11,15], target = 9 +Output: [1,2] +Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. +#+end_src + + +*Example 2:* + + +#+begin_src +Input: numbers = [2,3,4], target = 6 +Output: [1,3] +Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. +#+end_src + + +*Example 3:* + + +#+begin_src +Input: numbers = [-1,0], target = -1 +Output: [1,2] +Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. +#+end_src + + +*Constraints:* + + - ~2 <= numbers.length <= 3 * 10^{4}~ + + - ~-1000 <= numbers[i] <= 1000~ + + - ~numbers~ is sorted in *non-decreasing order*. + + - ~-1000 <= target <= 1000~ + + - The tests are generated such that there is *exactly one solution*. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + vector twoSum(vector& numbers, int target) { + + } +}; #+end_src diff --git a/org/study_deck_02/dsa/two-pointers/0259-3sum-smaller.org b/org/study_deck_02/dsa/two-pointers/0259-3sum-smaller.org index 6613b2e..e734c09 100644 --- a/org/study_deck_02/dsa/two-pointers/0259-3sum-smaller.org +++ b/org/study_deck_02/dsa/two-pointers/0259-3sum-smaller.org @@ -1,7 +1,7 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0259. 3Sum Smaller :medium: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0259. 3Sum Smaller][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0259. 3Sum Smaller][0259. 3Sum Smaller]] :END: ** TODO Approach diff --git a/org/study_deck_02/dsa/two-pointers/0344-reverse-string.org b/org/study_deck_02/dsa/two-pointers/0344-reverse-string.org index 0b10141..ce52af0 100644 --- a/org/study_deck_02/dsa/two-pointers/0344-reverse-string.org +++ b/org/study_deck_02/dsa/two-pointers/0344-reverse-string.org @@ -1,18 +1,53 @@ #+PROPERTY: STUDY_DECK_02 * TODO 0344. Reverse String :easy: :PROPERTIES: -:NEETCODE: [[file:../../roadmap.org::*0344. Reverse String][Roadmap]] +:NEETCODE: [[file:../../roadmap.org::*0344. Reverse String][0344. Reverse String]] :END: +Write a function that reverses a string. The input string is given as an array of characters ~s~. + +You must do this by modifying the input array in-place with ~O(1)~ extra memory. + +*Example 1:* + + +#+begin_src +Input: s = ["h","e","l","l","o"] +Output: ["o","l","l","e","h"] +#+end_src +*Example 2:* + + +#+begin_src +Input: s = ["H","a","n","n","a","h"] +Output: ["h","a","n","n","a","H"] +#+end_src + + +*Constraints:* + + - ~1 <= s.length <= 10^{5}~ + + - ~s[i]~ is a printable ascii character. + ** TODO Approach Write your approach here. ** TODO Python #+begin_src python - +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ #+end_src ** TODO C++ #+begin_src cpp - +class Solution { +public: + void reverseString(vector& s) { + + } +}; #+end_src